oc_pvc.py 61 KB

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