oc_objectvalidator.py 47 KB

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