oc_clusterrole.py 61 KB

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