oc_env.py 66 KB

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