oc_pvc.py 60 KB

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