oc_clusterrole.py 59 KB

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