oc_scale.py 61 KB

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