oc_volume.py 69 KB

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