oc_volume.py 68 KB

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