oc_storageclass.py 56 KB

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