oc_pvc.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # flake8: noqa: T001
  4. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  5. # / __| __| \| | __| _ \ /_\_ _| __| \
  6. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  7. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  8. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  9. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  10. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  11. #
  12. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  13. # and other contributors as indicated by the @author tags.
  14. #
  15. # Licensed under the Apache License, Version 2.0 (the "License");
  16. # you may not use this file except in compliance with the License.
  17. # You may obtain a copy of the License at
  18. #
  19. # http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26. #
  27. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  28. '''
  29. OpenShiftCLI class that wraps the oc commands in a subprocess
  30. '''
  31. # pylint: disable=too-many-lines
  32. from __future__ import print_function
  33. import atexit
  34. import copy
  35. import json
  36. import os
  37. import re
  38. import shutil
  39. import subprocess
  40. import tempfile
  41. # pylint: disable=import-error
  42. try:
  43. import ruamel.yaml as yaml
  44. except ImportError:
  45. import yaml
  46. from ansible.module_utils.basic import AnsibleModule
  47. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  48. # -*- -*- -*- Begin included fragment: doc/pvc -*- -*- -*-
  49. DOCUMENTATION = '''
  50. ---
  51. module: oc_pvc
  52. short_description: Modify, and idempotently manage openshift persistent volume claims
  53. description:
  54. - Modify openshift persistent volume claims programmatically.
  55. options:
  56. state:
  57. description:
  58. - Supported states, present, absent, list
  59. - present - will ensure object is created or updated to the value specified
  60. - list - will return a pvc
  61. - absent - will remove a pvc
  62. required: False
  63. default: present
  64. choices: ["present", 'absent', 'list']
  65. aliases: []
  66. kubeconfig:
  67. description:
  68. - The path for the kubeconfig file to use for authentication
  69. required: false
  70. default: /etc/origin/master/admin.kubeconfig
  71. aliases: []
  72. debug:
  73. description:
  74. - Turn on debug output.
  75. required: false
  76. default: False
  77. aliases: []
  78. name:
  79. description:
  80. - Name of the object that is being queried.
  81. required: false
  82. default: None
  83. aliases: []
  84. namespace:
  85. description:
  86. - The namespace where the object lives.
  87. required: false
  88. default: str
  89. aliases: []
  90. volume_capacity:
  91. description:
  92. - The requested volume capacity
  93. required: False
  94. default: 1G
  95. aliases: []
  96. access_modes:
  97. description:
  98. - The access modes allowed for the pvc
  99. - Expects a list
  100. required: False
  101. default: ReadWriteOnce
  102. choices:
  103. - ReadWriteOnce
  104. - ReadOnlyMany
  105. - ReadWriteMany
  106. aliases: []
  107. author:
  108. - "Kenny Woodson <kwoodson@redhat.com>"
  109. extends_documentation_fragment: []
  110. '''
  111. EXAMPLES = '''
  112. - name: create a pvc
  113. oc_pvc:
  114. namespace: awesomeapp
  115. name: dbstorage
  116. access_modes:
  117. - ReadWriteOnce
  118. volume_capacity: 5G
  119. register: pvcout
  120. '''
  121. # -*- -*- -*- End included fragment: doc/pvc -*- -*- -*-
  122. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  123. class YeditException(Exception): # pragma: no cover
  124. ''' Exception class for Yedit '''
  125. pass
  126. # pylint: disable=too-many-public-methods
  127. class Yedit(object): # pragma: no cover
  128. ''' Class to modify yaml files '''
  129. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  130. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  131. com_sep = set(['.', '#', '|', ':'])
  132. # pylint: disable=too-many-arguments
  133. def __init__(self,
  134. filename=None,
  135. content=None,
  136. content_type='yaml',
  137. separator='.',
  138. backup=False):
  139. self.content = content
  140. self._separator = separator
  141. self.filename = filename
  142. self.__yaml_dict = content
  143. self.content_type = content_type
  144. self.backup = backup
  145. self.load(content_type=self.content_type)
  146. if self.__yaml_dict is None:
  147. self.__yaml_dict = {}
  148. @property
  149. def separator(self):
  150. ''' getter method for separator '''
  151. return self._separator
  152. @separator.setter
  153. def separator(self, inc_sep):
  154. ''' setter method for separator '''
  155. self._separator = inc_sep
  156. @property
  157. def yaml_dict(self):
  158. ''' getter method for yaml_dict '''
  159. return self.__yaml_dict
  160. @yaml_dict.setter
  161. def yaml_dict(self, value):
  162. ''' setter method for yaml_dict '''
  163. self.__yaml_dict = value
  164. @staticmethod
  165. def parse_key(key, sep='.'):
  166. '''parse the key allowing the appropriate separator'''
  167. common_separators = list(Yedit.com_sep - set([sep]))
  168. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  169. @staticmethod
  170. def valid_key(key, sep='.'):
  171. '''validate the incoming key'''
  172. common_separators = list(Yedit.com_sep - set([sep]))
  173. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  174. return False
  175. return True
  176. @staticmethod
  177. def remove_entry(data, key, sep='.'):
  178. ''' remove data at location key '''
  179. if key == '' and isinstance(data, dict):
  180. data.clear()
  181. return True
  182. elif key == '' and isinstance(data, list):
  183. del data[:]
  184. return True
  185. if not (key and Yedit.valid_key(key, sep)) and \
  186. isinstance(data, (list, dict)):
  187. return None
  188. key_indexes = Yedit.parse_key(key, sep)
  189. for arr_ind, dict_key in key_indexes[:-1]:
  190. if dict_key and isinstance(data, dict):
  191. data = data.get(dict_key)
  192. elif (arr_ind and isinstance(data, list) and
  193. int(arr_ind) <= len(data) - 1):
  194. data = data[int(arr_ind)]
  195. else:
  196. return None
  197. # process last index for remove
  198. # expected list entry
  199. if key_indexes[-1][0]:
  200. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  201. del data[int(key_indexes[-1][0])]
  202. return True
  203. # expected dict entry
  204. elif key_indexes[-1][1]:
  205. if isinstance(data, dict):
  206. del data[key_indexes[-1][1]]
  207. return True
  208. @staticmethod
  209. def add_entry(data, key, item=None, sep='.'):
  210. ''' Get an item from a dictionary with key notation a.b.c
  211. d = {'a': {'b': 'c'}}}
  212. key = a#b
  213. return c
  214. '''
  215. if key == '':
  216. pass
  217. elif (not (key and Yedit.valid_key(key, sep)) and
  218. isinstance(data, (list, dict))):
  219. return None
  220. key_indexes = Yedit.parse_key(key, sep)
  221. for arr_ind, dict_key in key_indexes[:-1]:
  222. if dict_key:
  223. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  224. data = data[dict_key]
  225. continue
  226. elif data and not isinstance(data, dict):
  227. raise YeditException("Unexpected item type found while going through key " +
  228. "path: {} (at key: {})".format(key, dict_key))
  229. data[dict_key] = {}
  230. data = data[dict_key]
  231. elif (arr_ind and isinstance(data, list) and
  232. int(arr_ind) <= len(data) - 1):
  233. data = data[int(arr_ind)]
  234. else:
  235. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  236. if key == '':
  237. data = item
  238. # process last index for add
  239. # expected list entry
  240. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  241. data[int(key_indexes[-1][0])] = item
  242. # expected dict entry
  243. elif key_indexes[-1][1] and isinstance(data, dict):
  244. data[key_indexes[-1][1]] = item
  245. # didn't add/update to an existing list, nor add/update key to a dict
  246. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  247. # non-existent array
  248. else:
  249. raise YeditException("Error adding to object at path: {}".format(key))
  250. return data
  251. @staticmethod
  252. def get_entry(data, key, sep='.'):
  253. ''' Get an item from a dictionary with key notation a.b.c
  254. d = {'a': {'b': 'c'}}}
  255. key = a.b
  256. return c
  257. '''
  258. if key == '':
  259. pass
  260. elif (not (key and Yedit.valid_key(key, sep)) and
  261. isinstance(data, (list, dict))):
  262. return None
  263. key_indexes = Yedit.parse_key(key, sep)
  264. for arr_ind, dict_key in key_indexes:
  265. if dict_key and isinstance(data, dict):
  266. data = data.get(dict_key)
  267. elif (arr_ind and isinstance(data, list) and
  268. int(arr_ind) <= len(data) - 1):
  269. data = data[int(arr_ind)]
  270. else:
  271. return None
  272. return data
  273. @staticmethod
  274. def _write(filename, contents):
  275. ''' Actually write the file contents to disk. This helps with mocking. '''
  276. tmp_filename = filename + '.yedit'
  277. with open(tmp_filename, 'w') as yfd:
  278. yfd.write(contents)
  279. os.rename(tmp_filename, filename)
  280. def write(self):
  281. ''' write to file '''
  282. if not self.filename:
  283. raise YeditException('Please specify a filename.')
  284. if self.backup and self.file_exists():
  285. shutil.copy(self.filename, self.filename + '.orig')
  286. # Try to set format attributes if supported
  287. try:
  288. self.yaml_dict.fa.set_block_style()
  289. except AttributeError:
  290. pass
  291. # Try to use RoundTripDumper if supported.
  292. try:
  293. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  294. except AttributeError:
  295. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  296. return (True, self.yaml_dict)
  297. def read(self):
  298. ''' read from file '''
  299. # check if it exists
  300. if self.filename is None or not self.file_exists():
  301. return None
  302. contents = None
  303. with open(self.filename) as yfd:
  304. contents = yfd.read()
  305. return contents
  306. def file_exists(self):
  307. ''' return whether file exists '''
  308. if os.path.exists(self.filename):
  309. return True
  310. return False
  311. def load(self, content_type='yaml'):
  312. ''' return yaml file '''
  313. contents = self.read()
  314. if not contents and not self.content:
  315. return None
  316. if self.content:
  317. if isinstance(self.content, dict):
  318. self.yaml_dict = self.content
  319. return self.yaml_dict
  320. elif isinstance(self.content, str):
  321. contents = self.content
  322. # check if it is yaml
  323. try:
  324. if content_type == 'yaml' and contents:
  325. # Try to set format attributes if supported
  326. try:
  327. self.yaml_dict.fa.set_block_style()
  328. except AttributeError:
  329. pass
  330. # Try to use RoundTripLoader if supported.
  331. try:
  332. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  333. except AttributeError:
  334. self.yaml_dict = yaml.safe_load(contents)
  335. # Try to set format attributes if supported
  336. try:
  337. self.yaml_dict.fa.set_block_style()
  338. except AttributeError:
  339. pass
  340. elif content_type == 'json' and contents:
  341. self.yaml_dict = json.loads(contents)
  342. except yaml.YAMLError as err:
  343. # Error loading yaml or json
  344. raise YeditException('Problem with loading yaml file. {}'.format(err))
  345. return self.yaml_dict
  346. def get(self, key):
  347. ''' get a specified key'''
  348. try:
  349. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  350. except KeyError:
  351. entry = None
  352. return entry
  353. def pop(self, path, key_or_item):
  354. ''' remove a key, value pair from a dict or an item for a list'''
  355. try:
  356. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  357. except KeyError:
  358. entry = None
  359. if entry is None:
  360. return (False, self.yaml_dict)
  361. if isinstance(entry, dict):
  362. # AUDIT:maybe-no-member makes sense due to fuzzy types
  363. # pylint: disable=maybe-no-member
  364. if key_or_item in entry:
  365. entry.pop(key_or_item)
  366. return (True, self.yaml_dict)
  367. return (False, self.yaml_dict)
  368. elif isinstance(entry, list):
  369. # AUDIT:maybe-no-member makes sense due to fuzzy types
  370. # pylint: disable=maybe-no-member
  371. ind = None
  372. try:
  373. ind = entry.index(key_or_item)
  374. except ValueError:
  375. return (False, self.yaml_dict)
  376. entry.pop(ind)
  377. return (True, self.yaml_dict)
  378. return (False, self.yaml_dict)
  379. def delete(self, path):
  380. ''' remove path from a dict'''
  381. try:
  382. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  383. except KeyError:
  384. entry = None
  385. if entry is None:
  386. return (False, self.yaml_dict)
  387. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  388. if not result:
  389. return (False, self.yaml_dict)
  390. return (True, self.yaml_dict)
  391. def exists(self, path, value):
  392. ''' check if value exists at path'''
  393. try:
  394. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  395. except KeyError:
  396. entry = None
  397. if isinstance(entry, list):
  398. if value in entry:
  399. return True
  400. return False
  401. elif isinstance(entry, dict):
  402. if isinstance(value, dict):
  403. rval = False
  404. for key, val in value.items():
  405. if entry[key] != val:
  406. rval = False
  407. break
  408. else:
  409. rval = True
  410. return rval
  411. return value in entry
  412. return entry == value
  413. def append(self, path, value):
  414. '''append value to a list'''
  415. try:
  416. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  417. except KeyError:
  418. entry = None
  419. if entry is None:
  420. self.put(path, [])
  421. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  422. if not isinstance(entry, list):
  423. return (False, self.yaml_dict)
  424. # AUDIT:maybe-no-member makes sense due to loading data from
  425. # a serialized format.
  426. # pylint: disable=maybe-no-member
  427. entry.append(value)
  428. return (True, self.yaml_dict)
  429. # pylint: disable=too-many-arguments
  430. def update(self, path, value, index=None, curr_value=None):
  431. ''' put path, value into a dict '''
  432. try:
  433. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  434. except KeyError:
  435. entry = None
  436. if isinstance(entry, dict):
  437. # AUDIT:maybe-no-member makes sense due to fuzzy types
  438. # pylint: disable=maybe-no-member
  439. if not isinstance(value, dict):
  440. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  441. 'value=[{}] type=[{}]'.format(value, type(value)))
  442. entry.update(value)
  443. return (True, self.yaml_dict)
  444. elif isinstance(entry, list):
  445. # AUDIT:maybe-no-member makes sense due to fuzzy types
  446. # pylint: disable=maybe-no-member
  447. ind = None
  448. if curr_value:
  449. try:
  450. ind = entry.index(curr_value)
  451. except ValueError:
  452. return (False, self.yaml_dict)
  453. elif index is not None:
  454. ind = index
  455. if ind is not None and entry[ind] != value:
  456. entry[ind] = value
  457. return (True, self.yaml_dict)
  458. # see if it exists in the list
  459. try:
  460. ind = entry.index(value)
  461. except ValueError:
  462. # doesn't exist, append it
  463. entry.append(value)
  464. return (True, self.yaml_dict)
  465. # already exists, return
  466. if ind is not None:
  467. return (False, self.yaml_dict)
  468. return (False, self.yaml_dict)
  469. def put(self, path, value):
  470. ''' put path, value into a dict '''
  471. try:
  472. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  473. except KeyError:
  474. entry = None
  475. if entry == value:
  476. return (False, self.yaml_dict)
  477. # deepcopy didn't work
  478. # Try to use ruamel.yaml and fallback to pyyaml
  479. try:
  480. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  481. default_flow_style=False),
  482. yaml.RoundTripLoader)
  483. except AttributeError:
  484. tmp_copy = copy.deepcopy(self.yaml_dict)
  485. # set the format attributes if available
  486. try:
  487. tmp_copy.fa.set_block_style()
  488. except AttributeError:
  489. pass
  490. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  491. if result is None:
  492. return (False, self.yaml_dict)
  493. # When path equals "" it is a special case.
  494. # "" refers to the root of the document
  495. # Only update the root path (entire document) when its a list or dict
  496. if path == '':
  497. if isinstance(result, list) or isinstance(result, dict):
  498. self.yaml_dict = result
  499. return (True, self.yaml_dict)
  500. return (False, self.yaml_dict)
  501. self.yaml_dict = tmp_copy
  502. return (True, self.yaml_dict)
  503. def create(self, path, value):
  504. ''' create a yaml file '''
  505. if not self.file_exists():
  506. # deepcopy didn't work
  507. # Try to use ruamel.yaml and fallback to pyyaml
  508. try:
  509. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  510. default_flow_style=False),
  511. yaml.RoundTripLoader)
  512. except AttributeError:
  513. tmp_copy = copy.deepcopy(self.yaml_dict)
  514. # set the format attributes if available
  515. try:
  516. tmp_copy.fa.set_block_style()
  517. except AttributeError:
  518. pass
  519. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  520. if result is not None:
  521. self.yaml_dict = tmp_copy
  522. return (True, self.yaml_dict)
  523. return (False, self.yaml_dict)
  524. @staticmethod
  525. def get_curr_value(invalue, val_type):
  526. '''return the current value'''
  527. if invalue is None:
  528. return None
  529. curr_value = invalue
  530. if val_type == 'yaml':
  531. curr_value = yaml.load(invalue)
  532. elif val_type == 'json':
  533. curr_value = json.loads(invalue)
  534. return curr_value
  535. @staticmethod
  536. def parse_value(inc_value, vtype=''):
  537. '''determine value type passed'''
  538. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  539. 'on', 'On', 'ON', ]
  540. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  541. 'off', 'Off', 'OFF']
  542. # It came in as a string but you didn't specify value_type as string
  543. # we will convert to bool if it matches any of the above cases
  544. if isinstance(inc_value, str) and 'bool' in vtype:
  545. if inc_value not in true_bools and inc_value not in false_bools:
  546. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  547. elif isinstance(inc_value, bool) and 'str' in vtype:
  548. inc_value = str(inc_value)
  549. # There is a special case where '' will turn into None after yaml loading it so skip
  550. if isinstance(inc_value, str) and inc_value == '':
  551. pass
  552. # If vtype is not str then go ahead and attempt to yaml load it.
  553. elif isinstance(inc_value, str) and 'str' not in vtype:
  554. try:
  555. inc_value = yaml.safe_load(inc_value)
  556. except Exception:
  557. raise YeditException('Could not determine type of incoming value. ' +
  558. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  559. return inc_value
  560. @staticmethod
  561. def process_edits(edits, yamlfile):
  562. '''run through a list of edits and process them one-by-one'''
  563. results = []
  564. for edit in edits:
  565. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  566. if edit.get('action') == 'update':
  567. # pylint: disable=line-too-long
  568. curr_value = Yedit.get_curr_value(
  569. Yedit.parse_value(edit.get('curr_value')),
  570. edit.get('curr_value_format'))
  571. rval = yamlfile.update(edit['key'],
  572. value,
  573. edit.get('index'),
  574. curr_value)
  575. elif edit.get('action') == 'append':
  576. rval = yamlfile.append(edit['key'], value)
  577. else:
  578. rval = yamlfile.put(edit['key'], value)
  579. if rval[0]:
  580. results.append({'key': edit['key'], 'edit': rval[1]})
  581. return {'changed': len(results) > 0, 'results': results}
  582. # pylint: disable=too-many-return-statements,too-many-branches
  583. @staticmethod
  584. def run_ansible(params):
  585. '''perform the idempotent crud operations'''
  586. yamlfile = Yedit(filename=params['src'],
  587. backup=params['backup'],
  588. separator=params['separator'])
  589. state = params['state']
  590. if params['src']:
  591. rval = yamlfile.load()
  592. if yamlfile.yaml_dict is None and state != 'present':
  593. return {'failed': True,
  594. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  595. 'file exists, that it is has correct permissions, and is valid yaml.'}
  596. if state == 'list':
  597. if params['content']:
  598. content = Yedit.parse_value(params['content'], params['content_type'])
  599. yamlfile.yaml_dict = content
  600. if params['key']:
  601. rval = yamlfile.get(params['key']) or {}
  602. return {'changed': False, 'result': rval, 'state': state}
  603. elif state == 'absent':
  604. if params['content']:
  605. content = Yedit.parse_value(params['content'], params['content_type'])
  606. yamlfile.yaml_dict = content
  607. if params['update']:
  608. rval = yamlfile.pop(params['key'], params['value'])
  609. else:
  610. rval = yamlfile.delete(params['key'])
  611. if rval[0] and params['src']:
  612. yamlfile.write()
  613. return {'changed': rval[0], 'result': rval[1], 'state': state}
  614. elif state == 'present':
  615. # check if content is different than what is in the file
  616. if params['content']:
  617. content = Yedit.parse_value(params['content'], params['content_type'])
  618. # We had no edits to make and the contents are the same
  619. if yamlfile.yaml_dict == content and \
  620. params['value'] is None:
  621. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  622. yamlfile.yaml_dict = content
  623. # If we were passed a key, value then
  624. # we enapsulate it in a list and process it
  625. # Key, Value passed to the module : Converted to Edits list #
  626. edits = []
  627. _edit = {}
  628. if params['value'] is not None:
  629. _edit['value'] = params['value']
  630. _edit['value_type'] = params['value_type']
  631. _edit['key'] = params['key']
  632. if params['update']:
  633. _edit['action'] = 'update'
  634. _edit['curr_value'] = params['curr_value']
  635. _edit['curr_value_format'] = params['curr_value_format']
  636. _edit['index'] = params['index']
  637. elif params['append']:
  638. _edit['action'] = 'append'
  639. edits.append(_edit)
  640. elif params['edits'] is not None:
  641. edits = params['edits']
  642. if edits:
  643. results = Yedit.process_edits(edits, yamlfile)
  644. # if there were changes and a src provided to us we need to write
  645. if results['changed'] and params['src']:
  646. yamlfile.write()
  647. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  648. # no edits to make
  649. if params['src']:
  650. # pylint: disable=redefined-variable-type
  651. rval = yamlfile.write()
  652. return {'changed': rval[0],
  653. 'result': rval[1],
  654. 'state': state}
  655. # We were passed content but no src, key or value, or edits. Return contents in memory
  656. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  657. return {'failed': True, 'msg': 'Unkown state passed'}
  658. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  659. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  660. # pylint: disable=too-many-lines
  661. # noqa: E301,E302,E303,T001
  662. class OpenShiftCLIError(Exception):
  663. '''Exception class for openshiftcli'''
  664. pass
  665. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  666. def locate_oc_binary():
  667. ''' Find and return oc binary file '''
  668. # https://github.com/openshift/openshift-ansible/issues/3410
  669. # oc can be in /usr/local/bin in some cases, but that may not
  670. # be in $PATH due to ansible/sudo
  671. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  672. oc_binary = 'oc'
  673. # Use shutil.which if it is available, otherwise fallback to a naive path search
  674. try:
  675. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  676. if which_result is not None:
  677. oc_binary = which_result
  678. except AttributeError:
  679. for path in paths:
  680. if os.path.exists(os.path.join(path, oc_binary)):
  681. oc_binary = os.path.join(path, oc_binary)
  682. break
  683. return oc_binary
  684. # pylint: disable=too-few-public-methods
  685. class OpenShiftCLI(object):
  686. ''' Class to wrap the command line tools '''
  687. def __init__(self,
  688. namespace,
  689. kubeconfig='/etc/origin/master/admin.kubeconfig',
  690. verbose=False,
  691. all_namespaces=False):
  692. ''' Constructor for OpenshiftCLI '''
  693. self.namespace = namespace
  694. self.verbose = verbose
  695. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  696. self.all_namespaces = all_namespaces
  697. self.oc_binary = locate_oc_binary()
  698. # Pylint allows only 5 arguments to be passed.
  699. # pylint: disable=too-many-arguments
  700. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  701. ''' replace the current object with the content '''
  702. res = self._get(resource, rname)
  703. if not res['results']:
  704. return res
  705. fname = Utils.create_tmpfile(rname + '-')
  706. yed = Yedit(fname, res['results'][0], separator=sep)
  707. changes = []
  708. for key, value in content.items():
  709. changes.append(yed.put(key, value))
  710. if any([change[0] for change in changes]):
  711. yed.write()
  712. atexit.register(Utils.cleanup, [fname])
  713. return self._replace(fname, force)
  714. return {'returncode': 0, 'updated': False}
  715. def _replace(self, fname, force=False):
  716. '''replace the current object with oc replace'''
  717. # We are removing the 'resourceVersion' to handle
  718. # a race condition when modifying oc objects
  719. yed = Yedit(fname)
  720. results = yed.delete('metadata.resourceVersion')
  721. if results[0]:
  722. yed.write()
  723. cmd = ['replace', '-f', fname]
  724. if force:
  725. cmd.append('--force')
  726. return self.openshift_cmd(cmd)
  727. def _create_from_content(self, rname, content):
  728. '''create a temporary file and then call oc create on it'''
  729. fname = Utils.create_tmpfile(rname + '-')
  730. yed = Yedit(fname, content=content)
  731. yed.write()
  732. atexit.register(Utils.cleanup, [fname])
  733. return self._create(fname)
  734. def _create(self, fname):
  735. '''call oc create on a filename'''
  736. return self.openshift_cmd(['create', '-f', fname])
  737. def _delete(self, resource, name=None, selector=None):
  738. '''call oc delete on a resource'''
  739. cmd = ['delete', resource]
  740. if selector is not None:
  741. cmd.append('--selector={}'.format(selector))
  742. elif name is not None:
  743. cmd.append(name)
  744. else:
  745. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  746. return self.openshift_cmd(cmd)
  747. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  748. '''process a template
  749. template_name: the name of the template to process
  750. create: whether to send to oc create after processing
  751. params: the parameters for the template
  752. template_data: the incoming template's data; instead of a file
  753. '''
  754. cmd = ['process']
  755. if template_data:
  756. cmd.extend(['-f', '-'])
  757. else:
  758. cmd.append(template_name)
  759. if params:
  760. param_str = ["{}={}".format(key, value) for key, value in params.items()]
  761. cmd.append('-v')
  762. cmd.extend(param_str)
  763. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  764. if results['returncode'] != 0 or not create:
  765. return results
  766. fname = Utils.create_tmpfile(template_name + '-')
  767. yed = Yedit(fname, results['results'])
  768. yed.write()
  769. atexit.register(Utils.cleanup, [fname])
  770. return self.openshift_cmd(['create', '-f', fname])
  771. def _get(self, resource, name=None, selector=None):
  772. '''return a resource by name '''
  773. cmd = ['get', resource]
  774. if selector is not None:
  775. cmd.append('--selector={}'.format(selector))
  776. elif name is not None:
  777. cmd.append(name)
  778. cmd.extend(['-o', 'json'])
  779. rval = self.openshift_cmd(cmd, output=True)
  780. # Ensure results are retuned in an array
  781. if 'items' in rval:
  782. rval['results'] = rval['items']
  783. elif not isinstance(rval['results'], list):
  784. rval['results'] = [rval['results']]
  785. return rval
  786. def _schedulable(self, node=None, selector=None, schedulable=True):
  787. ''' perform oadm manage-node scheduable '''
  788. cmd = ['manage-node']
  789. if node:
  790. cmd.extend(node)
  791. else:
  792. cmd.append('--selector={}'.format(selector))
  793. cmd.append('--schedulable={}'.format(schedulable))
  794. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  795. def _list_pods(self, node=None, selector=None, pod_selector=None):
  796. ''' perform oadm list pods
  797. node: the node in which to list pods
  798. selector: the label selector filter if provided
  799. pod_selector: the pod selector filter if provided
  800. '''
  801. cmd = ['manage-node']
  802. if node:
  803. cmd.extend(node)
  804. else:
  805. cmd.append('--selector={}'.format(selector))
  806. if pod_selector:
  807. cmd.append('--pod-selector={}'.format(pod_selector))
  808. cmd.extend(['--list-pods', '-o', 'json'])
  809. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  810. # pylint: disable=too-many-arguments
  811. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  812. ''' perform oadm manage-node evacuate '''
  813. cmd = ['manage-node']
  814. if node:
  815. cmd.extend(node)
  816. else:
  817. cmd.append('--selector={}'.format(selector))
  818. if dry_run:
  819. cmd.append('--dry-run')
  820. if pod_selector:
  821. cmd.append('--pod-selector={}'.format(pod_selector))
  822. if grace_period:
  823. cmd.append('--grace-period={}'.format(int(grace_period)))
  824. if force:
  825. cmd.append('--force')
  826. cmd.append('--evacuate')
  827. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  828. def _version(self):
  829. ''' return the openshift version'''
  830. return self.openshift_cmd(['version'], output=True, output_type='raw')
  831. def _import_image(self, url=None, name=None, tag=None):
  832. ''' perform image import '''
  833. cmd = ['import-image']
  834. image = '{0}'.format(name)
  835. if tag:
  836. image += ':{0}'.format(tag)
  837. cmd.append(image)
  838. if url:
  839. cmd.append('--from={0}/{1}'.format(url, image))
  840. cmd.append('-n{0}'.format(self.namespace))
  841. cmd.append('--confirm')
  842. return self.openshift_cmd(cmd)
  843. def _run(self, cmds, input_data):
  844. ''' Actually executes the command. This makes mocking easier. '''
  845. curr_env = os.environ.copy()
  846. curr_env.update({'KUBECONFIG': self.kubeconfig})
  847. proc = subprocess.Popen(cmds,
  848. stdin=subprocess.PIPE,
  849. stdout=subprocess.PIPE,
  850. stderr=subprocess.PIPE,
  851. env=curr_env)
  852. stdout, stderr = proc.communicate(input_data)
  853. return proc.returncode, stdout.decode(), stderr.decode()
  854. # pylint: disable=too-many-arguments,too-many-branches
  855. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  856. '''Base command for oc '''
  857. cmds = [self.oc_binary]
  858. if oadm:
  859. cmds.append('adm')
  860. cmds.extend(cmd)
  861. if self.all_namespaces:
  862. cmds.extend(['--all-namespaces'])
  863. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  864. cmds.extend(['-n', self.namespace])
  865. rval = {}
  866. results = ''
  867. err = None
  868. if self.verbose:
  869. print(' '.join(cmds))
  870. try:
  871. returncode, stdout, stderr = self._run(cmds, input_data)
  872. except OSError as ex:
  873. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  874. rval = {"returncode": returncode,
  875. "results": results,
  876. "cmd": ' '.join(cmds)}
  877. if returncode == 0:
  878. if output:
  879. if output_type == 'json':
  880. try:
  881. rval['results'] = json.loads(stdout)
  882. except ValueError as verr:
  883. if "No JSON object could be decoded" in verr.args:
  884. err = verr.args
  885. elif output_type == 'raw':
  886. rval['results'] = stdout
  887. if self.verbose:
  888. print("STDOUT: {0}".format(stdout))
  889. print("STDERR: {0}".format(stderr))
  890. if err:
  891. rval.update({"err": err,
  892. "stderr": stderr,
  893. "stdout": stdout,
  894. "cmd": cmds})
  895. else:
  896. rval.update({"stderr": stderr,
  897. "stdout": stdout,
  898. "results": {}})
  899. return rval
  900. class Utils(object): # pragma: no cover
  901. ''' utilities for openshiftcli modules '''
  902. @staticmethod
  903. def _write(filename, contents):
  904. ''' Actually write the file contents to disk. This helps with mocking. '''
  905. with open(filename, 'w') as sfd:
  906. sfd.write(contents)
  907. @staticmethod
  908. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  909. ''' create a file in tmp with name and contents'''
  910. tmp = Utils.create_tmpfile(prefix=rname)
  911. if ftype == 'yaml':
  912. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  913. # pylint: disable=no-member
  914. if hasattr(yaml, 'RoundTripDumper'):
  915. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  916. else:
  917. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  918. elif ftype == 'json':
  919. Utils._write(tmp, json.dumps(data))
  920. else:
  921. Utils._write(tmp, data)
  922. # Register cleanup when module is done
  923. atexit.register(Utils.cleanup, [tmp])
  924. return tmp
  925. @staticmethod
  926. def create_tmpfile_copy(inc_file):
  927. '''create a temporary copy of a file'''
  928. tmpfile = Utils.create_tmpfile('lib_openshift-')
  929. Utils._write(tmpfile, open(inc_file).read())
  930. # Cleanup the tmpfile
  931. atexit.register(Utils.cleanup, [tmpfile])
  932. return tmpfile
  933. @staticmethod
  934. def create_tmpfile(prefix='tmp'):
  935. ''' Generates and returns a temporary file name '''
  936. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  937. return tmp.name
  938. @staticmethod
  939. def create_tmp_files_from_contents(content, content_type=None):
  940. '''Turn an array of dict: filename, content into a files array'''
  941. if not isinstance(content, list):
  942. content = [content]
  943. files = []
  944. for item in content:
  945. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  946. item['data'],
  947. ftype=content_type)
  948. files.append({'name': os.path.basename(item['path']),
  949. 'path': path})
  950. return files
  951. @staticmethod
  952. def cleanup(files):
  953. '''Clean up on exit '''
  954. for sfile in files:
  955. if os.path.exists(sfile):
  956. if os.path.isdir(sfile):
  957. shutil.rmtree(sfile)
  958. elif os.path.isfile(sfile):
  959. os.remove(sfile)
  960. @staticmethod
  961. def exists(results, _name):
  962. ''' Check to see if the results include the name '''
  963. if not results:
  964. return False
  965. if Utils.find_result(results, _name):
  966. return True
  967. return False
  968. @staticmethod
  969. def find_result(results, _name):
  970. ''' Find the specified result by name'''
  971. rval = None
  972. for result in results:
  973. if 'metadata' in result and result['metadata']['name'] == _name:
  974. rval = result
  975. break
  976. return rval
  977. @staticmethod
  978. def get_resource_file(sfile, sfile_type='yaml'):
  979. ''' return the service file '''
  980. contents = None
  981. with open(sfile) as sfd:
  982. contents = sfd.read()
  983. if sfile_type == 'yaml':
  984. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  985. # pylint: disable=no-member
  986. if hasattr(yaml, 'RoundTripLoader'):
  987. contents = yaml.load(contents, yaml.RoundTripLoader)
  988. else:
  989. contents = yaml.safe_load(contents)
  990. elif sfile_type == 'json':
  991. contents = json.loads(contents)
  992. return contents
  993. @staticmethod
  994. def filter_versions(stdout):
  995. ''' filter the oc version output '''
  996. version_dict = {}
  997. version_search = ['oc', 'openshift', 'kubernetes']
  998. for line in stdout.strip().split('\n'):
  999. for term in version_search:
  1000. if not line:
  1001. continue
  1002. if line.startswith(term):
  1003. version_dict[term] = line.split()[-1]
  1004. # horrible hack to get openshift version in Openshift 3.2
  1005. # By default "oc version in 3.2 does not return an "openshift" version
  1006. if "openshift" not in version_dict:
  1007. version_dict["openshift"] = version_dict["oc"]
  1008. return version_dict
  1009. @staticmethod
  1010. def add_custom_versions(versions):
  1011. ''' create custom versions strings '''
  1012. versions_dict = {}
  1013. for tech, version in versions.items():
  1014. # clean up "-" from version
  1015. if "-" in version:
  1016. version = version.split("-")[0]
  1017. if version.startswith('v'):
  1018. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1019. # "v3.3.0.33" is what we have, we want "3.3"
  1020. versions_dict[tech + '_short'] = version[1:4]
  1021. return versions_dict
  1022. @staticmethod
  1023. def openshift_installed():
  1024. ''' check if openshift is installed '''
  1025. import yum
  1026. yum_base = yum.YumBase()
  1027. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1028. return True
  1029. return False
  1030. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1031. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1032. @staticmethod
  1033. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1034. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1035. # Currently these values are autogenerated and we do not need to check them
  1036. skip = ['metadata', 'status']
  1037. if skip_keys:
  1038. skip.extend(skip_keys)
  1039. for key, value in result_def.items():
  1040. if key in skip:
  1041. continue
  1042. # Both are lists
  1043. if isinstance(value, list):
  1044. if key not in user_def:
  1045. if debug:
  1046. print('User data does not have key [%s]' % key)
  1047. print('User data: %s' % user_def)
  1048. return False
  1049. if not isinstance(user_def[key], list):
  1050. if debug:
  1051. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1052. return False
  1053. if len(user_def[key]) != len(value):
  1054. if debug:
  1055. print("List lengths are not equal.")
  1056. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1057. print("user_def: %s" % user_def[key])
  1058. print("value: %s" % value)
  1059. return False
  1060. for values in zip(user_def[key], value):
  1061. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1062. if debug:
  1063. print('sending list - list')
  1064. print(type(values[0]))
  1065. print(type(values[1]))
  1066. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1067. if not result:
  1068. print('list compare returned false')
  1069. return False
  1070. elif value != user_def[key]:
  1071. if debug:
  1072. print('value should be identical')
  1073. print(user_def[key])
  1074. print(value)
  1075. return False
  1076. # recurse on a dictionary
  1077. elif isinstance(value, dict):
  1078. if key not in user_def:
  1079. if debug:
  1080. print("user_def does not have key [%s]" % key)
  1081. return False
  1082. if not isinstance(user_def[key], dict):
  1083. if debug:
  1084. print("dict returned false: not instance of dict")
  1085. return False
  1086. # before passing ensure keys match
  1087. api_values = set(value.keys()) - set(skip)
  1088. user_values = set(user_def[key].keys()) - set(skip)
  1089. if api_values != user_values:
  1090. if debug:
  1091. print("keys are not equal in dict")
  1092. print(user_values)
  1093. print(api_values)
  1094. return False
  1095. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1096. if not result:
  1097. if debug:
  1098. print("dict returned false")
  1099. print(result)
  1100. return False
  1101. # Verify each key, value pair is the same
  1102. else:
  1103. if key not in user_def or value != user_def[key]:
  1104. if debug:
  1105. print("value not equal; user_def does not have key")
  1106. print(key)
  1107. print(value)
  1108. if key in user_def:
  1109. print(user_def[key])
  1110. return False
  1111. if debug:
  1112. print('returning true')
  1113. return True
  1114. class OpenShiftCLIConfig(object):
  1115. '''Generic Config'''
  1116. def __init__(self, rname, namespace, kubeconfig, options):
  1117. self.kubeconfig = kubeconfig
  1118. self.name = rname
  1119. self.namespace = namespace
  1120. self._options = options
  1121. @property
  1122. def config_options(self):
  1123. ''' return config options '''
  1124. return self._options
  1125. def to_option_list(self):
  1126. '''return all options as a string'''
  1127. return self.stringify()
  1128. def stringify(self):
  1129. ''' return the options hash as cli params in a string '''
  1130. rval = []
  1131. for key in sorted(self.config_options.keys()):
  1132. data = self.config_options[key]
  1133. if data['include'] \
  1134. and (data['value'] or isinstance(data['value'], int)):
  1135. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1136. return rval
  1137. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1138. # -*- -*- -*- Begin included fragment: lib/pvc.py -*- -*- -*-
  1139. # pylint: disable=too-many-instance-attributes
  1140. class PersistentVolumeClaimConfig(object):
  1141. ''' Handle pvc options '''
  1142. # pylint: disable=too-many-arguments
  1143. def __init__(self,
  1144. sname,
  1145. namespace,
  1146. kubeconfig,
  1147. access_modes=None,
  1148. vol_capacity='1G'):
  1149. ''' constructor for handling pvc options '''
  1150. self.kubeconfig = kubeconfig
  1151. self.name = sname
  1152. self.namespace = namespace
  1153. self.access_modes = access_modes
  1154. self.vol_capacity = vol_capacity
  1155. self.data = {}
  1156. self.create_dict()
  1157. def create_dict(self):
  1158. ''' return a service as a dict '''
  1159. # version
  1160. self.data['apiVersion'] = 'v1'
  1161. # kind
  1162. self.data['kind'] = 'PersistentVolumeClaim'
  1163. # metadata
  1164. self.data['metadata'] = {}
  1165. self.data['metadata']['name'] = self.name
  1166. # spec
  1167. self.data['spec'] = {}
  1168. self.data['spec']['accessModes'] = ['ReadWriteOnce']
  1169. if self.access_modes:
  1170. self.data['spec']['accessModes'] = self.access_modes
  1171. # storage capacity
  1172. self.data['spec']['resources'] = {}
  1173. self.data['spec']['resources']['requests'] = {}
  1174. self.data['spec']['resources']['requests']['storage'] = self.vol_capacity
  1175. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1176. class PersistentVolumeClaim(Yedit):
  1177. ''' Class to wrap the oc command line tools '''
  1178. access_modes_path = "spec.accessModes"
  1179. volume_capacity_path = "spec.requests.storage"
  1180. volume_name_path = "spec.volumeName"
  1181. bound_path = "status.phase"
  1182. kind = 'PersistentVolumeClaim'
  1183. def __init__(self, content):
  1184. '''RoleBinding constructor'''
  1185. super(PersistentVolumeClaim, self).__init__(content=content)
  1186. self._access_modes = None
  1187. self._volume_capacity = None
  1188. self._volume_name = None
  1189. @property
  1190. def volume_name(self):
  1191. ''' volume_name property '''
  1192. if self._volume_name is None:
  1193. self._volume_name = self.get_volume_name()
  1194. return self._volume_name
  1195. @volume_name.setter
  1196. def volume_name(self, data):
  1197. ''' volume_name property setter'''
  1198. self._volume_name = data
  1199. @property
  1200. def access_modes(self):
  1201. ''' access_modes property '''
  1202. if self._access_modes is None:
  1203. self._access_modes = self.get_access_modes()
  1204. if not isinstance(self._access_modes, list):
  1205. self._access_modes = list(self._access_modes)
  1206. return self._access_modes
  1207. @access_modes.setter
  1208. def access_modes(self, data):
  1209. ''' access_modes property setter'''
  1210. if not isinstance(data, list):
  1211. data = list(data)
  1212. self._access_modes = data
  1213. @property
  1214. def volume_capacity(self):
  1215. ''' volume_capacity property '''
  1216. if self._volume_capacity is None:
  1217. self._volume_capacity = self.get_volume_capacity()
  1218. return self._volume_capacity
  1219. @volume_capacity.setter
  1220. def volume_capacity(self, data):
  1221. ''' volume_capacity property setter'''
  1222. self._volume_capacity = data
  1223. def get_access_modes(self):
  1224. '''get access_modes'''
  1225. return self.get(PersistentVolumeClaim.access_modes_path) or []
  1226. def get_volume_capacity(self):
  1227. '''get volume_capacity'''
  1228. return self.get(PersistentVolumeClaim.volume_capacity_path) or []
  1229. def get_volume_name(self):
  1230. '''get volume_name'''
  1231. return self.get(PersistentVolumeClaim.volume_name_path) or []
  1232. def is_bound(self):
  1233. '''return whether volume is bound'''
  1234. return self.get(PersistentVolumeClaim.bound_path) or []
  1235. #### ADD #####
  1236. def add_access_mode(self, inc_mode):
  1237. ''' add an access_mode'''
  1238. if self.access_modes:
  1239. self.access_modes.append(inc_mode)
  1240. else:
  1241. self.put(PersistentVolumeClaim.access_modes_path, [inc_mode])
  1242. return True
  1243. #### /ADD #####
  1244. #### Remove #####
  1245. def remove_access_mode(self, inc_mode):
  1246. ''' remove an access_mode'''
  1247. try:
  1248. self.access_modes.remove(inc_mode)
  1249. except ValueError as _:
  1250. return False
  1251. return True
  1252. #### /REMOVE #####
  1253. #### UPDATE #####
  1254. def update_access_mode(self, inc_mode):
  1255. ''' update an access_mode'''
  1256. try:
  1257. index = self.access_modes.index(inc_mode)
  1258. except ValueError as _:
  1259. return self.add_access_mode(inc_mode)
  1260. self.access_modes[index] = inc_mode
  1261. return True
  1262. #### /UPDATE #####
  1263. #### FIND ####
  1264. def find_access_mode(self, inc_mode):
  1265. ''' find a user '''
  1266. index = None
  1267. try:
  1268. index = self.access_modes.index(inc_mode)
  1269. except ValueError as _:
  1270. return index
  1271. return index
  1272. # -*- -*- -*- End included fragment: lib/pvc.py -*- -*- -*-
  1273. # -*- -*- -*- Begin included fragment: class/oc_pvc.py -*- -*- -*-
  1274. # pylint: disable=too-many-instance-attributes
  1275. class OCPVC(OpenShiftCLI):
  1276. ''' Class to wrap the oc command line tools '''
  1277. kind = 'pvc'
  1278. # pylint allows 5
  1279. # pylint: disable=too-many-arguments
  1280. def __init__(self,
  1281. config,
  1282. verbose=False):
  1283. ''' Constructor for OCVolume '''
  1284. super(OCPVC, self).__init__(config.namespace, config.kubeconfig)
  1285. self.config = config
  1286. self.namespace = config.namespace
  1287. self._pvc = None
  1288. @property
  1289. def pvc(self):
  1290. ''' property function pvc'''
  1291. if not self._pvc:
  1292. self.get()
  1293. return self._pvc
  1294. @pvc.setter
  1295. def pvc(self, data):
  1296. ''' setter function for yedit var '''
  1297. self._pvc = data
  1298. def bound(self):
  1299. '''return whether the pvc is bound'''
  1300. if self.pvc.get_volume_name():
  1301. return True
  1302. return False
  1303. def exists(self):
  1304. ''' return whether a pvc exists '''
  1305. if self.pvc:
  1306. return True
  1307. return False
  1308. def get(self):
  1309. '''return pvc information '''
  1310. result = self._get(self.kind, self.config.name)
  1311. if result['returncode'] == 0:
  1312. self.pvc = PersistentVolumeClaim(content=result['results'][0])
  1313. elif '\"%s\" not found' % self.config.name in result['stderr']:
  1314. result['returncode'] = 0
  1315. result['results'] = [{}]
  1316. return result
  1317. def delete(self):
  1318. '''delete the object'''
  1319. return self._delete(self.kind, self.config.name)
  1320. def create(self):
  1321. '''create the object'''
  1322. return self._create_from_content(self.config.name, self.config.data)
  1323. def update(self):
  1324. '''update the object'''
  1325. # need to update the tls information and the service name
  1326. return self._replace_content(self.kind, self.config.name, self.config.data)
  1327. def needs_update(self):
  1328. ''' verify an update is needed '''
  1329. if self.pvc.get_volume_name() or self.pvc.is_bound():
  1330. return False
  1331. skip = []
  1332. return not Utils.check_def_equal(self.config.data, self.pvc.yaml_dict, skip_keys=skip, debug=True)
  1333. # pylint: disable=too-many-branches,too-many-return-statements
  1334. @staticmethod
  1335. def run_ansible(params, check_mode):
  1336. '''run the idempotent ansible code'''
  1337. pconfig = PersistentVolumeClaimConfig(params['name'],
  1338. params['namespace'],
  1339. params['kubeconfig'],
  1340. params['access_modes'],
  1341. params['volume_capacity'],
  1342. )
  1343. oc_pvc = OCPVC(pconfig, verbose=params['debug'])
  1344. state = params['state']
  1345. api_rval = oc_pvc.get()
  1346. if api_rval['returncode'] != 0:
  1347. return {'failed': True, 'msg': api_rval}
  1348. #####
  1349. # Get
  1350. #####
  1351. if state == 'list':
  1352. return {'changed': False, 'results': api_rval['results'], 'state': state}
  1353. ########
  1354. # Delete
  1355. ########
  1356. if state == 'absent':
  1357. if oc_pvc.exists():
  1358. if check_mode:
  1359. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1360. api_rval = oc_pvc.delete()
  1361. if api_rval['returncode'] != 0:
  1362. return {'failed': True, 'msg': api_rval}
  1363. return {'changed': True, 'results': api_rval, 'state': state}
  1364. return {'changed': False, 'state': state}
  1365. if state == 'present':
  1366. ########
  1367. # Create
  1368. ########
  1369. if not oc_pvc.exists():
  1370. if check_mode:
  1371. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  1372. # Create it here
  1373. api_rval = oc_pvc.create()
  1374. if api_rval['returncode'] != 0:
  1375. return {'failed': True, 'msg': api_rval}
  1376. # return the created object
  1377. api_rval = oc_pvc.get()
  1378. if api_rval['returncode'] != 0:
  1379. return {'failed': True, 'msg': api_rval}
  1380. return {'changed': True, 'results': api_rval, 'state': state}
  1381. ########
  1382. # Update
  1383. ########
  1384. if oc_pvc.pvc.is_bound() or oc_pvc.pvc.get_volume_name():
  1385. api_rval['msg'] = '##### - This volume is currently bound. Will not update - ####'
  1386. return {'changed': False, 'results': api_rval, 'state': state}
  1387. if oc_pvc.needs_update():
  1388. api_rval = oc_pvc.update()
  1389. if api_rval['returncode'] != 0:
  1390. return {'failed': True, 'msg': api_rval}
  1391. # return the created object
  1392. api_rval = oc_pvc.get()
  1393. if api_rval['returncode'] != 0:
  1394. return {'failed': True, 'msg': api_rval}
  1395. return {'changed': True, 'results': api_rval, 'state': state}
  1396. return {'changed': False, 'results': api_rval, 'state': state}
  1397. return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)}
  1398. # -*- -*- -*- End included fragment: class/oc_pvc.py -*- -*- -*-
  1399. # -*- -*- -*- Begin included fragment: ansible/oc_pvc.py -*- -*- -*-
  1400. #pylint: disable=too-many-branches
  1401. def main():
  1402. '''
  1403. ansible oc module for pvc
  1404. '''
  1405. module = AnsibleModule(
  1406. argument_spec=dict(
  1407. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1408. state=dict(default='present', type='str',
  1409. choices=['present', 'absent', 'list']),
  1410. debug=dict(default=False, type='bool'),
  1411. name=dict(default=None, required=True, type='str'),
  1412. namespace=dict(default=None, required=True, type='str'),
  1413. volume_capacity=dict(default='1G', type='str'),
  1414. access_modes=dict(default='ReadWriteOnce',
  1415. choices=['ReadWriteOnce', 'ReadOnlyMany', 'ReadWriteMany'],
  1416. type='str'),
  1417. ),
  1418. supports_check_mode=True,
  1419. )
  1420. rval = OCPVC.run_ansible(module.params, module.check_mode)
  1421. if 'failed' in rval:
  1422. module.fail_json(**rval)
  1423. return module.exit_json(**rval)
  1424. if __name__ == '__main__':
  1425. main()
  1426. # -*- -*- -*- End included fragment: ansible/oc_pvc.py -*- -*- -*-