oc_pvc.py 61 KB

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