oc_scale.py 62 KB

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