oc_env.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  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{}/_-]+)"
  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'])
  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. # We are removing the 'resourceVersion' to handle
  724. # a race condition when modifying oc objects
  725. yed = Yedit(fname)
  726. results = yed.delete('metadata.resourceVersion')
  727. if results[0]:
  728. yed.write()
  729. cmd = ['replace', '-f', fname]
  730. if force:
  731. cmd.append('--force')
  732. return self.openshift_cmd(cmd)
  733. def _create_from_content(self, rname, content):
  734. '''create a temporary file and then call oc create on it'''
  735. fname = Utils.create_tmpfile(rname + '-')
  736. yed = Yedit(fname, content=content)
  737. yed.write()
  738. atexit.register(Utils.cleanup, [fname])
  739. return self._create(fname)
  740. def _create(self, fname):
  741. '''call oc create on a filename'''
  742. return self.openshift_cmd(['create', '-f', fname])
  743. def _delete(self, resource, name=None, selector=None):
  744. '''call oc delete on a resource'''
  745. cmd = ['delete', resource]
  746. if selector is not None:
  747. cmd.append('--selector={}'.format(selector))
  748. elif name is not None:
  749. cmd.append(name)
  750. else:
  751. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  752. return self.openshift_cmd(cmd)
  753. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  754. '''process a template
  755. template_name: the name of the template to process
  756. create: whether to send to oc create after processing
  757. params: the parameters for the template
  758. template_data: the incoming template's data; instead of a file
  759. '''
  760. cmd = ['process']
  761. if template_data:
  762. cmd.extend(['-f', '-'])
  763. else:
  764. cmd.append(template_name)
  765. if params:
  766. param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
  767. cmd.append('-v')
  768. cmd.extend(param_str)
  769. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  770. if results['returncode'] != 0 or not create:
  771. return results
  772. fname = Utils.create_tmpfile(template_name + '-')
  773. yed = Yedit(fname, results['results'])
  774. yed.write()
  775. atexit.register(Utils.cleanup, [fname])
  776. return self.openshift_cmd(['create', '-f', fname])
  777. def _get(self, resource, name=None, selector=None):
  778. '''return a resource by name '''
  779. cmd = ['get', resource]
  780. if selector is not None:
  781. cmd.append('--selector={}'.format(selector))
  782. elif name is not None:
  783. cmd.append(name)
  784. cmd.extend(['-o', 'json'])
  785. rval = self.openshift_cmd(cmd, output=True)
  786. # Ensure results are retuned in an array
  787. if 'items' in rval:
  788. rval['results'] = rval['items']
  789. elif not isinstance(rval['results'], list):
  790. rval['results'] = [rval['results']]
  791. return rval
  792. def _schedulable(self, node=None, selector=None, schedulable=True):
  793. ''' perform oadm manage-node scheduable '''
  794. cmd = ['manage-node']
  795. if node:
  796. cmd.extend(node)
  797. else:
  798. cmd.append('--selector={}'.format(selector))
  799. cmd.append('--schedulable={}'.format(schedulable))
  800. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  801. def _list_pods(self, node=None, selector=None, pod_selector=None):
  802. ''' perform oadm list pods
  803. node: the node in which to list pods
  804. selector: the label selector filter if provided
  805. pod_selector: the pod selector filter if provided
  806. '''
  807. cmd = ['manage-node']
  808. if node:
  809. cmd.extend(node)
  810. else:
  811. cmd.append('--selector={}'.format(selector))
  812. if pod_selector:
  813. cmd.append('--pod-selector={}'.format(pod_selector))
  814. cmd.extend(['--list-pods', '-o', 'json'])
  815. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  816. # pylint: disable=too-many-arguments
  817. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  818. ''' perform oadm manage-node evacuate '''
  819. cmd = ['manage-node']
  820. if node:
  821. cmd.extend(node)
  822. else:
  823. cmd.append('--selector={}'.format(selector))
  824. if dry_run:
  825. cmd.append('--dry-run')
  826. if pod_selector:
  827. cmd.append('--pod-selector={}'.format(pod_selector))
  828. if grace_period:
  829. cmd.append('--grace-period={}'.format(int(grace_period)))
  830. if force:
  831. cmd.append('--force')
  832. cmd.append('--evacuate')
  833. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  834. def _version(self):
  835. ''' return the openshift version'''
  836. return self.openshift_cmd(['version'], output=True, output_type='raw')
  837. def _import_image(self, url=None, name=None, tag=None):
  838. ''' perform image import '''
  839. cmd = ['import-image']
  840. image = '{0}'.format(name)
  841. if tag:
  842. image += ':{0}'.format(tag)
  843. cmd.append(image)
  844. if url:
  845. cmd.append('--from={0}/{1}'.format(url, image))
  846. cmd.append('-n{0}'.format(self.namespace))
  847. cmd.append('--confirm')
  848. return self.openshift_cmd(cmd)
  849. def _run(self, cmds, input_data):
  850. ''' Actually executes the command. This makes mocking easier. '''
  851. curr_env = os.environ.copy()
  852. curr_env.update({'KUBECONFIG': self.kubeconfig})
  853. proc = subprocess.Popen(cmds,
  854. stdin=subprocess.PIPE,
  855. stdout=subprocess.PIPE,
  856. stderr=subprocess.PIPE,
  857. env=curr_env)
  858. stdout, stderr = proc.communicate(input_data)
  859. return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
  860. # pylint: disable=too-many-arguments,too-many-branches
  861. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  862. '''Base command for oc '''
  863. cmds = [self.oc_binary]
  864. if oadm:
  865. cmds.append('adm')
  866. cmds.extend(cmd)
  867. if self.all_namespaces:
  868. cmds.extend(['--all-namespaces'])
  869. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  870. cmds.extend(['-n', self.namespace])
  871. if self.verbose:
  872. print(' '.join(cmds))
  873. try:
  874. returncode, stdout, stderr = self._run(cmds, input_data)
  875. except OSError as ex:
  876. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  877. rval = {"returncode": returncode,
  878. "cmd": ' '.join(cmds)}
  879. if output_type == 'json':
  880. rval['results'] = {}
  881. if output and stdout:
  882. try:
  883. rval['results'] = json.loads(stdout)
  884. except ValueError as verr:
  885. if "No JSON object could be decoded" in verr.args:
  886. rval['err'] = verr.args
  887. elif output_type == 'raw':
  888. rval['results'] = stdout if output else ''
  889. if self.verbose:
  890. print("STDOUT: {0}".format(stdout))
  891. print("STDERR: {0}".format(stderr))
  892. if 'err' in rval or returncode != 0:
  893. rval.update({"stderr": stderr,
  894. "stdout": stdout})
  895. return rval
  896. class Utils(object): # pragma: no cover
  897. ''' utilities for openshiftcli modules '''
  898. @staticmethod
  899. def _write(filename, contents):
  900. ''' Actually write the file contents to disk. This helps with mocking. '''
  901. with open(filename, 'w') as sfd:
  902. sfd.write(contents)
  903. @staticmethod
  904. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  905. ''' create a file in tmp with name and contents'''
  906. tmp = Utils.create_tmpfile(prefix=rname)
  907. if ftype == 'yaml':
  908. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  909. # pylint: disable=no-member
  910. if hasattr(yaml, 'RoundTripDumper'):
  911. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  912. else:
  913. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  914. elif ftype == 'json':
  915. Utils._write(tmp, json.dumps(data))
  916. else:
  917. Utils._write(tmp, data)
  918. # Register cleanup when module is done
  919. atexit.register(Utils.cleanup, [tmp])
  920. return tmp
  921. @staticmethod
  922. def create_tmpfile_copy(inc_file):
  923. '''create a temporary copy of a file'''
  924. tmpfile = Utils.create_tmpfile('lib_openshift-')
  925. Utils._write(tmpfile, open(inc_file).read())
  926. # Cleanup the tmpfile
  927. atexit.register(Utils.cleanup, [tmpfile])
  928. return tmpfile
  929. @staticmethod
  930. def create_tmpfile(prefix='tmp'):
  931. ''' Generates and returns a temporary file name '''
  932. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  933. return tmp.name
  934. @staticmethod
  935. def create_tmp_files_from_contents(content, content_type=None):
  936. '''Turn an array of dict: filename, content into a files array'''
  937. if not isinstance(content, list):
  938. content = [content]
  939. files = []
  940. for item in content:
  941. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  942. item['data'],
  943. ftype=content_type)
  944. files.append({'name': os.path.basename(item['path']),
  945. 'path': path})
  946. return files
  947. @staticmethod
  948. def cleanup(files):
  949. '''Clean up on exit '''
  950. for sfile in files:
  951. if os.path.exists(sfile):
  952. if os.path.isdir(sfile):
  953. shutil.rmtree(sfile)
  954. elif os.path.isfile(sfile):
  955. os.remove(sfile)
  956. @staticmethod
  957. def exists(results, _name):
  958. ''' Check to see if the results include the name '''
  959. if not results:
  960. return False
  961. if Utils.find_result(results, _name):
  962. return True
  963. return False
  964. @staticmethod
  965. def find_result(results, _name):
  966. ''' Find the specified result by name'''
  967. rval = None
  968. for result in results:
  969. if 'metadata' in result and result['metadata']['name'] == _name:
  970. rval = result
  971. break
  972. return rval
  973. @staticmethod
  974. def get_resource_file(sfile, sfile_type='yaml'):
  975. ''' return the service file '''
  976. contents = None
  977. with open(sfile) as sfd:
  978. contents = sfd.read()
  979. if sfile_type == 'yaml':
  980. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  981. # pylint: disable=no-member
  982. if hasattr(yaml, 'RoundTripLoader'):
  983. contents = yaml.load(contents, yaml.RoundTripLoader)
  984. else:
  985. contents = yaml.safe_load(contents)
  986. elif sfile_type == 'json':
  987. contents = json.loads(contents)
  988. return contents
  989. @staticmethod
  990. def filter_versions(stdout):
  991. ''' filter the oc version output '''
  992. version_dict = {}
  993. version_search = ['oc', 'openshift', 'kubernetes']
  994. for line in stdout.strip().split('\n'):
  995. for term in version_search:
  996. if not line:
  997. continue
  998. if line.startswith(term):
  999. version_dict[term] = line.split()[-1]
  1000. # horrible hack to get openshift version in Openshift 3.2
  1001. # By default "oc version in 3.2 does not return an "openshift" version
  1002. if "openshift" not in version_dict:
  1003. version_dict["openshift"] = version_dict["oc"]
  1004. return version_dict
  1005. @staticmethod
  1006. def add_custom_versions(versions):
  1007. ''' create custom versions strings '''
  1008. versions_dict = {}
  1009. for tech, version in versions.items():
  1010. # clean up "-" from version
  1011. if "-" in version:
  1012. version = version.split("-")[0]
  1013. if version.startswith('v'):
  1014. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1015. # "v3.3.0.33" is what we have, we want "3.3"
  1016. versions_dict[tech + '_short'] = version[1:4]
  1017. return versions_dict
  1018. @staticmethod
  1019. def openshift_installed():
  1020. ''' check if openshift is installed '''
  1021. import rpm
  1022. transaction_set = rpm.TransactionSet()
  1023. rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
  1024. return rpmquery.count() > 0
  1025. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1026. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1027. @staticmethod
  1028. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1029. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1030. # Currently these values are autogenerated and we do not need to check them
  1031. skip = ['metadata', 'status']
  1032. if skip_keys:
  1033. skip.extend(skip_keys)
  1034. for key, value in result_def.items():
  1035. if key in skip:
  1036. continue
  1037. # Both are lists
  1038. if isinstance(value, list):
  1039. if key not in user_def:
  1040. if debug:
  1041. print('User data does not have key [%s]' % key)
  1042. print('User data: %s' % user_def)
  1043. return False
  1044. if not isinstance(user_def[key], list):
  1045. if debug:
  1046. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1047. return False
  1048. if len(user_def[key]) != len(value):
  1049. if debug:
  1050. print("List lengths are not equal.")
  1051. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1052. print("user_def: %s" % user_def[key])
  1053. print("value: %s" % value)
  1054. return False
  1055. for values in zip(user_def[key], value):
  1056. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1057. if debug:
  1058. print('sending list - list')
  1059. print(type(values[0]))
  1060. print(type(values[1]))
  1061. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1062. if not result:
  1063. print('list compare returned false')
  1064. return False
  1065. elif value != user_def[key]:
  1066. if debug:
  1067. print('value should be identical')
  1068. print(user_def[key])
  1069. print(value)
  1070. return False
  1071. # recurse on a dictionary
  1072. elif isinstance(value, dict):
  1073. if key not in user_def:
  1074. if debug:
  1075. print("user_def does not have key [%s]" % key)
  1076. return False
  1077. if not isinstance(user_def[key], dict):
  1078. if debug:
  1079. print("dict returned false: not instance of dict")
  1080. return False
  1081. # before passing ensure keys match
  1082. api_values = set(value.keys()) - set(skip)
  1083. user_values = set(user_def[key].keys()) - set(skip)
  1084. if api_values != user_values:
  1085. if debug:
  1086. print("keys are not equal in dict")
  1087. print(user_values)
  1088. print(api_values)
  1089. return False
  1090. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1091. if not result:
  1092. if debug:
  1093. print("dict returned false")
  1094. print(result)
  1095. return False
  1096. # Verify each key, value pair is the same
  1097. else:
  1098. if key not in user_def or value != user_def[key]:
  1099. if debug:
  1100. print("value not equal; user_def does not have key")
  1101. print(key)
  1102. print(value)
  1103. if key in user_def:
  1104. print(user_def[key])
  1105. return False
  1106. if debug:
  1107. print('returning true')
  1108. return True
  1109. class OpenShiftCLIConfig(object):
  1110. '''Generic Config'''
  1111. def __init__(self, rname, namespace, kubeconfig, options):
  1112. self.kubeconfig = kubeconfig
  1113. self.name = rname
  1114. self.namespace = namespace
  1115. self._options = options
  1116. @property
  1117. def config_options(self):
  1118. ''' return config options '''
  1119. return self._options
  1120. def to_option_list(self, ascommalist=''):
  1121. '''return all options as a string
  1122. if ascommalist is set to the name of a key, and
  1123. the value of that key is a dict, format the dict
  1124. as a list of comma delimited key=value pairs'''
  1125. return self.stringify(ascommalist)
  1126. def stringify(self, ascommalist=''):
  1127. ''' return the options hash as cli params in a string
  1128. if ascommalist is set to the name of a key, and
  1129. the value of that key is a dict, format the dict
  1130. as a list of comma delimited key=value pairs '''
  1131. rval = []
  1132. for key in sorted(self.config_options.keys()):
  1133. data = self.config_options[key]
  1134. if data['include'] \
  1135. and (data['value'] is not None or isinstance(data['value'], int)):
  1136. if key == ascommalist:
  1137. val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
  1138. else:
  1139. val = data['value']
  1140. rval.append('--{}={}'.format(key.replace('_', '-'), val))
  1141. return rval
  1142. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1143. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1144. # pylint: disable=too-many-public-methods
  1145. class DeploymentConfig(Yedit):
  1146. ''' Class to model an openshift DeploymentConfig'''
  1147. default_deployment_config = '''
  1148. apiVersion: v1
  1149. kind: DeploymentConfig
  1150. metadata:
  1151. name: default_dc
  1152. namespace: default
  1153. spec:
  1154. replicas: 0
  1155. selector:
  1156. default_dc: default_dc
  1157. strategy:
  1158. resources: {}
  1159. rollingParams:
  1160. intervalSeconds: 1
  1161. maxSurge: 0
  1162. maxUnavailable: 25%
  1163. timeoutSeconds: 600
  1164. updatePercent: -25
  1165. updatePeriodSeconds: 1
  1166. type: Rolling
  1167. template:
  1168. metadata:
  1169. spec:
  1170. containers:
  1171. - env:
  1172. - name: default
  1173. value: default
  1174. image: default
  1175. imagePullPolicy: IfNotPresent
  1176. name: default_dc
  1177. ports:
  1178. - containerPort: 8000
  1179. hostPort: 8000
  1180. protocol: TCP
  1181. name: default_port
  1182. resources: {}
  1183. terminationMessagePath: /dev/termination-log
  1184. dnsPolicy: ClusterFirst
  1185. hostNetwork: true
  1186. nodeSelector:
  1187. type: compute
  1188. restartPolicy: Always
  1189. securityContext: {}
  1190. serviceAccount: default
  1191. serviceAccountName: default
  1192. terminationGracePeriodSeconds: 30
  1193. triggers:
  1194. - type: ConfigChange
  1195. '''
  1196. replicas_path = "spec.replicas"
  1197. env_path = "spec.template.spec.containers[0].env"
  1198. volumes_path = "spec.template.spec.volumes"
  1199. container_path = "spec.template.spec.containers"
  1200. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1201. def __init__(self, content=None):
  1202. ''' Constructor for deploymentconfig '''
  1203. if not content:
  1204. content = DeploymentConfig.default_deployment_config
  1205. super(DeploymentConfig, self).__init__(content=content)
  1206. def add_env_value(self, key, value):
  1207. ''' add key, value pair to env array '''
  1208. rval = False
  1209. env = self.get_env_vars()
  1210. if env:
  1211. env.append({'name': key, 'value': value})
  1212. rval = True
  1213. else:
  1214. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1215. rval = result[0]
  1216. return rval
  1217. def exists_env_value(self, key, value):
  1218. ''' return whether a key, value pair exists '''
  1219. results = self.get_env_vars()
  1220. if not results:
  1221. return False
  1222. for result in results:
  1223. if result['name'] == key and result['value'] == value:
  1224. return True
  1225. return False
  1226. def exists_env_key(self, key):
  1227. ''' return whether a key, value pair exists '''
  1228. results = self.get_env_vars()
  1229. if not results:
  1230. return False
  1231. for result in results:
  1232. if result['name'] == key:
  1233. return True
  1234. return False
  1235. def get_env_var(self, key):
  1236. '''return a environment variables '''
  1237. results = self.get(DeploymentConfig.env_path) or []
  1238. if not results:
  1239. return None
  1240. for env_var in results:
  1241. if env_var['name'] == key:
  1242. return env_var
  1243. return None
  1244. def get_env_vars(self):
  1245. '''return a environment variables '''
  1246. return self.get(DeploymentConfig.env_path) or []
  1247. def delete_env_var(self, keys):
  1248. '''delete a list of keys '''
  1249. if not isinstance(keys, list):
  1250. keys = [keys]
  1251. env_vars_array = self.get_env_vars()
  1252. modified = False
  1253. idx = None
  1254. for key in keys:
  1255. for env_idx, env_var in enumerate(env_vars_array):
  1256. if env_var['name'] == key:
  1257. idx = env_idx
  1258. break
  1259. if idx:
  1260. modified = True
  1261. del env_vars_array[idx]
  1262. if modified:
  1263. return True
  1264. return False
  1265. def update_env_var(self, key, value):
  1266. '''place an env in the env var list'''
  1267. env_vars_array = self.get_env_vars()
  1268. idx = None
  1269. for env_idx, env_var in enumerate(env_vars_array):
  1270. if env_var['name'] == key:
  1271. idx = env_idx
  1272. break
  1273. if idx:
  1274. env_vars_array[idx]['value'] = value
  1275. else:
  1276. self.add_env_value(key, value)
  1277. return True
  1278. def exists_volume_mount(self, volume_mount):
  1279. ''' return whether a volume mount exists '''
  1280. exist_volume_mounts = self.get_volume_mounts()
  1281. if not exist_volume_mounts:
  1282. return False
  1283. volume_mount_found = False
  1284. for exist_volume_mount in exist_volume_mounts:
  1285. if exist_volume_mount['name'] == volume_mount['name']:
  1286. volume_mount_found = True
  1287. break
  1288. return volume_mount_found
  1289. def exists_volume(self, volume):
  1290. ''' return whether a volume exists '''
  1291. exist_volumes = self.get_volumes()
  1292. volume_found = False
  1293. for exist_volume in exist_volumes:
  1294. if exist_volume['name'] == volume['name']:
  1295. volume_found = True
  1296. break
  1297. return volume_found
  1298. def find_volume_by_name(self, volume, mounts=False):
  1299. ''' return the index of a volume '''
  1300. volumes = []
  1301. if mounts:
  1302. volumes = self.get_volume_mounts()
  1303. else:
  1304. volumes = self.get_volumes()
  1305. for exist_volume in volumes:
  1306. if exist_volume['name'] == volume['name']:
  1307. return exist_volume
  1308. return None
  1309. def get_replicas(self):
  1310. ''' return replicas setting '''
  1311. return self.get(DeploymentConfig.replicas_path)
  1312. def get_volume_mounts(self):
  1313. '''return volume mount information '''
  1314. return self.get_volumes(mounts=True)
  1315. def get_volumes(self, mounts=False):
  1316. '''return volume mount information '''
  1317. if mounts:
  1318. return self.get(DeploymentConfig.volume_mounts_path) or []
  1319. return self.get(DeploymentConfig.volumes_path) or []
  1320. def delete_volume_by_name(self, volume):
  1321. '''delete a volume '''
  1322. modified = False
  1323. exist_volume_mounts = self.get_volume_mounts()
  1324. exist_volumes = self.get_volumes()
  1325. del_idx = None
  1326. for idx, exist_volume in enumerate(exist_volumes):
  1327. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1328. del_idx = idx
  1329. break
  1330. if del_idx != None:
  1331. del exist_volumes[del_idx]
  1332. modified = True
  1333. del_idx = None
  1334. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1335. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1336. del_idx = idx
  1337. break
  1338. if del_idx != None:
  1339. del exist_volume_mounts[idx]
  1340. modified = True
  1341. return modified
  1342. def add_volume_mount(self, volume_mount):
  1343. ''' add a volume or volume mount to the proper location '''
  1344. exist_volume_mounts = self.get_volume_mounts()
  1345. if not exist_volume_mounts and volume_mount:
  1346. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1347. else:
  1348. exist_volume_mounts.append(volume_mount)
  1349. def add_volume(self, volume):
  1350. ''' add a volume or volume mount to the proper location '''
  1351. exist_volumes = self.get_volumes()
  1352. if not volume:
  1353. return
  1354. if not exist_volumes:
  1355. self.put(DeploymentConfig.volumes_path, [volume])
  1356. else:
  1357. exist_volumes.append(volume)
  1358. def update_replicas(self, replicas):
  1359. ''' update replicas value '''
  1360. self.put(DeploymentConfig.replicas_path, replicas)
  1361. def update_volume(self, volume):
  1362. '''place an env in the env var list'''
  1363. exist_volumes = self.get_volumes()
  1364. if not volume:
  1365. return False
  1366. # update the volume
  1367. update_idx = None
  1368. for idx, exist_vol in enumerate(exist_volumes):
  1369. if exist_vol['name'] == volume['name']:
  1370. update_idx = idx
  1371. break
  1372. if update_idx != None:
  1373. exist_volumes[update_idx] = volume
  1374. else:
  1375. self.add_volume(volume)
  1376. return True
  1377. def update_volume_mount(self, volume_mount):
  1378. '''place an env in the env var list'''
  1379. modified = False
  1380. exist_volume_mounts = self.get_volume_mounts()
  1381. if not volume_mount:
  1382. return False
  1383. # update the volume mount
  1384. for exist_vol_mount in exist_volume_mounts:
  1385. if exist_vol_mount['name'] == volume_mount['name']:
  1386. if 'mountPath' in exist_vol_mount and \
  1387. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1388. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1389. modified = True
  1390. break
  1391. if not modified:
  1392. self.add_volume_mount(volume_mount)
  1393. modified = True
  1394. return modified
  1395. def needs_update_volume(self, volume, volume_mount):
  1396. ''' verify a volume update is needed '''
  1397. exist_volume = self.find_volume_by_name(volume)
  1398. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1399. results = []
  1400. results.append(exist_volume['name'] == volume['name'])
  1401. if 'secret' in volume:
  1402. results.append('secret' in exist_volume)
  1403. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1404. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1405. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1406. elif 'emptyDir' in volume:
  1407. results.append(exist_volume_mount['name'] == volume['name'])
  1408. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1409. elif 'persistentVolumeClaim' in volume:
  1410. pvc = 'persistentVolumeClaim'
  1411. results.append(pvc in exist_volume)
  1412. if results[-1]:
  1413. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1414. if 'claimSize' in volume[pvc]:
  1415. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1416. elif 'hostpath' in volume:
  1417. results.append('hostPath' in exist_volume)
  1418. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1419. return not all(results)
  1420. def needs_update_replicas(self, replicas):
  1421. ''' verify whether a replica update is needed '''
  1422. current_reps = self.get(DeploymentConfig.replicas_path)
  1423. return not current_reps == replicas
  1424. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1425. # -*- -*- -*- Begin included fragment: class/oc_env.py -*- -*- -*-
  1426. # pylint: disable=too-many-instance-attributes
  1427. class OCEnv(OpenShiftCLI):
  1428. ''' Class to wrap the oc command line tools '''
  1429. container_path = {"pod": "spec.containers[0].env",
  1430. "dc": "spec.template.spec.containers[0].env",
  1431. "rc": "spec.template.spec.containers[0].env",
  1432. }
  1433. # pylint allows 5. we need 6
  1434. # pylint: disable=too-many-arguments
  1435. def __init__(self,
  1436. namespace,
  1437. kind,
  1438. env_vars,
  1439. resource_name=None,
  1440. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1441. verbose=False):
  1442. ''' Constructor for OpenshiftOC '''
  1443. super(OCEnv, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose)
  1444. self.kind = kind
  1445. self.name = resource_name
  1446. self.env_vars = env_vars
  1447. self._resource = None
  1448. @property
  1449. def resource(self):
  1450. ''' property function for resource var'''
  1451. if not self._resource:
  1452. self.get()
  1453. return self._resource
  1454. @resource.setter
  1455. def resource(self, data):
  1456. ''' setter function for resource var'''
  1457. self._resource = data
  1458. def key_value_exists(self, key, value):
  1459. ''' return whether a key, value pair exists '''
  1460. return self.resource.exists_env_value(key, value)
  1461. def key_exists(self, key):
  1462. ''' return whether a key exists '''
  1463. return self.resource.exists_env_key(key)
  1464. def get(self):
  1465. '''return environment variables '''
  1466. result = self._get(self.kind, self.name)
  1467. if result['returncode'] == 0:
  1468. if self.kind == 'dc':
  1469. self.resource = DeploymentConfig(content=result['results'][0])
  1470. result['results'] = self.resource.get(OCEnv.container_path[self.kind]) or []
  1471. return result
  1472. def delete(self):
  1473. ''' delete environment variables '''
  1474. if self.resource.delete_env_var(self.env_vars.keys()):
  1475. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1476. return {'returncode': 0, 'changed': False}
  1477. def put(self):
  1478. '''place env vars into dc '''
  1479. for update_key, update_value in self.env_vars.items():
  1480. self.resource.update_env_var(update_key, update_value)
  1481. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1482. # pylint: disable=too-many-return-statements
  1483. @staticmethod
  1484. def run_ansible(params, check_mode):
  1485. '''run the idempotent ansible code'''
  1486. ocenv = OCEnv(params['namespace'],
  1487. params['kind'],
  1488. params['env_vars'],
  1489. resource_name=params['name'],
  1490. kubeconfig=params['kubeconfig'],
  1491. verbose=params['debug'])
  1492. state = params['state']
  1493. api_rval = ocenv.get()
  1494. #####
  1495. # Get
  1496. #####
  1497. if state == 'list':
  1498. return {'changed': False, 'results': api_rval['results'], 'state': "list"}
  1499. ########
  1500. # Delete
  1501. ########
  1502. if state == 'absent':
  1503. for key in params.get('env_vars', {}).keys():
  1504. if ocenv.resource.exists_env_key(key):
  1505. if check_mode:
  1506. return {'changed': False,
  1507. 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1508. api_rval = ocenv.delete()
  1509. return {'changed': True, 'state': 'absent'}
  1510. return {'changed': False, 'state': 'absent'}
  1511. if state == 'present':
  1512. ########
  1513. # Create
  1514. ########
  1515. for key, value in params.get('env_vars', {}).items():
  1516. if not ocenv.key_value_exists(key, value):
  1517. if check_mode:
  1518. return {'changed': False,
  1519. 'msg': 'CHECK_MODE: Would have performed a create.'}
  1520. # Create it here
  1521. api_rval = ocenv.put()
  1522. if api_rval['returncode'] != 0:
  1523. return {'failed': True, 'msg': api_rval}
  1524. # return the created object
  1525. api_rval = ocenv.get()
  1526. if api_rval['returncode'] != 0:
  1527. return {'failed': True, 'msg': api_rval}
  1528. return {'changed': True, 'results': api_rval['results'], 'state': 'present'}
  1529. return {'changed': False, 'results': api_rval['results'], 'state': 'present'}
  1530. return {'failed': True,
  1531. 'changed': False,
  1532. 'msg': 'Unknown state passed. %s' % state}
  1533. # -*- -*- -*- End included fragment: class/oc_env.py -*- -*- -*-
  1534. # -*- -*- -*- Begin included fragment: ansible/oc_env.py -*- -*- -*-
  1535. def main():
  1536. '''
  1537. ansible oc module for environment variables
  1538. '''
  1539. module = AnsibleModule(
  1540. argument_spec=dict(
  1541. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1542. state=dict(default='present', type='str',
  1543. choices=['present', 'absent', 'list']),
  1544. debug=dict(default=False, type='bool'),
  1545. kind=dict(default='rc', choices=['dc', 'rc', 'pods'], type='str'),
  1546. namespace=dict(default='default', type='str'),
  1547. name=dict(default=None, required=True, type='str'),
  1548. env_vars=dict(default=None, type='dict'),
  1549. ),
  1550. mutually_exclusive=[["content", "files"]],
  1551. supports_check_mode=True,
  1552. )
  1553. results = OCEnv.run_ansible(module.params, module.check_mode)
  1554. if 'failed' in results:
  1555. module.fail_json(**results)
  1556. module.exit_json(**results)
  1557. if __name__ == '__main__':
  1558. main()
  1559. # -*- -*- -*- End included fragment: ansible/oc_env.py -*- -*- -*-