oc_obj.py 58 KB

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