oc_version.py 40 KB

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