oc_sdnvalidator.py 46 KB

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