oc_version.py 43 KB

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