oc_scale.py 59 KB

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