oc_volume.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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): # pragma: no cover
  153. ''' Exception class for Yedit '''
  154. pass
  155. # pylint: disable=too-many-public-methods
  156. class Yedit(object): # pragma: no cover
  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.format(''.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.format(''.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)
  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)
  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. {}'.format(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 dict with non-dict type. ' +
  470. 'value=[{}] type=[{}]'.format(value, type(value)))
  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=[{}] vtype=[{}]'.format(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 value. ' +
  587. 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
  588. return inc_value
  589. @staticmethod
  590. def process_edits(edits, yamlfile):
  591. '''run through a list of edits and process them one-by-one'''
  592. results = []
  593. for edit in edits:
  594. value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
  595. if edit.get('action') == 'update':
  596. # pylint: disable=line-too-long
  597. curr_value = Yedit.get_curr_value(
  598. Yedit.parse_value(edit.get('curr_value')),
  599. edit.get('curr_value_format'))
  600. rval = yamlfile.update(edit['key'],
  601. value,
  602. edit.get('index'),
  603. curr_value)
  604. elif edit.get('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 [{}]. Verify that the '.format(params['src']) +
  624. 'file exists, that it is has correct permissions, and is valid yaml.'}
  625. if state == 'list':
  626. if params['content']:
  627. content = Yedit.parse_value(params['content'], params['content_type'])
  628. yamlfile.yaml_dict = content
  629. if params['key']:
  630. rval = yamlfile.get(params['key']) or {}
  631. return {'changed': False, 'result': rval, 'state': state}
  632. elif state == 'absent':
  633. if params['content']:
  634. content = Yedit.parse_value(params['content'], params['content_type'])
  635. yamlfile.yaml_dict = content
  636. if params['update']:
  637. rval = yamlfile.pop(params['key'], params['value'])
  638. else:
  639. rval = yamlfile.delete(params['key'])
  640. if rval[0] and params['src']:
  641. yamlfile.write()
  642. return {'changed': rval[0], 'result': rval[1], 'state': state}
  643. elif state == 'present':
  644. # check if content is different than what is in the file
  645. if params['content']:
  646. content = Yedit.parse_value(params['content'], params['content_type'])
  647. # We had no edits to make and the contents are the same
  648. if yamlfile.yaml_dict == content and \
  649. params['value'] is None:
  650. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  651. yamlfile.yaml_dict = content
  652. # If we were passed a key, value then
  653. # we enapsulate it in a list and process it
  654. # Key, Value passed to the module : Converted to Edits list #
  655. edits = []
  656. _edit = {}
  657. if params['value'] is not None:
  658. _edit['value'] = params['value']
  659. _edit['value_type'] = params['value_type']
  660. _edit['key'] = params['key']
  661. if params['update']:
  662. _edit['action'] = 'update'
  663. _edit['curr_value'] = params['curr_value']
  664. _edit['curr_value_format'] = params['curr_value_format']
  665. _edit['index'] = params['index']
  666. elif params['append']:
  667. _edit['action'] = 'append'
  668. edits.append(_edit)
  669. elif params['edits'] is not None:
  670. edits = params['edits']
  671. if edits:
  672. results = Yedit.process_edits(edits, yamlfile)
  673. # if there were changes and a src provided to us we need to write
  674. if results['changed'] and params['src']:
  675. yamlfile.write()
  676. return {'changed': results['changed'], 'result': results['results'], 'state': state}
  677. # no edits to make
  678. if params['src']:
  679. # pylint: disable=redefined-variable-type
  680. rval = yamlfile.write()
  681. return {'changed': rval[0],
  682. 'result': rval[1],
  683. 'state': state}
  684. # We were passed content but no src, key or value, or edits. Return contents in memory
  685. return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
  686. return {'failed': True, 'msg': 'Unkown state passed'}
  687. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  688. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  689. # pylint: disable=too-many-lines
  690. # noqa: E301,E302,E303,T001
  691. class OpenShiftCLIError(Exception):
  692. '''Exception class for openshiftcli'''
  693. pass
  694. ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
  695. def locate_oc_binary():
  696. ''' Find and return oc binary file '''
  697. # https://github.com/openshift/openshift-ansible/issues/3410
  698. # oc can be in /usr/local/bin in some cases, but that may not
  699. # be in $PATH due to ansible/sudo
  700. paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
  701. oc_binary = 'oc'
  702. # Use shutil.which if it is available, otherwise fallback to a naive path search
  703. try:
  704. which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
  705. if which_result is not None:
  706. oc_binary = which_result
  707. except AttributeError:
  708. for path in paths:
  709. if os.path.exists(os.path.join(path, oc_binary)):
  710. oc_binary = os.path.join(path, oc_binary)
  711. break
  712. return oc_binary
  713. # pylint: disable=too-few-public-methods
  714. class OpenShiftCLI(object):
  715. ''' Class to wrap the command line tools '''
  716. def __init__(self,
  717. namespace,
  718. kubeconfig='/etc/origin/master/admin.kubeconfig',
  719. verbose=False,
  720. all_namespaces=False):
  721. ''' Constructor for OpenshiftCLI '''
  722. self.namespace = namespace
  723. self.verbose = verbose
  724. self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
  725. self.all_namespaces = all_namespaces
  726. self.oc_binary = locate_oc_binary()
  727. # Pylint allows only 5 arguments to be passed.
  728. # pylint: disable=too-many-arguments
  729. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  730. ''' replace the current object with the content '''
  731. res = self._get(resource, rname)
  732. if not res['results']:
  733. return res
  734. fname = Utils.create_tmpfile(rname + '-')
  735. yed = Yedit(fname, res['results'][0], separator=sep)
  736. changes = []
  737. for key, value in content.items():
  738. changes.append(yed.put(key, value))
  739. if any([change[0] for change in changes]):
  740. yed.write()
  741. atexit.register(Utils.cleanup, [fname])
  742. return self._replace(fname, force)
  743. return {'returncode': 0, 'updated': False}
  744. def _replace(self, fname, force=False):
  745. '''replace the current object with oc replace'''
  746. cmd = ['replace', '-f', fname]
  747. if force:
  748. cmd.append('--force')
  749. return self.openshift_cmd(cmd)
  750. def _create_from_content(self, rname, content):
  751. '''create a temporary file and then call oc create on it'''
  752. fname = Utils.create_tmpfile(rname + '-')
  753. yed = Yedit(fname, content=content)
  754. yed.write()
  755. atexit.register(Utils.cleanup, [fname])
  756. return self._create(fname)
  757. def _create(self, fname):
  758. '''call oc create on a filename'''
  759. return self.openshift_cmd(['create', '-f', fname])
  760. def _delete(self, resource, name=None, selector=None):
  761. '''call oc delete on a resource'''
  762. cmd = ['delete', resource]
  763. if selector is not None:
  764. cmd.append('--selector={}'.format(selector))
  765. elif name is not None:
  766. cmd.append(name)
  767. else:
  768. raise OpenShiftCLIError('Either name or selector is required when calling delete.')
  769. return self.openshift_cmd(cmd)
  770. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  771. '''process a template
  772. template_name: the name of the template to process
  773. create: whether to send to oc create after processing
  774. params: the parameters for the template
  775. template_data: the incoming template's data; instead of a file
  776. '''
  777. cmd = ['process']
  778. if template_data:
  779. cmd.extend(['-f', '-'])
  780. else:
  781. cmd.append(template_name)
  782. if params:
  783. param_str = ["{}={}".format(key, value) for key, value in params.items()]
  784. cmd.append('-v')
  785. cmd.extend(param_str)
  786. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  787. if results['returncode'] != 0 or not create:
  788. return results
  789. fname = Utils.create_tmpfile(template_name + '-')
  790. yed = Yedit(fname, results['results'])
  791. yed.write()
  792. atexit.register(Utils.cleanup, [fname])
  793. return self.openshift_cmd(['create', '-f', fname])
  794. def _get(self, resource, name=None, selector=None):
  795. '''return a resource by name '''
  796. cmd = ['get', resource]
  797. if selector is not None:
  798. cmd.append('--selector={}'.format(selector))
  799. elif name is not None:
  800. cmd.append(name)
  801. cmd.extend(['-o', 'json'])
  802. rval = self.openshift_cmd(cmd, output=True)
  803. # Ensure results are retuned in an array
  804. if 'items' in rval:
  805. rval['results'] = rval['items']
  806. elif not isinstance(rval['results'], list):
  807. rval['results'] = [rval['results']]
  808. return rval
  809. def _schedulable(self, node=None, selector=None, schedulable=True):
  810. ''' perform oadm manage-node scheduable '''
  811. cmd = ['manage-node']
  812. if node:
  813. cmd.extend(node)
  814. else:
  815. cmd.append('--selector={}'.format(selector))
  816. cmd.append('--schedulable={}'.format(schedulable))
  817. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  818. def _list_pods(self, node=None, selector=None, pod_selector=None):
  819. ''' perform oadm list pods
  820. node: the node in which to list pods
  821. selector: the label selector filter if provided
  822. pod_selector: the pod selector filter if provided
  823. '''
  824. cmd = ['manage-node']
  825. if node:
  826. cmd.extend(node)
  827. else:
  828. cmd.append('--selector={}'.format(selector))
  829. if pod_selector:
  830. cmd.append('--pod-selector={}'.format(pod_selector))
  831. cmd.extend(['--list-pods', '-o', 'json'])
  832. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  833. # pylint: disable=too-many-arguments
  834. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  835. ''' perform oadm manage-node evacuate '''
  836. cmd = ['manage-node']
  837. if node:
  838. cmd.extend(node)
  839. else:
  840. cmd.append('--selector={}'.format(selector))
  841. if dry_run:
  842. cmd.append('--dry-run')
  843. if pod_selector:
  844. cmd.append('--pod-selector={}'.format(pod_selector))
  845. if grace_period:
  846. cmd.append('--grace-period={}'.format(int(grace_period)))
  847. if force:
  848. cmd.append('--force')
  849. cmd.append('--evacuate')
  850. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  851. def _version(self):
  852. ''' return the openshift version'''
  853. return self.openshift_cmd(['version'], output=True, output_type='raw')
  854. def _import_image(self, url=None, name=None, tag=None):
  855. ''' perform image import '''
  856. cmd = ['import-image']
  857. image = '{0}'.format(name)
  858. if tag:
  859. image += ':{0}'.format(tag)
  860. cmd.append(image)
  861. if url:
  862. cmd.append('--from={0}/{1}'.format(url, image))
  863. cmd.append('-n{0}'.format(self.namespace))
  864. cmd.append('--confirm')
  865. return self.openshift_cmd(cmd)
  866. def _run(self, cmds, input_data):
  867. ''' Actually executes the command. This makes mocking easier. '''
  868. curr_env = os.environ.copy()
  869. curr_env.update({'KUBECONFIG': self.kubeconfig})
  870. proc = subprocess.Popen(cmds,
  871. stdin=subprocess.PIPE,
  872. stdout=subprocess.PIPE,
  873. stderr=subprocess.PIPE,
  874. env=curr_env)
  875. stdout, stderr = proc.communicate(input_data)
  876. return proc.returncode, stdout.decode(), stderr.decode()
  877. # pylint: disable=too-many-arguments,too-many-branches
  878. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  879. '''Base command for oc '''
  880. cmds = [self.oc_binary]
  881. if oadm:
  882. cmds.append('adm')
  883. cmds.extend(cmd)
  884. if self.all_namespaces:
  885. cmds.extend(['--all-namespaces'])
  886. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  887. cmds.extend(['-n', self.namespace])
  888. rval = {}
  889. results = ''
  890. err = None
  891. if self.verbose:
  892. print(' '.join(cmds))
  893. try:
  894. returncode, stdout, stderr = self._run(cmds, input_data)
  895. except OSError as ex:
  896. returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
  897. rval = {"returncode": returncode,
  898. "results": results,
  899. "cmd": ' '.join(cmds)}
  900. if returncode == 0:
  901. if output:
  902. if output_type == 'json':
  903. try:
  904. rval['results'] = json.loads(stdout)
  905. except ValueError as verr:
  906. if "No JSON object could be decoded" in verr.args:
  907. err = verr.args
  908. elif output_type == 'raw':
  909. rval['results'] = stdout
  910. if self.verbose:
  911. print("STDOUT: {0}".format(stdout))
  912. print("STDERR: {0}".format(stderr))
  913. if err:
  914. rval.update({"err": err,
  915. "stderr": stderr,
  916. "stdout": stdout,
  917. "cmd": cmds})
  918. else:
  919. rval.update({"stderr": stderr,
  920. "stdout": stdout,
  921. "results": {}})
  922. return rval
  923. class Utils(object): # pragma: no cover
  924. ''' utilities for openshiftcli modules '''
  925. @staticmethod
  926. def _write(filename, contents):
  927. ''' Actually write the file contents to disk. This helps with mocking. '''
  928. with open(filename, 'w') as sfd:
  929. sfd.write(contents)
  930. @staticmethod
  931. def create_tmp_file_from_contents(rname, data, ftype='yaml'):
  932. ''' create a file in tmp with name and contents'''
  933. tmp = Utils.create_tmpfile(prefix=rname)
  934. if ftype == 'yaml':
  935. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  936. # pylint: disable=no-member
  937. if hasattr(yaml, 'RoundTripDumper'):
  938. Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
  939. else:
  940. Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
  941. elif ftype == 'json':
  942. Utils._write(tmp, json.dumps(data))
  943. else:
  944. Utils._write(tmp, data)
  945. # Register cleanup when module is done
  946. atexit.register(Utils.cleanup, [tmp])
  947. return tmp
  948. @staticmethod
  949. def create_tmpfile_copy(inc_file):
  950. '''create a temporary copy of a file'''
  951. tmpfile = Utils.create_tmpfile('lib_openshift-')
  952. Utils._write(tmpfile, open(inc_file).read())
  953. # Cleanup the tmpfile
  954. atexit.register(Utils.cleanup, [tmpfile])
  955. return tmpfile
  956. @staticmethod
  957. def create_tmpfile(prefix='tmp'):
  958. ''' Generates and returns a temporary file name '''
  959. with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
  960. return tmp.name
  961. @staticmethod
  962. def create_tmp_files_from_contents(content, content_type=None):
  963. '''Turn an array of dict: filename, content into a files array'''
  964. if not isinstance(content, list):
  965. content = [content]
  966. files = []
  967. for item in content:
  968. path = Utils.create_tmp_file_from_contents(item['path'] + '-',
  969. item['data'],
  970. ftype=content_type)
  971. files.append({'name': os.path.basename(item['path']),
  972. 'path': path})
  973. return files
  974. @staticmethod
  975. def cleanup(files):
  976. '''Clean up on exit '''
  977. for sfile in files:
  978. if os.path.exists(sfile):
  979. if os.path.isdir(sfile):
  980. shutil.rmtree(sfile)
  981. elif os.path.isfile(sfile):
  982. os.remove(sfile)
  983. @staticmethod
  984. def exists(results, _name):
  985. ''' Check to see if the results include the name '''
  986. if not results:
  987. return False
  988. if Utils.find_result(results, _name):
  989. return True
  990. return False
  991. @staticmethod
  992. def find_result(results, _name):
  993. ''' Find the specified result by name'''
  994. rval = None
  995. for result in results:
  996. if 'metadata' in result and result['metadata']['name'] == _name:
  997. rval = result
  998. break
  999. return rval
  1000. @staticmethod
  1001. def get_resource_file(sfile, sfile_type='yaml'):
  1002. ''' return the service file '''
  1003. contents = None
  1004. with open(sfile) as sfd:
  1005. contents = sfd.read()
  1006. if sfile_type == 'yaml':
  1007. # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
  1008. # pylint: disable=no-member
  1009. if hasattr(yaml, 'RoundTripLoader'):
  1010. contents = yaml.load(contents, yaml.RoundTripLoader)
  1011. else:
  1012. contents = yaml.safe_load(contents)
  1013. elif sfile_type == 'json':
  1014. contents = json.loads(contents)
  1015. return contents
  1016. @staticmethod
  1017. def filter_versions(stdout):
  1018. ''' filter the oc version output '''
  1019. version_dict = {}
  1020. version_search = ['oc', 'openshift', 'kubernetes']
  1021. for line in stdout.strip().split('\n'):
  1022. for term in version_search:
  1023. if not line:
  1024. continue
  1025. if line.startswith(term):
  1026. version_dict[term] = line.split()[-1]
  1027. # horrible hack to get openshift version in Openshift 3.2
  1028. # By default "oc version in 3.2 does not return an "openshift" version
  1029. if "openshift" not in version_dict:
  1030. version_dict["openshift"] = version_dict["oc"]
  1031. return version_dict
  1032. @staticmethod
  1033. def add_custom_versions(versions):
  1034. ''' create custom versions strings '''
  1035. versions_dict = {}
  1036. for tech, version in versions.items():
  1037. # clean up "-" from version
  1038. if "-" in version:
  1039. version = version.split("-")[0]
  1040. if version.startswith('v'):
  1041. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  1042. # "v3.3.0.33" is what we have, we want "3.3"
  1043. versions_dict[tech + '_short'] = version[1:4]
  1044. return versions_dict
  1045. @staticmethod
  1046. def openshift_installed():
  1047. ''' check if openshift is installed '''
  1048. import yum
  1049. yum_base = yum.YumBase()
  1050. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  1051. return True
  1052. return False
  1053. # Disabling too-many-branches. This is a yaml dictionary comparison function
  1054. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  1055. @staticmethod
  1056. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  1057. ''' Given a user defined definition, compare it with the results given back by our query. '''
  1058. # Currently these values are autogenerated and we do not need to check them
  1059. skip = ['metadata', 'status']
  1060. if skip_keys:
  1061. skip.extend(skip_keys)
  1062. for key, value in result_def.items():
  1063. if key in skip:
  1064. continue
  1065. # Both are lists
  1066. if isinstance(value, list):
  1067. if key not in user_def:
  1068. if debug:
  1069. print('User data does not have key [%s]' % key)
  1070. print('User data: %s' % user_def)
  1071. return False
  1072. if not isinstance(user_def[key], list):
  1073. if debug:
  1074. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  1075. return False
  1076. if len(user_def[key]) != len(value):
  1077. if debug:
  1078. print("List lengths are not equal.")
  1079. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  1080. print("user_def: %s" % user_def[key])
  1081. print("value: %s" % value)
  1082. return False
  1083. for values in zip(user_def[key], value):
  1084. if isinstance(values[0], dict) and isinstance(values[1], dict):
  1085. if debug:
  1086. print('sending list - list')
  1087. print(type(values[0]))
  1088. print(type(values[1]))
  1089. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  1090. if not result:
  1091. print('list compare returned false')
  1092. return False
  1093. elif value != user_def[key]:
  1094. if debug:
  1095. print('value should be identical')
  1096. print(user_def[key])
  1097. print(value)
  1098. return False
  1099. # recurse on a dictionary
  1100. elif isinstance(value, dict):
  1101. if key not in user_def:
  1102. if debug:
  1103. print("user_def does not have key [%s]" % key)
  1104. return False
  1105. if not isinstance(user_def[key], dict):
  1106. if debug:
  1107. print("dict returned false: not instance of dict")
  1108. return False
  1109. # before passing ensure keys match
  1110. api_values = set(value.keys()) - set(skip)
  1111. user_values = set(user_def[key].keys()) - set(skip)
  1112. if api_values != user_values:
  1113. if debug:
  1114. print("keys are not equal in dict")
  1115. print(user_values)
  1116. print(api_values)
  1117. return False
  1118. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  1119. if not result:
  1120. if debug:
  1121. print("dict returned false")
  1122. print(result)
  1123. return False
  1124. # Verify each key, value pair is the same
  1125. else:
  1126. if key not in user_def or value != user_def[key]:
  1127. if debug:
  1128. print("value not equal; user_def does not have key")
  1129. print(key)
  1130. print(value)
  1131. if key in user_def:
  1132. print(user_def[key])
  1133. return False
  1134. if debug:
  1135. print('returning true')
  1136. return True
  1137. class OpenShiftCLIConfig(object):
  1138. '''Generic Config'''
  1139. def __init__(self, rname, namespace, kubeconfig, options):
  1140. self.kubeconfig = kubeconfig
  1141. self.name = rname
  1142. self.namespace = namespace
  1143. self._options = options
  1144. @property
  1145. def config_options(self):
  1146. ''' return config options '''
  1147. return self._options
  1148. def to_option_list(self):
  1149. '''return all options as a string'''
  1150. return self.stringify()
  1151. def stringify(self):
  1152. ''' return the options hash as cli params in a string '''
  1153. rval = []
  1154. for key in sorted(self.config_options.keys()):
  1155. data = self.config_options[key]
  1156. if data['include'] \
  1157. and (data['value'] or isinstance(data['value'], int)):
  1158. rval.append('--{}={}'.format(key.replace('_', '-'), data['value']))
  1159. return rval
  1160. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  1161. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  1162. # pylint: disable=too-many-public-methods
  1163. class DeploymentConfig(Yedit):
  1164. ''' Class to model an openshift DeploymentConfig'''
  1165. default_deployment_config = '''
  1166. apiVersion: v1
  1167. kind: DeploymentConfig
  1168. metadata:
  1169. name: default_dc
  1170. namespace: default
  1171. spec:
  1172. replicas: 0
  1173. selector:
  1174. default_dc: default_dc
  1175. strategy:
  1176. resources: {}
  1177. rollingParams:
  1178. intervalSeconds: 1
  1179. maxSurge: 0
  1180. maxUnavailable: 25%
  1181. timeoutSeconds: 600
  1182. updatePercent: -25
  1183. updatePeriodSeconds: 1
  1184. type: Rolling
  1185. template:
  1186. metadata:
  1187. spec:
  1188. containers:
  1189. - env:
  1190. - name: default
  1191. value: default
  1192. image: default
  1193. imagePullPolicy: IfNotPresent
  1194. name: default_dc
  1195. ports:
  1196. - containerPort: 8000
  1197. hostPort: 8000
  1198. protocol: TCP
  1199. name: default_port
  1200. resources: {}
  1201. terminationMessagePath: /dev/termination-log
  1202. dnsPolicy: ClusterFirst
  1203. hostNetwork: true
  1204. nodeSelector:
  1205. type: compute
  1206. restartPolicy: Always
  1207. securityContext: {}
  1208. serviceAccount: default
  1209. serviceAccountName: default
  1210. terminationGracePeriodSeconds: 30
  1211. triggers:
  1212. - type: ConfigChange
  1213. '''
  1214. replicas_path = "spec.replicas"
  1215. env_path = "spec.template.spec.containers[0].env"
  1216. volumes_path = "spec.template.spec.volumes"
  1217. container_path = "spec.template.spec.containers"
  1218. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1219. def __init__(self, content=None):
  1220. ''' Constructor for deploymentconfig '''
  1221. if not content:
  1222. content = DeploymentConfig.default_deployment_config
  1223. super(DeploymentConfig, self).__init__(content=content)
  1224. def add_env_value(self, key, value):
  1225. ''' add key, value pair to env array '''
  1226. rval = False
  1227. env = self.get_env_vars()
  1228. if env:
  1229. env.append({'name': key, 'value': value})
  1230. rval = True
  1231. else:
  1232. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1233. rval = result[0]
  1234. return rval
  1235. def exists_env_value(self, key, value):
  1236. ''' return whether a key, value pair exists '''
  1237. results = self.get_env_vars()
  1238. if not results:
  1239. return False
  1240. for result in results:
  1241. if result['name'] == key and result['value'] == value:
  1242. return True
  1243. return False
  1244. def exists_env_key(self, key):
  1245. ''' return whether a key, value pair exists '''
  1246. results = self.get_env_vars()
  1247. if not results:
  1248. return False
  1249. for result in results:
  1250. if result['name'] == key:
  1251. return True
  1252. return False
  1253. def get_env_var(self, key):
  1254. '''return a environment variables '''
  1255. results = self.get(DeploymentConfig.env_path) or []
  1256. if not results:
  1257. return None
  1258. for env_var in results:
  1259. if env_var['name'] == key:
  1260. return env_var
  1261. return None
  1262. def get_env_vars(self):
  1263. '''return a environment variables '''
  1264. return self.get(DeploymentConfig.env_path) or []
  1265. def delete_env_var(self, keys):
  1266. '''delete a list of keys '''
  1267. if not isinstance(keys, list):
  1268. keys = [keys]
  1269. env_vars_array = self.get_env_vars()
  1270. modified = False
  1271. idx = None
  1272. for key in keys:
  1273. for env_idx, env_var in enumerate(env_vars_array):
  1274. if env_var['name'] == key:
  1275. idx = env_idx
  1276. break
  1277. if idx:
  1278. modified = True
  1279. del env_vars_array[idx]
  1280. if modified:
  1281. return True
  1282. return False
  1283. def update_env_var(self, key, value):
  1284. '''place an env in the env var list'''
  1285. env_vars_array = self.get_env_vars()
  1286. idx = None
  1287. for env_idx, env_var in enumerate(env_vars_array):
  1288. if env_var['name'] == key:
  1289. idx = env_idx
  1290. break
  1291. if idx:
  1292. env_vars_array[idx]['value'] = value
  1293. else:
  1294. self.add_env_value(key, value)
  1295. return True
  1296. def exists_volume_mount(self, volume_mount):
  1297. ''' return whether a volume mount exists '''
  1298. exist_volume_mounts = self.get_volume_mounts()
  1299. if not exist_volume_mounts:
  1300. return False
  1301. volume_mount_found = False
  1302. for exist_volume_mount in exist_volume_mounts:
  1303. if exist_volume_mount['name'] == volume_mount['name']:
  1304. volume_mount_found = True
  1305. break
  1306. return volume_mount_found
  1307. def exists_volume(self, volume):
  1308. ''' return whether a volume exists '''
  1309. exist_volumes = self.get_volumes()
  1310. volume_found = False
  1311. for exist_volume in exist_volumes:
  1312. if exist_volume['name'] == volume['name']:
  1313. volume_found = True
  1314. break
  1315. return volume_found
  1316. def find_volume_by_name(self, volume, mounts=False):
  1317. ''' return the index of a volume '''
  1318. volumes = []
  1319. if mounts:
  1320. volumes = self.get_volume_mounts()
  1321. else:
  1322. volumes = self.get_volumes()
  1323. for exist_volume in volumes:
  1324. if exist_volume['name'] == volume['name']:
  1325. return exist_volume
  1326. return None
  1327. def get_replicas(self):
  1328. ''' return replicas setting '''
  1329. return self.get(DeploymentConfig.replicas_path)
  1330. def get_volume_mounts(self):
  1331. '''return volume mount information '''
  1332. return self.get_volumes(mounts=True)
  1333. def get_volumes(self, mounts=False):
  1334. '''return volume mount information '''
  1335. if mounts:
  1336. return self.get(DeploymentConfig.volume_mounts_path) or []
  1337. return self.get(DeploymentConfig.volumes_path) or []
  1338. def delete_volume_by_name(self, volume):
  1339. '''delete a volume '''
  1340. modified = False
  1341. exist_volume_mounts = self.get_volume_mounts()
  1342. exist_volumes = self.get_volumes()
  1343. del_idx = None
  1344. for idx, exist_volume in enumerate(exist_volumes):
  1345. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1346. del_idx = idx
  1347. break
  1348. if del_idx != None:
  1349. del exist_volumes[del_idx]
  1350. modified = True
  1351. del_idx = None
  1352. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1353. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1354. del_idx = idx
  1355. break
  1356. if del_idx != None:
  1357. del exist_volume_mounts[idx]
  1358. modified = True
  1359. return modified
  1360. def add_volume_mount(self, volume_mount):
  1361. ''' add a volume or volume mount to the proper location '''
  1362. exist_volume_mounts = self.get_volume_mounts()
  1363. if not exist_volume_mounts and volume_mount:
  1364. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1365. else:
  1366. exist_volume_mounts.append(volume_mount)
  1367. def add_volume(self, volume):
  1368. ''' add a volume or volume mount to the proper location '''
  1369. exist_volumes = self.get_volumes()
  1370. if not volume:
  1371. return
  1372. if not exist_volumes:
  1373. self.put(DeploymentConfig.volumes_path, [volume])
  1374. else:
  1375. exist_volumes.append(volume)
  1376. def update_replicas(self, replicas):
  1377. ''' update replicas value '''
  1378. self.put(DeploymentConfig.replicas_path, replicas)
  1379. def update_volume(self, volume):
  1380. '''place an env in the env var list'''
  1381. exist_volumes = self.get_volumes()
  1382. if not volume:
  1383. return False
  1384. # update the volume
  1385. update_idx = None
  1386. for idx, exist_vol in enumerate(exist_volumes):
  1387. if exist_vol['name'] == volume['name']:
  1388. update_idx = idx
  1389. break
  1390. if update_idx != None:
  1391. exist_volumes[update_idx] = volume
  1392. else:
  1393. self.add_volume(volume)
  1394. return True
  1395. def update_volume_mount(self, volume_mount):
  1396. '''place an env in the env var list'''
  1397. modified = False
  1398. exist_volume_mounts = self.get_volume_mounts()
  1399. if not volume_mount:
  1400. return False
  1401. # update the volume mount
  1402. for exist_vol_mount in exist_volume_mounts:
  1403. if exist_vol_mount['name'] == volume_mount['name']:
  1404. if 'mountPath' in exist_vol_mount and \
  1405. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1406. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1407. modified = True
  1408. break
  1409. if not modified:
  1410. self.add_volume_mount(volume_mount)
  1411. modified = True
  1412. return modified
  1413. def needs_update_volume(self, volume, volume_mount):
  1414. ''' verify a volume update is needed '''
  1415. exist_volume = self.find_volume_by_name(volume)
  1416. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1417. results = []
  1418. results.append(exist_volume['name'] == volume['name'])
  1419. if 'secret' in volume:
  1420. results.append('secret' in exist_volume)
  1421. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1422. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1423. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1424. elif 'emptyDir' in volume:
  1425. results.append(exist_volume_mount['name'] == volume['name'])
  1426. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1427. elif 'persistentVolumeClaim' in volume:
  1428. pvc = 'persistentVolumeClaim'
  1429. results.append(pvc in exist_volume)
  1430. if results[-1]:
  1431. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1432. if 'claimSize' in volume[pvc]:
  1433. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1434. elif 'hostpath' in volume:
  1435. results.append('hostPath' in exist_volume)
  1436. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1437. return not all(results)
  1438. def needs_update_replicas(self, replicas):
  1439. ''' verify whether a replica update is needed '''
  1440. current_reps = self.get(DeploymentConfig.replicas_path)
  1441. return not current_reps == replicas
  1442. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1443. # -*- -*- -*- Begin included fragment: lib/volume.py -*- -*- -*-
  1444. class Volume(object):
  1445. ''' Class to represent an openshift volume object'''
  1446. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1447. "dc": "spec.template.spec.containers[0].volumeMounts",
  1448. "rc": "spec.template.spec.containers[0].volumeMounts",
  1449. }
  1450. volumes_path = {"pod": "spec.volumes",
  1451. "dc": "spec.template.spec.volumes",
  1452. "rc": "spec.template.spec.volumes",
  1453. }
  1454. @staticmethod
  1455. def create_volume_structure(volume_info):
  1456. ''' return a properly structured volume '''
  1457. volume_mount = None
  1458. volume = {'name': volume_info['name']}
  1459. volume_type = volume_info['type'].lower()
  1460. if volume_type == 'secret':
  1461. volume['secret'] = {}
  1462. volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
  1463. volume_mount = {'mountPath': volume_info['path'],
  1464. 'name': volume_info['name']}
  1465. elif volume_type == 'emptydir':
  1466. volume['emptyDir'] = {}
  1467. volume_mount = {'mountPath': volume_info['path'],
  1468. 'name': volume_info['name']}
  1469. elif volume_type == 'pvc' or volume_type == 'persistentvolumeclaim':
  1470. volume['persistentVolumeClaim'] = {}
  1471. volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
  1472. volume['persistentVolumeClaim']['claimSize'] = volume_info['claimSize']
  1473. elif volume_type == 'hostpath':
  1474. volume['hostPath'] = {}
  1475. volume['hostPath']['path'] = volume_info['path']
  1476. elif volume_type == 'configmap':
  1477. volume['configMap'] = {}
  1478. volume['configMap']['name'] = volume_info['configmap_name']
  1479. volume_mount = {'mountPath': volume_info['path'],
  1480. 'name': volume_info['name']}
  1481. return (volume, volume_mount)
  1482. # -*- -*- -*- End included fragment: lib/volume.py -*- -*- -*-
  1483. # -*- -*- -*- Begin included fragment: class/oc_volume.py -*- -*- -*-
  1484. # pylint: disable=too-many-instance-attributes
  1485. class OCVolume(OpenShiftCLI):
  1486. ''' Class to wrap the oc command line tools '''
  1487. volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
  1488. "dc": "spec.template.spec.containers[0].volumeMounts",
  1489. "rc": "spec.template.spec.containers[0].volumeMounts",
  1490. }
  1491. volumes_path = {"pod": "spec.volumes",
  1492. "dc": "spec.template.spec.volumes",
  1493. "rc": "spec.template.spec.volumes",
  1494. }
  1495. # pylint allows 5
  1496. # pylint: disable=too-many-arguments
  1497. def __init__(self,
  1498. kind,
  1499. resource_name,
  1500. namespace,
  1501. vol_name,
  1502. mount_path,
  1503. mount_type,
  1504. secret_name,
  1505. claim_size,
  1506. claim_name,
  1507. configmap_name,
  1508. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1509. verbose=False):
  1510. ''' Constructor for OCVolume '''
  1511. super(OCVolume, self).__init__(namespace, kubeconfig)
  1512. self.kind = kind
  1513. self.volume_info = {'name': vol_name,
  1514. 'secret_name': secret_name,
  1515. 'path': mount_path,
  1516. 'type': mount_type,
  1517. 'claimSize': claim_size,
  1518. 'claimName': claim_name,
  1519. 'configmap_name': configmap_name}
  1520. self.volume, self.volume_mount = Volume.create_volume_structure(self.volume_info)
  1521. self.name = resource_name
  1522. self.namespace = namespace
  1523. self.kubeconfig = kubeconfig
  1524. self.verbose = verbose
  1525. self._resource = None
  1526. @property
  1527. def resource(self):
  1528. ''' property function for resource var '''
  1529. if not self._resource:
  1530. self.get()
  1531. return self._resource
  1532. @resource.setter
  1533. def resource(self, data):
  1534. ''' setter function for resource var '''
  1535. self._resource = data
  1536. def exists(self):
  1537. ''' return whether a volume exists '''
  1538. volume_mount_found = False
  1539. volume_found = self.resource.exists_volume(self.volume)
  1540. if not self.volume_mount and volume_found:
  1541. return True
  1542. if self.volume_mount:
  1543. volume_mount_found = self.resource.exists_volume_mount(self.volume_mount)
  1544. if volume_found and self.volume_mount and volume_mount_found:
  1545. return True
  1546. return False
  1547. def get(self):
  1548. '''return volume information '''
  1549. vol = self._get(self.kind, self.name)
  1550. if vol['returncode'] == 0:
  1551. if self.kind == 'dc':
  1552. self.resource = DeploymentConfig(content=vol['results'][0])
  1553. vol['results'] = self.resource.get_volumes()
  1554. return vol
  1555. def delete(self):
  1556. '''remove a volume'''
  1557. self.resource.delete_volume_by_name(self.volume)
  1558. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1559. def put(self):
  1560. '''place volume into dc '''
  1561. self.resource.update_volume(self.volume)
  1562. self.resource.get_volumes()
  1563. self.resource.update_volume_mount(self.volume_mount)
  1564. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1565. def needs_update(self):
  1566. ''' verify an update is needed '''
  1567. return self.resource.needs_update_volume(self.volume, self.volume_mount)
  1568. # pylint: disable=too-many-branches,too-many-return-statements
  1569. @staticmethod
  1570. def run_ansible(params, check_mode=False):
  1571. '''run the idempotent ansible code'''
  1572. oc_volume = OCVolume(params['kind'],
  1573. params['name'],
  1574. params['namespace'],
  1575. params['vol_name'],
  1576. params['mount_path'],
  1577. params['mount_type'],
  1578. # secrets
  1579. params['secret_name'],
  1580. # pvc
  1581. params['claim_size'],
  1582. params['claim_name'],
  1583. # configmap
  1584. params['configmap_name'],
  1585. kubeconfig=params['kubeconfig'],
  1586. verbose=params['debug'])
  1587. state = params['state']
  1588. api_rval = oc_volume.get()
  1589. if api_rval['returncode'] != 0:
  1590. return {'failed': True, 'msg': api_rval}
  1591. #####
  1592. # Get
  1593. #####
  1594. if state == 'list':
  1595. return {'changed': False, 'results': api_rval['results'], 'state': state}
  1596. ########
  1597. # Delete
  1598. ########
  1599. if state == 'absent':
  1600. if oc_volume.exists():
  1601. if check_mode:
  1602. return {'changed': False, 'msg': 'CHECK_MODE: Would have performed a delete.'}
  1603. api_rval = oc_volume.delete()
  1604. if api_rval['returncode'] != 0:
  1605. return {'failed': True, 'msg': api_rval}
  1606. return {'changed': True, 'results': api_rval, 'state': state}
  1607. return {'changed': False, 'state': state}
  1608. if state == 'present':
  1609. ########
  1610. # Create
  1611. ########
  1612. if not oc_volume.exists():
  1613. if check_mode:
  1614. return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
  1615. # Create it here
  1616. api_rval = oc_volume.put()
  1617. if api_rval['returncode'] != 0:
  1618. return {'failed': True, 'msg': api_rval}
  1619. # return the created object
  1620. api_rval = oc_volume.get()
  1621. if api_rval['returncode'] != 0:
  1622. return {'failed': True, 'msg': api_rval}
  1623. return {'changed': True, 'results': api_rval, 'state': state}
  1624. ########
  1625. # Update
  1626. ########
  1627. if oc_volume.needs_update():
  1628. api_rval = oc_volume.put()
  1629. if api_rval['returncode'] != 0:
  1630. return {'failed': True, 'msg': api_rval}
  1631. # return the created object
  1632. api_rval = oc_volume.get()
  1633. if api_rval['returncode'] != 0:
  1634. return {'failed': True, 'msg': api_rval}
  1635. return {'changed': True, 'results': api_rval, state: state}
  1636. return {'changed': False, 'results': api_rval, state: state}
  1637. return {'failed': True, 'msg': 'Unknown state passed. {}'.format(state)}
  1638. # -*- -*- -*- End included fragment: class/oc_volume.py -*- -*- -*-
  1639. # -*- -*- -*- Begin included fragment: ansible/oc_volume.py -*- -*- -*-
  1640. def main():
  1641. '''
  1642. ansible oc module for volumes
  1643. '''
  1644. module = AnsibleModule(
  1645. argument_spec=dict(
  1646. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1647. state=dict(default='present', type='str',
  1648. choices=['present', 'absent', 'list']),
  1649. debug=dict(default=False, type='bool'),
  1650. kind=dict(default='dc', choices=['dc', 'rc', 'pods'], type='str'),
  1651. namespace=dict(default='default', type='str'),
  1652. vol_name=dict(default=None, type='str'),
  1653. name=dict(default=None, type='str'),
  1654. mount_type=dict(default=None,
  1655. choices=['emptydir', 'hostpath', 'secret', 'pvc', 'configmap'],
  1656. type='str'),
  1657. mount_path=dict(default=None, type='str'),
  1658. # secrets require a name
  1659. secret_name=dict(default=None, type='str'),
  1660. # pvc requires a size
  1661. claim_size=dict(default=None, type='str'),
  1662. claim_name=dict(default=None, type='str'),
  1663. # configmap requires a name
  1664. configmap_name=dict(default=None, type='str'),
  1665. ),
  1666. supports_check_mode=True,
  1667. )
  1668. rval = OCVolume.run_ansible(module.params, module.check_mode)
  1669. if 'failed' in rval:
  1670. module.fail_json(**rval)
  1671. module.exit_json(**rval)
  1672. if __name__ == '__main__':
  1673. main()
  1674. # -*- -*- -*- End included fragment: ansible/oc_volume.py -*- -*- -*-