oc_scale.py 55 KB

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