oc_obj.py 45 KB

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