|
| 1 | +# Copyright (c) 2019 Ansible Project |
| 2 | +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 | + |
| 4 | +from __future__ import (absolute_import, division, print_function) |
| 5 | +__metaclass__ = type |
| 6 | + |
| 7 | +import os |
| 8 | +import shutil |
| 9 | +import json |
| 10 | +from subprocess import Popen, PIPE |
| 11 | + |
| 12 | +from copy import deepcopy |
| 13 | + |
| 14 | +from ansible.module_utils.six import StringIO, string_types |
| 15 | +from ansible.errors import AnsibleError, AnsibleFilterError |
| 16 | +from ansible.utils.display import Display |
| 17 | +from ansible.utils.path import unfrackpath, makedirs_safe |
| 18 | + |
| 19 | +display = Display() |
| 20 | + |
| 21 | +SECTIONS = ('ANSIBLE_METADATA', 'DOCUMENTATION', 'EXAMPLES', 'RETURN') |
| 22 | + |
| 23 | +DOC_SECTION_SANITIZE = ('mutually_exclusive', 'required_together', 'required_one_of', 'supports_check_mode', 'required_if') |
| 24 | + |
| 25 | +DEFAULT_RETURN = """ |
| 26 | +before: |
| 27 | + description: The configuration prior to the model invocation. |
| 28 | + returned: always |
| 29 | + sample: The configuration returned will always be in the same format of the parameters above. |
| 30 | +after: |
| 31 | + description: The resulting configuration model invocation. |
| 32 | + returned: when changed |
| 33 | + sample: The configuration returned will always be in the same format of the parameters above. |
| 34 | +commands: |
| 35 | + description: The set of commands pushed to the remote device. |
| 36 | + returned: always |
| 37 | + type: list |
| 38 | + sample: ['command 1', 'command 2', 'command 3'] |
| 39 | +""" |
| 40 | + |
| 41 | +output = StringIO() |
| 42 | +RM_DIR_PATH = "~/.ansible/tmp/resource_model" |
| 43 | + |
| 44 | + |
| 45 | +def to_list(val): |
| 46 | + if isinstance(val, (list, tuple, set)): |
| 47 | + return list(val) |
| 48 | + elif val is not None: |
| 49 | + return [val] |
| 50 | + else: |
| 51 | + return list() |
| 52 | + |
| 53 | + |
| 54 | +def add(line, spaces=0, newline=True): |
| 55 | + line = line.rjust(len(line)+spaces, ' ') |
| 56 | + if newline: |
| 57 | + output.write(line + '\n') |
| 58 | + else: |
| 59 | + output.write(line) |
| 60 | + |
| 61 | + |
| 62 | +def get_ansible_metadata(spec, path): |
| 63 | + # write ansible metadata |
| 64 | + if 'ANSIBLE_METADATA' not in spec: |
| 65 | + raise AnsibleFilterError("missing required element 'ANSIBLE_METADATA' in model") |
| 66 | + |
| 67 | + metadata = spec['ANSIBLE_METADATA'] |
| 68 | + if not isinstance(metadata, string_types): |
| 69 | + raise AnsibleFilterError("value of element 'ANSIBLE_METADATA' should be of type string") |
| 70 | + |
| 71 | + add('ANSIBLE_METADATA = %s' % metadata, newline=True) |
| 72 | + #add(metadata) |
| 73 | + |
| 74 | + |
| 75 | +def get_documentation(spec, path): |
| 76 | + # write documentation |
| 77 | + if 'DOCUMENTATION' not in spec: |
| 78 | + raise AnsibleFilterError("missing required element 'DOCUMENTATION' in model") |
| 79 | + |
| 80 | + doc = spec['DOCUMENTATION'] |
| 81 | + if not isinstance(doc, string_types): |
| 82 | + raise AnsibleFilterError("value of element 'DOCUMENTATION' should be of type string") |
| 83 | + |
| 84 | + add('DOCUMENTATION = """') |
| 85 | + add('---') |
| 86 | + add('%s' % doc) |
| 87 | + add('"""') |
| 88 | + |
| 89 | + |
| 90 | +def get_examples(spec, path): |
| 91 | + # write examples |
| 92 | + if 'EXAMPLES' not in spec: |
| 93 | + raise AnsibleFilterError("missing required element 'EXAMPLES' in model") |
| 94 | + |
| 95 | + add('EXAMPLES = """') |
| 96 | + dir_name = os.path.dirname(path) |
| 97 | + for item in to_list(spec['EXAMPLES']): |
| 98 | + with open(os.path.join(dir_name, item)) as fp: |
| 99 | + add(fp.read().strip("\n")) |
| 100 | + add("\n") |
| 101 | + add('"""') |
| 102 | + |
| 103 | + |
| 104 | +def get_return(spec, path): |
| 105 | + # write return |
| 106 | + ret = spec.get('RETURN') |
| 107 | + add('RETURN = """') |
| 108 | + add(ret) if ret else add(DEFAULT_RETURN.strip()) |
| 109 | + add('"""') |
| 110 | + |
| 111 | + |
| 112 | +def validate_model(model, contents): |
| 113 | + try: |
| 114 | + resource_module_dir = unfrackpath(RM_DIR_PATH) |
| 115 | + makedirs_safe(resource_module_dir) |
| 116 | + module_name = "%s_%s" % (model['NETWORK_OS'], model['RESOURCE']) |
| 117 | + module_file_path = os.path.join(RM_DIR_PATH, '%s.%s' % (module_name, 'py')) |
| 118 | + module_file_path = os.path.realpath(os.path.expanduser(module_file_path)) |
| 119 | + with open(module_file_path, 'w+') as fp: |
| 120 | + fp.write(contents) |
| 121 | + |
| 122 | + display.debug("Module file: %s" % module_file_path) |
| 123 | + |
| 124 | + # validate the model |
| 125 | + cmd = ["ansible-doc", "-M", os.path.dirname(module_file_path), module_name] |
| 126 | + p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) |
| 127 | + out, err = p.communicate() |
| 128 | + if err: |
| 129 | + raise AnsibleError("Error while parsing module: %s" % err) |
| 130 | + display.debug("Module output:\n%s" % out) |
| 131 | + except Exception as e: |
| 132 | + raise AnsibleError('Failed to validate the model with error: %s\n%s' % (e, contents)) |
| 133 | + finally: |
| 134 | + shutil.rmtree(os.path.realpath(os.path.expanduser(resource_module_dir)), ignore_errors=True) |
| 135 | + |
| 136 | + |
| 137 | +def _sanitize_documentation(doc): |
| 138 | + sanitize_doc =[] |
| 139 | + for line in doc.splitlines(): |
| 140 | + for item in DOC_SECTION_SANITIZE: |
| 141 | + if line.strip().startswith(item): |
| 142 | + break |
| 143 | + else: |
| 144 | + sanitize_doc.append(line) |
| 145 | + return "\n".join(sanitize_doc) |
| 146 | + |
| 147 | + |
| 148 | +def to_doc(rm, path): |
| 149 | + model = deepcopy(rm) |
| 150 | + model['DOCUMENTATION'] = _sanitize_documentation(rm['DOCUMENTATION']) |
| 151 | + path = os.path.realpath(os.path.expanduser(path)) |
| 152 | + if not os.path.isfile(path): |
| 153 | + raise AnsibleFilterError("model file %s does not exist" % path) |
| 154 | + |
| 155 | + for name in SECTIONS: |
| 156 | + func = globals().get('get_%s' % name.lower()) |
| 157 | + func(model, path) |
| 158 | + |
| 159 | + contents = output.getvalue() |
| 160 | + display.debug("%s" % contents) |
| 161 | + validate_model(model, contents) |
| 162 | + |
| 163 | + return contents |
| 164 | + |
| 165 | + |
| 166 | +class FilterModule(object): |
| 167 | + def filters(self): |
| 168 | + return { |
| 169 | + 'to_doc': to_doc, |
| 170 | + } |
0 commit comments