oc_clusterrole.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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 fcntl
  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/clusterrole -*- -*- -*-
  50. DOCUMENTATION = '''
  51. ---
  52. module: oc_clusterrole
  53. short_description: Modify, and idempotently manage openshift clusterroles
  54. description:
  55. - Manage openshift clusterroles
  56. options:
  57. state:
  58. description:
  59. - Supported states, present, absent, list
  60. - present - will ensure object is created or updated to the value specified
  61. - list - will return a clusterrole
  62. - absent - will remove a clusterrole
  63. required: False
  64. default: present
  65. choices: ["present", 'absent', 'list']
  66. aliases: []
  67. kubeconfig:
  68. description:
  69. - The path for the kubeconfig file to use for authentication
  70. required: false
  71. default: /etc/origin/master/admin.kubeconfig
  72. aliases: []
  73. debug:
  74. description:
  75. - Turn on debug output.
  76. required: false
  77. default: False
  78. aliases: []
  79. name:
  80. description:
  81. - Name of the object that is being queried.
  82. required: false
  83. default: None
  84. aliases: []
  85. rules:
  86. description:
  87. - A list of dictionaries that have the rule parameters.
  88. - e.g. rules=[{'apiGroups': [""], 'attributeRestrictions': None, 'verbs': ['get'], 'resources': []}]
  89. required: false
  90. default: None
  91. aliases: []
  92. author:
  93. - "Kenny Woodson <kwoodson@redhat.com>"
  94. extends_documentation_fragment: []
  95. '''
  96. EXAMPLES = '''
  97. - name: query a list of env vars on dc
  98. oc_clusterrole:
  99. name: myclusterrole
  100. state: list
  101. - name: Set the following variables.
  102. oc_clusterrole:
  103. name: myclusterrole
  104. rules:
  105. apiGroups:
  106. - ""
  107. attributeRestrictions: null
  108. verbs: []
  109. resources: []
  110. '''
  111. # -*- -*- -*- End included fragment: doc/clusterrole -*- -*- -*-
  112. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  113. class YeditException(Exception): # pragma: no cover
  114. ''' Exception class for Yedit '''
  115. pass
  116. # pylint: disable=too-many-public-methods
  117. class Yedit(object): # pragma: no cover
  118. ''' Class to modify yaml files '''
  119. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  120. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
  121. com_sep = set(['.', '#', '|', ':'])
  122. # pylint: disable=too-many-arguments
  123. def __init__(self,
  124. filename=None,
  125. content=None,
  126. content_type='yaml',
  127. separator='.',
  128. backup=False):
  129. self.content = content
  130. self._separator = separator
  131. self.filename = filename
  132. self.__yaml_dict = content
  133. self.content_type = content_type
  134. self.backup = backup
  135. self.load(content_type=self.content_type)
  136. if self.__yaml_dict is None:
  137. self.__yaml_dict = {}
  138. @property
  139. def separator(self):
  140. ''' getter method for separator '''
  141. return self._separator
  142. @separator.setter
  143. def separator(self, inc_sep):
  144. ''' setter method for separator '''
  145. self._separator = inc_sep
  146. @property
  147. def yaml_dict(self):
  148. ''' getter method for yaml_dict '''
  149. return self.__yaml_dict
  150. @yaml_dict.setter
  151. def yaml_dict(self, value):
  152. ''' setter method for yaml_dict '''
  153. self.__yaml_dict = value
  154. @staticmethod
  155. def parse_key(key, sep='.'):
  156. '''parse the key allowing the appropriate separator'''
  157. common_separators = list(Yedit.com_sep - set([sep]))
  158. return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
  159. @staticmethod
  160. def valid_key(key, sep='.'):
  161. '''validate the incoming key'''
  162. common_separators = list(Yedit.com_sep - set([sep]))
  163. if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
  164. return False
  165. return True
  166. # pylint: disable=too-many-return-statements,too-many-branches
  167. @staticmethod
  168. def remove_entry(data, key, index=None, value=None, sep='.'):
  169. ''' remove data at location key '''
  170. if key == '' and isinstance(data, dict):
  171. if value is not None:
  172. data.pop(value)
  173. elif index is not None:
  174. raise YeditException("remove_entry for a dictionary does not have an index {}".format(index))
  175. else:
  176. data.clear()
  177. return True
  178. elif key == '' and isinstance(data, list):
  179. ind = None
  180. if value is not None:
  181. try:
  182. ind = data.index(value)
  183. except ValueError:
  184. return False
  185. elif index is not None:
  186. ind = index
  187. else:
  188. del data[:]
  189. if ind is not None:
  190. data.pop(ind)
  191. return True
  192. if not (key and Yedit.valid_key(key, sep)) and \
  193. isinstance(data, (list, dict)):
  194. return None
  195. key_indexes = Yedit.parse_key(key, sep)
  196. for arr_ind, dict_key in key_indexes[:-1]:
  197. if dict_key and isinstance(data, dict):
  198. data = data.get(dict_key)
  199. elif (arr_ind and isinstance(data, list) and
  200. int(arr_ind) <= len(data) - 1):
  201. data = data[int(arr_ind)]
  202. else:
  203. return None
  204. # process last index for remove
  205. # expected list entry
  206. if key_indexes[-1][0]:
  207. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  208. del data[int(key_indexes[-1][0])]
  209. return True
  210. # expected dict entry
  211. elif key_indexes[-1][1]:
  212. if isinstance(data, dict):
  213. del data[key_indexes[-1][1]]
  214. return True
  215. @staticmethod
  216. def add_entry(data, key, item=None, sep='.'):
  217. ''' Get an item from a dictionary with key notation a.b.c
  218. d = {'a': {'b': 'c'}}}
  219. key = a#b
  220. return c
  221. '''
  222. if key == '':
  223. pass
  224. elif (not (key and Yedit.valid_key(key, sep)) and
  225. isinstance(data, (list, dict))):
  226. return None
  227. key_indexes = Yedit.parse_key(key, sep)
  228. for arr_ind, dict_key in key_indexes[:-1]:
  229. if dict_key:
  230. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  231. data = data[dict_key]
  232. continue
  233. elif data and not isinstance(data, dict):
  234. raise YeditException("Unexpected item type found while going through key " +
  235. "path: {} (at key: {})".format(key, dict_key))
  236. data[dict_key] = {}
  237. data = data[dict_key]
  238. elif (arr_ind and isinstance(data, list) and
  239. int(arr_ind) <= len(data) - 1):
  240. data = data[int(arr_ind)]
  241. else:
  242. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  243. if key == '':
  244. data = item
  245. # process last index for add
  246. # expected list entry
  247. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  248. data[int(key_indexes[-1][0])] = item
  249. # expected dict entry
  250. elif key_indexes[-1][1] and isinstance(data, dict):
  251. data[key_indexes[-1][1]] = item
  252. # didn't add/update to an existing list, nor add/update key to a dict
  253. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  254. # non-existent array
  255. else:
  256. raise YeditException("Error adding to object at path: {}".format(key))
  257. return data
  258. @staticmethod
  259. def get_entry(data, key, sep='.'):
  260. ''' Get an item from a dictionary with key notation a.b.c
  261. d = {'a': {'b': 'c'}}}
  262. key = a.b
  263. return c
  264. '''
  265. if key == '':
  266. pass
  267. elif (not (key and Yedit.valid_key(key, sep)) and
  268. isinstance(data, (list, dict))):
  269. return None
  270. key_indexes = Yedit.parse_key(key, sep)
  271. for arr_ind, dict_key in key_indexes:
  272. if dict_key and isinstance(data, dict):
  273. data = data.get(dict_key)
  274. elif (arr_ind and isinstance(data, list) and
  275. int(arr_ind) <= len(data) - 1):
  276. data = data[int(arr_ind)]
  277. else:
  278. return None
  279. return data
  280. @staticmethod
  281. def _write(filename, contents):
  282. ''' Actually write the file contents to disk. This helps with mocking. '''
  283. tmp_filename = filename + '.yedit'
  284. with open(tmp_filename, 'w') as yfd:
  285. fcntl.flock(yfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  286. yfd.write(contents)
  287. fcntl.flock(yfd, fcntl.LOCK_UN)
  288. os.rename(tmp_filename, filename)
  289. def write(self):
  290. ''' write to file '''
  291. if not self.filename:
  292. raise YeditException('Please specify a filename.')
  293. if self.backup and self.file_exists():
  294. shutil.copy(self.filename, self.filename + '.orig')
  295. # Try to set format attributes if supported
  296. try:
  297. self.yaml_dict.fa.set_block_style()
  298. except AttributeError:
  299. pass
  300. # Try to use RoundTripDumper if supported.
  301. if self.content_type == 'yaml':
  302. try:
  303. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  304. except AttributeError:
  305. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  306. elif self.content_type == 'json':
  307. Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
  308. else:
  309. raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
  310. 'Please specify a content_type of yaml or json.')
  311. return (True, self.yaml_dict)
  312. def read(self):
  313. ''' read from file '''
  314. # check if it exists
  315. if self.filename is None or not self.file_exists():
  316. return None
  317. contents = None
  318. with open(self.filename) as yfd:
  319. contents = yfd.read()
  320. return contents
  321. def file_exists(self):
  322. ''' return whether file exists '''
  323. if os.path.exists(self.filename):
  324. return True
  325. return False
  326. def load(self, content_type='yaml'):
  327. ''' return yaml file '''
  328. contents = self.read()
  329. if not contents and not self.content:
  330. return None
  331. if self.content:
  332. if isinstance(self.content, dict):
  333. self.yaml_dict = self.content
  334. return self.yaml_dict
  335. elif isinstance(self.content, str):
  336. contents = self.content
  337. # check if it is yaml
  338. try:
  339. if content_type == 'yaml' and contents:
  340. # Try to set format attributes if supported
  341. try:
  342. self.yaml_dict.fa.set_block_style()
  343. except AttributeError:
  344. pass
  345. # Try to use RoundTripLoader if supported.
  346. try:
  347. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  348. except AttributeError:
  349. self.yaml_dict = yaml.safe_load(contents)
  350. # Try to set format attributes if supported
  351. try:
  352. self.yaml_dict.fa.set_block_style()
  353. except AttributeError:
  354. pass
  355. elif content_type == 'json' and contents:
  356. self.yaml_dict = json.loads(contents)
  357. except yaml.YAMLError as err:
  358. # Error loading yaml or json
  359. raise YeditException('Problem with loading yaml file. {}'.format(err))
  360. return self.yaml_dict
  361. def get(self, key):
  362. ''' get a specified key'''
  363. try:
  364. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  365. except KeyError:
  366. entry = None
  367. return entry
  368. def pop(self, path, key_or_item):
  369. ''' remove a key, value pair from a dict or an item for a list'''
  370. try:
  371. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  372. except KeyError:
  373. entry = None
  374. if entry is None:
  375. return (False, self.yaml_dict)
  376. if isinstance(entry, dict):
  377. # AUDIT:maybe-no-member makes sense due to fuzzy types
  378. # pylint: disable=maybe-no-member
  379. if key_or_item in entry:
  380. entry.pop(key_or_item)
  381. return (True, self.yaml_dict)
  382. return (False, self.yaml_dict)
  383. elif isinstance(entry, list):
  384. # AUDIT:maybe-no-member makes sense due to fuzzy types
  385. # pylint: disable=maybe-no-member
  386. ind = None
  387. try:
  388. ind = entry.index(key_or_item)
  389. except ValueError:
  390. return (False, self.yaml_dict)
  391. entry.pop(ind)
  392. return (True, self.yaml_dict)
  393. return (False, self.yaml_dict)
  394. def delete(self, path, index=None, value=None):
  395. ''' remove path from a dict'''
  396. try:
  397. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  398. except KeyError:
  399. entry = None
  400. if entry is None:
  401. return (False, self.yaml_dict)
  402. result = Yedit.remove_entry(self.yaml_dict, path, index, value, self.separator)
  403. if not result:
  404. return (False, self.yaml_dict)
  405. return (True, self.yaml_dict)
  406. def exists(self, path, value):
  407. ''' check if value exists at path'''
  408. try:
  409. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  410. except KeyError:
  411. entry = None
  412. if isinstance(entry, list):
  413. if value in entry:
  414. return True
  415. return False
  416. elif isinstance(entry, dict):
  417. if isinstance(value, dict):
  418. rval = False
  419. for key, val in value.items():
  420. if entry[key] != val:
  421. rval = False
  422. break
  423. else:
  424. rval = True
  425. return rval
  426. return value in entry
  427. return entry == value
  428. def append(self, path, value):
  429. '''append value to a list'''
  430. try:
  431. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  432. except KeyError:
  433. entry = None
  434. if entry is None:
  435. self.put(path, [])
  436. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  437. if not isinstance(entry, list):
  438. return (False, self.yaml_dict)
  439. # AUDIT:maybe-no-member makes sense due to loading data from
  440. # a serialized format.
  441. # pylint: disable=maybe-no-member
  442. entry.append(value)
  443. return (True, self.yaml_dict)
  444. # pylint: disable=too-many-arguments
  445. def update(self, path, value, index=None, curr_value=None):
  446. ''' put path, value into a dict '''
  447. try:
  448. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  449. except KeyError:
  450. entry = None
  451. if isinstance(entry, dict):
  452. # AUDIT:maybe-no-member makes sense due to fuzzy types
  453. # pylint: disable=maybe-no-member
  454. if not isinstance(value, dict):
  455. raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
  456. 'value=[{}] type=[{}]'.format(value, type(value)))
  457. entry.update(value)
  458. return (True, self.yaml_dict)
  459. elif isinstance(entry, list):
  460. # AUDIT:maybe-no-member makes sense due to fuzzy types
  461. # pylint: disable=maybe-no-member
  462. ind = None
  463. if curr_value:
  464. try:
  465. ind = entry.index(curr_value)
  466. except ValueError:
  467. return (False, self.yaml_dict)
  468. elif index is not None:
  469. ind = index
  470. if ind is not None and entry[ind] != value:
  471. entry[ind] = value
  472. return (True, self.yaml_dict)
  473. # see if it exists in the list
  474. try:
  475. ind = entry.index(value)
  476. except ValueError:
  477. # doesn't exist, append it
  478. entry.append(value)
  479. return (True, self.yaml_dict)
  480. # already exists, return
  481. if ind is not None:
  482. return (False, self.yaml_dict)
  483. return (False, self.yaml_dict)
  484. def put(self, path, value):
  485. ''' put path, value into a dict '''
  486. try:
  487. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  488. except KeyError:
  489. entry = None
  490. if entry == value:
  491. return (False, self.yaml_dict)
  492. # deepcopy didn't work
  493. # Try to use ruamel.yaml and fallback to pyyaml
  494. try:
  495. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  496. default_flow_style=False),
  497. yaml.RoundTripLoader)
  498. except AttributeError:
  499. tmp_copy = copy.deepcopy(self.yaml_dict)
  500. # set the format attributes if available
  501. try:
  502. tmp_copy.fa.set_block_style()
  503. except AttributeError:
  504. pass
  505. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  506. if result is None:
  507. return (False, self.yaml_dict)
  508. # When path equals "" it is a special case.
  509. # "" refers to the root of the document
  510. # Only update the root path (entire document) when its a list or dict
  511. if path == '':
  512. if isinstance(result, list) or isinstance(result, dict):
  513. self.yaml_dict = result
  514. return (True, self.yaml_dict)
  515. return (False, self.yaml_dict)
  516. self.yaml_dict = tmp_copy
  517. return (True, self.yaml_dict)
  518. def create(self, path, value):
  519. ''' create a yaml file '''
  520. if not self.file_exists():
  521. # deepcopy didn't work
  522. # Try to use ruamel.yaml and fallback to pyyaml
  523. try:
  524. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  525. default_flow_style=False),
  526. yaml.RoundTripLoader)
  527. except AttributeError:
  528. tmp_copy = copy.deepcopy(self.yaml_dict)
  529. # set the format attributes if available
  530. try:
  531. tmp_copy.fa.set_block_style()
  532. except AttributeError:
  533. pass
  534. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  535. if result is not None:
  536. self.yaml_dict = tmp_copy
  537. return (True, self.yaml_dict)
  538. return (False, self.yaml_dict)
  539. @staticmethod
  540. def get_curr_value(invalue, val_type):
  541. '''return the current value'''
  542. if invalue is None:
  543. return None
  544. curr_value = invalue
  545. if val_type == 'yaml':
  546. try:
  547. # AUDIT:maybe-no-member makes sense due to different yaml libraries
  548. # pylint: disable=maybe-no-member
  549. curr_value = yaml.safe_load(invalue, Loader=yaml.RoundTripLoader)
  550. except AttributeError:
  551. curr_value = yaml.safe_load(invalue)
  552. elif val_type == 'json':
  553. curr_value = json.loads(invalue)
  554. return curr_value
  555. @staticmethod
  556. def parse_value(inc_value, vtype=''):
  557. '''determine value type passed'''
  558. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  559. 'on', 'On', 'ON', ]
  560. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  561. 'off', 'Off', 'OFF']
  562. # It came in as a string but you didn't specify value_type as string
  563. # we will convert to bool if it matches any of the above cases
  564. if isinstance(inc_value, str) and 'bool' in vtype:
  565. if inc_value not in true_bools and inc_value not in false_bools:
  566. raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
  567. elif isinstance(inc_value, bool) and 'str' in vtype:
  568. inc_value = str(inc_value)
  569. # There is a special case where '' will turn into None after yaml loading it so skip
  570. if isinstance(inc_value, str) and inc_value == '':
  571. pass
  572. # If vtype is not str then go ahead and attempt to yaml load it.
  573. elif isinstance(inc_value, str) and 'str' not in vtype:
  574. try:
  575. inc_value = yaml.safe_load(inc_value)
  576. except Exception:
  577. raise YeditException('Could not determine type of incoming value. ' +
  578. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  579. return inc_value
  580. @staticmethod
  581. def process_edits(edits, yamlfile):
  582. '''run through a list of edits and process them one-by-one'''
  583. results = []
  584. for edit in edits:
  585. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  586. if edit.get('action') == 'update':
  587. # pylint: disable=line-too-long
  588. curr_value = Yedit.get_curr_value(
  589. Yedit.parse_value(edit.get('curr_value')),
  590. edit.get('curr_value_format'))
  591. rval = yamlfile.update(edit['key'],
  592. value,
  593. edit.get('index'),
  594. curr_value)
  595. elif edit.get('action') == 'append':
  596. rval = yamlfile.append(edit['key'], value)
  597. else:
  598. rval = yamlfile.put(edit['key'], value)
  599. if rval[0]:
  600. results.append({'key': edit['key'], 'edit': rval[1]})
  601. return {'changed': len(results) > 0, 'results': results}
  602. # pylint: disable=too-many-return-statements,too-many-branches
  603. @staticmethod
  604. def run_ansible(params):
  605. '''perform the idempotent crud operations'''
  606. yamlfile = Yedit(filename=params['src'],
  607. backup=params['backup'],
  608. content_type=params['content_type'],
  609. separator=params['separator'])
  610. state = params['state']
  611. if params['src']:
  612. rval = yamlfile.load()
  613. if yamlfile.yaml_dict is None and state != 'present':
  614. return {'failed': True,
  615. 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
  616. 'file exists, that it is has correct permissions, and is valid yaml.'}
  617. if state == 'list':
  618. if params['content']:
  619. content = Yedit.parse_value(params['content'], params['content_type'])
  620. yamlfile.yaml_dict = content
  621. if params['key']:
  622. rval = yamlfile.get(params['key'])
  623. return {'changed': False, 'result': rval, 'state': state}
  624. elif state == 'absent':
  625. if params['content']:
  626. content = Yedit.parse_value(params['content'], params['content_type'])
  627. yamlfile.yaml_dict = content
  628. if params['update']:
  629. rval = yamlfile.pop(params['key'], params['value'])
  630. else:
  631. rval = yamlfile.delete(params['key'], params['index'], params['value'])
  632. if rval[0] and params['src']:
  633. yamlfile.write()
  634. return {'changed': rval[0], 'result': rval[1], 'state': state}
  635. elif state == 'present':
  636. # check if content is different than what is in the file
  637. if params['content']:
  638. content = Yedit.parse_value(params['content'], params['content_type'])
  639. # We had no edits to make and the contents are the same
  640. if yamlfile.yaml_dict == content and \
  641. params['value'] is None:
  642. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  643. yamlfile.yaml_dict = content
  644. # If we were passed a key, value then
  645. # we enapsulate it in a list and process it
  646. # Key, Value passed to the module : Converted to Edits list #
  647. edits = []
  648. _edit = {}
  649. if params['value'] is not None:
  650. _edit['value'] = params['value']
  651. _edit['value_type'] = params['value_type']
  652. _edit['key'] = params['key']
  653. if params['update']:
  654. _edit['action'] = 'update'
  655. _edit['curr_value'] = params['curr_value']
  656. _edit['curr_value_format'] = params['curr_value_format']
  657. _edit['index'] = params['index']
  658. elif params['append']:
  659. _edit['action'] = 'append'
  660. edits.append(_edit)
  661. elif params['edits'] is not None:
  662. edits = params['edits']
  663. if edits:
  664. results = Yedit.process_edits(edits, yamlfile)
  665. # if there were changes and a src provided to us we need to write
  666. if results['changed'] and params['src']:
  667. yamlfile.write()
  668. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  669. # no edits to make
  670. if params['src']:
  671. # pylint: disable=redefined-variable-type
  672. rval = yamlfile.write()
  673. return {'changed': rval[0],
  674. 'result': rval[1],
  675. 'state': state}
  676. # We were passed content but no src, key or value, or edits. Return contents in memory
  677. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  678. return {'failed': True, 'msg': 'Unkown state passed'}
  679. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  680. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  681. # pylint: disable=too-many-lines
  682. # noqa: E301,E302,E303,T001
  683. class OpenShiftCLIError(Exception):
  684. '''Exception class for openshiftcli'''
  685. pass
  686. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  687. def locate_oc_binary():
  688. ''' Find and return oc binary file '''
  689. # https://github.com/openshift/openshift-ansible/issues/3410
  690. # oc can be in /usr/local/bin in some cases, but that may not
  691. # be in $PATH due to ansible/sudo
  692. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  693. oc_binary = 'oc'
  694. # Use shutil.which if it is available, otherwise fallback to a naive path search
  695. try:
  696. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  697. if which_result is not None:
  698. oc_binary = which_result
  699. except AttributeError:
  700. for path in paths:
  701. if os.path.exists(os.path.join(path, oc_binary)):
  702. oc_binary = os.path.join(path, oc_binary)
  703. break
  704. return oc_binary
  705. # pylint: disable=too-few-public-methods
  706. class OpenShiftCLI(object):
  707. ''' Class to wrap the command line tools '''
  708. def __init__(self,
  709. namespace,
  710. kubeconfig='/etc/origin/master/admin.kubeconfig',
  711. verbose=False,
  712. all_namespaces=False):
  713. ''' Constructor for OpenshiftCLI '''
  714. self.namespace = namespace
  715. self.verbose = verbose
  716. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  717. self.all_namespaces = all_namespaces
  718. self.oc_binary = locate_oc_binary()
  719. # Pylint allows only 5 arguments to be passed.
  720. # pylint: disable=too-many-arguments
  721. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  722. ''' replace the current object with the content '''
  723. res = self._get(resource, rname)
  724. if not res['results']:
  725. return res
  726. fname = Utils.create_tmpfile(rname + '-')
  727. yed = Yedit(fname, res['results'][0], separator=sep)
  728. changes = []
  729. for key, value in content.items():
  730. changes.append(yed.put(key, value))
  731. if any([change[0] for change in changes]):
  732. yed.write()
  733. atexit.register(Utils.cleanup, [fname])
  734. return self._replace(fname, force)
  735. return {'returncode': 0, 'updated': False}
  736. def _replace(self, fname, force=False):
  737. '''replace the current object with oc replace'''
  738. # We are removing the 'resourceVersion' to handle
  739. # a race condition when modifying oc objects
  740. yed = Yedit(fname)
  741. results = yed.delete('metadata.resourceVersion')
  742. if results[0]:
  743. yed.write()
  744. cmd = ['replace', '-f', fname]
  745. if force:
  746. cmd.append('--force')
  747. return self.openshift_cmd(cmd)
  748. def _create_from_content(self, rname, content):
  749. '''create a temporary file and then call oc create on it'''
  750. fname = Utils.create_tmpfile(rname + '-')
  751. yed = Yedit(fname, content=content)
  752. yed.write()
  753. atexit.register(Utils.cleanup, [fname])
  754. return self._create(fname)
  755. def _create(self, fname):
  756. '''call oc create on a filename'''
  757. return self.openshift_cmd(['create', '-f', fname])
  758. def _delete(self, resource, name=None, selector=None):
  759. '''call oc delete on a resource'''
  760. cmd = ['delete', resource]
  761. if selector is not None:
  762. cmd.append('--selector={}'.format(selector))
  763. elif name is not None:
  764. cmd.append(name)
  765. else:
  766. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  767. return self.openshift_cmd(cmd)
  768. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  769. '''process a template
  770. template_name: the name of the template to process
  771. create: whether to send to oc create after processing
  772. params: the parameters for the template
  773. template_data: the incoming template's data; instead of a file
  774. '''
  775. cmd = ['process']
  776. if template_data:
  777. cmd.extend(['-f', '-'])
  778. else:
  779. cmd.append(template_name)
  780. if params:
  781. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  782. cmd.append('-v')
  783. cmd.extend(param_str)
  784. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  785. if results['returncode'] != 0 or not create:
  786. return results
  787. fname = Utils.create_tmpfile(template_name + '-')
  788. yed = Yedit(fname, results['results'])
  789. yed.write()
  790. atexit.register(Utils.cleanup, [fname])
  791. return self.openshift_cmd(['create', '-f', fname])
  792. def _get(self, resource, name=None, selector=None):
  793. '''return a resource by name '''
  794. cmd = ['get', resource]
  795. if selector is not None:
  796. cmd.append('--selector={}'.format(selector))
  797. elif name is not None:
  798. cmd.append(name)
  799. cmd.extend(['-o', 'json'])
  800. rval = self.openshift_cmd(cmd, output=True)
  801. # Ensure results are retuned in an array
  802. if 'items' in rval:
  803. rval['results'] = rval['items']
  804. elif not isinstance(rval['results'], list):
  805. rval['results'] = [rval['results']]
  806. return rval
  807. def _schedulable(self, node=None, selector=None, schedulable=True):
  808. ''' perform oadm manage-node scheduable '''
  809. cmd = ['manage-node']
  810. if node:
  811. cmd.extend(node)
  812. else:
  813. cmd.append('--selector={}'.format(selector))
  814. cmd.append('--schedulable={}'.format(schedulable))
  815. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  816. def _list_pods(self, node=None, selector=None, pod_selector=None):
  817. ''' perform oadm list pods
  818. node: the node in which to list pods
  819. selector: the label selector filter if provided
  820. pod_selector: the pod selector filter if provided
  821. '''
  822. cmd = ['manage-node']
  823. if node:
  824. cmd.extend(node)
  825. else:
  826. cmd.append('--selector={}'.format(selector))
  827. if pod_selector:
  828. cmd.append('--pod-selector={}'.format(pod_selector))
  829. cmd.extend(['--list-pods', '-o', 'json'])
  830. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  831. # pylint: disable=too-many-arguments
  832. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  833. ''' perform oadm manage-node evacuate '''
  834. cmd = ['manage-node']
  835. if node:
  836. cmd.extend(node)
  837. else:
  838. cmd.append('--selector={}'.format(selector))
  839. if dry_run:
  840. cmd.append('--dry-run')
  841. if pod_selector:
  842. cmd.append('--pod-selector={}'.format(pod_selector))
  843. if grace_period:
  844. cmd.append('--grace-period={}'.format(int(grace_period)))
  845. if force:
  846. cmd.append('--force')
  847. cmd.append('--evacuate')
  848. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  849. def _version(self):
  850. ''' return the openshift version'''
  851. return self.openshift_cmd(['version'], output=True, output_type='raw')
  852. def _import_image(self, url=None, name=None, tag=None):
  853. ''' perform image import '''
  854. cmd = ['import-image']
  855. image = '{0}'.format(name)
  856. if tag:
  857. image += ':{0}'.format(tag)
  858. cmd.append(image)
  859. if url:
  860. cmd.append('--from={0}/{1}'.format(url, image))
  861. cmd.append('-n{0}'.format(self.namespace))
  862. cmd.append('--confirm')
  863. return self.openshift_cmd(cmd)
  864. def _run(self, cmds, input_data):
  865. ''' Actually executes the command. This makes mocking easier. '''
  866. curr_env = os.environ.copy()
  867. curr_env.update({'KUBECONFIG': self.kubeconfig})
  868. proc = subprocess.Popen(cmds,
  869. stdin=subprocess.PIPE,
  870. stdout=subprocess.PIPE,
  871. stderr=subprocess.PIPE,
  872. env=curr_env)
  873. stdout, stderr = proc.communicate(input_data)
  874. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  875. # pylint: disable=too-many-arguments,too-many-branches
  876. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  877. '''Base command for oc '''
  878. cmds = [self.oc_binary]
  879. if oadm:
  880. cmds.append('adm')
  881. cmds.extend(cmd)
  882. if self.all_namespaces:
  883. cmds.extend(['--all-namespaces'])
  884. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  885. cmds.extend(['-n', self.namespace])
  886. if self.verbose:
  887. print(' '.join(cmds))
  888. try:
  889. returncode, stdout, stderr = self._run(cmds, input_data)
  890. except OSError as ex:
  891. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  892. rval = {"returncode": returncode,
  893. "cmd": ' '.join(cmds)}
  894. if output_type == 'json':
  895. rval['results'] = {}
  896. if output and stdout:
  897. try:
  898. rval['results'] = json.loads(stdout)
  899. except ValueError as verr:
  900. if "No JSON object could be decoded" in verr.args:
  901. rval['err'] = verr.args
  902. elif output_type == 'raw':
  903. rval['results'] = stdout if output else ''
  904. if self.verbose:
  905. print("STDOUT: {0}".format(stdout))
  906. print("STDERR: {0}".format(stderr))
  907. if 'err' in rval or returncode != 0:
  908. rval.update({"stderr": stderr,
  909. "stdout": stdout})
  910. return rval
  911. class Utils(object): # pragma: no cover
  912. ''' utilities for openshiftcli modules '''
  913. @staticmethod
  914. def _write(filename, contents):
  915. ''' Actually write the file contents to disk. This helps with mocking. '''
  916. with open(filename, 'w') as sfd:
  917. sfd.write(str(contents))
  918. @staticmethod
  919. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  920. ''' create a file in tmp with name and contents'''
  921. tmp = Utils.create_tmpfile(prefix=rname)
  922. if ftype == 'yaml':
  923. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  924. # pylint: disable=no-member
  925. if hasattr(yaml, 'RoundTripDumper'):
  926. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  927. else:
  928. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  929. elif ftype == 'json':
  930. Utils._write(tmp, json.dumps(data))
  931. else:
  932. Utils._write(tmp, data)
  933. # Register cleanup when module is done
  934. atexit.register(Utils.cleanup, [tmp])
  935. return tmp
  936. @staticmethod
  937. def create_tmpfile_copy(inc_file):
  938. '''create a temporary copy of a file'''
  939. tmpfile = Utils.create_tmpfile('lib_openshift-')
  940. Utils._write(tmpfile, open(inc_file).read())
  941. # Cleanup the tmpfile
  942. atexit.register(Utils.cleanup, [tmpfile])
  943. return tmpfile
  944. @staticmethod
  945. def create_tmpfile(prefix='tmp'):
  946. ''' Generates and returns a temporary file name '''
  947. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  948. return tmp.name
  949. @staticmethod
  950. def create_tmp_files_from_contents(content, content_type=None):
  951. '''Turn an array of dict: filename, content into a files array'''
  952. if not isinstance(content, list):
  953. content = [content]
  954. files = []
  955. for item in content:
  956. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  957. item['data'],
  958. ftype=content_type)
  959. files.append({'name': os.path.basename(item['path']),
  960. 'path': path})
  961. return files
  962. @staticmethod
  963. def cleanup(files):
  964. '''Clean up on exit '''
  965. for sfile in files:
  966. if os.path.exists(sfile):
  967. if os.path.isdir(sfile):
  968. shutil.rmtree(sfile)
  969. elif os.path.isfile(sfile):
  970. os.remove(sfile)
  971. @staticmethod
  972. def exists(results, _name):
  973. ''' Check to see if the results include the name '''
  974. if not results:
  975. return False
  976. if Utils.find_result(results, _name):
  977. return True
  978. return False
  979. @staticmethod
  980. def find_result(results, _name):
  981. ''' Find the specified result by name'''
  982. rval = None
  983. for result in results:
  984. if 'metadata' in result and result['metadata']['name'] == _name:
  985. rval = result
  986. break
  987. return rval
  988. @staticmethod
  989. def get_resource_file(sfile, sfile_type='yaml'):
  990. ''' return the service file '''
  991. contents = None
  992. with open(sfile) as sfd:
  993. contents = sfd.read()
  994. if sfile_type == 'yaml':
  995. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  996. # pylint: disable=no-member
  997. if hasattr(yaml, 'RoundTripLoader'):
  998. contents = yaml.load(contents, yaml.RoundTripLoader)
  999. else:
  1000. contents = yaml.safe_load(contents)
  1001. elif sfile_type == 'json':
  1002. contents = json.loads(contents)
  1003. return contents
  1004. @staticmethod
  1005. def filter_versions(stdout):
  1006. ''' filter the oc version output '''
  1007. version_dict = {}
  1008. version_search = ['oc', 'openshift', 'kubernetes']
  1009. for line in stdout.strip().split('\n'):
  1010. for term in version_search:
  1011. if not line:
  1012. continue
  1013. if line.startswith(term):
  1014. version_dict[term] = line.split()[-1]
  1015. # horrible hack to get openshift version in Openshift 3.2
  1016. # By default "oc version in 3.2 does not return an "openshift" version
  1017. if "openshift" not in version_dict:
  1018. version_dict["openshift"] = version_dict["oc"]
  1019. return version_dict
  1020. @staticmethod
  1021. def add_custom_versions(versions):
  1022. ''' create custom versions strings '''
  1023. versions_dict = {}
  1024. for tech, version in versions.items():
  1025. # clean up "-" from version
  1026. if "-" in version:
  1027. version = version.split("-")[0]
  1028. if version.startswith('v'):
  1029. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1030. # "v3.3.0.33" is what we have, we want "3.3"
  1031. versions_dict[tech + '_short'] = version[1:4]
  1032. return versions_dict
  1033. @staticmethod
  1034. def openshift_installed():
  1035. ''' check if openshift is installed '''
  1036. import rpm
  1037. transaction_set = rpm.TransactionSet()
  1038. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1039. return rpmquery.count() > 0
  1040. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1041. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1042. @staticmethod
  1043. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1044. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1045. # Currently these values are autogenerated and we do not need to check them
  1046. skip = ['metadata', 'status']
  1047. if skip_keys:
  1048. skip.extend(skip_keys)
  1049. for key, value in result_def.items():
  1050. if key in skip:
  1051. continue
  1052. # Both are lists
  1053. if isinstance(value, list):
  1054. if key not in user_def:
  1055. if debug:
  1056. print('User data does not have key [%s]' % key)
  1057. print('User data: %s' % user_def)
  1058. return False
  1059. if not isinstance(user_def[key], list):
  1060. if debug:
  1061. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1062. return False
  1063. if len(user_def[key]) != len(value):
  1064. if debug:
  1065. print("List lengths are not equal.")
  1066. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1067. print("user_def: %s" % user_def[key])
  1068. print("value: %s" % value)
  1069. return False
  1070. for values in zip(user_def[key], value):
  1071. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1072. if debug:
  1073. print('sending list - list')
  1074. print(type(values[0]))
  1075. print(type(values[1]))
  1076. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1077. if not result:
  1078. print('list compare returned false')
  1079. return False
  1080. elif value != user_def[key]:
  1081. if debug:
  1082. print('value should be identical')
  1083. print(user_def[key])
  1084. print(value)
  1085. return False
  1086. # recurse on a dictionary
  1087. elif isinstance(value, dict):
  1088. if key not in user_def:
  1089. if debug:
  1090. print("user_def does not have key [%s]" % key)
  1091. return False
  1092. if not isinstance(user_def[key], dict):
  1093. if debug:
  1094. print("dict returned false: not instance of dict")
  1095. return False
  1096. # before passing ensure keys match
  1097. api_values = set(value.keys()) - set(skip)
  1098. user_values = set(user_def[key].keys()) - set(skip)
  1099. if api_values != user_values:
  1100. if debug:
  1101. print("keys are not equal in dict")
  1102. print(user_values)
  1103. print(api_values)
  1104. return False
  1105. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1106. if not result:
  1107. if debug:
  1108. print("dict returned false")
  1109. print(result)
  1110. return False
  1111. # Verify each key, value pair is the same
  1112. else:
  1113. if key not in user_def or value != user_def[key]:
  1114. if debug:
  1115. print("value not equal; user_def does not have key")
  1116. print(key)
  1117. print(value)
  1118. if key in user_def:
  1119. print(user_def[key])
  1120. return False
  1121. if debug:
  1122. print('returning true')
  1123. return True
  1124. class OpenShiftCLIConfig(object):
  1125. '''Generic Config'''
  1126. def __init__(self, rname, namespace, kubeconfig, options):
  1127. self.kubeconfig = kubeconfig
  1128. self.name = rname
  1129. self.namespace = namespace
  1130. self._options = options
  1131. @property
  1132. def config_options(self):
  1133. ''' return config options '''
  1134. return self._options
  1135. def to_option_list(self, ascommalist=''):
  1136. '''return all options as a string
  1137. if ascommalist is set to the name of a key, and
  1138. the value of that key is a dict, format the dict
  1139. as a list of comma delimited key=value pairs'''
  1140. return self.stringify(ascommalist)
  1141. def stringify(self, ascommalist=''):
  1142. ''' return the options hash as cli params in a string
  1143. if ascommalist is set to the name of a key, and
  1144. the value of that key is a dict, format the dict
  1145. as a list of comma delimited key=value pairs '''
  1146. rval = []
  1147. for key in sorted(self.config_options.keys()):
  1148. data = self.config_options[key]
  1149. if data['include'] \
  1150. and (data['value'] is not None or isinstance(data['value'], int)):
  1151. if key == ascommalist:
  1152. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1153. else:
  1154. val = data['value']
  1155. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1156. return rval
  1157. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1158. # -*- -*- -*- Begin included fragment: lib/rule.py -*- -*- -*-
  1159. class Rule(object):
  1160. '''class to represent a clusterrole rule
  1161. Example Rule Object's yaml:
  1162. - apiGroups:
  1163. - ""
  1164. attributeRestrictions: null
  1165. resources:
  1166. - persistentvolumes
  1167. verbs:
  1168. - create
  1169. - delete
  1170. - deletecollection
  1171. - get
  1172. - list
  1173. - patch
  1174. - update
  1175. - watch
  1176. '''
  1177. def __init__(self,
  1178. api_groups=None,
  1179. attr_restrictions=None,
  1180. resources=None,
  1181. verbs=None):
  1182. self.__api_groups = api_groups if api_groups is not None else [""]
  1183. self.__verbs = verbs if verbs is not None else []
  1184. self.__resources = resources if resources is not None else []
  1185. self.__attribute_restrictions = attr_restrictions if attr_restrictions is not None else None
  1186. @property
  1187. def verbs(self):
  1188. '''property for verbs'''
  1189. if self.__verbs is None:
  1190. return []
  1191. return self.__verbs
  1192. @verbs.setter
  1193. def verbs(self, data):
  1194. '''setter for verbs'''
  1195. self.__verbs = data
  1196. @property
  1197. def api_groups(self):
  1198. '''property for api_groups'''
  1199. if self.__api_groups is None:
  1200. return []
  1201. return self.__api_groups
  1202. @api_groups.setter
  1203. def api_groups(self, data):
  1204. '''setter for api_groups'''
  1205. self.__api_groups = data
  1206. @property
  1207. def resources(self):
  1208. '''property for resources'''
  1209. if self.__resources is None:
  1210. return []
  1211. return self.__resources
  1212. @resources.setter
  1213. def resources(self, data):
  1214. '''setter for resources'''
  1215. self.__resources = data
  1216. @property
  1217. def attribute_restrictions(self):
  1218. '''property for attribute_restrictions'''
  1219. return self.__attribute_restrictions
  1220. @attribute_restrictions.setter
  1221. def attribute_restrictions(self, data):
  1222. '''setter for attribute_restrictions'''
  1223. self.__attribute_restrictions = data
  1224. def add_verb(self, inc_verb):
  1225. '''add a verb to the verbs array'''
  1226. self.verbs.append(inc_verb)
  1227. def add_api_group(self, inc_apigroup):
  1228. '''add an api_group to the api_groups array'''
  1229. self.api_groups.append(inc_apigroup)
  1230. def add_resource(self, inc_resource):
  1231. '''add an resource to the resources array'''
  1232. self.resources.append(inc_resource)
  1233. def remove_verb(self, inc_verb):
  1234. '''add a verb to the verbs array'''
  1235. try:
  1236. self.verbs.remove(inc_verb)
  1237. return True
  1238. except ValueError:
  1239. pass
  1240. return False
  1241. def remove_api_group(self, inc_api_group):
  1242. '''add a verb to the verbs array'''
  1243. try:
  1244. self.api_groups.remove(inc_api_group)
  1245. return True
  1246. except ValueError:
  1247. pass
  1248. return False
  1249. def remove_resource(self, inc_resource):
  1250. '''add a verb to the verbs array'''
  1251. try:
  1252. self.resources.remove(inc_resource)
  1253. return True
  1254. except ValueError:
  1255. pass
  1256. return False
  1257. def __eq__(self, other):
  1258. '''return whether rules are equal'''
  1259. return (self.attribute_restrictions == other.attribute_restrictions and
  1260. self.api_groups == other.api_groups and
  1261. self.resources == other.resources and
  1262. self.verbs == other.verbs)
  1263. @staticmethod
  1264. def parse_rules(inc_rules):
  1265. '''create rules from an array'''
  1266. results = []
  1267. for rule in inc_rules:
  1268. results.append(Rule(rule.get('apiGroups', ['']),
  1269. rule.get('attributeRestrictions', None),
  1270. rule.get('resources', []),
  1271. rule.get('verbs', [])))
  1272. return results
  1273. # -*- -*- -*- End included fragment: lib/rule.py -*- -*- -*-
  1274. # -*- -*- -*- Begin included fragment: lib/clusterrole.py -*- -*- -*-
  1275. # pylint: disable=too-many-public-methods
  1276. class ClusterRole(Yedit):
  1277. ''' Class to model an openshift ClusterRole'''
  1278. rules_path = "rules"
  1279. def __init__(self, name=None, content=None):
  1280. ''' Constructor for clusterrole '''
  1281. if content is None:
  1282. content = ClusterRole.builder(name).yaml_dict
  1283. super(ClusterRole, self).__init__(content=content)
  1284. self.__rules = Rule.parse_rules(self.get(ClusterRole.rules_path)) or []
  1285. @property
  1286. def rules(self):
  1287. return self.__rules
  1288. @rules.setter
  1289. def rules(self, data):
  1290. self.__rules = data
  1291. self.put(ClusterRole.rules_path, self.__rules)
  1292. def rule_exists(self, inc_rule):
  1293. '''attempt to find the inc_rule in the rules list'''
  1294. for rule in self.rules:
  1295. if rule == inc_rule:
  1296. return True
  1297. return False
  1298. def compare(self, other, verbose=False):
  1299. '''compare function for clusterrole'''
  1300. for rule in other.rules:
  1301. if rule not in self.rules:
  1302. if verbose:
  1303. print('Rule in other not found in self. [{}]'.format(rule))
  1304. return False
  1305. for rule in self.rules:
  1306. if rule not in other.rules:
  1307. if verbose:
  1308. print('Rule in self not found in other. [{}]'.format(rule))
  1309. return False
  1310. return True
  1311. @staticmethod
  1312. def builder(name='default_clusterrole', rules=None):
  1313. '''return a clusterrole with name and/or rules'''
  1314. if rules is None:
  1315. rules = [{'apiGroups': [""],
  1316. 'attributeRestrictions': None,
  1317. 'verbs': [],
  1318. 'resources': []}]
  1319. content = {
  1320. 'apiVersion': 'v1',
  1321. 'kind': 'ClusterRole',
  1322. 'metadata': {'name': '{}'.format(name)},
  1323. 'rules': rules,
  1324. }
  1325. return ClusterRole(content=content)
  1326. # -*- -*- -*- End included fragment: lib/clusterrole.py -*- -*- -*-
  1327. # -*- -*- -*- Begin included fragment: class/oc_clusterrole.py -*- -*- -*-
  1328. # pylint: disable=too-many-instance-attributes
  1329. class OCClusterRole(OpenShiftCLI):
  1330. ''' Class to manage clusterrole objects'''
  1331. kind = 'clusterrole'
  1332. def __init__(self,
  1333. name,
  1334. rules=None,
  1335. kubeconfig=None,
  1336. verbose=False):
  1337. ''' Constructor for OCClusterRole '''
  1338. super(OCClusterRole, self).__init__(None, kubeconfig=kubeconfig, verbose=verbose)
  1339. self.verbose = verbose
  1340. self.name = name
  1341. self._clusterrole = None
  1342. self._inc_clusterrole = ClusterRole.builder(name, rules)
  1343. @property
  1344. def clusterrole(self):
  1345. ''' property for clusterrole'''
  1346. if self._clusterrole is None:
  1347. self.get()
  1348. return self._clusterrole
  1349. @clusterrole.setter
  1350. def clusterrole(self, data):
  1351. ''' setter function for clusterrole property'''
  1352. self._clusterrole = data
  1353. @property
  1354. def inc_clusterrole(self):
  1355. ''' property for inc_clusterrole'''
  1356. return self._inc_clusterrole
  1357. @inc_clusterrole.setter
  1358. def inc_clusterrole(self, data):
  1359. ''' setter function for inc_clusterrole property'''
  1360. self._inc_clusterrole = data
  1361. def exists(self):
  1362. ''' return whether a clusterrole exists '''
  1363. if self.clusterrole:
  1364. return True
  1365. return False
  1366. def get(self):
  1367. '''return a clusterrole '''
  1368. result = self._get(self.kind, self.name)
  1369. if result['returncode'] == 0:
  1370. self.clusterrole = ClusterRole(content=result['results'][0])
  1371. result['results'] = self.clusterrole.yaml_dict
  1372. elif '"{}" not found'.format(self.name) in result['stderr']:
  1373. result['returncode'] = 0
  1374. self.clusterrole = None
  1375. return result
  1376. def delete(self):
  1377. '''delete the object'''
  1378. return self._delete(self.kind, self.name)
  1379. def create(self):
  1380. '''create a clusterrole from the proposed incoming clusterrole'''
  1381. return self._create_from_content(self.name, self.inc_clusterrole.yaml_dict)
  1382. def update(self):
  1383. '''update a project'''
  1384. return self._replace_content(self.kind, self.name, self.inc_clusterrole.yaml_dict)
  1385. def needs_update(self):
  1386. ''' verify an update is needed'''
  1387. return not self.clusterrole.compare(self.inc_clusterrole, self.verbose)
  1388. # pylint: disable=too-many-return-statements,too-many-branches
  1389. @staticmethod
  1390. def run_ansible(params, check_mode):
  1391. '''run the idempotent ansible code'''
  1392. oc_clusterrole = OCClusterRole(params['name'],
  1393. params['rules'],
  1394. params['kubeconfig'],
  1395. params['debug'])
  1396. state = params['state']
  1397. api_rval = oc_clusterrole.get()
  1398. #####
  1399. # Get
  1400. #####
  1401. if state == 'list':
  1402. return {'changed': False, 'results': api_rval, 'state': state}
  1403. ########
  1404. # Delete
  1405. ########
  1406. if state == 'absent':
  1407. if oc_clusterrole.exists():
  1408. if check_mode:
  1409. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1410. api_rval = oc_clusterrole.delete()
  1411. if api_rval['returncode'] != 0:
  1412. return {'failed': True, 'msg': api_rval}
  1413. return {'changed': True, 'results': api_rval, 'state': state}
  1414. return {'changed': False, 'state': state}
  1415. if state == 'present':
  1416. ########
  1417. # Create
  1418. ########
  1419. if not oc_clusterrole.exists():
  1420. if check_mode:
  1421. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  1422. # Create it here
  1423. api_rval = oc_clusterrole.create()
  1424. if api_rval['returncode'] != 0:
  1425. return {'failed': True, 'msg': api_rval}
  1426. # return the created object
  1427. api_rval = oc_clusterrole.get()
  1428. if api_rval['returncode'] != 0:
  1429. return {'failed': True, 'msg': api_rval}
  1430. return {'changed': True, 'results': api_rval, 'state': state}
  1431. ########
  1432. # Update
  1433. ########
  1434. if oc_clusterrole.needs_update():
  1435. if check_mode:
  1436. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
  1437. api_rval = oc_clusterrole.update()
  1438. if api_rval['returncode'] != 0:
  1439. return {'failed': True, 'msg': api_rval}
  1440. # return the created object
  1441. api_rval = oc_clusterrole.get()
  1442. if api_rval['returncode'] != 0:
  1443. return {'failed': True, 'msg': api_rval}
  1444. return {'changed': True, 'results': api_rval, 'state': state}
  1445. return {'changed': False, 'results': api_rval, 'state': state}
  1446. return {'failed': True,
  1447. 'changed': False,
  1448. 'msg': 'Unknown state passed. [%s]' % state}
  1449. # -*- -*- -*- End included fragment: class/oc_clusterrole.py -*- -*- -*-
  1450. # -*- -*- -*- Begin included fragment: ansible/oc_clusterrole.py -*- -*- -*-
  1451. def main():
  1452. '''
  1453. ansible oc module for clusterrole
  1454. '''
  1455. module = AnsibleModule(
  1456. argument_spec=dict(
  1457. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1458. state=dict(default='present', type='str',
  1459. choices=['present', 'absent', 'list']),
  1460. debug=dict(default=False, type='bool'),
  1461. name=dict(default=None, type='str'),
  1462. rules=dict(default=None, type='list'),
  1463. ),
  1464. supports_check_mode=True,
  1465. )
  1466. results = OCClusterRole.run_ansible(module.params, module.check_mode)
  1467. if 'failed' in results:
  1468. module.fail_json(**results)
  1469. module.exit_json(**results)
  1470. if __name__ == '__main__':
  1471. main()
  1472. # -*- -*- -*- End included fragment: ansible/oc_clusterrole.py -*- -*- -*-