oc_obj.py 55 KB

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