oc_sdnvalidator.py 45 KB

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