Adam Tengler | b1ebaca | 2017-05-04 21:06:08 +0000 | [diff] [blame^] | 1 | import io |
| 2 | import json |
| 3 | import logging |
| 4 | |
| 5 | LOG = logging.getLogger(__name__) |
| 6 | |
| 7 | |
| 8 | def __virtual__(): |
| 9 | return True |
| 10 | |
| 11 | |
| 12 | def rule_list(path, **kwargs): |
| 13 | try: |
| 14 | with io.open(path, 'r') as file_handle: |
| 15 | rules = json.loads(file_handle.read()) |
| 16 | rules = {str(k): str(v) for (k, v) in rules.items()} |
| 17 | except Exception as e: |
| 18 | msg = "Unable to load policy JSON %s: %s" % (path, repr(e)) |
| 19 | LOG.debug(msg) |
| 20 | rules = {'Error': msg} |
| 21 | return rules |
| 22 | |
| 23 | |
| 24 | def rule_delete(name, path, **kwargs): |
| 25 | ret = {} |
| 26 | rules = __salt__['keystone_policy.rule_list'](path, **kwargs) |
| 27 | if 'Error' not in rules: |
| 28 | if name not in rules: |
| 29 | return ret |
| 30 | del rules[name] |
| 31 | try: |
| 32 | with io.open(path, 'w') as file_handle: |
| 33 | file_handle.write(unicode(json.dumps(rules, indent=4))) |
| 34 | except Exception as e: |
| 35 | msg = "Unable to save policy json: %s" % repr(e) |
| 36 | LOG.error(msg) |
| 37 | return {'Error': msg} |
| 38 | ret = 'Rule {0} deleted'.format(name) |
| 39 | return ret |
| 40 | |
| 41 | |
| 42 | def rule_set(name, rule, path, **kwargs): |
| 43 | rules = __salt__['keystone_policy.rule_list'](path, **kwargs) |
| 44 | if 'Error' not in rules: |
| 45 | if name in rules and rules[name] == rule: |
| 46 | return {name: 'Rule %s already exists and is in correct state' % name} |
| 47 | rules.update({name: rule}) |
| 48 | try: |
| 49 | with io.open(path, 'w') as file_handle: |
| 50 | file_handle.write(unicode(json.dumps(rules, indent=4))) |
| 51 | except Exception as e: |
| 52 | msg = "Unable to save policy JSON %s: %s" % (path, repr(e)) |
| 53 | LOG.error(msg) |
| 54 | return {'Error': msg} |
| 55 | return rule_get(name, path, **kwargs) |
| 56 | return rules |
| 57 | |
| 58 | |
| 59 | def rule_get(name, path, **kwargs): |
| 60 | ret = {} |
| 61 | rules = __salt__['keystone_policy.rule_list'](path, **kwargs) |
| 62 | if 'Error' in rules: |
| 63 | ret['Error'] = rules['Error'] |
| 64 | elif name in rules: |
| 65 | ret[name] = rules.get(name) |
| 66 | |
| 67 | return ret |
| 68 | |