oc_env.py 64 KB

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