oc_scale.py 55 KB

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