oc_env.py 64 KB

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