oc_version.py 45 KB

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