oc_pvc.py 62 KB

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