oc_scale.py 56 KB

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