oc_env.py 60 KB

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