oc_scale.py 63 KB

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