oc_obj.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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):
  143. ''' Exception class for Yedit '''
  144. pass
  145. # pylint: disable=too-many-public-methods
  146. class Yedit(object):
  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 % ''.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 % ''.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, None)
  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, None)
  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. %s' % 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 ' +
  460. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  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=[%s] vtype=[%s]' % (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 ' +
  577. 'value. value=[%s] vtype=[%s]'
  578. % (type(inc_value), vtype))
  579. return inc_value
  580. @staticmethod
  581. def process_edits(edits, yamlfile):
  582. '''run through a list of edits and process them one-by-one'''
  583. results = []
  584. for edit in edits:
  585. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  586. if 'action' in edit and edit['action'] == 'update':
  587. # pylint: disable=line-too-long
  588. curr_value = Yedit.get_curr_value(Yedit.parse_value(edit.get('curr_value', None)), # noqa: E501
  589. edit.get('curr_value_format', None)) # noqa: E501
  590. rval = yamlfile.update(edit['key'],
  591. value,
  592. edit.get('index', None),
  593. curr_value)
  594. elif 'action' in edit and edit['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 [%s]. Verify that the ' +
  614. 'file exists, that it is has correct' +
  615. ' permissions, and is valid yaml.'}
  616. if state == 'list':
  617. if params['content']:
  618. content = Yedit.parse_value(params['content'], params['content_type'])
  619. yamlfile.yaml_dict = content
  620. if params['key']:
  621. rval = yamlfile.get(params['key']) or {}
  622. return {'changed': False, 'result': rval, 'state': state}
  623. elif state == 'absent':
  624. if params['content']:
  625. content = Yedit.parse_value(params['content'], params['content_type'])
  626. yamlfile.yaml_dict = content
  627. if params['update']:
  628. rval = yamlfile.pop(params['key'], params['value'])
  629. else:
  630. rval = yamlfile.delete(params['key'])
  631. if rval[0] and params['src']:
  632. yamlfile.write()
  633. return {'changed': rval[0], 'result': rval[1], 'state': state}
  634. elif state == 'present':
  635. # check if content is different than what is in the file
  636. if params['content']:
  637. content = Yedit.parse_value(params['content'], params['content_type'])
  638. # We had no edits to make and the contents are the same
  639. if yamlfile.yaml_dict == content and \
  640. params['value'] is None:
  641. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  642. yamlfile.yaml_dict = content
  643. # If we were passed a key, value then
  644. # we enapsulate it in a list and process it
  645. # Key, Value passed to the module : Converted to Edits list #
  646. edits = []
  647. _edit = {}
  648. if params['value'] is not None:
  649. _edit['value'] = params['value']
  650. _edit['value_type'] = params['value_type']
  651. _edit['key'] = params['key']
  652. if params['update']:
  653. _edit['action'] = 'update'
  654. _edit['curr_value'] = params['curr_value']
  655. _edit['curr_value_format'] = params['curr_value_format']
  656. _edit['index'] = params['index']
  657. elif params['append']:
  658. _edit['action'] = 'append'
  659. edits.append(_edit)
  660. elif params['edits'] is not None:
  661. edits = params['edits']
  662. if edits:
  663. results = Yedit.process_edits(edits, yamlfile)
  664. # if there were changes and a src provided to us we need to write
  665. if results['changed'] and params['src']:
  666. yamlfile.write()
  667. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  668. # no edits to make
  669. if params['src']:
  670. # pylint: disable=redefined-variable-type
  671. rval = yamlfile.write()
  672. return {'changed': rval[0],
  673. 'result': rval[1],
  674. 'state': state}
  675. # We were passed content but no src, key or value, or edits. Return contents in memory
  676. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  677. return {'failed': True, 'msg': 'Unkown state passed'}
  678. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  679. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  680. # pylint: disable=too-many-lines
  681. # noqa: E301,E302,E303,T001
  682. class OpenShiftCLIError(Exception):
  683. '''Exception class for openshiftcli'''
  684. pass
  685. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  686. def locate_oc_binary():
  687. ''' Find and return oc binary file '''
  688. # https://github.com/openshift/openshift-ansible/issues/3410
  689. # oc can be in /usr/local/bin in some cases, but that may not
  690. # be in $PATH due to ansible/sudo
  691. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  692. oc_binary = 'oc'
  693. # Use shutil.which if it is available, otherwise fallback to a naive path search
  694. try:
  695. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  696. if which_result is not None:
  697. oc_binary = which_result
  698. except AttributeError:
  699. for path in paths:
  700. if os.path.exists(os.path.join(path, oc_binary)):
  701. oc_binary = os.path.join(path, oc_binary)
  702. break
  703. return oc_binary
  704. # pylint: disable=too-few-public-methods
  705. class OpenShiftCLI(object):
  706. ''' Class to wrap the command line tools '''
  707. def __init__(self,
  708. namespace,
  709. kubeconfig='/etc/origin/master/admin.kubeconfig',
  710. verbose=False,
  711. all_namespaces=False):
  712. ''' Constructor for OpenshiftCLI '''
  713. self.namespace = namespace
  714. self.verbose = verbose
  715. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  716. self.all_namespaces = all_namespaces
  717. self.oc_binary = locate_oc_binary()
  718. # Pylint allows only 5 arguments to be passed.
  719. # pylint: disable=too-many-arguments
  720. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  721. ''' replace the current object with the content '''
  722. res = self._get(resource, rname)
  723. if not res['results']:
  724. return res
  725. fname = Utils.create_tmpfile(rname + '-')
  726. yed = Yedit(fname, res['results'][0], separator=sep)
  727. changes = []
  728. for key, value in content.items():
  729. changes.append(yed.put(key, value))
  730. if any([change[0] for change in changes]):
  731. yed.write()
  732. atexit.register(Utils.cleanup, [fname])
  733. return self._replace(fname, force)
  734. return {'returncode': 0, 'updated': False}
  735. def _replace(self, fname, force=False):
  736. '''replace the current object with oc replace'''
  737. cmd = ['replace', '-f', fname]
  738. if force:
  739. cmd.append('--force')
  740. return self.openshift_cmd(cmd)
  741. def _create_from_content(self, rname, content):
  742. '''create a temporary file and then call oc create on it'''
  743. fname = Utils.create_tmpfile(rname + '-')
  744. yed = Yedit(fname, content=content)
  745. yed.write()
  746. atexit.register(Utils.cleanup, [fname])
  747. return self._create(fname)
  748. def _create(self, fname):
  749. '''call oc create on a filename'''
  750. return self.openshift_cmd(['create', '-f', fname])
  751. def _delete(self, resource, rname, selector=None):
  752. '''call oc delete on a resource'''
  753. cmd = ['delete', resource, rname]
  754. if selector:
  755. cmd.append('--selector=%s' % selector)
  756. return self.openshift_cmd(cmd)
  757. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  758. '''process a template
  759. template_name: the name of the template to process
  760. create: whether to send to oc create after processing
  761. params: the parameters for the template
  762. template_data: the incoming template's data; instead of a file
  763. '''
  764. cmd = ['process']
  765. if template_data:
  766. cmd.extend(['-f', '-'])
  767. else:
  768. cmd.append(template_name)
  769. if params:
  770. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  771. cmd.append('-v')
  772. cmd.extend(param_str)
  773. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  774. if results['returncode'] != 0 or not create:
  775. return results
  776. fname = Utils.create_tmpfile(template_name + '-')
  777. yed = Yedit(fname, results['results'])
  778. yed.write()
  779. atexit.register(Utils.cleanup, [fname])
  780. return self.openshift_cmd(['create', '-f', fname])
  781. def _get(self, resource, rname=None, selector=None):
  782. '''return a resource by name '''
  783. cmd = ['get', resource]
  784. if selector:
  785. cmd.append('--selector=%s' % selector)
  786. elif rname:
  787. cmd.append(rname)
  788. cmd.extend(['-o', 'json'])
  789. rval = self.openshift_cmd(cmd, output=True)
  790. # Ensure results are retuned in an array
  791. if 'items' in rval:
  792. rval['results'] = rval['items']
  793. elif not isinstance(rval['results'], list):
  794. rval['results'] = [rval['results']]
  795. return rval
  796. def _schedulable(self, node=None, selector=None, schedulable=True):
  797. ''' perform oadm manage-node scheduable '''
  798. cmd = ['manage-node']
  799. if node:
  800. cmd.extend(node)
  801. else:
  802. cmd.append('--selector=%s' % selector)
  803. cmd.append('--schedulable=%s' % schedulable)
  804. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  805. def _list_pods(self, node=None, selector=None, pod_selector=None):
  806. ''' perform oadm list pods
  807. node: the node in which to list pods
  808. selector: the label selector filter if provided
  809. pod_selector: the pod selector filter if provided
  810. '''
  811. cmd = ['manage-node']
  812. if node:
  813. cmd.extend(node)
  814. else:
  815. cmd.append('--selector=%s' % selector)
  816. if pod_selector:
  817. cmd.append('--pod-selector=%s' % pod_selector)
  818. cmd.extend(['--list-pods', '-o', 'json'])
  819. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  820. # pylint: disable=too-many-arguments
  821. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  822. ''' perform oadm manage-node evacuate '''
  823. cmd = ['manage-node']
  824. if node:
  825. cmd.extend(node)
  826. else:
  827. cmd.append('--selector=%s' % selector)
  828. if dry_run:
  829. cmd.append('--dry-run')
  830. if pod_selector:
  831. cmd.append('--pod-selector=%s' % pod_selector)
  832. if grace_period:
  833. cmd.append('--grace-period=%s' % int(grace_period))
  834. if force:
  835. cmd.append('--force')
  836. cmd.append('--evacuate')
  837. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  838. def _version(self):
  839. ''' return the openshift version'''
  840. return self.openshift_cmd(['version'], output=True, output_type='raw')
  841. def _import_image(self, url=None, name=None, tag=None):
  842. ''' perform image import '''
  843. cmd = ['import-image']
  844. image = '{0}'.format(name)
  845. if tag:
  846. image += ':{0}'.format(tag)
  847. cmd.append(image)
  848. if url:
  849. cmd.append('--from={0}/{1}'.format(url, image))
  850. cmd.append('-n{0}'.format(self.namespace))
  851. cmd.append('--confirm')
  852. return self.openshift_cmd(cmd)
  853. def _run(self, cmds, input_data):
  854. ''' Actually executes the command. This makes mocking easier. '''
  855. curr_env = os.environ.copy()
  856. curr_env.update({'KUBECONFIG': self.kubeconfig})
  857. proc = subprocess.Popen(cmds,
  858. stdin=subprocess.PIPE,
  859. stdout=subprocess.PIPE,
  860. stderr=subprocess.PIPE,
  861. env=curr_env)
  862. stdout, stderr = proc.communicate(input_data)
  863. return proc.returncode, stdout.decode(), stderr.decode()
  864. # pylint: disable=too-many-arguments,too-many-branches
  865. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  866. '''Base command for oc '''
  867. cmds = [self.oc_binary]
  868. if oadm:
  869. cmds.append('adm')
  870. cmds.extend(cmd)
  871. if self.all_namespaces:
  872. cmds.extend(['--all-namespaces'])
  873. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  874. cmds.extend(['-n', self.namespace])
  875. rval = {}
  876. results = ''
  877. err = None
  878. if self.verbose:
  879. print(' '.join(cmds))
  880. try:
  881. returncode, stdout, stderr = self._run(cmds, input_data)
  882. except OSError as ex:
  883. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  884. rval = {"returncode": returncode,
  885. "results": results,
  886. "cmd": ' '.join(cmds)}
  887. if returncode == 0:
  888. if output:
  889. if output_type == 'json':
  890. try:
  891. rval['results'] = json.loads(stdout)
  892. except ValueError as verr:
  893. if "No JSON object could be decoded" in verr.args:
  894. err = verr.args
  895. elif output_type == 'raw':
  896. rval['results'] = stdout
  897. if self.verbose:
  898. print("STDOUT: {0}".format(stdout))
  899. print("STDERR: {0}".format(stderr))
  900. if err:
  901. rval.update({"err": err,
  902. "stderr": stderr,
  903. "stdout": stdout,
  904. "cmd": cmds})
  905. else:
  906. rval.update({"stderr": stderr,
  907. "stdout": stdout,
  908. "results": {}})
  909. return rval
  910. class Utils(object):
  911. ''' utilities for openshiftcli modules '''
  912. @staticmethod
  913. def _write(filename, contents):
  914. ''' Actually write the file contents to disk. This helps with mocking. '''
  915. with open(filename, 'w') as sfd:
  916. sfd.write(contents)
  917. @staticmethod
  918. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  919. ''' create a file in tmp with name and contents'''
  920. tmp = Utils.create_tmpfile(prefix=rname)
  921. if ftype == 'yaml':
  922. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  923. # pylint: disable=no-member
  924. if hasattr(yaml, 'RoundTripDumper'):
  925. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  926. else:
  927. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  928. elif ftype == 'json':
  929. Utils._write(tmp, json.dumps(data))
  930. else:
  931. Utils._write(tmp, data)
  932. # Register cleanup when module is done
  933. atexit.register(Utils.cleanup, [tmp])
  934. return tmp
  935. @staticmethod
  936. def create_tmpfile_copy(inc_file):
  937. '''create a temporary copy of a file'''
  938. tmpfile = Utils.create_tmpfile('lib_openshift-')
  939. Utils._write(tmpfile, open(inc_file).read())
  940. # Cleanup the tmpfile
  941. atexit.register(Utils.cleanup, [tmpfile])
  942. return tmpfile
  943. @staticmethod
  944. def create_tmpfile(prefix='tmp'):
  945. ''' Generates and returns a temporary file name '''
  946. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  947. return tmp.name
  948. @staticmethod
  949. def create_tmp_files_from_contents(content, content_type=None):
  950. '''Turn an array of dict: filename, content into a files array'''
  951. if not isinstance(content, list):
  952. content = [content]
  953. files = []
  954. for item in content:
  955. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  956. item['data'],
  957. ftype=content_type)
  958. files.append({'name': os.path.basename(item['path']),
  959. 'path': path})
  960. return files
  961. @staticmethod
  962. def cleanup(files):
  963. '''Clean up on exit '''
  964. for sfile in files:
  965. if os.path.exists(sfile):
  966. if os.path.isdir(sfile):
  967. shutil.rmtree(sfile)
  968. elif os.path.isfile(sfile):
  969. os.remove(sfile)
  970. @staticmethod
  971. def exists(results, _name):
  972. ''' Check to see if the results include the name '''
  973. if not results:
  974. return False
  975. if Utils.find_result(results, _name):
  976. return True
  977. return False
  978. @staticmethod
  979. def find_result(results, _name):
  980. ''' Find the specified result by name'''
  981. rval = None
  982. for result in results:
  983. if 'metadata' in result and result['metadata']['name'] == _name:
  984. rval = result
  985. break
  986. return rval
  987. @staticmethod
  988. def get_resource_file(sfile, sfile_type='yaml'):
  989. ''' return the service file '''
  990. contents = None
  991. with open(sfile) as sfd:
  992. contents = sfd.read()
  993. if sfile_type == 'yaml':
  994. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  995. # pylint: disable=no-member
  996. if hasattr(yaml, 'RoundTripLoader'):
  997. contents = yaml.load(contents, yaml.RoundTripLoader)
  998. else:
  999. contents = yaml.safe_load(contents)
  1000. elif sfile_type == 'json':
  1001. contents = json.loads(contents)
  1002. return contents
  1003. @staticmethod
  1004. def filter_versions(stdout):
  1005. ''' filter the oc version output '''
  1006. version_dict = {}
  1007. version_search = ['oc', 'openshift', 'kubernetes']
  1008. for line in stdout.strip().split('\n'):
  1009. for term in version_search:
  1010. if not line:
  1011. continue
  1012. if line.startswith(term):
  1013. version_dict[term] = line.split()[-1]
  1014. # horrible hack to get openshift version in Openshift 3.2
  1015. # By default "oc version in 3.2 does not return an "openshift" version
  1016. if "openshift" not in version_dict:
  1017. version_dict["openshift"] = version_dict["oc"]
  1018. return version_dict
  1019. @staticmethod
  1020. def add_custom_versions(versions):
  1021. ''' create custom versions strings '''
  1022. versions_dict = {}
  1023. for tech, version in versions.items():
  1024. # clean up "-" from version
  1025. if "-" in version:
  1026. version = version.split("-")[0]
  1027. if version.startswith('v'):
  1028. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1029. # "v3.3.0.33" is what we have, we want "3.3"
  1030. versions_dict[tech + '_short'] = version[1:4]
  1031. return versions_dict
  1032. @staticmethod
  1033. def openshift_installed():
  1034. ''' check if openshift is installed '''
  1035. import yum
  1036. yum_base = yum.YumBase()
  1037. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1038. return True
  1039. return False
  1040. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1041. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1042. @staticmethod
  1043. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1044. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1045. # Currently these values are autogenerated and we do not need to check them
  1046. skip = ['metadata', 'status']
  1047. if skip_keys:
  1048. skip.extend(skip_keys)
  1049. for key, value in result_def.items():
  1050. if key in skip:
  1051. continue
  1052. # Both are lists
  1053. if isinstance(value, list):
  1054. if key not in user_def:
  1055. if debug:
  1056. print('User data does not have key [%s]' % key)
  1057. print('User data: %s' % user_def)
  1058. return False
  1059. if not isinstance(user_def[key], list):
  1060. if debug:
  1061. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1062. return False
  1063. if len(user_def[key]) != len(value):
  1064. if debug:
  1065. print("List lengths are not equal.")
  1066. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1067. print("user_def: %s" % user_def[key])
  1068. print("value: %s" % value)
  1069. return False
  1070. for values in zip(user_def[key], value):
  1071. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1072. if debug:
  1073. print('sending list - list')
  1074. print(type(values[0]))
  1075. print(type(values[1]))
  1076. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1077. if not result:
  1078. print('list compare returned false')
  1079. return False
  1080. elif value != user_def[key]:
  1081. if debug:
  1082. print('value should be identical')
  1083. print(user_def[key])
  1084. print(value)
  1085. return False
  1086. # recurse on a dictionary
  1087. elif isinstance(value, dict):
  1088. if key not in user_def:
  1089. if debug:
  1090. print("user_def does not have key [%s]" % key)
  1091. return False
  1092. if not isinstance(user_def[key], dict):
  1093. if debug:
  1094. print("dict returned false: not instance of dict")
  1095. return False
  1096. # before passing ensure keys match
  1097. api_values = set(value.keys()) - set(skip)
  1098. user_values = set(user_def[key].keys()) - set(skip)
  1099. if api_values != user_values:
  1100. if debug:
  1101. print("keys are not equal in dict")
  1102. print(user_values)
  1103. print(api_values)
  1104. return False
  1105. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1106. if not result:
  1107. if debug:
  1108. print("dict returned false")
  1109. print(result)
  1110. return False
  1111. # Verify each key, value pair is the same
  1112. else:
  1113. if key not in user_def or value != user_def[key]:
  1114. if debug:
  1115. print("value not equal; user_def does not have key")
  1116. print(key)
  1117. print(value)
  1118. if key in user_def:
  1119. print(user_def[key])
  1120. return False
  1121. if debug:
  1122. print('returning true')
  1123. return True
  1124. class OpenShiftCLIConfig(object):
  1125. '''Generic Config'''
  1126. def __init__(self, rname, namespace, kubeconfig, options):
  1127. self.kubeconfig = kubeconfig
  1128. self.name = rname
  1129. self.namespace = namespace
  1130. self._options = options
  1131. @property
  1132. def config_options(self):
  1133. ''' return config options '''
  1134. return self._options
  1135. def to_option_list(self):
  1136. '''return all options as a string'''
  1137. return self.stringify()
  1138. def stringify(self):
  1139. ''' return the options hash as cli params in a string '''
  1140. rval = []
  1141. for key in sorted(self.config_options.keys()):
  1142. data = self.config_options[key]
  1143. if data['include'] \
  1144. and (data['value'] or isinstance(data['value'], int)):
  1145. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1146. return rval
  1147. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1148. # -*- -*- -*- Begin included fragment: class/oc_obj.py -*- -*- -*-
  1149. # pylint: disable=too-many-instance-attributes
  1150. class OCObject(OpenShiftCLI):
  1151. ''' Class to wrap the oc command line tools '''
  1152. # pylint allows 5. we need 6
  1153. # pylint: disable=too-many-arguments
  1154. def __init__(self,
  1155. kind,
  1156. namespace,
  1157. rname=None,
  1158. selector=None,
  1159. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1160. verbose=False,
  1161. all_namespaces=False):
  1162. ''' Constructor for OpenshiftOC '''
  1163. super(OCObject, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose,
  1164. all_namespaces=all_namespaces)
  1165. self.kind = kind
  1166. self.name = rname
  1167. self.selector = selector
  1168. def get(self):
  1169. '''return a kind by name '''
  1170. results = self._get(self.kind, rname=self.name, selector=self.selector)
  1171. if results['returncode'] != 0 and 'stderr' in results and \
  1172. '\"%s\" not found' % self.name in results['stderr']:
  1173. results['returncode'] = 0
  1174. return results
  1175. def delete(self):
  1176. '''return all pods '''
  1177. return self._delete(self.kind, self.name)
  1178. def create(self, files=None, content=None):
  1179. '''
  1180. Create a config
  1181. NOTE: This creates the first file OR the first conent.
  1182. TODO: Handle all files and content passed in
  1183. '''
  1184. if files:
  1185. return self._create(files[0])
  1186. content['data'] = yaml.dump(content['data'])
  1187. content_file = Utils.create_tmp_files_from_contents(content)[0]
  1188. return self._create(content_file['path'])
  1189. # pylint: disable=too-many-function-args
  1190. def update(self, files=None, content=None, force=False):
  1191. '''update a current openshift object
  1192. This receives a list of file names or content
  1193. and takes the first and calls replace.
  1194. TODO: take an entire list
  1195. '''
  1196. if files:
  1197. return self._replace(files[0], force)
  1198. if content and 'data' in content:
  1199. content = content['data']
  1200. return self.update_content(content, force)
  1201. def update_content(self, content, force=False):
  1202. '''update an object through using the content param'''
  1203. return self._replace_content(self.kind, self.name, content, force=force)
  1204. def needs_update(self, files=None, content=None, content_type='yaml'):
  1205. ''' check to see if we need to update '''
  1206. objects = self.get()
  1207. if objects['returncode'] != 0:
  1208. return objects
  1209. data = None
  1210. if files:
  1211. data = Utils.get_resource_file(files[0], content_type)
  1212. elif content and 'data' in content:
  1213. data = content['data']
  1214. else:
  1215. data = content
  1216. # if equal then no need. So not equal is True
  1217. return not Utils.check_def_equal(data, objects['results'][0], skip_keys=None, debug=False)
  1218. # pylint: disable=too-many-return-statements,too-many-branches
  1219. @staticmethod
  1220. def run_ansible(params, check_mode=False):
  1221. '''perform the ansible idempotent code'''
  1222. ocobj = OCObject(params['kind'],
  1223. params['namespace'],
  1224. params['name'],
  1225. params['selector'],
  1226. kubeconfig=params['kubeconfig'],
  1227. verbose=params['debug'],
  1228. all_namespaces=params['all_namespaces'])
  1229. state = params['state']
  1230. api_rval = ocobj.get()
  1231. #####
  1232. # Get
  1233. #####
  1234. if state == 'list':
  1235. return {'changed': False, 'results': api_rval, 'state': 'list'}
  1236. if not params['name']:
  1237. return {'failed': True, 'msg': 'Please specify a name when state is absent|present.'} # noqa: E501
  1238. ########
  1239. # Delete
  1240. ########
  1241. if state == 'absent':
  1242. if not Utils.exists(api_rval['results'], params['name']):
  1243. return {'changed': False, 'state': 'absent'}
  1244. if check_mode:
  1245. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'}
  1246. api_rval = ocobj.delete()
  1247. return {'changed': True, 'results': api_rval, 'state': 'absent'}
  1248. if state == 'present':
  1249. ########
  1250. # Create
  1251. ########
  1252. if not Utils.exists(api_rval['results'], params['name']):
  1253. if check_mode:
  1254. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'}
  1255. # Create it here
  1256. api_rval = ocobj.create(params['files'], params['content'])
  1257. if api_rval['returncode'] != 0:
  1258. return {'failed': True, 'msg': api_rval}
  1259. # return the created object
  1260. api_rval = ocobj.get()
  1261. if api_rval['returncode'] != 0:
  1262. return {'failed': True, 'msg': api_rval}
  1263. # Remove files
  1264. if params['files'] and params['delete_after']:
  1265. Utils.cleanup(params['files'])
  1266. return {'changed': True, 'results': api_rval, 'state': "present"}
  1267. ########
  1268. # Update
  1269. ########
  1270. # if a file path is passed, use it.
  1271. update = ocobj.needs_update(params['files'], params['content'])
  1272. if not isinstance(update, bool):
  1273. return {'failed': True, 'msg': update}
  1274. # No changes
  1275. if not update:
  1276. if params['files'] and params['delete_after']:
  1277. Utils.cleanup(params['files'])
  1278. return {'changed': False, 'results': api_rval['results'][0], 'state': "present"}
  1279. if check_mode:
  1280. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  1281. api_rval = ocobj.update(params['files'],
  1282. params['content'],
  1283. params['force'])
  1284. if api_rval['returncode'] != 0:
  1285. return {'failed': True, 'msg': api_rval}
  1286. # return the created object
  1287. api_rval = ocobj.get()
  1288. if api_rval['returncode'] != 0:
  1289. return {'failed': True, 'msg': api_rval}
  1290. return {'changed': True, 'results': api_rval, 'state': "present"}
  1291. # -*- -*- -*- End included fragment: class/oc_obj.py -*- -*- -*-
  1292. # -*- -*- -*- Begin included fragment: ansible/oc_obj.py -*- -*- -*-
  1293. # pylint: disable=too-many-branches
  1294. def main():
  1295. '''
  1296. ansible oc module for services
  1297. '''
  1298. module = AnsibleModule(
  1299. argument_spec=dict(
  1300. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1301. state=dict(default='present', type='str',
  1302. choices=['present', 'absent', 'list']),
  1303. debug=dict(default=False, type='bool'),
  1304. namespace=dict(default='default', type='str'),
  1305. all_namespaces=dict(defaul=False, type='bool'),
  1306. name=dict(default=None, type='str'),
  1307. files=dict(default=None, type='list'),
  1308. kind=dict(required=True, type='str'),
  1309. delete_after=dict(default=False, type='bool'),
  1310. content=dict(default=None, type='dict'),
  1311. force=dict(default=False, type='bool'),
  1312. selector=dict(default=None, type='str'),
  1313. ),
  1314. mutually_exclusive=[["content", "files"]],
  1315. supports_check_mode=True,
  1316. )
  1317. rval = OCObject.run_ansible(module.params, module.check_mode)
  1318. if 'failed' in rval:
  1319. module.fail_json(**rval)
  1320. module.exit_json(**rval)
  1321. if __name__ == '__main__':
  1322. main()
  1323. # -*- -*- -*- End included fragment: ansible/oc_obj.py -*- -*- -*-