oc_version.py 42 KB

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