oc_version.py 41 KB

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