oc_pvc.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. cmd = ['replace', '-f', fname]
  718. if force:
  719. cmd.append('--force')
  720. return self.openshift_cmd(cmd)
  721. def _create_from_content(self, rname, content):
  722. '''create a temporary file and then call oc create on it'''
  723. fname = Utils.create_tmpfile(rname + '-')
  724. yed = Yedit(fname, content=content)
  725. yed.write()
  726. atexit.register(Utils.cleanup, [fname])
  727. return self._create(fname)
  728. def _create(self, fname):
  729. '''call oc create on a filename'''
  730. return self.openshift_cmd(['create', '-f', fname])
  731. def _delete(self, resource, name=None, selector=None):
  732. '''call oc delete on a resource'''
  733. cmd = ['delete', resource]
  734. if selector is not None:
  735. cmd.append('--selector={}'.format(selector))
  736. elif name is not None:
  737. cmd.append(name)
  738. else:
  739. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  740. return self.openshift_cmd(cmd)
  741. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  742. '''process a template
  743. template_name: the name of the template to process
  744. create: whether to send to oc create after processing
  745. params: the parameters for the template
  746. template_data: the incoming template's data; instead of a file
  747. '''
  748. cmd = ['process']
  749. if template_data:
  750. cmd.extend(['-f', '-'])
  751. else:
  752. cmd.append(template_name)
  753. if params:
  754. param_str = ["{}={}".format(key, value) for key, value in params.items()]
  755. cmd.append('-v')
  756. cmd.extend(param_str)
  757. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  758. if results['returncode'] != 0 or not create:
  759. return results
  760. fname = Utils.create_tmpfile(template_name + '-')
  761. yed = Yedit(fname, results['results'])
  762. yed.write()
  763. atexit.register(Utils.cleanup, [fname])
  764. return self.openshift_cmd(['create', '-f', fname])
  765. def _get(self, resource, name=None, selector=None):
  766. '''return a resource by name '''
  767. cmd = ['get', resource]
  768. if selector is not None:
  769. cmd.append('--selector={}'.format(selector))
  770. elif name is not None:
  771. cmd.append(name)
  772. cmd.extend(['-o', 'json'])
  773. rval = self.openshift_cmd(cmd, output=True)
  774. # Ensure results are retuned in an array
  775. if 'items' in rval:
  776. rval['results'] = rval['items']
  777. elif not isinstance(rval['results'], list):
  778. rval['results'] = [rval['results']]
  779. return rval
  780. def _schedulable(self, node=None, selector=None, schedulable=True):
  781. ''' perform oadm manage-node scheduable '''
  782. cmd = ['manage-node']
  783. if node:
  784. cmd.extend(node)
  785. else:
  786. cmd.append('--selector={}'.format(selector))
  787. cmd.append('--schedulable={}'.format(schedulable))
  788. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  789. def _list_pods(self, node=None, selector=None, pod_selector=None):
  790. ''' perform oadm list pods
  791. node: the node in which to list pods
  792. selector: the label selector filter if provided
  793. pod_selector: the pod selector filter if provided
  794. '''
  795. cmd = ['manage-node']
  796. if node:
  797. cmd.extend(node)
  798. else:
  799. cmd.append('--selector={}'.format(selector))
  800. if pod_selector:
  801. cmd.append('--pod-selector={}'.format(pod_selector))
  802. cmd.extend(['--list-pods', '-o', 'json'])
  803. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  804. # pylint: disable=too-many-arguments
  805. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  806. ''' perform oadm manage-node evacuate '''
  807. cmd = ['manage-node']
  808. if node:
  809. cmd.extend(node)
  810. else:
  811. cmd.append('--selector={}'.format(selector))
  812. if dry_run:
  813. cmd.append('--dry-run')
  814. if pod_selector:
  815. cmd.append('--pod-selector={}'.format(pod_selector))
  816. if grace_period:
  817. cmd.append('--grace-period={}'.format(int(grace_period)))
  818. if force:
  819. cmd.append('--force')
  820. cmd.append('--evacuate')
  821. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  822. def _version(self):
  823. ''' return the openshift version'''
  824. return self.openshift_cmd(['version'], output=True, output_type='raw')
  825. def _import_image(self, url=None, name=None, tag=None):
  826. ''' perform image import '''
  827. cmd = ['import-image']
  828. image = '{0}'.format(name)
  829. if tag:
  830. image += ':{0}'.format(tag)
  831. cmd.append(image)
  832. if url:
  833. cmd.append('--from={0}/{1}'.format(url, image))
  834. cmd.append('-n{0}'.format(self.namespace))
  835. cmd.append('--confirm')
  836. return self.openshift_cmd(cmd)
  837. def _run(self, cmds, input_data):
  838. ''' Actually executes the command. This makes mocking easier. '''
  839. curr_env = os.environ.copy()
  840. curr_env.update({'KUBECONFIG': self.kubeconfig})
  841. proc = subprocess.Popen(cmds,
  842. stdin=subprocess.PIPE,
  843. stdout=subprocess.PIPE,
  844. stderr=subprocess.PIPE,
  845. env=curr_env)
  846. stdout, stderr = proc.communicate(input_data)
  847. return proc.returncode, stdout.decode(), stderr.decode()
  848. # pylint: disable=too-many-arguments,too-many-branches
  849. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  850. '''Base command for oc '''
  851. cmds = [self.oc_binary]
  852. if oadm:
  853. cmds.append('adm')
  854. cmds.extend(cmd)
  855. if self.all_namespaces:
  856. cmds.extend(['--all-namespaces'])
  857. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  858. cmds.extend(['-n', self.namespace])
  859. rval = {}
  860. results = ''
  861. err = None
  862. if self.verbose:
  863. print(' '.join(cmds))
  864. try:
  865. returncode, stdout, stderr = self._run(cmds, input_data)
  866. except OSError as ex:
  867. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  868. rval = {"returncode": returncode,
  869. "results": results,
  870. "cmd": ' '.join(cmds)}
  871. if returncode == 0:
  872. if output:
  873. if output_type == 'json':
  874. try:
  875. rval['results'] = json.loads(stdout)
  876. except ValueError as verr:
  877. if "No JSON object could be decoded" in verr.args:
  878. err = verr.args
  879. elif output_type == 'raw':
  880. rval['results'] = stdout
  881. if self.verbose:
  882. print("STDOUT: {0}".format(stdout))
  883. print("STDERR: {0}".format(stderr))
  884. if err:
  885. rval.update({"err": err,
  886. "stderr": stderr,
  887. "stdout": stdout,
  888. "cmd": cmds})
  889. else:
  890. rval.update({"stderr": stderr,
  891. "stdout": stdout,
  892. "results": {}})
  893. return rval
  894. class Utils(object): # pragma: no cover
  895. ''' utilities for openshiftcli modules '''
  896. @staticmethod
  897. def _write(filename, contents):
  898. ''' Actually write the file contents to disk. This helps with mocking. '''
  899. with open(filename, 'w') as sfd:
  900. sfd.write(contents)
  901. @staticmethod
  902. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  903. ''' create a file in tmp with name and contents'''
  904. tmp = Utils.create_tmpfile(prefix=rname)
  905. if ftype == 'yaml':
  906. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  907. # pylint: disable=no-member
  908. if hasattr(yaml, 'RoundTripDumper'):
  909. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  910. else:
  911. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  912. elif ftype == 'json':
  913. Utils._write(tmp, json.dumps(data))
  914. else:
  915. Utils._write(tmp, data)
  916. # Register cleanup when module is done
  917. atexit.register(Utils.cleanup, [tmp])
  918. return tmp
  919. @staticmethod
  920. def create_tmpfile_copy(inc_file):
  921. '''create a temporary copy of a file'''
  922. tmpfile = Utils.create_tmpfile('lib_openshift-')
  923. Utils._write(tmpfile, open(inc_file).read())
  924. # Cleanup the tmpfile
  925. atexit.register(Utils.cleanup, [tmpfile])
  926. return tmpfile
  927. @staticmethod
  928. def create_tmpfile(prefix='tmp'):
  929. ''' Generates and returns a temporary file name '''
  930. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  931. return tmp.name
  932. @staticmethod
  933. def create_tmp_files_from_contents(content, content_type=None):
  934. '''Turn an array of dict: filename, content into a files array'''
  935. if not isinstance(content, list):
  936. content = [content]
  937. files = []
  938. for item in content:
  939. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  940. item['data'],
  941. ftype=content_type)
  942. files.append({'name': os.path.basename(item['path']),
  943. 'path': path})
  944. return files
  945. @staticmethod
  946. def cleanup(files):
  947. '''Clean up on exit '''
  948. for sfile in files:
  949. if os.path.exists(sfile):
  950. if os.path.isdir(sfile):
  951. shutil.rmtree(sfile)
  952. elif os.path.isfile(sfile):
  953. os.remove(sfile)
  954. @staticmethod
  955. def exists(results, _name):
  956. ''' Check to see if the results include the name '''
  957. if not results:
  958. return False
  959. if Utils.find_result(results, _name):
  960. return True
  961. return False
  962. @staticmethod
  963. def find_result(results, _name):
  964. ''' Find the specified result by name'''
  965. rval = None
  966. for result in results:
  967. if 'metadata' in result and result['metadata']['name'] == _name:
  968. rval = result
  969. break
  970. return rval
  971. @staticmethod
  972. def get_resource_file(sfile, sfile_type='yaml'):
  973. ''' return the service file '''
  974. contents = None
  975. with open(sfile) as sfd:
  976. contents = sfd.read()
  977. if sfile_type == 'yaml':
  978. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  979. # pylint: disable=no-member
  980. if hasattr(yaml, 'RoundTripLoader'):
  981. contents = yaml.load(contents, yaml.RoundTripLoader)
  982. else:
  983. contents = yaml.safe_load(contents)
  984. elif sfile_type == 'json':
  985. contents = json.loads(contents)
  986. return contents
  987. @staticmethod
  988. def filter_versions(stdout):
  989. ''' filter the oc version output '''
  990. version_dict = {}
  991. version_search = ['oc', 'openshift', 'kubernetes']
  992. for line in stdout.strip().split('\n'):
  993. for term in version_search:
  994. if not line:
  995. continue
  996. if line.startswith(term):
  997. version_dict[term] = line.split()[-1]
  998. # horrible hack to get openshift version in Openshift 3.2
  999. # By default "oc version in 3.2 does not return an "openshift" version
  1000. if "openshift" not in version_dict:
  1001. version_dict["openshift"] = version_dict["oc"]
  1002. return version_dict
  1003. @staticmethod
  1004. def add_custom_versions(versions):
  1005. ''' create custom versions strings '''
  1006. versions_dict = {}
  1007. for tech, version in versions.items():
  1008. # clean up "-" from version
  1009. if "-" in version:
  1010. version = version.split("-")[0]
  1011. if version.startswith('v'):
  1012. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1013. # "v3.3.0.33" is what we have, we want "3.3"
  1014. versions_dict[tech + '_short'] = version[1:4]
  1015. return versions_dict
  1016. @staticmethod
  1017. def openshift_installed():
  1018. ''' check if openshift is installed '''
  1019. import yum
  1020. yum_base = yum.YumBase()
  1021. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1022. return True
  1023. return False
  1024. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1025. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1026. @staticmethod
  1027. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1028. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1029. # Currently these values are autogenerated and we do not need to check them
  1030. skip = ['metadata', 'status']
  1031. if skip_keys:
  1032. skip.extend(skip_keys)
  1033. for key, value in result_def.items():
  1034. if key in skip:
  1035. continue
  1036. # Both are lists
  1037. if isinstance(value, list):
  1038. if key not in user_def:
  1039. if debug:
  1040. print('User data does not have key [%s]' % key)
  1041. print('User data: %s' % user_def)
  1042. return False
  1043. if not isinstance(user_def[key], list):
  1044. if debug:
  1045. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1046. return False
  1047. if len(user_def[key]) != len(value):
  1048. if debug:
  1049. print("List lengths are not equal.")
  1050. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1051. print("user_def: %s" % user_def[key])
  1052. print("value: %s" % value)
  1053. return False
  1054. for values in zip(user_def[key], value):
  1055. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1056. if debug:
  1057. print('sending list - list')
  1058. print(type(values[0]))
  1059. print(type(values[1]))
  1060. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1061. if not result:
  1062. print('list compare returned false')
  1063. return False
  1064. elif value != user_def[key]:
  1065. if debug:
  1066. print('value should be identical')
  1067. print(user_def[key])
  1068. print(value)
  1069. return False
  1070. # recurse on a dictionary
  1071. elif isinstance(value, dict):
  1072. if key not in user_def:
  1073. if debug:
  1074. print("user_def does not have key [%s]" % key)
  1075. return False
  1076. if not isinstance(user_def[key], dict):
  1077. if debug:
  1078. print("dict returned false: not instance of dict")
  1079. return False
  1080. # before passing ensure keys match
  1081. api_values = set(value.keys()) - set(skip)
  1082. user_values = set(user_def[key].keys()) - set(skip)
  1083. if api_values != user_values:
  1084. if debug:
  1085. print("keys are not equal in dict")
  1086. print(user_values)
  1087. print(api_values)
  1088. return False
  1089. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1090. if not result:
  1091. if debug:
  1092. print("dict returned false")
  1093. print(result)
  1094. return False
  1095. # Verify each key, value pair is the same
  1096. else:
  1097. if key not in user_def or value != user_def[key]:
  1098. if debug:
  1099. print("value not equal; user_def does not have key")
  1100. print(key)
  1101. print(value)
  1102. if key in user_def:
  1103. print(user_def[key])
  1104. return False
  1105. if debug:
  1106. print('returning true')
  1107. return True
  1108. class OpenShiftCLIConfig(object):
  1109. '''Generic Config'''
  1110. def __init__(self, rname, namespace, kubeconfig, options):
  1111. self.kubeconfig = kubeconfig
  1112. self.name = rname
  1113. self.namespace = namespace
  1114. self._options = options
  1115. @property
  1116. def config_options(self):
  1117. ''' return config options '''
  1118. return self._options
  1119. def to_option_list(self):
  1120. '''return all options as a string'''
  1121. return self.stringify()
  1122. def stringify(self):
  1123. ''' return the options hash as cli params in a string '''
  1124. rval = []
  1125. for key in sorted(self.config_options.keys()):
  1126. data = self.config_options[key]
  1127. if data['include'] \
  1128. and (data['value'] or isinstance(data['value'], int)):
  1129. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1130. return rval
  1131. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1132. # -*- -*- -*- Begin included fragment: lib/pvc.py -*- -*- -*-
  1133. # pylint: disable=too-many-instance-attributes
  1134. class PersistentVolumeClaimConfig(object):
  1135. ''' Handle pvc options '''
  1136. # pylint: disable=too-many-arguments
  1137. def __init__(self,
  1138. sname,
  1139. namespace,
  1140. kubeconfig,
  1141. access_modes=None,
  1142. vol_capacity='1G'):
  1143. ''' constructor for handling pvc options '''
  1144. self.kubeconfig = kubeconfig
  1145. self.name = sname
  1146. self.namespace = namespace
  1147. self.access_modes = access_modes
  1148. self.vol_capacity = vol_capacity
  1149. self.data = {}
  1150. self.create_dict()
  1151. def create_dict(self):
  1152. ''' return a service as a dict '''
  1153. # version
  1154. self.data['apiVersion'] = 'v1'
  1155. # kind
  1156. self.data['kind'] = 'PersistentVolumeClaim'
  1157. # metadata
  1158. self.data['metadata'] = {}
  1159. self.data['metadata']['name'] = self.name
  1160. # spec
  1161. self.data['spec'] = {}
  1162. self.data['spec']['accessModes'] = ['ReadWriteOnce']
  1163. if self.access_modes:
  1164. self.data['spec']['accessModes'] = self.access_modes
  1165. # storage capacity
  1166. self.data['spec']['resources'] = {}
  1167. self.data['spec']['resources']['requests'] = {}
  1168. self.data['spec']['resources']['requests']['storage'] = self.vol_capacity
  1169. # pylint: disable=too-many-instance-attributes,too-many-public-methods
  1170. class PersistentVolumeClaim(Yedit):
  1171. ''' Class to wrap the oc command line tools '''
  1172. access_modes_path = "spec.accessModes"
  1173. volume_capacity_path = "spec.requests.storage"
  1174. volume_name_path = "spec.volumeName"
  1175. bound_path = "status.phase"
  1176. kind = 'PersistentVolumeClaim'
  1177. def __init__(self, content):
  1178. '''RoleBinding constructor'''
  1179. super(PersistentVolumeClaim, self).__init__(content=content)
  1180. self._access_modes = None
  1181. self._volume_capacity = None
  1182. self._volume_name = None
  1183. @property
  1184. def volume_name(self):
  1185. ''' volume_name property '''
  1186. if self._volume_name is None:
  1187. self._volume_name = self.get_volume_name()
  1188. return self._volume_name
  1189. @volume_name.setter
  1190. def volume_name(self, data):
  1191. ''' volume_name property setter'''
  1192. self._volume_name = data
  1193. @property
  1194. def access_modes(self):
  1195. ''' access_modes property '''
  1196. if self._access_modes is None:
  1197. self._access_modes = self.get_access_modes()
  1198. if not isinstance(self._access_modes, list):
  1199. self._access_modes = list(self._access_modes)
  1200. return self._access_modes
  1201. @access_modes.setter
  1202. def access_modes(self, data):
  1203. ''' access_modes property setter'''
  1204. if not isinstance(data, list):
  1205. data = list(data)
  1206. self._access_modes = data
  1207. @property
  1208. def volume_capacity(self):
  1209. ''' volume_capacity property '''
  1210. if self._volume_capacity is None:
  1211. self._volume_capacity = self.get_volume_capacity()
  1212. return self._volume_capacity
  1213. @volume_capacity.setter
  1214. def volume_capacity(self, data):
  1215. ''' volume_capacity property setter'''
  1216. self._volume_capacity = data
  1217. def get_access_modes(self):
  1218. '''get access_modes'''
  1219. return self.get(PersistentVolumeClaim.access_modes_path) or []
  1220. def get_volume_capacity(self):
  1221. '''get volume_capacity'''
  1222. return self.get(PersistentVolumeClaim.volume_capacity_path) or []
  1223. def get_volume_name(self):
  1224. '''get volume_name'''
  1225. return self.get(PersistentVolumeClaim.volume_name_path) or []
  1226. def is_bound(self):
  1227. '''return whether volume is bound'''
  1228. return self.get(PersistentVolumeClaim.bound_path) or []
  1229. #### ADD #####
  1230. def add_access_mode(self, inc_mode):
  1231. ''' add an access_mode'''
  1232. if self.access_modes:
  1233. self.access_modes.append(inc_mode)
  1234. else:
  1235. self.put(PersistentVolumeClaim.access_modes_path, [inc_mode])
  1236. return True
  1237. #### /ADD #####
  1238. #### Remove #####
  1239. def remove_access_mode(self, inc_mode):
  1240. ''' remove an access_mode'''
  1241. try:
  1242. self.access_modes.remove(inc_mode)
  1243. except ValueError as _:
  1244. return False
  1245. return True
  1246. #### /REMOVE #####
  1247. #### UPDATE #####
  1248. def update_access_mode(self, inc_mode):
  1249. ''' update an access_mode'''
  1250. try:
  1251. index = self.access_modes.index(inc_mode)
  1252. except ValueError as _:
  1253. return self.add_access_mode(inc_mode)
  1254. self.access_modes[index] = inc_mode
  1255. return True
  1256. #### /UPDATE #####
  1257. #### FIND ####
  1258. def find_access_mode(self, inc_mode):
  1259. ''' find a user '''
  1260. index = None
  1261. try:
  1262. index = self.access_modes.index(inc_mode)
  1263. except ValueError as _:
  1264. return index
  1265. return index
  1266. # -*- -*- -*- End included fragment: lib/pvc.py -*- -*- -*-
  1267. # -*- -*- -*- Begin included fragment: class/oc_pvc.py -*- -*- -*-
  1268. # pylint: disable=too-many-instance-attributes
  1269. class OCPVC(OpenShiftCLI):
  1270. ''' Class to wrap the oc command line tools '''
  1271. kind = 'pvc'
  1272. # pylint allows 5
  1273. # pylint: disable=too-many-arguments
  1274. def __init__(self,
  1275. config,
  1276. verbose=False):
  1277. ''' Constructor for OCVolume '''
  1278. super(OCPVC, self).__init__(config.namespace, config.kubeconfig)
  1279. self.config = config
  1280. self.namespace = config.namespace
  1281. self._pvc = None
  1282. @property
  1283. def pvc(self):
  1284. ''' property function pvc'''
  1285. if not self._pvc:
  1286. self.get()
  1287. return self._pvc
  1288. @pvc.setter
  1289. def pvc(self, data):
  1290. ''' setter function for yedit var '''
  1291. self._pvc = data
  1292. def bound(self):
  1293. '''return whether the pvc is bound'''
  1294. if self.pvc.get_volume_name():
  1295. return True
  1296. return False
  1297. def exists(self):
  1298. ''' return whether a pvc exists '''
  1299. if self.pvc:
  1300. return True
  1301. return False
  1302. def get(self):
  1303. '''return pvc information '''
  1304. result = self._get(self.kind, self.config.name)
  1305. if result['returncode'] == 0:
  1306. self.pvc = PersistentVolumeClaim(content=result['results'][0])
  1307. elif '\"%s\" not found' % self.config.name in result['stderr']:
  1308. result['returncode'] = 0
  1309. result['results'] = [{}]
  1310. return result
  1311. def delete(self):
  1312. '''delete the object'''
  1313. return self._delete(self.kind, self.config.name)
  1314. def create(self):
  1315. '''create the object'''
  1316. return self._create_from_content(self.config.name, self.config.data)
  1317. def update(self):
  1318. '''update the object'''
  1319. # need to update the tls information and the service name
  1320. return self._replace_content(self.kind, self.config.name, self.config.data)
  1321. def needs_update(self):
  1322. ''' verify an update is needed '''
  1323. if self.pvc.get_volume_name() or self.pvc.is_bound():
  1324. return False
  1325. skip = []
  1326. return not Utils.check_def_equal(self.config.data, self.pvc.yaml_dict, skip_keys=skip, debug=True)
  1327. # pylint: disable=too-many-branches,too-many-return-statements
  1328. @staticmethod
  1329. def run_ansible(params, check_mode):
  1330. '''run the idempotent ansible code'''
  1331. pconfig = PersistentVolumeClaimConfig(params['name'],
  1332. params['namespace'],
  1333. params['kubeconfig'],
  1334. params['access_modes'],
  1335. params['volume_capacity'],
  1336. )
  1337. oc_pvc = OCPVC(pconfig, verbose=params['debug'])
  1338. state = params['state']
  1339. api_rval = oc_pvc.get()
  1340. if api_rval['returncode'] != 0:
  1341. return {'failed': True, 'msg': api_rval}
  1342. #####
  1343. # Get
  1344. #####
  1345. if state == 'list':
  1346. return {'changed': False, 'results': api_rval['results'], 'state': state}
  1347. ########
  1348. # Delete
  1349. ########
  1350. if state == 'absent':
  1351. if oc_pvc.exists():
  1352. if check_mode:
  1353. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1354. api_rval = oc_pvc.delete()
  1355. if api_rval['returncode'] != 0:
  1356. return {'failed': True, 'msg': api_rval}
  1357. return {'changed': True, 'results': api_rval, 'state': state}
  1358. return {'changed': False, 'state': state}
  1359. if state == 'present':
  1360. ########
  1361. # Create
  1362. ########
  1363. if not oc_pvc.exists():
  1364. if check_mode:
  1365. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  1366. # Create it here
  1367. api_rval = oc_pvc.create()
  1368. if api_rval['returncode'] != 0:
  1369. return {'failed': True, 'msg': api_rval}
  1370. # return the created object
  1371. api_rval = oc_pvc.get()
  1372. if api_rval['returncode'] != 0:
  1373. return {'failed': True, 'msg': api_rval}
  1374. return {'changed': True, 'results': api_rval, 'state': state}
  1375. ########
  1376. # Update
  1377. ########
  1378. if oc_pvc.pvc.is_bound() or oc_pvc.pvc.get_volume_name():
  1379. api_rval['msg'] = '##### - This volume is currently bound. Will not update - ####'
  1380. return {'changed': False, 'results': api_rval, 'state': state}
  1381. if oc_pvc.needs_update():
  1382. api_rval = oc_pvc.update()
  1383. if api_rval['returncode'] != 0:
  1384. return {'failed': True, 'msg': api_rval}
  1385. # return the created object
  1386. api_rval = oc_pvc.get()
  1387. if api_rval['returncode'] != 0:
  1388. return {'failed': True, 'msg': api_rval}
  1389. return {'changed': True, 'results': api_rval, 'state': state}
  1390. return {'changed': False, 'results': api_rval, 'state': state}
  1391. return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)}
  1392. # -*- -*- -*- End included fragment: class/oc_pvc.py -*- -*- -*-
  1393. # -*- -*- -*- Begin included fragment: ansible/oc_pvc.py -*- -*- -*-
  1394. #pylint: disable=too-many-branches
  1395. def main():
  1396. '''
  1397. ansible oc module for pvc
  1398. '''
  1399. module = AnsibleModule(
  1400. argument_spec=dict(
  1401. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1402. state=dict(default='present', type='str',
  1403. choices=['present', 'absent', 'list']),
  1404. debug=dict(default=False, type='bool'),
  1405. name=dict(default=None, required=True, type='str'),
  1406. namespace=dict(default=None, required=True, type='str'),
  1407. volume_capacity=dict(default='1G', type='str'),
  1408. access_modes=dict(default='ReadWriteOnce',
  1409. choices=['ReadWriteOnce', 'ReadOnlyMany', 'ReadWriteMany'],
  1410. type='str'),
  1411. ),
  1412. supports_check_mode=True,
  1413. )
  1414. rval = OCPVC.run_ansible(module.params, module.check_mode)
  1415. if 'failed' in rval:
  1416. module.fail_json(**rval)
  1417. return module.exit_json(**rval)
  1418. if __name__ == '__main__':
  1419. main()
  1420. # -*- -*- -*- End included fragment: ansible/oc_pvc.py -*- -*- -*-