oc_obj.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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 = ['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])
  640. def _delete(self, resource, rname, selector=None):
  641. '''call oc delete on a resource'''
  642. cmd = ['delete', resource, rname]
  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']
  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(['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. cmd.extend(['-o', 'json'])
  676. if rname:
  677. cmd.append(rname)
  678. rval = self.openshift_cmd(cmd, output=True)
  679. # Ensure results are retuned in an array
  680. if 'items' in rval:
  681. rval['results'] = rval['items']
  682. elif not isinstance(rval['results'], list):
  683. rval['results'] = [rval['results']]
  684. return rval
  685. def _schedulable(self, node=None, selector=None, schedulable=True):
  686. ''' perform oadm manage-node scheduable '''
  687. cmd = ['manage-node']
  688. if node:
  689. cmd.extend(node)
  690. else:
  691. cmd.append('--selector=%s' % selector)
  692. cmd.append('--schedulable=%s' % schedulable)
  693. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  694. def _list_pods(self, node=None, selector=None, pod_selector=None):
  695. ''' perform oadm list pods
  696. node: the node in which to list pods
  697. selector: the label selector filter if provided
  698. pod_selector: the pod selector filter if provided
  699. '''
  700. cmd = ['manage-node']
  701. if node:
  702. cmd.extend(node)
  703. else:
  704. cmd.append('--selector=%s' % selector)
  705. if pod_selector:
  706. cmd.append('--pod-selector=%s' % pod_selector)
  707. cmd.extend(['--list-pods', '-o', 'json'])
  708. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  709. # pylint: disable=too-many-arguments
  710. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  711. ''' perform oadm manage-node evacuate '''
  712. cmd = ['manage-node']
  713. if node:
  714. cmd.extend(node)
  715. else:
  716. cmd.append('--selector=%s' % selector)
  717. if dry_run:
  718. cmd.append('--dry-run')
  719. if pod_selector:
  720. cmd.append('--pod-selector=%s' % pod_selector)
  721. if grace_period:
  722. cmd.append('--grace-period=%s' % int(grace_period))
  723. if force:
  724. cmd.append('--force')
  725. cmd.append('--evacuate')
  726. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  727. def _version(self):
  728. ''' return the openshift version'''
  729. return self.openshift_cmd(['version'], output=True, output_type='raw')
  730. def _import_image(self, url=None, name=None, tag=None):
  731. ''' perform image import '''
  732. cmd = ['import-image']
  733. image = '{0}'.format(name)
  734. if tag:
  735. image += ':{0}'.format(tag)
  736. cmd.append(image)
  737. if url:
  738. cmd.append('--from={0}/{1}'.format(url, image))
  739. cmd.append('-n{0}'.format(self.namespace))
  740. cmd.append('--confirm')
  741. return self.openshift_cmd(cmd)
  742. # pylint: disable=too-many-arguments,too-many-branches
  743. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  744. '''Base command for oc '''
  745. cmds = []
  746. if oadm:
  747. cmds = ['/usr/bin/oadm']
  748. else:
  749. cmds = ['/usr/bin/oc']
  750. if self.all_namespaces:
  751. cmds.extend(['--all-namespaces'])
  752. elif self.namespace:
  753. cmds.extend(['-n', self.namespace])
  754. cmds.extend(cmd)
  755. rval = {}
  756. results = ''
  757. err = None
  758. if self.verbose:
  759. print(' '.join(cmds))
  760. proc = subprocess.Popen(cmds,
  761. stdin=subprocess.PIPE,
  762. stdout=subprocess.PIPE,
  763. stderr=subprocess.PIPE,
  764. env={'KUBECONFIG': self.kubeconfig})
  765. stdout, stderr = proc.communicate(input_data)
  766. rval = {"returncode": proc.returncode,
  767. "results": results,
  768. "cmd": ' '.join(cmds)}
  769. if proc.returncode == 0:
  770. if output:
  771. if output_type == 'json':
  772. try:
  773. rval['results'] = json.loads(stdout)
  774. except ValueError as err:
  775. if "No JSON object could be decoded" in err.args:
  776. err = err.args
  777. elif output_type == 'raw':
  778. rval['results'] = stdout
  779. if self.verbose:
  780. print("STDOUT: {0}".format(stdout))
  781. print("STDERR: {0}".format(stderr))
  782. if err:
  783. rval.update({"err": err,
  784. "stderr": stderr,
  785. "stdout": stdout,
  786. "cmd": cmds})
  787. else:
  788. rval.update({"stderr": stderr,
  789. "stdout": stdout,
  790. "results": {}})
  791. return rval
  792. class Utils(object):
  793. ''' utilities for openshiftcli modules '''
  794. @staticmethod
  795. def create_file(rname, data, ftype='yaml'):
  796. ''' create a file in tmp with name and contents'''
  797. path = os.path.join('/tmp', rname)
  798. with open(path, 'w') as fds:
  799. if ftype == 'yaml':
  800. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  801. elif ftype == 'json':
  802. fds.write(json.dumps(data))
  803. else:
  804. fds.write(data)
  805. # Register cleanup when module is done
  806. atexit.register(Utils.cleanup, [path])
  807. return path
  808. @staticmethod
  809. def create_files_from_contents(content, content_type=None):
  810. '''Turn an array of dict: filename, content into a files array'''
  811. if not isinstance(content, list):
  812. content = [content]
  813. files = []
  814. for item in content:
  815. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  816. files.append({'name': os.path.basename(path), 'path': path})
  817. return files
  818. @staticmethod
  819. def cleanup(files):
  820. '''Clean up on exit '''
  821. for sfile in files:
  822. if os.path.exists(sfile):
  823. if os.path.isdir(sfile):
  824. shutil.rmtree(sfile)
  825. elif os.path.isfile(sfile):
  826. os.remove(sfile)
  827. @staticmethod
  828. def exists(results, _name):
  829. ''' Check to see if the results include the name '''
  830. if not results:
  831. return False
  832. if Utils.find_result(results, _name):
  833. return True
  834. return False
  835. @staticmethod
  836. def find_result(results, _name):
  837. ''' Find the specified result by name'''
  838. rval = None
  839. for result in results:
  840. if 'metadata' in result and result['metadata']['name'] == _name:
  841. rval = result
  842. break
  843. return rval
  844. @staticmethod
  845. def get_resource_file(sfile, sfile_type='yaml'):
  846. ''' return the service file '''
  847. contents = None
  848. with open(sfile) as sfd:
  849. contents = sfd.read()
  850. if sfile_type == 'yaml':
  851. contents = yaml.load(contents, yaml.RoundTripLoader)
  852. elif sfile_type == 'json':
  853. contents = json.loads(contents)
  854. return contents
  855. @staticmethod
  856. def filter_versions(stdout):
  857. ''' filter the oc version output '''
  858. version_dict = {}
  859. version_search = ['oc', 'openshift', 'kubernetes']
  860. for line in stdout.strip().split('\n'):
  861. for term in version_search:
  862. if not line:
  863. continue
  864. if line.startswith(term):
  865. version_dict[term] = line.split()[-1]
  866. # horrible hack to get openshift version in Openshift 3.2
  867. # By default "oc version in 3.2 does not return an "openshift" version
  868. if "openshift" not in version_dict:
  869. version_dict["openshift"] = version_dict["oc"]
  870. return version_dict
  871. @staticmethod
  872. def add_custom_versions(versions):
  873. ''' create custom versions strings '''
  874. versions_dict = {}
  875. for tech, version in versions.items():
  876. # clean up "-" from version
  877. if "-" in version:
  878. version = version.split("-")[0]
  879. if version.startswith('v'):
  880. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  881. # "v3.3.0.33" is what we have, we want "3.3"
  882. versions_dict[tech + '_short'] = version[1:4]
  883. return versions_dict
  884. @staticmethod
  885. def openshift_installed():
  886. ''' check if openshift is installed '''
  887. import yum
  888. yum_base = yum.YumBase()
  889. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  890. return True
  891. return False
  892. # Disabling too-many-branches. This is a yaml dictionary comparison function
  893. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  894. @staticmethod
  895. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  896. ''' Given a user defined definition, compare it with the results given back by our query. '''
  897. # Currently these values are autogenerated and we do not need to check them
  898. skip = ['metadata', 'status']
  899. if skip_keys:
  900. skip.extend(skip_keys)
  901. for key, value in result_def.items():
  902. if key in skip:
  903. continue
  904. # Both are lists
  905. if isinstance(value, list):
  906. if key not in user_def:
  907. if debug:
  908. print('User data does not have key [%s]' % key)
  909. print('User data: %s' % user_def)
  910. return False
  911. if not isinstance(user_def[key], list):
  912. if debug:
  913. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  914. return False
  915. if len(user_def[key]) != len(value):
  916. if debug:
  917. print("List lengths are not equal.")
  918. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  919. print("user_def: %s" % user_def[key])
  920. print("value: %s" % value)
  921. return False
  922. for values in zip(user_def[key], value):
  923. if isinstance(values[0], dict) and isinstance(values[1], dict):
  924. if debug:
  925. print('sending list - list')
  926. print(type(values[0]))
  927. print(type(values[1]))
  928. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  929. if not result:
  930. print('list compare returned false')
  931. return False
  932. elif value != user_def[key]:
  933. if debug:
  934. print('value should be identical')
  935. print(value)
  936. print(user_def[key])
  937. return False
  938. # recurse on a dictionary
  939. elif isinstance(value, dict):
  940. if key not in user_def:
  941. if debug:
  942. print("user_def does not have key [%s]" % key)
  943. return False
  944. if not isinstance(user_def[key], dict):
  945. if debug:
  946. print("dict returned false: not instance of dict")
  947. return False
  948. # before passing ensure keys match
  949. api_values = set(value.keys()) - set(skip)
  950. user_values = set(user_def[key].keys()) - set(skip)
  951. if api_values != user_values:
  952. if debug:
  953. print("keys are not equal in dict")
  954. print(api_values)
  955. print(user_values)
  956. return False
  957. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  958. if not result:
  959. if debug:
  960. print("dict returned false")
  961. print(result)
  962. return False
  963. # Verify each key, value pair is the same
  964. else:
  965. if key not in user_def or value != user_def[key]:
  966. if debug:
  967. print("value not equal; user_def does not have key")
  968. print(key)
  969. print(value)
  970. if key in user_def:
  971. print(user_def[key])
  972. return False
  973. if debug:
  974. print('returning true')
  975. return True
  976. class OpenShiftCLIConfig(object):
  977. '''Generic Config'''
  978. def __init__(self, rname, namespace, kubeconfig, options):
  979. self.kubeconfig = kubeconfig
  980. self.name = rname
  981. self.namespace = namespace
  982. self._options = options
  983. @property
  984. def config_options(self):
  985. ''' return config options '''
  986. return self._options
  987. def to_option_list(self):
  988. '''return all options as a string'''
  989. return self.stringify()
  990. def stringify(self):
  991. ''' return the options hash as cli params in a string '''
  992. rval = []
  993. for key, data in self.config_options.items():
  994. if data['include'] \
  995. and (data['value'] or isinstance(data['value'], int)):
  996. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  997. return rval
  998. # pylint: disable=too-many-instance-attributes
  999. class OCObject(OpenShiftCLI):
  1000. ''' Class to wrap the oc command line tools '''
  1001. # pylint allows 5. we need 6
  1002. # pylint: disable=too-many-arguments
  1003. def __init__(self,
  1004. kind,
  1005. namespace,
  1006. rname=None,
  1007. selector=None,
  1008. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1009. verbose=False,
  1010. all_namespaces=False):
  1011. ''' Constructor for OpenshiftOC '''
  1012. super(OCObject, self).__init__(namespace, kubeconfig,
  1013. all_namespaces=all_namespaces)
  1014. self.kind = kind
  1015. self.namespace = namespace
  1016. self.name = rname
  1017. self.selector = selector
  1018. self.kubeconfig = kubeconfig
  1019. self.verbose = verbose
  1020. def get(self):
  1021. '''return a kind by name '''
  1022. results = self._get(self.kind, rname=self.name, selector=self.selector)
  1023. if results['returncode'] != 0 and 'stderr' in results and \
  1024. '\"%s\" not found' % self.name in results['stderr']:
  1025. results['returncode'] = 0
  1026. return results
  1027. def delete(self):
  1028. '''return all pods '''
  1029. return self._delete(self.kind, self.name)
  1030. def create(self, files=None, content=None):
  1031. '''
  1032. Create a config
  1033. NOTE: This creates the first file OR the first conent.
  1034. TODO: Handle all files and content passed in
  1035. '''
  1036. if files:
  1037. return self._create(files[0])
  1038. content['data'] = yaml.dump(content['data'])
  1039. content_file = Utils.create_files_from_contents(content)[0]
  1040. return self._create(content_file['path'])
  1041. # pylint: disable=too-many-function-args
  1042. def update(self, files=None, content=None, force=False):
  1043. '''update a current openshift object
  1044. This receives a list of file names or content
  1045. and takes the first and calls replace.
  1046. TODO: take an entire list
  1047. '''
  1048. if files:
  1049. return self._replace(files[0], force)
  1050. if content and 'data' in content:
  1051. content = content['data']
  1052. return self.update_content(content, force)
  1053. def update_content(self, content, force=False):
  1054. '''update an object through using the content param'''
  1055. return self._replace_content(self.kind, self.name, content, force=force)
  1056. def needs_update(self, files=None, content=None, content_type='yaml'):
  1057. ''' check to see if we need to update '''
  1058. objects = self.get()
  1059. if objects['returncode'] != 0:
  1060. return objects
  1061. # pylint: disable=no-member
  1062. data = None
  1063. if files:
  1064. data = Utils.get_resource_file(files[0], content_type)
  1065. elif content and 'data' in content:
  1066. data = content['data']
  1067. else:
  1068. data = content
  1069. # if equal then no need. So not equal is True
  1070. return not Utils.check_def_equal(data, objects['results'][0], skip_keys=None, debug=False)
  1071. # pylint: disable=too-many-return-statements,too-many-branches
  1072. @staticmethod
  1073. def run_ansible(params, check_mode=False):
  1074. '''perform the ansible idempotent code'''
  1075. ocobj = OCObject(params['kind'],
  1076. params['namespace'],
  1077. params['name'],
  1078. params['selector'],
  1079. kubeconfig=params['kubeconfig'],
  1080. verbose=params['debug'],
  1081. all_namespaces=params['all_namespaces'])
  1082. state = params['state']
  1083. api_rval = ocobj.get()
  1084. #####
  1085. # Get
  1086. #####
  1087. if state == 'list':
  1088. return {'changed': False, 'results': api_rval, 'state': 'list'}
  1089. if not params['name']:
  1090. return {'failed': True, 'msg': 'Please specify a name when state is absent|present.'} # noqa: E501
  1091. ########
  1092. # Delete
  1093. ########
  1094. if state == 'absent':
  1095. if not Utils.exists(api_rval['results'], params['name']):
  1096. return {'changed': False, 'state': 'absent'}
  1097. if check_mode:
  1098. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete'}
  1099. api_rval = ocobj.delete()
  1100. return {'changed': True, 'results': api_rval, 'state': 'absent'}
  1101. if state == 'present':
  1102. ########
  1103. # Create
  1104. ########
  1105. if not Utils.exists(api_rval['results'], params['name']):
  1106. if check_mode:
  1107. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create'}
  1108. # Create it here
  1109. api_rval = ocobj.create(params['files'], params['content'])
  1110. if api_rval['returncode'] != 0:
  1111. return {'failed': True, 'msg': api_rval}
  1112. # return the created object
  1113. api_rval = ocobj.get()
  1114. if api_rval['returncode'] != 0:
  1115. return {'failed': True, 'msg': api_rval}
  1116. # Remove files
  1117. if params['files'] and params['delete_after']:
  1118. Utils.cleanup(params['files'])
  1119. return {'changed': True, 'results': api_rval, 'state': "present"}
  1120. ########
  1121. # Update
  1122. ########
  1123. # if a file path is passed, use it.
  1124. update = ocobj.needs_update(params['files'], params['content'])
  1125. if not isinstance(update, bool):
  1126. return {'failed': True, 'msg': update}
  1127. # No changes
  1128. if not update:
  1129. if params['files'] and params['delete_after']:
  1130. Utils.cleanup(params['files'])
  1131. return {'changed': False, 'results': api_rval['results'][0], 'state': "present"}
  1132. if check_mode:
  1133. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  1134. api_rval = ocobj.update(params['files'],
  1135. params['content'],
  1136. params['force'])
  1137. if api_rval['returncode'] != 0:
  1138. return {'failed': True, 'msg': api_rval}
  1139. # return the created object
  1140. api_rval = ocobj.get()
  1141. if api_rval['returncode'] != 0:
  1142. return {'failed': True, 'msg': api_rval}
  1143. return {'changed': True, 'results': api_rval, 'state': "present"}
  1144. # pylint: disable=too-many-branches
  1145. def main():
  1146. '''
  1147. ansible oc module for services
  1148. '''
  1149. module = AnsibleModule(
  1150. argument_spec=dict(
  1151. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1152. state=dict(default='present', type='str',
  1153. choices=['present', 'absent', 'list']),
  1154. debug=dict(default=False, type='bool'),
  1155. namespace=dict(default='default', type='str'),
  1156. all_namespaces=dict(defaul=False, type='bool'),
  1157. name=dict(default=None, type='str'),
  1158. files=dict(default=None, type='list'),
  1159. kind=dict(required=True, type='str'),
  1160. delete_after=dict(default=False, type='bool'),
  1161. content=dict(default=None, type='dict'),
  1162. force=dict(default=False, type='bool'),
  1163. selector=dict(default=None, type='str'),
  1164. ),
  1165. mutually_exclusive=[["content", "files"]],
  1166. supports_check_mode=True,
  1167. )
  1168. rval = OCObject.run_ansible(module.params, module.check_mode)
  1169. if 'failed' in rval:
  1170. module.fail_json(**rval)
  1171. module.exit_json(**rval)
  1172. if __name__ == '__main__':
  1173. main()