oc_scale.py 56 KB

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