oc_clusterrole.py 60 KB

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