oc_scale.py 57 KB

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