oc_version.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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. # pylint: disable=too-few-public-methods
  593. class OpenShiftCLI(object):
  594. ''' Class to wrap the command line tools '''
  595. def __init__(self,
  596. namespace,
  597. kubeconfig='/etc/origin/master/admin.kubeconfig',
  598. verbose=False,
  599. all_namespaces=False):
  600. ''' Constructor for OpenshiftCLI '''
  601. self.namespace = namespace
  602. self.verbose = verbose
  603. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  604. self.all_namespaces = all_namespaces
  605. # Pylint allows only 5 arguments to be passed.
  606. # pylint: disable=too-many-arguments
  607. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  608. ''' replace the current object with the content '''
  609. res = self._get(resource, rname)
  610. if not res['results']:
  611. return res
  612. fname = Utils.create_tmpfile(rname + '-')
  613. yed = Yedit(fname, res['results'][0], separator=sep)
  614. changes = []
  615. for key, value in content.items():
  616. changes.append(yed.put(key, value))
  617. if any([change[0] for change in changes]):
  618. yed.write()
  619. atexit.register(Utils.cleanup, [fname])
  620. return self._replace(fname, force)
  621. return {'returncode': 0, 'updated': False}
  622. def _replace(self, fname, force=False):
  623. '''replace the current object with oc replace'''
  624. cmd = ['replace', '-f', fname]
  625. if force:
  626. cmd.append('--force')
  627. return self.openshift_cmd(cmd)
  628. def _create_from_content(self, rname, content):
  629. '''create a temporary file and then call oc create on it'''
  630. fname = Utils.create_tmpfile(rname + '-')
  631. yed = Yedit(fname, content=content)
  632. yed.write()
  633. atexit.register(Utils.cleanup, [fname])
  634. return self._create(fname)
  635. def _create(self, fname):
  636. '''call oc create on a filename'''
  637. return self.openshift_cmd(['create', '-f', fname])
  638. def _delete(self, resource, rname, selector=None):
  639. '''call oc delete on a resource'''
  640. cmd = ['delete', resource, rname]
  641. if selector:
  642. cmd.append('--selector=%s' % selector)
  643. return self.openshift_cmd(cmd)
  644. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  645. '''process a template
  646. template_name: the name of the template to process
  647. create: whether to send to oc create after processing
  648. params: the parameters for the template
  649. template_data: the incoming template's data; instead of a file
  650. '''
  651. cmd = ['process']
  652. if template_data:
  653. cmd.extend(['-f', '-'])
  654. else:
  655. cmd.append(template_name)
  656. if params:
  657. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  658. cmd.append('-v')
  659. cmd.extend(param_str)
  660. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  661. if results['returncode'] != 0 or not create:
  662. return results
  663. fname = Utils.create_tmpfile(template_name + '-')
  664. yed = Yedit(fname, results['results'])
  665. yed.write()
  666. atexit.register(Utils.cleanup, [fname])
  667. return self.openshift_cmd(['create', '-f', fname])
  668. def _get(self, resource, rname=None, selector=None):
  669. '''return a resource by name '''
  670. cmd = ['get', resource]
  671. if selector:
  672. cmd.append('--selector=%s' % selector)
  673. elif rname:
  674. cmd.append(rname)
  675. cmd.extend(['-o', 'json'])
  676. rval = self.openshift_cmd(cmd, output=True)
  677. # Ensure results are retuned in an array
  678. if 'items' in rval:
  679. rval['results'] = rval['items']
  680. elif not isinstance(rval['results'], list):
  681. rval['results'] = [rval['results']]
  682. return rval
  683. def _schedulable(self, node=None, selector=None, schedulable=True):
  684. ''' perform oadm manage-node scheduable '''
  685. cmd = ['manage-node']
  686. if node:
  687. cmd.extend(node)
  688. else:
  689. cmd.append('--selector=%s' % selector)
  690. cmd.append('--schedulable=%s' % schedulable)
  691. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  692. def _list_pods(self, node=None, selector=None, pod_selector=None):
  693. ''' perform oadm list pods
  694. node: the node in which to list pods
  695. selector: the label selector filter if provided
  696. pod_selector: the pod selector filter if provided
  697. '''
  698. cmd = ['manage-node']
  699. if node:
  700. cmd.extend(node)
  701. else:
  702. cmd.append('--selector=%s' % selector)
  703. if pod_selector:
  704. cmd.append('--pod-selector=%s' % pod_selector)
  705. cmd.extend(['--list-pods', '-o', 'json'])
  706. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  707. # pylint: disable=too-many-arguments
  708. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  709. ''' perform oadm manage-node evacuate '''
  710. cmd = ['manage-node']
  711. if node:
  712. cmd.extend(node)
  713. else:
  714. cmd.append('--selector=%s' % selector)
  715. if dry_run:
  716. cmd.append('--dry-run')
  717. if pod_selector:
  718. cmd.append('--pod-selector=%s' % pod_selector)
  719. if grace_period:
  720. cmd.append('--grace-period=%s' % int(grace_period))
  721. if force:
  722. cmd.append('--force')
  723. cmd.append('--evacuate')
  724. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  725. def _version(self):
  726. ''' return the openshift version'''
  727. return self.openshift_cmd(['version'], output=True, output_type='raw')
  728. def _import_image(self, url=None, name=None, tag=None):
  729. ''' perform image import '''
  730. cmd = ['import-image']
  731. image = '{0}'.format(name)
  732. if tag:
  733. image += ':{0}'.format(tag)
  734. cmd.append(image)
  735. if url:
  736. cmd.append('--from={0}/{1}'.format(url, image))
  737. cmd.append('-n{0}'.format(self.namespace))
  738. cmd.append('--confirm')
  739. return self.openshift_cmd(cmd)
  740. def _run(self, cmds, input_data):
  741. ''' Actually executes the command. This makes mocking easier. '''
  742. curr_env = os.environ.copy()
  743. curr_env.update({'KUBECONFIG': self.kubeconfig})
  744. proc = subprocess.Popen(cmds,
  745. stdin=subprocess.PIPE,
  746. stdout=subprocess.PIPE,
  747. stderr=subprocess.PIPE,
  748. env=curr_env)
  749. stdout, stderr = proc.communicate(input_data)
  750. return proc.returncode, stdout.decode(), stderr.decode()
  751. # pylint: disable=too-many-arguments,too-many-branches
  752. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  753. '''Base command for oc '''
  754. cmds = []
  755. if oadm:
  756. cmds = ['oadm']
  757. else:
  758. cmds = ['oc']
  759. if self.all_namespaces:
  760. cmds.extend(['--all-namespaces'])
  761. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  762. cmds.extend(['-n', self.namespace])
  763. cmds.extend(cmd)
  764. rval = {}
  765. results = ''
  766. err = None
  767. if self.verbose:
  768. print(' '.join(cmds))
  769. returncode, stdout, stderr = self._run(cmds, input_data)
  770. rval = {"returncode": returncode,
  771. "results": results,
  772. "cmd": ' '.join(cmds)}
  773. if returncode == 0:
  774. if output:
  775. if output_type == 'json':
  776. try:
  777. rval['results'] = json.loads(stdout)
  778. except ValueError as err:
  779. if "No JSON object could be decoded" in err.args:
  780. err = err.args
  781. elif output_type == 'raw':
  782. rval['results'] = stdout
  783. if self.verbose:
  784. print("STDOUT: {0}".format(stdout))
  785. print("STDERR: {0}".format(stderr))
  786. if err:
  787. rval.update({"err": err,
  788. "stderr": stderr,
  789. "stdout": stdout,
  790. "cmd": cmds})
  791. else:
  792. rval.update({"stderr": stderr,
  793. "stdout": stdout,
  794. "results": {}})
  795. return rval
  796. class Utils(object):
  797. ''' utilities for openshiftcli modules '''
  798. @staticmethod
  799. def _write(filename, contents):
  800. ''' Actually write the file contents to disk. This helps with mocking. '''
  801. with open(filename, 'w') as sfd:
  802. sfd.write(contents)
  803. @staticmethod
  804. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  805. ''' create a file in tmp with name and contents'''
  806. tmp = Utils.create_tmpfile(prefix=rname)
  807. if ftype == 'yaml':
  808. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  809. # pylint: disable=no-member
  810. if hasattr(yaml, 'RoundTripDumper'):
  811. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  812. else:
  813. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  814. elif ftype == 'json':
  815. Utils._write(tmp, json.dumps(data))
  816. else:
  817. Utils._write(tmp, data)
  818. # Register cleanup when module is done
  819. atexit.register(Utils.cleanup, [tmp])
  820. return tmp
  821. @staticmethod
  822. def create_tmpfile_copy(inc_file):
  823. '''create a temporary copy of a file'''
  824. tmpfile = Utils.create_tmpfile('lib_openshift-')
  825. Utils._write(tmpfile, open(inc_file).read())
  826. # Cleanup the tmpfile
  827. atexit.register(Utils.cleanup, [tmpfile])
  828. return tmpfile
  829. @staticmethod
  830. def create_tmpfile(prefix='tmp'):
  831. ''' Generates and returns a temporary file name '''
  832. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  833. return tmp.name
  834. @staticmethod
  835. def create_tmp_files_from_contents(content, content_type=None):
  836. '''Turn an array of dict: filename, content into a files array'''
  837. if not isinstance(content, list):
  838. content = [content]
  839. files = []
  840. for item in content:
  841. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  842. item['data'],
  843. ftype=content_type)
  844. files.append({'name': os.path.basename(item['path']),
  845. 'path': path})
  846. return files
  847. @staticmethod
  848. def cleanup(files):
  849. '''Clean up on exit '''
  850. for sfile in files:
  851. if os.path.exists(sfile):
  852. if os.path.isdir(sfile):
  853. shutil.rmtree(sfile)
  854. elif os.path.isfile(sfile):
  855. os.remove(sfile)
  856. @staticmethod
  857. def exists(results, _name):
  858. ''' Check to see if the results include the name '''
  859. if not results:
  860. return False
  861. if Utils.find_result(results, _name):
  862. return True
  863. return False
  864. @staticmethod
  865. def find_result(results, _name):
  866. ''' Find the specified result by name'''
  867. rval = None
  868. for result in results:
  869. if 'metadata' in result and result['metadata']['name'] == _name:
  870. rval = result
  871. break
  872. return rval
  873. @staticmethod
  874. def get_resource_file(sfile, sfile_type='yaml'):
  875. ''' return the service file '''
  876. contents = None
  877. with open(sfile) as sfd:
  878. contents = sfd.read()
  879. if sfile_type == 'yaml':
  880. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  881. # pylint: disable=no-member
  882. if hasattr(yaml, 'RoundTripLoader'):
  883. contents = yaml.load(contents, yaml.RoundTripLoader)
  884. else:
  885. contents = yaml.safe_load(contents)
  886. elif sfile_type == 'json':
  887. contents = json.loads(contents)
  888. return contents
  889. @staticmethod
  890. def filter_versions(stdout):
  891. ''' filter the oc version output '''
  892. version_dict = {}
  893. version_search = ['oc', 'openshift', 'kubernetes']
  894. for line in stdout.strip().split('\n'):
  895. for term in version_search:
  896. if not line:
  897. continue
  898. if line.startswith(term):
  899. version_dict[term] = line.split()[-1]
  900. # horrible hack to get openshift version in Openshift 3.2
  901. # By default "oc version in 3.2 does not return an "openshift" version
  902. if "openshift" not in version_dict:
  903. version_dict["openshift"] = version_dict["oc"]
  904. return version_dict
  905. @staticmethod
  906. def add_custom_versions(versions):
  907. ''' create custom versions strings '''
  908. versions_dict = {}
  909. for tech, version in versions.items():
  910. # clean up "-" from version
  911. if "-" in version:
  912. version = version.split("-")[0]
  913. if version.startswith('v'):
  914. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  915. # "v3.3.0.33" is what we have, we want "3.3"
  916. versions_dict[tech + '_short'] = version[1:4]
  917. return versions_dict
  918. @staticmethod
  919. def openshift_installed():
  920. ''' check if openshift is installed '''
  921. import yum
  922. yum_base = yum.YumBase()
  923. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  924. return True
  925. return False
  926. # Disabling too-many-branches. This is a yaml dictionary comparison function
  927. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  928. @staticmethod
  929. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  930. ''' Given a user defined definition, compare it with the results given back by our query. '''
  931. # Currently these values are autogenerated and we do not need to check them
  932. skip = ['metadata', 'status']
  933. if skip_keys:
  934. skip.extend(skip_keys)
  935. for key, value in result_def.items():
  936. if key in skip:
  937. continue
  938. # Both are lists
  939. if isinstance(value, list):
  940. if key not in user_def:
  941. if debug:
  942. print('User data does not have key [%s]' % key)
  943. print('User data: %s' % user_def)
  944. return False
  945. if not isinstance(user_def[key], list):
  946. if debug:
  947. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  948. return False
  949. if len(user_def[key]) != len(value):
  950. if debug:
  951. print("List lengths are not equal.")
  952. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  953. print("user_def: %s" % user_def[key])
  954. print("value: %s" % value)
  955. return False
  956. for values in zip(user_def[key], value):
  957. if isinstance(values[0], dict) and isinstance(values[1], dict):
  958. if debug:
  959. print('sending list - list')
  960. print(type(values[0]))
  961. print(type(values[1]))
  962. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  963. if not result:
  964. print('list compare returned false')
  965. return False
  966. elif value != user_def[key]:
  967. if debug:
  968. print('value should be identical')
  969. print(value)
  970. print(user_def[key])
  971. return False
  972. # recurse on a dictionary
  973. elif isinstance(value, dict):
  974. if key not in user_def:
  975. if debug:
  976. print("user_def does not have key [%s]" % key)
  977. return False
  978. if not isinstance(user_def[key], dict):
  979. if debug:
  980. print("dict returned false: not instance of dict")
  981. return False
  982. # before passing ensure keys match
  983. api_values = set(value.keys()) - set(skip)
  984. user_values = set(user_def[key].keys()) - set(skip)
  985. if api_values != user_values:
  986. if debug:
  987. print("keys are not equal in dict")
  988. print(api_values)
  989. print(user_values)
  990. return False
  991. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  992. if not result:
  993. if debug:
  994. print("dict returned false")
  995. print(result)
  996. return False
  997. # Verify each key, value pair is the same
  998. else:
  999. if key not in user_def or value != user_def[key]:
  1000. if debug:
  1001. print("value not equal; user_def does not have key")
  1002. print(key)
  1003. print(value)
  1004. if key in user_def:
  1005. print(user_def[key])
  1006. return False
  1007. if debug:
  1008. print('returning true')
  1009. return True
  1010. class OpenShiftCLIConfig(object):
  1011. '''Generic Config'''
  1012. def __init__(self, rname, namespace, kubeconfig, options):
  1013. self.kubeconfig = kubeconfig
  1014. self.name = rname
  1015. self.namespace = namespace
  1016. self._options = options
  1017. @property
  1018. def config_options(self):
  1019. ''' return config options '''
  1020. return self._options
  1021. def to_option_list(self):
  1022. '''return all options as a string'''
  1023. return self.stringify()
  1024. def stringify(self):
  1025. ''' return the options hash as cli params in a string '''
  1026. rval = []
  1027. for key, data in self.config_options.items():
  1028. if data['include'] \
  1029. and (data['value'] or isinstance(data['value'], int)):
  1030. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  1031. return rval
  1032. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1033. # -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
  1034. # pylint: disable=too-many-instance-attributes
  1035. class OCVersion(OpenShiftCLI):
  1036. ''' Class to wrap the oc command line tools '''
  1037. # pylint allows 5
  1038. # pylint: disable=too-many-arguments
  1039. def __init__(self,
  1040. config,
  1041. debug):
  1042. ''' Constructor for OCVersion '''
  1043. super(OCVersion, self).__init__(None, config)
  1044. self.debug = debug
  1045. def get(self):
  1046. '''get and return version information '''
  1047. results = {}
  1048. version_results = self._version()
  1049. if version_results['returncode'] == 0:
  1050. filtered_vers = Utils.filter_versions(version_results['results'])
  1051. custom_vers = Utils.add_custom_versions(filtered_vers)
  1052. results['returncode'] = version_results['returncode']
  1053. results.update(filtered_vers)
  1054. results.update(custom_vers)
  1055. return results
  1056. raise OpenShiftCLIError('Problem detecting openshift version.')
  1057. @staticmethod
  1058. def run_ansible(params):
  1059. '''run the idempotent ansible code'''
  1060. oc_version = OCVersion(params['kubeconfig'], params['debug'])
  1061. if params['state'] == 'list':
  1062. #pylint: disable=protected-access
  1063. result = oc_version.get()
  1064. return {'state': params['state'],
  1065. 'results': result,
  1066. 'changed': False}
  1067. # -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
  1068. # -*- -*- -*- Begin included fragment: ansible/oc_version.py -*- -*- -*-
  1069. def main():
  1070. ''' ansible oc module for version '''
  1071. module = AnsibleModule(
  1072. argument_spec=dict(
  1073. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1074. state=dict(default='list', type='str',
  1075. choices=['list']),
  1076. debug=dict(default=False, type='bool'),
  1077. ),
  1078. supports_check_mode=True,
  1079. )
  1080. rval = OCVersion.run_ansible(module.params)
  1081. if 'failed' in rval:
  1082. module.fail_json(**rval)
  1083. module.exit_json(**rval)
  1084. if __name__ == '__main__':
  1085. main()
  1086. # -*- -*- -*- End included fragment: ansible/oc_version.py -*- -*- -*-