oc_env.py 63 KB

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