oc_process.py 57 KB

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