oc_volume.py 69 KB

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