oc_env.py 66 KB

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