oc_scale.py 59 KB

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