oc_scale.py 59 KB

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