oc_edit.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. #!/usr/bin/env python
  2. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  3. # / __| __| \| | __| _ \ /_\_ _| __| \
  4. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  5. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  6. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  7. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  8. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  9. '''
  10. OpenShiftCLI class that wraps the oc commands in a subprocess
  11. '''
  12. import atexit
  13. import json
  14. import os
  15. import shutil
  16. import subprocess
  17. import re
  18. import yaml
  19. # This is here because of a bug that causes yaml
  20. # to incorrectly handle timezone info on timestamps
  21. def timestamp_constructor(_, node):
  22. '''return timestamps as strings'''
  23. return str(node.value)
  24. yaml.add_constructor(u'tag:yaml.org,2002:timestamp', timestamp_constructor)
  25. # pylint: disable=too-few-public-methods
  26. class OpenShiftCLI(object):
  27. ''' Class to wrap the command line tools '''
  28. def __init__(self,
  29. namespace,
  30. kubeconfig='/etc/origin/master/admin.kubeconfig',
  31. verbose=False):
  32. ''' Constructor for OpenshiftCLI '''
  33. self.namespace = namespace
  34. self.verbose = verbose
  35. self.kubeconfig = kubeconfig
  36. # Pylint allows only 5 arguments to be passed.
  37. # pylint: disable=too-many-arguments
  38. def _replace_content(self, resource, rname, content, force=False):
  39. ''' replace the current object with the content '''
  40. res = self._get(resource, rname)
  41. if not res['results']:
  42. return res
  43. fname = '/tmp/%s' % rname
  44. yed = Yedit(fname, res['results'][0])
  45. changes = []
  46. for key, value in content.items():
  47. changes.append(yed.put(key, value))
  48. if any([not change[0] for change in changes]):
  49. return {'returncode': 0, 'updated': False}
  50. yed.write()
  51. atexit.register(Utils.cleanup, [fname])
  52. return self._replace(fname, force)
  53. def _replace(self, fname, force=False):
  54. '''return all pods '''
  55. cmd = ['-n', self.namespace, 'replace', '-f', fname]
  56. if force:
  57. cmd.append('--force')
  58. return self.openshift_cmd(cmd)
  59. def _create(self, fname):
  60. '''return all pods '''
  61. return self.openshift_cmd(['create', '-f', fname, '-n', self.namespace])
  62. def _delete(self, resource, rname):
  63. '''return all pods '''
  64. return self.openshift_cmd(['delete', resource, rname, '-n', self.namespace])
  65. def _get(self, resource, rname=None):
  66. '''return a secret by name '''
  67. cmd = ['get', resource, '-o', 'json', '-n', self.namespace]
  68. if rname:
  69. cmd.append(rname)
  70. rval = self.openshift_cmd(cmd, output=True)
  71. # Ensure results are retuned in an array
  72. if rval.has_key('items'):
  73. rval['results'] = rval['items']
  74. elif not isinstance(rval['results'], list):
  75. rval['results'] = [rval['results']]
  76. return rval
  77. def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json'):
  78. '''Base command for oc '''
  79. #cmds = ['/usr/bin/oc', '--config', self.kubeconfig]
  80. cmds = []
  81. if oadm:
  82. cmds = ['/usr/bin/oadm']
  83. else:
  84. cmds = ['/usr/bin/oc']
  85. cmds.extend(cmd)
  86. rval = {}
  87. results = ''
  88. err = None
  89. if self.verbose:
  90. print ' '.join(cmds)
  91. proc = subprocess.Popen(cmds,
  92. stdout=subprocess.PIPE,
  93. stderr=subprocess.PIPE,
  94. env={'KUBECONFIG': self.kubeconfig})
  95. proc.wait()
  96. stdout = proc.stdout.read()
  97. stderr = proc.stderr.read()
  98. rval = {"returncode": proc.returncode,
  99. "results": results,
  100. "cmd": ' '.join(cmds),
  101. }
  102. if proc.returncode == 0:
  103. if output:
  104. if output_type == 'json':
  105. try:
  106. rval['results'] = json.loads(stdout)
  107. except ValueError as err:
  108. if "No JSON object could be decoded" in err.message:
  109. err = err.message
  110. elif output_type == 'raw':
  111. rval['results'] = stdout
  112. if self.verbose:
  113. print stdout
  114. print stderr
  115. print
  116. if err:
  117. rval.update({"err": err,
  118. "stderr": stderr,
  119. "stdout": stdout,
  120. "cmd": cmds
  121. })
  122. else:
  123. rval.update({"stderr": stderr,
  124. "stdout": stdout,
  125. "results": {},
  126. })
  127. return rval
  128. class Utils(object):
  129. ''' utilities for openshiftcli modules '''
  130. @staticmethod
  131. def create_file(rname, data, ftype=None):
  132. ''' create a file in tmp with name and contents'''
  133. path = os.path.join('/tmp', rname)
  134. with open(path, 'w') as fds:
  135. if ftype == 'yaml':
  136. fds.write(yaml.safe_dump(data, default_flow_style=False))
  137. elif ftype == 'json':
  138. fds.write(json.dumps(data))
  139. else:
  140. fds.write(data)
  141. # Register cleanup when module is done
  142. atexit.register(Utils.cleanup, [path])
  143. return path
  144. @staticmethod
  145. def create_files_from_contents(data):
  146. '''Turn an array of dict: filename, content into a files array'''
  147. files = []
  148. for sfile in data:
  149. path = Utils.create_file(sfile['path'], sfile['content'])
  150. files.append(path)
  151. return files
  152. @staticmethod
  153. def cleanup(files):
  154. '''Clean up on exit '''
  155. for sfile in files:
  156. if os.path.exists(sfile):
  157. if os.path.isdir(sfile):
  158. shutil.rmtree(sfile)
  159. elif os.path.isfile(sfile):
  160. os.remove(sfile)
  161. @staticmethod
  162. def exists(results, _name):
  163. ''' Check to see if the results include the name '''
  164. if not results:
  165. return False
  166. if Utils.find_result(results, _name):
  167. return True
  168. return False
  169. @staticmethod
  170. def find_result(results, _name):
  171. ''' Find the specified result by name'''
  172. rval = None
  173. for result in results:
  174. if result.has_key('metadata') and result['metadata']['name'] == _name:
  175. rval = result
  176. break
  177. return rval
  178. @staticmethod
  179. def get_resource_file(sfile, sfile_type='yaml'):
  180. ''' return the service file '''
  181. contents = None
  182. with open(sfile) as sfd:
  183. contents = sfd.read()
  184. if sfile_type == 'yaml':
  185. contents = yaml.safe_load(contents)
  186. elif sfile_type == 'json':
  187. contents = json.loads(contents)
  188. return contents
  189. # Disabling too-many-branches. This is a yaml dictionary comparison function
  190. # pylint: disable=too-many-branches,too-many-return-statements
  191. @staticmethod
  192. def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
  193. ''' Given a user defined definition, compare it with the results given back by our query. '''
  194. # Currently these values are autogenerated and we do not need to check them
  195. skip = ['metadata', 'status']
  196. if skip_keys:
  197. skip.extend(skip_keys)
  198. for key, value in result_def.items():
  199. if key in skip:
  200. continue
  201. # Both are lists
  202. if isinstance(value, list):
  203. if not isinstance(user_def[key], list):
  204. if debug:
  205. print 'user_def[key] is not a list'
  206. return False
  207. for values in zip(user_def[key], value):
  208. if isinstance(values[0], dict) and isinstance(values[1], dict):
  209. if debug:
  210. print 'sending list - list'
  211. print type(values[0])
  212. print type(values[1])
  213. result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
  214. if not result:
  215. print 'list compare returned false'
  216. return False
  217. elif value != user_def[key]:
  218. if debug:
  219. print 'value should be identical'
  220. print value
  221. print user_def[key]
  222. return False
  223. # recurse on a dictionary
  224. elif isinstance(value, dict):
  225. if not isinstance(user_def[key], dict):
  226. if debug:
  227. print "dict returned false not instance of dict"
  228. return False
  229. # before passing ensure keys match
  230. api_values = set(value.keys()) - set(skip)
  231. user_values = set(user_def[key].keys()) - set(skip)
  232. if api_values != user_values:
  233. if debug:
  234. print api_values
  235. print user_values
  236. print "keys are not equal in dict"
  237. return False
  238. result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
  239. if not result:
  240. if debug:
  241. print "dict returned false"
  242. print result
  243. return False
  244. # Verify each key, value pair is the same
  245. else:
  246. if not user_def.has_key(key) or value != user_def[key]:
  247. if debug:
  248. print "value not equal; user_def does not have key"
  249. print value
  250. print user_def[key]
  251. return False
  252. return True
  253. class YeditException(Exception):
  254. ''' Exception class for Yedit '''
  255. pass
  256. class Yedit(object):
  257. ''' Class to modify yaml files '''
  258. re_valid_key = r"(((\[-?\d+\])|([a-zA-Z-./]+)).?)+$"
  259. re_key = r"(?:\[(-?\d+)\])|([a-zA-Z-./]+)"
  260. def __init__(self, filename=None, content=None, content_type='yaml'):
  261. self.content = content
  262. self.filename = filename
  263. self.__yaml_dict = content
  264. self.content_type = content_type
  265. if self.filename and not self.content:
  266. self.load(content_type=self.content_type)
  267. @property
  268. def yaml_dict(self):
  269. ''' getter method for yaml_dict '''
  270. return self.__yaml_dict
  271. @yaml_dict.setter
  272. def yaml_dict(self, value):
  273. ''' setter method for yaml_dict '''
  274. self.__yaml_dict = value
  275. @staticmethod
  276. def remove_entry(data, key):
  277. ''' remove data at location key '''
  278. if not (key and re.match(Yedit.re_valid_key, key) and isinstance(data, (list, dict))):
  279. return None
  280. key_indexes = re.findall(Yedit.re_key, key)
  281. for arr_ind, dict_key in key_indexes[:-1]:
  282. if dict_key and isinstance(data, dict):
  283. data = data.get(dict_key, None)
  284. elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1:
  285. data = data[int(arr_ind)]
  286. else:
  287. return None
  288. # process last index for remove
  289. # expected list entry
  290. if key_indexes[-1][0]:
  291. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1:
  292. del data[int(key_indexes[-1][0])]
  293. return True
  294. # expected dict entry
  295. elif key_indexes[-1][1]:
  296. if isinstance(data, dict):
  297. del data[key_indexes[-1][1]]
  298. return True
  299. @staticmethod
  300. def add_entry(data, key, item=None):
  301. ''' Get an item from a dictionary with key notation a.b.c
  302. d = {'a': {'b': 'c'}}}
  303. key = a.b
  304. return c
  305. '''
  306. if not (key and re.match(Yedit.re_valid_key, key) and isinstance(data, (list, dict))):
  307. return None
  308. curr_data = data
  309. key_indexes = re.findall(Yedit.re_key, key)
  310. for arr_ind, dict_key in key_indexes[:-1]:
  311. if dict_key:
  312. if isinstance(data, dict) and data.has_key(dict_key):
  313. data = data[dict_key]
  314. continue
  315. data[dict_key] = {}
  316. data = data[dict_key]
  317. elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1:
  318. data = data[int(arr_ind)]
  319. else:
  320. return None
  321. # process last index for add
  322. # expected list entry
  323. if key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1:
  324. data[int(key_indexes[-1][0])] = item
  325. # expected dict entry
  326. elif key_indexes[-1][1] and isinstance(data, dict):
  327. data[key_indexes[-1][1]] = item
  328. return curr_data
  329. @staticmethod
  330. def get_entry(data, key):
  331. ''' Get an item from a dictionary with key notation a.b.c
  332. d = {'a': {'b': 'c'}}}
  333. key = a.b
  334. return c
  335. '''
  336. if not (key and re.match(Yedit.re_valid_key, key) and isinstance(data, (list, dict))):
  337. return None
  338. key_indexes = re.findall(Yedit.re_key, key)
  339. for arr_ind, dict_key in key_indexes:
  340. if dict_key and isinstance(data, dict):
  341. data = data.get(dict_key, None)
  342. elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1:
  343. data = data[int(arr_ind)]
  344. else:
  345. return None
  346. return data
  347. def write(self):
  348. ''' write to file '''
  349. if not self.filename:
  350. raise YeditException('Please specify a filename.')
  351. with open(self.filename, 'w') as yfd:
  352. yfd.write(yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  353. def read(self):
  354. ''' write to file '''
  355. # check if it exists
  356. if not self.exists():
  357. return None
  358. contents = None
  359. with open(self.filename) as yfd:
  360. contents = yfd.read()
  361. return contents
  362. def exists(self):
  363. ''' return whether file exists '''
  364. if os.path.exists(self.filename):
  365. return True
  366. return False
  367. def load(self, content_type='yaml'):
  368. ''' return yaml file '''
  369. contents = self.read()
  370. if not contents:
  371. return None
  372. # check if it is yaml
  373. try:
  374. if content_type == 'yaml':
  375. self.yaml_dict = yaml.load(contents)
  376. elif content_type == 'json':
  377. self.yaml_dict = json.loads(contents)
  378. except yaml.YAMLError as _:
  379. # Error loading yaml or json
  380. return None
  381. return self.yaml_dict
  382. def get(self, key):
  383. ''' get a specified key'''
  384. try:
  385. entry = Yedit.get_entry(self.yaml_dict, key)
  386. except KeyError as _:
  387. entry = None
  388. return entry
  389. def delete(self, key):
  390. ''' remove key from a dict'''
  391. try:
  392. entry = Yedit.get_entry(self.yaml_dict, key)
  393. except KeyError as _:
  394. entry = None
  395. if not entry:
  396. return (False, self.yaml_dict)
  397. result = Yedit.remove_entry(self.yaml_dict, key)
  398. if not result:
  399. return (False, self.yaml_dict)
  400. return (True, self.yaml_dict)
  401. def put(self, key, value):
  402. ''' put key, value into a dict '''
  403. try:
  404. entry = Yedit.get_entry(self.yaml_dict, key)
  405. except KeyError as _:
  406. entry = None
  407. if entry == value:
  408. return (False, self.yaml_dict)
  409. result = Yedit.add_entry(self.yaml_dict, key, value)
  410. if not result:
  411. return (False, self.yaml_dict)
  412. return (True, self.yaml_dict)
  413. def create(self, key, value):
  414. ''' create a yaml file '''
  415. if not self.exists():
  416. self.yaml_dict = {key: value}
  417. return (True, self.yaml_dict)
  418. return (False, self.yaml_dict)
  419. class Edit(OpenShiftCLI):
  420. ''' Class to wrap the oc command line tools
  421. '''
  422. # pylint: disable=too-many-arguments
  423. def __init__(self,
  424. kind,
  425. namespace,
  426. resource_name=None,
  427. kubeconfig='/etc/origin/master/admin.kubeconfig',
  428. verbose=False):
  429. ''' Constructor for OpenshiftOC '''
  430. super(Edit, self).__init__(namespace, kubeconfig)
  431. self.namespace = namespace
  432. self.kind = kind
  433. self.name = resource_name
  434. self.kubeconfig = kubeconfig
  435. self.verbose = verbose
  436. def get(self):
  437. '''return a secret by name '''
  438. return self._get(self.kind, self.name)
  439. def update(self, file_name, content, force=False, content_type='yaml'):
  440. '''run update '''
  441. if file_name:
  442. if content_type == 'yaml':
  443. data = yaml.load(open(file_name))
  444. elif content_type == 'json':
  445. data = json.loads(open(file_name).read())
  446. changes = []
  447. yed = Yedit(file_name, data)
  448. for key, value in content.items():
  449. changes.append(yed.put(key, value))
  450. if any([not change[0] for change in changes]):
  451. return {'returncode': 0, 'updated': False}
  452. yed.write()
  453. atexit.register(Utils.cleanup, [file_name])
  454. return self._replace(file_name, force=force)
  455. return self._replace_content(self.kind, self.name, content, force=force)
  456. def main():
  457. '''
  458. ansible oc module for services
  459. '''
  460. module = AnsibleModule(
  461. argument_spec=dict(
  462. kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
  463. state=dict(default='present', type='str',
  464. choices=['present']),
  465. debug=dict(default=False, type='bool'),
  466. namespace=dict(default='default', type='str'),
  467. name=dict(default=None, required=True, type='str'),
  468. kind=dict(required=True,
  469. type='str',
  470. choices=['dc', 'deploymentconfig',
  471. 'svc', 'service',
  472. 'scc', 'securitycontextconstraints',
  473. 'ns', 'namespace', 'project', 'projects',
  474. 'is', 'imagestream',
  475. 'istag', 'imagestreamtag',
  476. 'bc', 'buildconfig',
  477. 'routes',
  478. 'node',
  479. 'secret',
  480. ]),
  481. file_name=dict(default=None, type='str'),
  482. file_format=dict(default='yaml', type='str'),
  483. content=dict(default=None, required=True, type='dict'),
  484. force=dict(default=False, type='bool'),
  485. ),
  486. supports_check_mode=True,
  487. )
  488. ocedit = Edit(module.params['kind'],
  489. module.params['namespace'],
  490. module.params['name'],
  491. kubeconfig=module.params['kubeconfig'],
  492. verbose=module.params['debug'])
  493. state = module.params['state']
  494. api_rval = ocedit.get()
  495. ########
  496. # Create
  497. ########
  498. if not Utils.exists(api_rval['results'], module.params['name']):
  499. module.fail_json(msg=api_rval)
  500. ########
  501. # Update
  502. ########
  503. api_rval = ocedit.update(module.params['file_name'],
  504. module.params['content'],
  505. module.params['force'],
  506. module.params['file_format'])
  507. if api_rval['returncode'] != 0:
  508. module.fail_json(msg=api_rval)
  509. if api_rval.has_key('updated') and not api_rval['updated']:
  510. module.exit_json(changed=False, results=api_rval, state="present")
  511. # return the created object
  512. api_rval = ocedit.get()
  513. if api_rval['returncode'] != 0:
  514. module.fail_json(msg=api_rval)
  515. module.exit_json(changed=True, results=api_rval, state="present")
  516. module.exit_json(failed=True,
  517. changed=False,
  518. results='Unknown state passed. %s' % state,
  519. state="unknown")
  520. # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
  521. # import module snippets. This are required
  522. from ansible.module_utils.basic import *
  523. main()