oc_scale.py 57 KB

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