oc_process.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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. # pylint: disable=import-error
  40. import ruamel.yaml as yaml
  41. from ansible.module_utils.basic import AnsibleModule
  42. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  43. # -*- -*- -*- Begin included fragment: doc/process -*- -*- -*-
  44. DOCUMENTATION = '''
  45. ---
  46. module: oc_process
  47. short_description: Module to process openshift templates
  48. description:
  49. - Process openshift templates programmatically.
  50. options:
  51. state:
  52. description:
  53. - Currently present is only supported state.
  54. default: present
  55. choices: ["present", "absent", "list"]
  56. aliases: []
  57. kubeconfig:
  58. description:
  59. - The path for the kubeconfig file to use for authentication
  60. required: false
  61. default: /etc/origin/master/admin.kubeconfig
  62. aliases: []
  63. debug:
  64. description:
  65. - Turn on debug output.
  66. required: false
  67. default: False
  68. aliases: []
  69. template_name:
  70. description:
  71. - Name of the openshift template that is being processed.
  72. required: false
  73. default: None
  74. aliases: []
  75. namespace:
  76. description:
  77. - The namespace where the template lives.
  78. required: false
  79. default: default
  80. aliases: []
  81. content:
  82. description:
  83. - Template content that will be processed.
  84. required: false
  85. default: None
  86. aliases: []
  87. params:
  88. description:
  89. - A list of parameters that will be inserted into the template.
  90. required: false
  91. default: None
  92. aliases: []
  93. create:
  94. description:
  95. - Whether or not to create the template after being processed. e.q oc process | oc create -f -
  96. required: false
  97. default: None
  98. aliases: []
  99. reconcile:
  100. description:
  101. - Whether or not to attempt to determine if there are updates or changes in the incoming template.
  102. default: true
  103. aliases: []
  104. author:
  105. - "Kenny Woodson <kwoodson@redhat.com>"
  106. extends_documentation_fragment: []
  107. '''
  108. EXAMPLES = '''
  109. - name: process the cloud volume provisioner template with variables
  110. oc_process:
  111. namespace: openshift-infra
  112. template_name: online-volume-provisioner
  113. create: True
  114. params:
  115. PLAT: rhel7
  116. register: processout
  117. run_once: true
  118. - debug: var=processout
  119. '''
  120. # -*- -*- -*- End included fragment: doc/process -*- -*- -*-
  121. # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  122. # noqa: E301,E302
  123. class YeditException(Exception):
  124. ''' Exception class for Yedit '''
  125. pass
  126. # pylint: disable=too-many-public-methods
  127. class Yedit(object):
  128. ''' Class to modify yaml files '''
  129. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  130. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  131. com_sep = set(['.', '#', '|', ':'])
  132. # pylint: disable=too-many-arguments
  133. def __init__(self,
  134. filename=None,
  135. content=None,
  136. content_type='yaml',
  137. separator='.',
  138. backup=False):
  139. self.content = content
  140. self._separator = separator
  141. self.filename = filename
  142. self.__yaml_dict = content
  143. self.content_type = content_type
  144. self.backup = backup
  145. self.load(content_type=self.content_type)
  146. if self.__yaml_dict is None:
  147. self.__yaml_dict = {}
  148. @property
  149. def separator(self):
  150. ''' getter method for yaml_dict '''
  151. return self._separator
  152. @separator.setter
  153. def separator(self):
  154. ''' getter method for yaml_dict '''
  155. return self._separator
  156. @property
  157. def yaml_dict(self):
  158. ''' getter method for yaml_dict '''
  159. return self.__yaml_dict
  160. @yaml_dict.setter
  161. def yaml_dict(self, value):
  162. ''' setter method for yaml_dict '''
  163. self.__yaml_dict = value
  164. @staticmethod
  165. def parse_key(key, sep='.'):
  166. '''parse the key allowing the appropriate separator'''
  167. common_separators = list(Yedit.com_sep - set([sep]))
  168. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  169. @staticmethod
  170. def valid_key(key, sep='.'):
  171. '''validate the incoming key'''
  172. common_separators = list(Yedit.com_sep - set([sep]))
  173. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  174. return False
  175. return True
  176. @staticmethod
  177. def remove_entry(data, key, sep='.'):
  178. ''' remove data at location key '''
  179. if key == '' and isinstance(data, dict):
  180. data.clear()
  181. return True
  182. elif key == '' and isinstance(data, list):
  183. del data[:]
  184. return True
  185. if not (key and Yedit.valid_key(key, sep)) and \
  186. isinstance(data, (list, dict)):
  187. return None
  188. key_indexes = Yedit.parse_key(key, sep)
  189. for arr_ind, dict_key in key_indexes[:-1]:
  190. if dict_key and isinstance(data, dict):
  191. data = data.get(dict_key, None)
  192. elif (arr_ind and isinstance(data, list) and
  193. int(arr_ind) <= len(data) - 1):
  194. data = data[int(arr_ind)]
  195. else:
  196. return None
  197. # process last index for remove
  198. # expected list entry
  199. if key_indexes[-1][0]:
  200. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  201. del data[int(key_indexes[-1][0])]
  202. return True
  203. # expected dict entry
  204. elif key_indexes[-1][1]:
  205. if isinstance(data, dict):
  206. del data[key_indexes[-1][1]]
  207. return True
  208. @staticmethod
  209. def add_entry(data, key, item=None, sep='.'):
  210. ''' Get an item from a dictionary with key notation a.b.c
  211. d = {'a': {'b': 'c'}}}
  212. key = a#b
  213. return c
  214. '''
  215. if key == '':
  216. pass
  217. elif (not (key and Yedit.valid_key(key, sep)) and
  218. isinstance(data, (list, dict))):
  219. return None
  220. key_indexes = Yedit.parse_key(key, sep)
  221. for arr_ind, dict_key in key_indexes[:-1]:
  222. if dict_key:
  223. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  224. data = data[dict_key]
  225. continue
  226. elif data and not isinstance(data, dict):
  227. return None
  228. data[dict_key] = {}
  229. data = data[dict_key]
  230. elif (arr_ind and isinstance(data, list) and
  231. int(arr_ind) <= len(data) - 1):
  232. data = data[int(arr_ind)]
  233. else:
  234. return None
  235. if key == '':
  236. data = item
  237. # process last index for add
  238. # expected list entry
  239. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  240. data[int(key_indexes[-1][0])] = item
  241. # expected dict entry
  242. elif key_indexes[-1][1] and isinstance(data, dict):
  243. data[key_indexes[-1][1]] = item
  244. return data
  245. @staticmethod
  246. def get_entry(data, key, sep='.'):
  247. ''' Get an item from a dictionary with key notation a.b.c
  248. d = {'a': {'b': 'c'}}}
  249. key = a.b
  250. return c
  251. '''
  252. if key == '':
  253. pass
  254. elif (not (key and Yedit.valid_key(key, sep)) and
  255. isinstance(data, (list, dict))):
  256. return None
  257. key_indexes = Yedit.parse_key(key, sep)
  258. for arr_ind, dict_key in key_indexes:
  259. if dict_key and isinstance(data, dict):
  260. data = data.get(dict_key, None)
  261. elif (arr_ind and isinstance(data, list) and
  262. int(arr_ind) <= len(data) - 1):
  263. data = data[int(arr_ind)]
  264. else:
  265. return None
  266. return data
  267. def write(self):
  268. ''' write to file '''
  269. if not self.filename:
  270. raise YeditException('Please specify a filename.')
  271. if self.backup and self.file_exists():
  272. shutil.copy(self.filename, self.filename + '.orig')
  273. tmp_filename = self.filename + '.yedit'
  274. with open(tmp_filename, 'w') as yfd:
  275. # pylint: disable=no-member
  276. if hasattr(self.yaml_dict, 'fa'):
  277. self.yaml_dict.fa.set_block_style()
  278. yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  279. os.rename(tmp_filename, self.filename)
  280. return (True, self.yaml_dict)
  281. def read(self):
  282. ''' read from file '''
  283. # check if it exists
  284. if self.filename is None or not self.file_exists():
  285. return None
  286. contents = None
  287. with open(self.filename) as yfd:
  288. contents = yfd.read()
  289. return contents
  290. def file_exists(self):
  291. ''' return whether file exists '''
  292. if os.path.exists(self.filename):
  293. return True
  294. return False
  295. def load(self, content_type='yaml'):
  296. ''' return yaml file '''
  297. contents = self.read()
  298. if not contents and not self.content:
  299. return None
  300. if self.content:
  301. if isinstance(self.content, dict):
  302. self.yaml_dict = self.content
  303. return self.yaml_dict
  304. elif isinstance(self.content, str):
  305. contents = self.content
  306. # check if it is yaml
  307. try:
  308. if content_type == 'yaml' and contents:
  309. self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
  310. # pylint: disable=no-member
  311. if hasattr(self.yaml_dict, 'fa'):
  312. self.yaml_dict.fa.set_block_style()
  313. elif content_type == 'json' and contents:
  314. self.yaml_dict = json.loads(contents)
  315. except yaml.YAMLError as err:
  316. # Error loading yaml or json
  317. raise YeditException('Problem with loading yaml file. %s' % err)
  318. return self.yaml_dict
  319. def get(self, key):
  320. ''' get a specified key'''
  321. try:
  322. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  323. except KeyError:
  324. entry = None
  325. return entry
  326. def pop(self, path, key_or_item):
  327. ''' remove a key, value pair from a dict or an item for a list'''
  328. try:
  329. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  330. except KeyError:
  331. entry = None
  332. if entry is None:
  333. return (False, self.yaml_dict)
  334. if isinstance(entry, dict):
  335. # pylint: disable=no-member,maybe-no-member
  336. if key_or_item in entry:
  337. entry.pop(key_or_item)
  338. return (True, self.yaml_dict)
  339. return (False, self.yaml_dict)
  340. elif isinstance(entry, list):
  341. # pylint: disable=no-member,maybe-no-member
  342. ind = None
  343. try:
  344. ind = entry.index(key_or_item)
  345. except ValueError:
  346. return (False, self.yaml_dict)
  347. entry.pop(ind)
  348. return (True, self.yaml_dict)
  349. return (False, self.yaml_dict)
  350. def delete(self, path):
  351. ''' remove path from a dict'''
  352. try:
  353. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  354. except KeyError:
  355. entry = None
  356. if entry is None:
  357. return (False, self.yaml_dict)
  358. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  359. if not result:
  360. return (False, self.yaml_dict)
  361. return (True, self.yaml_dict)
  362. def exists(self, path, value):
  363. ''' check if value exists at path'''
  364. try:
  365. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  366. except KeyError:
  367. entry = None
  368. if isinstance(entry, list):
  369. if value in entry:
  370. return True
  371. return False
  372. elif isinstance(entry, dict):
  373. if isinstance(value, dict):
  374. rval = False
  375. for key, val in value.items():
  376. if entry[key] != val:
  377. rval = False
  378. break
  379. else:
  380. rval = True
  381. return rval
  382. return value in entry
  383. return entry == value
  384. def append(self, path, value):
  385. '''append value to a list'''
  386. try:
  387. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  388. except KeyError:
  389. entry = None
  390. if entry is None:
  391. self.put(path, [])
  392. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  393. if not isinstance(entry, list):
  394. return (False, self.yaml_dict)
  395. # pylint: disable=no-member,maybe-no-member
  396. entry.append(value)
  397. return (True, self.yaml_dict)
  398. # pylint: disable=too-many-arguments
  399. def update(self, path, value, index=None, curr_value=None):
  400. ''' put path, value into a dict '''
  401. try:
  402. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  403. except KeyError:
  404. entry = None
  405. if isinstance(entry, dict):
  406. # pylint: disable=no-member,maybe-no-member
  407. if not isinstance(value, dict):
  408. raise YeditException('Cannot replace key, value entry in ' +
  409. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  410. entry.update(value)
  411. return (True, self.yaml_dict)
  412. elif isinstance(entry, list):
  413. # pylint: disable=no-member,maybe-no-member
  414. ind = None
  415. if curr_value:
  416. try:
  417. ind = entry.index(curr_value)
  418. except ValueError:
  419. return (False, self.yaml_dict)
  420. elif index is not None:
  421. ind = index
  422. if ind is not None and entry[ind] != value:
  423. entry[ind] = value
  424. return (True, self.yaml_dict)
  425. # see if it exists in the list
  426. try:
  427. ind = entry.index(value)
  428. except ValueError:
  429. # doesn't exist, append it
  430. entry.append(value)
  431. return (True, self.yaml_dict)
  432. # already exists, return
  433. if ind is not None:
  434. return (False, self.yaml_dict)
  435. return (False, self.yaml_dict)
  436. def put(self, path, value):
  437. ''' put path, value into a dict '''
  438. try:
  439. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  440. except KeyError:
  441. entry = None
  442. if entry == value:
  443. return (False, self.yaml_dict)
  444. # deepcopy didn't work
  445. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  446. default_flow_style=False),
  447. yaml.RoundTripLoader)
  448. # pylint: disable=no-member
  449. if hasattr(self.yaml_dict, 'fa'):
  450. tmp_copy.fa.set_block_style()
  451. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  452. if not result:
  453. return (False, self.yaml_dict)
  454. self.yaml_dict = tmp_copy
  455. return (True, self.yaml_dict)
  456. def create(self, path, value):
  457. ''' create a yaml file '''
  458. if not self.file_exists():
  459. # deepcopy didn't work
  460. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), # noqa: E501
  461. yaml.RoundTripLoader)
  462. # pylint: disable=no-member
  463. if hasattr(self.yaml_dict, 'fa'):
  464. tmp_copy.fa.set_block_style()
  465. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  466. if result:
  467. self.yaml_dict = tmp_copy
  468. return (True, self.yaml_dict)
  469. return (False, self.yaml_dict)
  470. @staticmethod
  471. def get_curr_value(invalue, val_type):
  472. '''return the current value'''
  473. if invalue is None:
  474. return None
  475. curr_value = invalue
  476. if val_type == 'yaml':
  477. curr_value = yaml.load(invalue)
  478. elif val_type == 'json':
  479. curr_value = json.loads(invalue)
  480. return curr_value
  481. @staticmethod
  482. def parse_value(inc_value, vtype=''):
  483. '''determine value type passed'''
  484. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  485. 'on', 'On', 'ON', ]
  486. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  487. 'off', 'Off', 'OFF']
  488. # It came in as a string but you didn't specify value_type as string
  489. # we will convert to bool if it matches any of the above cases
  490. if isinstance(inc_value, str) and 'bool' in vtype:
  491. if inc_value not in true_bools and inc_value not in false_bools:
  492. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  493. % (inc_value, vtype))
  494. elif isinstance(inc_value, bool) and 'str' in vtype:
  495. inc_value = str(inc_value)
  496. # If vtype is not str then go ahead and attempt to yaml load it.
  497. if isinstance(inc_value, str) and 'str' not in vtype:
  498. try:
  499. inc_value = yaml.load(inc_value)
  500. except Exception:
  501. raise YeditException('Could not determine type of incoming ' +
  502. 'value. value=[%s] vtype=[%s]'
  503. % (type(inc_value), vtype))
  504. return inc_value
  505. # pylint: disable=too-many-return-statements,too-many-branches
  506. @staticmethod
  507. def run_ansible(module):
  508. '''perform the idempotent crud operations'''
  509. yamlfile = Yedit(filename=module.params['src'],
  510. backup=module.params['backup'],
  511. separator=module.params['separator'])
  512. if module.params['src']:
  513. rval = yamlfile.load()
  514. if yamlfile.yaml_dict is None and \
  515. module.params['state'] != 'present':
  516. return {'failed': True,
  517. 'msg': 'Error opening file [%s]. Verify that the ' +
  518. 'file exists, that it is has correct' +
  519. ' permissions, and is valid yaml.'}
  520. if module.params['state'] == 'list':
  521. if module.params['content']:
  522. content = Yedit.parse_value(module.params['content'],
  523. module.params['content_type'])
  524. yamlfile.yaml_dict = content
  525. if module.params['key']:
  526. rval = yamlfile.get(module.params['key']) or {}
  527. return {'changed': False, 'result': rval, 'state': "list"}
  528. elif module.params['state'] == 'absent':
  529. if module.params['content']:
  530. content = Yedit.parse_value(module.params['content'],
  531. module.params['content_type'])
  532. yamlfile.yaml_dict = content
  533. if module.params['update']:
  534. rval = yamlfile.pop(module.params['key'],
  535. module.params['value'])
  536. else:
  537. rval = yamlfile.delete(module.params['key'])
  538. if rval[0] and module.params['src']:
  539. yamlfile.write()
  540. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  541. elif module.params['state'] == 'present':
  542. # check if content is different than what is in the file
  543. if module.params['content']:
  544. content = Yedit.parse_value(module.params['content'],
  545. module.params['content_type'])
  546. # We had no edits to make and the contents are the same
  547. if yamlfile.yaml_dict == content and \
  548. module.params['value'] is None:
  549. return {'changed': False,
  550. 'result': yamlfile.yaml_dict,
  551. 'state': "present"}
  552. yamlfile.yaml_dict = content
  553. # we were passed a value; parse it
  554. if module.params['value']:
  555. value = Yedit.parse_value(module.params['value'],
  556. module.params['value_type'])
  557. key = module.params['key']
  558. if module.params['update']:
  559. # pylint: disable=line-too-long
  560. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  561. module.params['curr_value_format']) # noqa: E501
  562. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  563. elif module.params['append']:
  564. rval = yamlfile.append(key, value)
  565. else:
  566. rval = yamlfile.put(key, value)
  567. if rval[0] and module.params['src']:
  568. yamlfile.write()
  569. return {'changed': rval[0],
  570. 'result': rval[1], 'state': "present"}
  571. # no edits to make
  572. if module.params['src']:
  573. # pylint: disable=redefined-variable-type
  574. rval = yamlfile.write()
  575. return {'changed': rval[0],
  576. 'result': rval[1],
  577. 'state': "present"}
  578. return {'failed': True, 'msg': 'Unkown state passed'}
  579. # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
  580. # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
  581. # pylint: disable=too-many-lines
  582. # noqa: E301,E302,E303,T001
  583. class OpenShiftCLIError(Exception):
  584. '''Exception class for openshiftcli'''
  585. pass
  586. # pylint: disable=too-few-public-methods
  587. class OpenShiftCLI(object):
  588. ''' Class to wrap the command line tools '''
  589. def __init__(self,
  590. namespace,
  591. kubeconfig='/etc/origin/master/admin.kubeconfig',
  592. verbose=False,
  593. all_namespaces=False):
  594. ''' Constructor for OpenshiftCLI '''
  595. self.namespace = namespace
  596. self.verbose = verbose
  597. self.kubeconfig = kubeconfig
  598. self.all_namespaces = all_namespaces
  599. # Pylint allows only 5 arguments to be passed.
  600. # pylint: disable=too-many-arguments
  601. def _replace_content(self, resource, rname, content, force=False, sep='.'):
  602. ''' replace the current object with the content '''
  603. res = self._get(resource, rname)
  604. if not res['results']:
  605. return res
  606. fname = '/tmp/%s' % rname
  607. yed = Yedit(fname, res['results'][0], separator=sep)
  608. changes = []
  609. for key, value in content.items():
  610. changes.append(yed.put(key, value))
  611. if any([change[0] for change in changes]):
  612. yed.write()
  613. atexit.register(Utils.cleanup, [fname])
  614. return self._replace(fname, force)
  615. return {'returncode': 0, 'updated': False}
  616. def _replace(self, fname, force=False):
  617. '''replace the current object with oc replace'''
  618. cmd = ['replace', '-f', fname]
  619. if force:
  620. cmd.append('--force')
  621. return self.openshift_cmd(cmd)
  622. def _create_from_content(self, rname, content):
  623. '''create a temporary file and then call oc create on it'''
  624. fname = '/tmp/%s' % rname
  625. yed = Yedit(fname, content=content)
  626. yed.write()
  627. atexit.register(Utils.cleanup, [fname])
  628. return self._create(fname)
  629. def _create(self, fname):
  630. '''call oc create on a filename'''
  631. return self.openshift_cmd(['create', '-f', fname])
  632. def _delete(self, resource, rname, selector=None):
  633. '''call oc delete on a resource'''
  634. cmd = ['delete', resource, rname]
  635. if selector:
  636. cmd.append('--selector=%s' % selector)
  637. return self.openshift_cmd(cmd)
  638. def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
  639. '''process a template
  640. template_name: the name of the template to process
  641. create: whether to send to oc create after processing
  642. params: the parameters for the template
  643. template_data: the incoming template's data; instead of a file
  644. '''
  645. cmd = ['process']
  646. if template_data:
  647. cmd.extend(['-f', '-'])
  648. else:
  649. cmd.append(template_name)
  650. if params:
  651. param_str = ["%s=%s" % (key, value) for key, value in params.items()]
  652. cmd.append('-v')
  653. cmd.extend(param_str)
  654. results = self.openshift_cmd(cmd, output=True, input_data=template_data)
  655. if results['returncode'] != 0 or not create:
  656. return results
  657. fname = '/tmp/%s' % template_name
  658. yed = Yedit(fname, results['results'])
  659. yed.write()
  660. atexit.register(Utils.cleanup, [fname])
  661. return self.openshift_cmd(['create', '-f', fname])
  662. def _get(self, resource, rname=None, selector=None):
  663. '''return a resource by name '''
  664. cmd = ['get', resource]
  665. if selector:
  666. cmd.append('--selector=%s' % selector)
  667. elif rname:
  668. cmd.append(rname)
  669. cmd.extend(['-o', 'json'])
  670. rval = self.openshift_cmd(cmd, output=True)
  671. # Ensure results are retuned in an array
  672. if 'items' in rval:
  673. rval['results'] = rval['items']
  674. elif not isinstance(rval['results'], list):
  675. rval['results'] = [rval['results']]
  676. return rval
  677. def _schedulable(self, node=None, selector=None, schedulable=True):
  678. ''' perform oadm manage-node scheduable '''
  679. cmd = ['manage-node']
  680. if node:
  681. cmd.extend(node)
  682. else:
  683. cmd.append('--selector=%s' % selector)
  684. cmd.append('--schedulable=%s' % schedulable)
  685. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
  686. def _list_pods(self, node=None, selector=None, pod_selector=None):
  687. ''' perform oadm list pods
  688. node: the node in which to list pods
  689. selector: the label selector filter if provided
  690. pod_selector: the pod selector filter if provided
  691. '''
  692. cmd = ['manage-node']
  693. if node:
  694. cmd.extend(node)
  695. else:
  696. cmd.append('--selector=%s' % selector)
  697. if pod_selector:
  698. cmd.append('--pod-selector=%s' % pod_selector)
  699. cmd.extend(['--list-pods', '-o', 'json'])
  700. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  701. # pylint: disable=too-many-arguments
  702. def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
  703. ''' perform oadm manage-node evacuate '''
  704. cmd = ['manage-node']
  705. if node:
  706. cmd.extend(node)
  707. else:
  708. cmd.append('--selector=%s' % selector)
  709. if dry_run:
  710. cmd.append('--dry-run')
  711. if pod_selector:
  712. cmd.append('--pod-selector=%s' % pod_selector)
  713. if grace_period:
  714. cmd.append('--grace-period=%s' % int(grace_period))
  715. if force:
  716. cmd.append('--force')
  717. cmd.append('--evacuate')
  718. return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
  719. def _version(self):
  720. ''' return the openshift version'''
  721. return self.openshift_cmd(['version'], output=True, output_type='raw')
  722. def _import_image(self, url=None, name=None, tag=None):
  723. ''' perform image import '''
  724. cmd = ['import-image']
  725. image = '{0}'.format(name)
  726. if tag:
  727. image += ':{0}'.format(tag)
  728. cmd.append(image)
  729. if url:
  730. cmd.append('--from={0}/{1}'.format(url, image))
  731. cmd.append('-n{0}'.format(self.namespace))
  732. cmd.append('--confirm')
  733. return self.openshift_cmd(cmd)
  734. def _run(self, cmds, input_data):
  735. ''' Actually executes the command. This makes mocking easier. '''
  736. curr_env = os.environ.copy()
  737. curr_env.update({'KUBECONFIG': self.kubeconfig})
  738. proc = subprocess.Popen(cmds,
  739. stdin=subprocess.PIPE,
  740. stdout=subprocess.PIPE,
  741. stderr=subprocess.PIPE,
  742. env=curr_env)
  743. stdout, stderr = proc.communicate(input_data)
  744. return proc.returncode, stdout, stderr
  745. # pylint: disable=too-many-arguments,too-many-branches
  746. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
  747. '''Base command for oc '''
  748. cmds = []
  749. if oadm:
  750. cmds = ['oadm']
  751. else:
  752. cmds = ['oc']
  753. if self.all_namespaces:
  754. cmds.extend(['--all-namespaces'])
  755. elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
  756. cmds.extend(['-n', self.namespace])
  757. cmds.extend(cmd)
  758. rval = {}
  759. results = ''
  760. err = None
  761. if self.verbose:
  762. print(' '.join(cmds))
  763. returncode, stdout, stderr = self._run(cmds, input_data)
  764. rval = {"returncode": returncode,
  765. "results": results,
  766. "cmd": ' '.join(cmds)}
  767. if returncode == 0:
  768. if output:
  769. if output_type == 'json':
  770. try:
  771. rval['results'] = json.loads(stdout)
  772. except ValueError as err:
  773. if "No JSON object could be decoded" in err.args:
  774. err = err.args
  775. elif output_type == 'raw':
  776. rval['results'] = stdout
  777. if self.verbose:
  778. print("STDOUT: {0}".format(stdout))
  779. print("STDERR: {0}".format(stderr))
  780. if err:
  781. rval.update({"err": err,
  782. "stderr": stderr,
  783. "stdout": stdout,
  784. "cmd": cmds})
  785. else:
  786. rval.update({"stderr": stderr,
  787. "stdout": stdout,
  788. "results": {}})
  789. return rval
  790. class Utils(object):
  791. ''' utilities for openshiftcli modules '''
  792. @staticmethod
  793. def create_file(rname, data, ftype='yaml'):
  794. ''' create a file in tmp with name and contents'''
  795. path = os.path.join('/tmp', rname)
  796. with open(path, 'w') as fds:
  797. if ftype == 'yaml':
  798. fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper))
  799. elif ftype == 'json':
  800. fds.write(json.dumps(data))
  801. else:
  802. fds.write(data)
  803. # Register cleanup when module is done
  804. atexit.register(Utils.cleanup, [path])
  805. return path
  806. @staticmethod
  807. def create_files_from_contents(content, content_type=None):
  808. '''Turn an array of dict: filename, content into a files array'''
  809. if not isinstance(content, list):
  810. content = [content]
  811. files = []
  812. for item in content:
  813. path = Utils.create_file(item['path'], item['data'], ftype=content_type)
  814. files.append({'name': os.path.basename(path), 'path': path})
  815. return files
  816. @staticmethod
  817. def cleanup(files):
  818. '''Clean up on exit '''
  819. for sfile in files:
  820. if os.path.exists(sfile):
  821. if os.path.isdir(sfile):
  822. shutil.rmtree(sfile)
  823. elif os.path.isfile(sfile):
  824. os.remove(sfile)
  825. @staticmethod
  826. def exists(results, _name):
  827. ''' Check to see if the results include the name '''
  828. if not results:
  829. return False
  830. if Utils.find_result(results, _name):
  831. return True
  832. return False
  833. @staticmethod
  834. def find_result(results, _name):
  835. ''' Find the specified result by name'''
  836. rval = None
  837. for result in results:
  838. if 'metadata' in result and result['metadata']['name'] == _name:
  839. rval = result
  840. break
  841. return rval
  842. @staticmethod
  843. def get_resource_file(sfile, sfile_type='yaml'):
  844. ''' return the service file '''
  845. contents = None
  846. with open(sfile) as sfd:
  847. contents = sfd.read()
  848. if sfile_type == 'yaml':
  849. contents = yaml.load(contents, yaml.RoundTripLoader)
  850. elif sfile_type == 'json':
  851. contents = json.loads(contents)
  852. return contents
  853. @staticmethod
  854. def filter_versions(stdout):
  855. ''' filter the oc version output '''
  856. version_dict = {}
  857. version_search = ['oc', 'openshift', 'kubernetes']
  858. for line in stdout.strip().split('\n'):
  859. for term in version_search:
  860. if not line:
  861. continue
  862. if line.startswith(term):
  863. version_dict[term] = line.split()[-1]
  864. # horrible hack to get openshift version in Openshift 3.2
  865. # By default "oc version in 3.2 does not return an "openshift" version
  866. if "openshift" not in version_dict:
  867. version_dict["openshift"] = version_dict["oc"]
  868. return version_dict
  869. @staticmethod
  870. def add_custom_versions(versions):
  871. ''' create custom versions strings '''
  872. versions_dict = {}
  873. for tech, version in versions.items():
  874. # clean up "-" from version
  875. if "-" in version:
  876. version = version.split("-")[0]
  877. if version.startswith('v'):
  878. versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
  879. # "v3.3.0.33" is what we have, we want "3.3"
  880. versions_dict[tech + '_short'] = version[1:4]
  881. return versions_dict
  882. @staticmethod
  883. def openshift_installed():
  884. ''' check if openshift is installed '''
  885. import yum
  886. yum_base = yum.YumBase()
  887. if yum_base.rpmdb.searchNevra(name='atomic-openshift'):
  888. return True
  889. return False
  890. # Disabling too-many-branches. This is a yaml dictionary comparison function
  891. # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
  892. @staticmethod
  893. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  894. ''' Given a user defined definition, compare it with the results given back by our query. '''
  895. # Currently these values are autogenerated and we do not need to check them
  896. skip = ['metadata', 'status']
  897. if skip_keys:
  898. skip.extend(skip_keys)
  899. for key, value in result_def.items():
  900. if key in skip:
  901. continue
  902. # Both are lists
  903. if isinstance(value, list):
  904. if key not in user_def:
  905. if debug:
  906. print('User data does not have key [%s]' % key)
  907. print('User data: %s' % user_def)
  908. return False
  909. if not isinstance(user_def[key], list):
  910. if debug:
  911. print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
  912. return False
  913. if len(user_def[key]) != len(value):
  914. if debug:
  915. print("List lengths are not equal.")
  916. print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
  917. print("user_def: %s" % user_def[key])
  918. print("value: %s" % value)
  919. return False
  920. for values in zip(user_def[key], value):
  921. if isinstance(values[0], dict) and isinstance(values[1], dict):
  922. if debug:
  923. print('sending list - list')
  924. print(type(values[0]))
  925. print(type(values[1]))
  926. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  927. if not result:
  928. print('list compare returned false')
  929. return False
  930. elif value != user_def[key]:
  931. if debug:
  932. print('value should be identical')
  933. print(value)
  934. print(user_def[key])
  935. return False
  936. # recurse on a dictionary
  937. elif isinstance(value, dict):
  938. if key not in user_def:
  939. if debug:
  940. print("user_def does not have key [%s]" % key)
  941. return False
  942. if not isinstance(user_def[key], dict):
  943. if debug:
  944. print("dict returned false: not instance of dict")
  945. return False
  946. # before passing ensure keys match
  947. api_values = set(value.keys()) - set(skip)
  948. user_values = set(user_def[key].keys()) - set(skip)
  949. if api_values != user_values:
  950. if debug:
  951. print("keys are not equal in dict")
  952. print(api_values)
  953. print(user_values)
  954. return False
  955. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  956. if not result:
  957. if debug:
  958. print("dict returned false")
  959. print(result)
  960. return False
  961. # Verify each key, value pair is the same
  962. else:
  963. if key not in user_def or value != user_def[key]:
  964. if debug:
  965. print("value not equal; user_def does not have key")
  966. print(key)
  967. print(value)
  968. if key in user_def:
  969. print(user_def[key])
  970. return False
  971. if debug:
  972. print('returning true')
  973. return True
  974. class OpenShiftCLIConfig(object):
  975. '''Generic Config'''
  976. def __init__(self, rname, namespace, kubeconfig, options):
  977. self.kubeconfig = kubeconfig
  978. self.name = rname
  979. self.namespace = namespace
  980. self._options = options
  981. @property
  982. def config_options(self):
  983. ''' return config options '''
  984. return self._options
  985. def to_option_list(self):
  986. '''return all options as a string'''
  987. return self.stringify()
  988. def stringify(self):
  989. ''' return the options hash as cli params in a string '''
  990. rval = []
  991. for key, data in self.config_options.items():
  992. if data['include'] \
  993. and (data['value'] or isinstance(data['value'], int)):
  994. rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))
  995. return rval
  996. # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
  997. # -*- -*- -*- Begin included fragment: class/oc_process.py -*- -*- -*-
  998. # pylint: disable=too-many-instance-attributes
  999. class OCProcess(OpenShiftCLI):
  1000. ''' Class to wrap the oc command line tools '''
  1001. # pylint allows 5. we need 6
  1002. # pylint: disable=too-many-arguments
  1003. def __init__(self,
  1004. namespace,
  1005. tname=None,
  1006. params=None,
  1007. create=False,
  1008. kubeconfig='/etc/origin/master/admin.kubeconfig',
  1009. tdata=None,
  1010. verbose=False):
  1011. ''' Constructor for OpenshiftOC '''
  1012. super(OCProcess, self).__init__(namespace, kubeconfig)
  1013. self.namespace = namespace
  1014. self.name = tname
  1015. self.data = tdata
  1016. self.params = params
  1017. self.create = create
  1018. self.kubeconfig = kubeconfig
  1019. self.verbose = verbose
  1020. self._template = None
  1021. @property
  1022. def template(self):
  1023. '''template property'''
  1024. if self._template == None:
  1025. results = self._process(self.name, False, self.params, self.data)
  1026. if results['returncode'] != 0:
  1027. raise OpenShiftCLIError('Error processing template [%s].' % self.name)
  1028. self._template = results['results']['items']
  1029. return self._template
  1030. def get(self):
  1031. '''get the template'''
  1032. results = self._get('template', self.name)
  1033. if results['returncode'] != 0:
  1034. # Does the template exist??
  1035. if 'not found' in results['stderr']:
  1036. results['returncode'] = 0
  1037. results['exists'] = False
  1038. results['results'] = []
  1039. return results
  1040. def delete(self, obj):
  1041. '''delete a resource'''
  1042. return self._delete(obj['kind'], obj['metadata']['name'])
  1043. def create_obj(self, obj):
  1044. '''create a resource'''
  1045. return self._create_from_content(obj['metadata']['name'], obj)
  1046. def process(self, create=None):
  1047. '''process a template'''
  1048. do_create = False
  1049. if create != None:
  1050. do_create = create
  1051. else:
  1052. do_create = self.create
  1053. return self._process(self.name, do_create, self.params, self.data)
  1054. def exists(self):
  1055. '''return whether the template exists'''
  1056. # Always return true if we're being passed template data
  1057. if self.data:
  1058. return True
  1059. t_results = self._get('template', self.name)
  1060. if t_results['returncode'] != 0:
  1061. # Does the template exist??
  1062. if 'not found' in t_results['stderr']:
  1063. return False
  1064. else:
  1065. raise OpenShiftCLIError('Something went wrong. %s' % t_results)
  1066. return True
  1067. def needs_update(self):
  1068. '''attempt to process the template and return it for comparison with oc objects'''
  1069. obj_results = []
  1070. for obj in self.template:
  1071. # build a list of types to skip
  1072. skip = []
  1073. if obj['kind'] == 'ServiceAccount':
  1074. skip.extend(['secrets', 'imagePullSecrets'])
  1075. if obj['kind'] == 'BuildConfig':
  1076. skip.extend(['lastTriggeredImageID'])
  1077. if obj['kind'] == 'ImageStream':
  1078. skip.extend(['generation'])
  1079. if obj['kind'] == 'DeploymentConfig':
  1080. skip.extend(['lastTriggeredImage'])
  1081. # fetch the current object
  1082. curr_obj_results = self._get(obj['kind'], obj['metadata']['name'])
  1083. if curr_obj_results['returncode'] != 0:
  1084. # Does the template exist??
  1085. if 'not found' in curr_obj_results['stderr']:
  1086. obj_results.append((obj, True))
  1087. continue
  1088. # check the generated object against the existing object
  1089. if not Utils.check_def_equal(obj, curr_obj_results['results'][0], skip_keys=skip):
  1090. obj_results.append((obj, True))
  1091. continue
  1092. obj_results.append((obj, False))
  1093. return obj_results
  1094. @staticmethod
  1095. def run_ansible(params, check_mode):
  1096. '''run the ansible idempotent code'''
  1097. ocprocess = OCProcess(params['namespace'],
  1098. params['template_name'],
  1099. params['params'],
  1100. params['create'],
  1101. kubeconfig=params['kubeconfig'],
  1102. tdata=params['content'],
  1103. verbose=params['debug'])
  1104. state = params['state']
  1105. api_rval = ocprocess.get()
  1106. if state == 'list':
  1107. if api_rval['returncode'] != 0:
  1108. return {"failed": True, "msg" : api_rval}
  1109. return {"changed" : False, "results": api_rval, "state": "list"}
  1110. elif state == 'present':
  1111. if not ocprocess.exists() or not params['reconcile']:
  1112. #FIXME: this code will never get run in a way that succeeds when
  1113. # module.params['reconcile'] is true. Because oc_process doesn't
  1114. # create the actual template, the check of ocprocess.exists()
  1115. # is meaningless. Either it's already here and this code
  1116. # won't be run, or this code will fail because there is no
  1117. # template available for oc process to use. Have we conflated
  1118. # the template's existence with the existence of the objects
  1119. # it describes?
  1120. # Create it here
  1121. api_rval = ocprocess.process()
  1122. if api_rval['returncode'] != 0:
  1123. return {"failed": True, "msg": api_rval}
  1124. if params['create']:
  1125. return {"changed": True, "results": api_rval, "state": "present"}
  1126. return {"changed": False, "results": api_rval, "state": "present"}
  1127. # verify results
  1128. update = False
  1129. rval = []
  1130. all_results = ocprocess.needs_update()
  1131. for obj, status in all_results:
  1132. if status:
  1133. ocprocess.delete(obj)
  1134. results = ocprocess.create_obj(obj)
  1135. results['kind'] = obj['kind']
  1136. rval.append(results)
  1137. update = True
  1138. if not update:
  1139. return {"changed": update, "results": api_rval, "state": "present"}
  1140. for cmd in rval:
  1141. if cmd['returncode'] != 0:
  1142. return {"failed": True, "changed": update, "results": rval, "state": "present"}
  1143. return {"changed": update, "results": rval, "state": "present"}
  1144. # -*- -*- -*- End included fragment: class/oc_process.py -*- -*- -*-
  1145. # -*- -*- -*- Begin included fragment: ansible/oc_process.py -*- -*- -*-
  1146. def main():
  1147. '''
  1148. ansible oc module for processing templates
  1149. '''
  1150. module = AnsibleModule(
  1151. argument_spec=dict(
  1152. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  1153. state=dict(default='present', type='str', choices=['present', 'list']),
  1154. debug=dict(default=False, type='bool'),
  1155. namespace=dict(default='default', type='str'),
  1156. template_name=dict(default=None, type='str'),
  1157. content=dict(default=None, type='str'),
  1158. params=dict(default=None, type='dict'),
  1159. create=dict(default=False, type='bool'),
  1160. reconcile=dict(default=True, type='bool'),
  1161. ),
  1162. supports_check_mode=True,
  1163. )
  1164. rval = OCProcess.run_ansible(module.params, module.check_mode)
  1165. if 'failed' in rval:
  1166. module.fail_json(**rval)
  1167. module.exit_json(**rval)
  1168. if __name__ == '__main__':
  1169. main()
  1170. # -*- -*- -*- End included fragment: ansible/oc_process.py -*- -*- -*-