oc_env.py 57 KB

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