oc_volume.py 68 KB

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