oc_pvc.py 62 KB

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