oc_scale.py 56 KB

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