oc_user.py 60 KB

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