oc_pvc.py 62 KB

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