oc_user.py 58 KB

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