oc_pvc.py 60 KB

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