oc_scale.py 58 KB

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