oc_env.py 66 KB

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