oc_volume.py 66 KB

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