oc_pvc.py 56 KB

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