oc_scale.py 64 KB

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