oc_scale.py 64 KB

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