oc_env.py 65 KB

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