oc_project.py 56 KB

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