oc_env.py 59 KB

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