oc_process.py 54 KB

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