oc_scale.py 61 KB

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