oc_scale.py 59 KB

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