oc_pvc.py 57 KB

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