oc_scale.py 64 KB

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