oc_scale.py 60 KB

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