oc_scale.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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. def _run(self, cmds, input_data):
  724. ''' Actually executes the command. This makes mocking easier. '''
  725. proc = subprocess.Popen(cmds,
  726. stdin=subprocess.PIPE,
  727. stdout=subprocess.PIPE,
  728. stderr=subprocess.PIPE,
  729. env={'KUBECONFIG': self.kubeconfig})
  730. stdout, stderr = proc.communicate(input_data)
  731. return proc.returncode, stdout, stderr
  732. # pylint: disable=too-many-arguments,too-many-branches
  733. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  734. '''Base command for oc '''
  735. cmds = []
  736. if oadm:
  737. cmds = ['/usr/bin/oadm']
  738. else:
  739. cmds = ['/usr/bin/oc']
  740. if self.all_namespaces:
  741. cmds.extend(['--all-namespaces'])
  742. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  743. cmds.extend(['-n', self.namespace])
  744. cmds.extend(cmd)
  745. rval = {}
  746. results = ''
  747. err = None
  748. if self.verbose:
  749. print(' '.join(cmds))
  750. returncode, stdout, stderr = self._run(cmds, input_data)
  751. rval = {"returncode": returncode,
  752. "results": results,
  753. "cmd": ' '.join(cmds)}
  754. if returncode == 0:
  755. if output:
  756. if output_type == 'json':
  757. try:
  758. rval['results'] = json.loads(stdout)
  759. except ValueError as err:
  760. if "No JSON object could be decoded" in err.args:
  761. err = err.args
  762. elif output_type == 'raw':
  763. rval['results'] = stdout
  764. if self.verbose:
  765. print("STDOUT: {0}".format(stdout))
  766. print("STDERR: {0}".format(stderr))
  767. if err:
  768. rval.update({"err": err,
  769. "stderr": stderr,
  770. "stdout": stdout,
  771. "cmd": cmds})
  772. else:
  773. rval.update({"stderr": stderr,
  774. "stdout": stdout,
  775. "results": {}})
  776. return rval
  777. class Utils(object):
  778. ''' utilities for openshiftcli modules '''
  779. @staticmethod
  780. def create_file(rname, data, ftype='yaml'):
  781. ''' create a file in tmp with name and contents'''
  782. path = os.path.join('/tmp', rname)
  783. with open(path, 'w') as fds:
  784. if ftype == 'yaml':
  785. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  786. elif ftype == 'json':
  787. fds.write(json.dumps(data))
  788. else:
  789. fds.write(data)
  790. # Register cleanup when module is done
  791. atexit.register(Utils.cleanup, [path])
  792. return path
  793. @staticmethod
  794. def create_files_from_contents(content, content_type=None):
  795. '''Turn an array of dict: filename, content into a files array'''
  796. if not isinstance(content, list):
  797. content = [content]
  798. files = []
  799. for item in content:
  800. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  801. files.append({'name': os.path.basename(path), 'path': path})
  802. return files
  803. @staticmethod
  804. def cleanup(files):
  805. '''Clean up on exit '''
  806. for sfile in files:
  807. if os.path.exists(sfile):
  808. if os.path.isdir(sfile):
  809. shutil.rmtree(sfile)
  810. elif os.path.isfile(sfile):
  811. os.remove(sfile)
  812. @staticmethod
  813. def exists(results, _name):
  814. ''' Check to see if the results include the name '''
  815. if not results:
  816. return False
  817. if Utils.find_result(results, _name):
  818. return True
  819. return False
  820. @staticmethod
  821. def find_result(results, _name):
  822. ''' Find the specified result by name'''
  823. rval = None
  824. for result in results:
  825. if 'metadata' in result and result['metadata']['name'] == _name:
  826. rval = result
  827. break
  828. return rval
  829. @staticmethod
  830. def get_resource_file(sfile, sfile_type='yaml'):
  831. ''' return the service file '''
  832. contents = None
  833. with open(sfile) as sfd:
  834. contents = sfd.read()
  835. if sfile_type == 'yaml':
  836. contents = yaml.load(contents, yaml.RoundTripLoader)
  837. elif sfile_type == 'json':
  838. contents = json.loads(contents)
  839. return contents
  840. @staticmethod
  841. def filter_versions(stdout):
  842. ''' filter the oc version output '''
  843. version_dict = {}
  844. version_search = ['oc', 'openshift', 'kubernetes']
  845. for line in stdout.strip().split('\n'):
  846. for term in version_search:
  847. if not line:
  848. continue
  849. if line.startswith(term):
  850. version_dict[term] = line.split()[-1]
  851. # horrible hack to get openshift version in Openshift 3.2
  852. # By default "oc version in 3.2 does not return an "openshift" version
  853. if "openshift" not in version_dict:
  854. version_dict["openshift"] = version_dict["oc"]
  855. return version_dict
  856. @staticmethod
  857. def add_custom_versions(versions):
  858. ''' create custom versions strings '''
  859. versions_dict = {}
  860. for tech, version in versions.items():
  861. # clean up "-" from version
  862. if "-" in version:
  863. version = version.split("-")[0]
  864. if version.startswith('v'):
  865. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  866. # "v3.3.0.33" is what we have, we want "3.3"
  867. versions_dict[tech + '_short'] = version[1:4]
  868. return versions_dict
  869. @staticmethod
  870. def openshift_installed():
  871. ''' check if openshift is installed '''
  872. import yum
  873. yum_base = yum.YumBase()
  874. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  875. return True
  876. return False
  877. # Disabling too-many-branches. This is a yaml dictionary comparison function
  878. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  879. @staticmethod
  880. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  881. ''' Given a user defined definition, compare it with the results given back by our query. '''
  882. # Currently these values are autogenerated and we do not need to check them
  883. skip = ['metadata', 'status']
  884. if skip_keys:
  885. skip.extend(skip_keys)
  886. for key, value in result_def.items():
  887. if key in skip:
  888. continue
  889. # Both are lists
  890. if isinstance(value, list):
  891. if key not in user_def:
  892. if debug:
  893. print('User data does not have key [%s]' % key)
  894. print('User data: %s' % user_def)
  895. return False
  896. if not isinstance(user_def[key], list):
  897. if debug:
  898. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  899. return False
  900. if len(user_def[key]) != len(value):
  901. if debug:
  902. print("List lengths are not equal.")
  903. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  904. print("user_def: %s" % user_def[key])
  905. print("value: %s" % value)
  906. return False
  907. for values in zip(user_def[key], value):
  908. if isinstance(values[0], dict) and isinstance(values[1], dict):
  909. if debug:
  910. print('sending list - list')
  911. print(type(values[0]))
  912. print(type(values[1]))
  913. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  914. if not result:
  915. print('list compare returned false')
  916. return False
  917. elif value != user_def[key]:
  918. if debug:
  919. print('value should be identical')
  920. print(value)
  921. print(user_def[key])
  922. return False
  923. # recurse on a dictionary
  924. elif isinstance(value, dict):
  925. if key not in user_def:
  926. if debug:
  927. print("user_def does not have key [%s]" % key)
  928. return False
  929. if not isinstance(user_def[key], dict):
  930. if debug:
  931. print("dict returned false: not instance of dict")
  932. return False
  933. # before passing ensure keys match
  934. api_values = set(value.keys()) - set(skip)
  935. user_values = set(user_def[key].keys()) - set(skip)
  936. if api_values != user_values:
  937. if debug:
  938. print("keys are not equal in dict")
  939. print(api_values)
  940. print(user_values)
  941. return False
  942. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  943. if not result:
  944. if debug:
  945. print("dict returned false")
  946. print(result)
  947. return False
  948. # Verify each key, value pair is the same
  949. else:
  950. if key not in user_def or value != user_def[key]:
  951. if debug:
  952. print("value not equal; user_def does not have key")
  953. print(key)
  954. print(value)
  955. if key in user_def:
  956. print(user_def[key])
  957. return False
  958. if debug:
  959. print('returning true')
  960. return True
  961. class OpenShiftCLIConfig(object):
  962. '''Generic Config'''
  963. def __init__(self, rname, namespace, kubeconfig, options):
  964. self.kubeconfig = kubeconfig
  965. self.name = rname
  966. self.namespace = namespace
  967. self._options = options
  968. @property
  969. def config_options(self):
  970. ''' return config options '''
  971. return self._options
  972. def to_option_list(self):
  973. '''return all options as a string'''
  974. return self.stringify()
  975. def stringify(self):
  976. ''' return the options hash as cli params in a string '''
  977. rval = []
  978. for key, data in self.config_options.items():
  979. if data['include'] \
  980. and (data['value'] or isinstance(data['value'], int)):
  981. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  982. return rval
  983. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  984. # -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
  985. # pylint: disable=too-many-public-methods
  986. class DeploymentConfig(Yedit):
  987. ''' Class to wrap the oc command line tools '''
  988. default_deployment_config = '''
  989. apiVersion: v1
  990. kind: DeploymentConfig
  991. metadata:
  992. name: default_dc
  993. namespace: default
  994. spec:
  995. replicas: 0
  996. selector:
  997. default_dc: default_dc
  998. strategy:
  999. resources: {}
  1000. rollingParams:
  1001. intervalSeconds: 1
  1002. maxSurge: 0
  1003. maxUnavailable: 25%
  1004. timeoutSeconds: 600
  1005. updatePercent: -25
  1006. updatePeriodSeconds: 1
  1007. type: Rolling
  1008. template:
  1009. metadata:
  1010. spec:
  1011. containers:
  1012. - env:
  1013. - name: default
  1014. value: default
  1015. image: default
  1016. imagePullPolicy: IfNotPresent
  1017. name: default_dc
  1018. ports:
  1019. - containerPort: 8000
  1020. hostPort: 8000
  1021. protocol: TCP
  1022. name: default_port
  1023. resources: {}
  1024. terminationMessagePath: /dev/termination-log
  1025. dnsPolicy: ClusterFirst
  1026. hostNetwork: true
  1027. nodeSelector:
  1028. type: compute
  1029. restartPolicy: Always
  1030. securityContext: {}
  1031. serviceAccount: default
  1032. serviceAccountName: default
  1033. terminationGracePeriodSeconds: 30
  1034. triggers:
  1035. - type: ConfigChange
  1036. '''
  1037. replicas_path = "spec.replicas"
  1038. env_path = "spec.template.spec.containers[0].env"
  1039. volumes_path = "spec.template.spec.volumes"
  1040. container_path = "spec.template.spec.containers"
  1041. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1042. def __init__(self, content=None):
  1043. ''' Constructor for deploymentconfig '''
  1044. if not content:
  1045. content = DeploymentConfig.default_deployment_config
  1046. super(DeploymentConfig, self).__init__(content=content)
  1047. # pylint: disable=no-member
  1048. def add_env_value(self, key, value):
  1049. ''' add key, value pair to env array '''
  1050. rval = False
  1051. env = self.get_env_vars()
  1052. if env:
  1053. env.append({'name': key, 'value': value})
  1054. rval = True
  1055. else:
  1056. result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
  1057. rval = result[0]
  1058. return rval
  1059. def exists_env_value(self, key, value):
  1060. ''' return whether a key, value pair exists '''
  1061. results = self.get_env_vars()
  1062. if not results:
  1063. return False
  1064. for result in results:
  1065. if result['name'] == key and result['value'] == value:
  1066. return True
  1067. return False
  1068. def exists_env_key(self, key):
  1069. ''' return whether a key, value pair exists '''
  1070. results = self.get_env_vars()
  1071. if not results:
  1072. return False
  1073. for result in results:
  1074. if result['name'] == key:
  1075. return True
  1076. return False
  1077. def get_env_vars(self):
  1078. '''return a environment variables '''
  1079. return self.get(DeploymentConfig.env_path) or []
  1080. def delete_env_var(self, keys):
  1081. '''delete a list of keys '''
  1082. if not isinstance(keys, list):
  1083. keys = [keys]
  1084. env_vars_array = self.get_env_vars()
  1085. modified = False
  1086. idx = None
  1087. for key in keys:
  1088. for env_idx, env_var in enumerate(env_vars_array):
  1089. if env_var['name'] == key:
  1090. idx = env_idx
  1091. break
  1092. if idx:
  1093. modified = True
  1094. del env_vars_array[idx]
  1095. if modified:
  1096. return True
  1097. return False
  1098. def update_env_var(self, key, value):
  1099. '''place an env in the env var list'''
  1100. env_vars_array = self.get_env_vars()
  1101. idx = None
  1102. for env_idx, env_var in enumerate(env_vars_array):
  1103. if env_var['name'] == key:
  1104. idx = env_idx
  1105. break
  1106. if idx:
  1107. env_vars_array[idx]['value'] = value
  1108. else:
  1109. self.add_env_value(key, value)
  1110. return True
  1111. def exists_volume_mount(self, volume_mount):
  1112. ''' return whether a volume mount exists '''
  1113. exist_volume_mounts = self.get_volume_mounts()
  1114. if not exist_volume_mounts:
  1115. return False
  1116. volume_mount_found = False
  1117. for exist_volume_mount in exist_volume_mounts:
  1118. if exist_volume_mount['name'] == volume_mount['name']:
  1119. volume_mount_found = True
  1120. break
  1121. return volume_mount_found
  1122. def exists_volume(self, volume):
  1123. ''' return whether a volume exists '''
  1124. exist_volumes = self.get_volumes()
  1125. volume_found = False
  1126. for exist_volume in exist_volumes:
  1127. if exist_volume['name'] == volume['name']:
  1128. volume_found = True
  1129. break
  1130. return volume_found
  1131. def find_volume_by_name(self, volume, mounts=False):
  1132. ''' return the index of a volume '''
  1133. volumes = []
  1134. if mounts:
  1135. volumes = self.get_volume_mounts()
  1136. else:
  1137. volumes = self.get_volumes()
  1138. for exist_volume in volumes:
  1139. if exist_volume['name'] == volume['name']:
  1140. return exist_volume
  1141. return None
  1142. def get_replicas(self):
  1143. ''' return replicas setting '''
  1144. return self.get(DeploymentConfig.replicas_path)
  1145. def get_volume_mounts(self):
  1146. '''return volume mount information '''
  1147. return self.get_volumes(mounts=True)
  1148. def get_volumes(self, mounts=False):
  1149. '''return volume mount information '''
  1150. if mounts:
  1151. return self.get(DeploymentConfig.volume_mounts_path) or []
  1152. return self.get(DeploymentConfig.volumes_path) or []
  1153. def delete_volume_by_name(self, volume):
  1154. '''delete a volume '''
  1155. modified = False
  1156. exist_volume_mounts = self.get_volume_mounts()
  1157. exist_volumes = self.get_volumes()
  1158. del_idx = None
  1159. for idx, exist_volume in enumerate(exist_volumes):
  1160. if 'name' in exist_volume and exist_volume['name'] == volume['name']:
  1161. del_idx = idx
  1162. break
  1163. if del_idx != None:
  1164. del exist_volumes[del_idx]
  1165. modified = True
  1166. del_idx = None
  1167. for idx, exist_volume_mount in enumerate(exist_volume_mounts):
  1168. if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
  1169. del_idx = idx
  1170. break
  1171. if del_idx != None:
  1172. del exist_volume_mounts[idx]
  1173. modified = True
  1174. return modified
  1175. def add_volume_mount(self, volume_mount):
  1176. ''' add a volume or volume mount to the proper location '''
  1177. exist_volume_mounts = self.get_volume_mounts()
  1178. if not exist_volume_mounts and volume_mount:
  1179. self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
  1180. else:
  1181. exist_volume_mounts.append(volume_mount)
  1182. def add_volume(self, volume):
  1183. ''' add a volume or volume mount to the proper location '''
  1184. exist_volumes = self.get_volumes()
  1185. if not volume:
  1186. return
  1187. if not exist_volumes:
  1188. self.put(DeploymentConfig.volumes_path, [volume])
  1189. else:
  1190. exist_volumes.append(volume)
  1191. def update_replicas(self, replicas):
  1192. ''' update replicas value '''
  1193. self.put(DeploymentConfig.replicas_path, replicas)
  1194. def update_volume(self, volume):
  1195. '''place an env in the env var list'''
  1196. exist_volumes = self.get_volumes()
  1197. if not volume:
  1198. return False
  1199. # update the volume
  1200. update_idx = None
  1201. for idx, exist_vol in enumerate(exist_volumes):
  1202. if exist_vol['name'] == volume['name']:
  1203. update_idx = idx
  1204. break
  1205. if update_idx != None:
  1206. exist_volumes[update_idx] = volume
  1207. else:
  1208. self.add_volume(volume)
  1209. return True
  1210. def update_volume_mount(self, volume_mount):
  1211. '''place an env in the env var list'''
  1212. modified = False
  1213. exist_volume_mounts = self.get_volume_mounts()
  1214. if not volume_mount:
  1215. return False
  1216. # update the volume mount
  1217. for exist_vol_mount in exist_volume_mounts:
  1218. if exist_vol_mount['name'] == volume_mount['name']:
  1219. if 'mountPath' in exist_vol_mount and \
  1220. str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
  1221. exist_vol_mount['mountPath'] = volume_mount['mountPath']
  1222. modified = True
  1223. break
  1224. if not modified:
  1225. self.add_volume_mount(volume_mount)
  1226. modified = True
  1227. return modified
  1228. def needs_update_volume(self, volume, volume_mount):
  1229. ''' verify a volume update is needed '''
  1230. exist_volume = self.find_volume_by_name(volume)
  1231. exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
  1232. results = []
  1233. results.append(exist_volume['name'] == volume['name'])
  1234. if 'secret' in volume:
  1235. results.append('secret' in exist_volume)
  1236. results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
  1237. results.append(exist_volume_mount['name'] == volume_mount['name'])
  1238. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1239. elif 'emptyDir' in volume:
  1240. results.append(exist_volume_mount['name'] == volume['name'])
  1241. results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
  1242. elif 'persistentVolumeClaim' in volume:
  1243. pvc = 'persistentVolumeClaim'
  1244. results.append(pvc in exist_volume)
  1245. if results[-1]:
  1246. results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
  1247. if 'claimSize' in volume[pvc]:
  1248. results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
  1249. elif 'hostpath' in volume:
  1250. results.append('hostPath' in exist_volume)
  1251. results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
  1252. return not all(results)
  1253. def needs_update_replicas(self, replicas):
  1254. ''' verify whether a replica update is needed '''
  1255. current_reps = self.get(DeploymentConfig.replicas_path)
  1256. return not current_reps == replicas
  1257. # -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
  1258. # -*- -*- -*- Begin included fragment: lib/replicationcontroller.py -*- -*- -*-
  1259. # pylint: disable=too-many-public-methods
  1260. class ReplicationController(DeploymentConfig):
  1261. ''' Class to wrap the oc command line tools '''
  1262. replicas_path = "spec.replicas"
  1263. env_path = "spec.template.spec.containers[0].env"
  1264. volumes_path = "spec.template.spec.volumes"
  1265. container_path = "spec.template.spec.containers"
  1266. volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
  1267. def __init__(self, content):
  1268. ''' Constructor for ReplicationController '''
  1269. super(ReplicationController, self).__init__(content=content)
  1270. # -*- -*- -*- End included fragment: lib/replicationcontroller.py -*- -*- -*-
  1271. # -*- -*- -*- Begin included fragment: class/oc_scale.py -*- -*- -*-
  1272. # pylint: disable=too-many-instance-attributes
  1273. class OCScale(OpenShiftCLI):
  1274. ''' Class to wrap the oc command line tools '''
  1275. # pylint allows 5
  1276. # pylint: disable=too-many-arguments
  1277. def __init__(self,
  1278. resource_name,
  1279. namespace,
  1280. replicas,
  1281. kind,
  1282. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1283. verbose=False):
  1284. ''' Constructor for OCScale '''
  1285. super(OCScale, self).__init__(namespace, kubeconfig)
  1286. self.kind = kind
  1287. self.replicas = replicas
  1288. self.name = resource_name
  1289. self.namespace = namespace
  1290. self.kubeconfig = kubeconfig
  1291. self.verbose = verbose
  1292. self._resource = None
  1293. @property
  1294. def resource(self):
  1295. ''' property function for resource var '''
  1296. if not self._resource:
  1297. self.get()
  1298. return self._resource
  1299. @resource.setter
  1300. def resource(self, data):
  1301. ''' setter function for resource var '''
  1302. self._resource = data
  1303. def get(self):
  1304. '''return replicas information '''
  1305. vol = self._get(self.kind, self.name)
  1306. if vol['returncode'] == 0:
  1307. if self.kind == 'dc':
  1308. # The resource returned from a query could be an rc or dc.
  1309. # pylint: disable=redefined-variable-type
  1310. self.resource = DeploymentConfig(content=vol['results'][0])
  1311. vol['results'] = [self.resource.get_replicas()]
  1312. if self.kind == 'rc':
  1313. # The resource returned from a query could be an rc or dc.
  1314. # pylint: disable=redefined-variable-type
  1315. self.resource = ReplicationController(content=vol['results'][0])
  1316. vol['results'] = [self.resource.get_replicas()]
  1317. return vol
  1318. def put(self):
  1319. '''update replicas into dc '''
  1320. self.resource.update_replicas(self.replicas)
  1321. return self._replace_content(self.kind, self.name, self.resource.yaml_dict)
  1322. def needs_update(self):
  1323. ''' verify whether an update is needed '''
  1324. return self.resource.needs_update_replicas(self.replicas)
  1325. # pylint: disable=too-many-return-statements
  1326. @staticmethod
  1327. def run_ansible(params, check_mode):
  1328. '''perform the idempotent ansible logic'''
  1329. oc_scale = OCScale(params['name'],
  1330. params['namespace'],
  1331. params['replicas'],
  1332. params['kind'],
  1333. params['kubeconfig'],
  1334. verbose=params['debug'])
  1335. state = params['state']
  1336. api_rval = oc_scale.get()
  1337. if api_rval['returncode'] != 0:
  1338. return {'failed': True, 'msg': api_rval}
  1339. #####
  1340. # Get
  1341. #####
  1342. if state == 'list':
  1343. return {'changed': False, 'result': api_rval['results'], 'state': 'list'} # noqa: E501
  1344. elif state == 'present':
  1345. ########
  1346. # Update
  1347. ########
  1348. if oc_scale.needs_update():
  1349. if check_mode:
  1350. return {'changed': True, 'result': 'CHECK_MODE: Would have updated.'} # noqa: E501
  1351. api_rval = oc_scale.put()
  1352. if api_rval['returncode'] != 0:
  1353. return {'failed': True, 'msg': api_rval}
  1354. # return the created object
  1355. api_rval = oc_scale.get()
  1356. if api_rval['returncode'] != 0:
  1357. return {'failed': True, 'msg': api_rval}
  1358. return {'changed': True, 'result': api_rval['results'], 'state': 'present'} # noqa: E501
  1359. return {'changed': False, 'result': api_rval['results'], 'state': 'present'} # noqa: E501
  1360. return {'failed': True, 'msg': 'Unknown state passed. [{}]'.format(state)}
  1361. # -*- -*- -*- End included fragment: class/oc_scale.py -*- -*- -*-
  1362. # -*- -*- -*- Begin included fragment: ansible/oc_scale.py -*- -*- -*-
  1363. def main():
  1364. '''
  1365. ansible oc module for scaling
  1366. '''
  1367. module = AnsibleModule(
  1368. argument_spec=dict(
  1369. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1370. state=dict(default='present', type='str', choices=['present', 'list']),
  1371. debug=dict(default=False, type='bool'),
  1372. kind=dict(default='dc', choices=['dc', 'rc'], type='str'),
  1373. namespace=dict(default='default', type='str'),
  1374. replicas=dict(default=None, type='int'),
  1375. name=dict(default=None, type='str'),
  1376. ),
  1377. supports_check_mode=True,
  1378. )
  1379. rval = OCScale.run_ansible(module.params, module.check_mode)
  1380. if 'failed' in rval:
  1381. module.fail_json(**rval)
  1382. module.exit_json(**rval)
  1383. if __name__ == '__main__':
  1384. main()
  1385. # -*- -*- -*- End included fragment: ansible/oc_scale.py -*- -*- -*-