Debian Codegraph @

hacking/test-module.py

raw
1 #!/usr/bin/env python
2
3 # (c) 2012, Michael DeHaan <[email protected]>
4 #
5 # This file is part of Ansible
6 #
7 # Ansible is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Ansible is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 # this script is for testing modules without running through the
22 # entire guts of ansible, and is very helpful for when developing
23 # modules
24 #
25 # example:
26 # ./hacking/test-module.py -m lib/ansible/modules/command.py -a "/bin/sleep 3"
27 # ./hacking/test-module.py -m lib/ansible/modules/command.py -a "/bin/sleep 3" --debugger /usr/bin/pdb
28 # ./hacking/test-module.py -m lib/ansible/modules/lineinfile.py -a "dest=/etc/exports line='/srv/home hostname1(rw,sync)'" --check
29 # ./hacking/test-module.py -m lib/ansible/modules/command.py -a "echo hello" -n -o "test_hello"
30
31 from __future__ import annotations
32
33 import glob
34 import optparse
35 import os
36 import subprocess
37 import sys
38 import traceback
39 import shutil
40
41 from pathlib import Path
42
43 from ansible.release import __version__
44 import ansible.utils.vars as utils_vars
45 from ansible.parsing.dataloader import DataLoader
46 from ansible.parsing.splitter import parse_kv
47 from ansible.plugins.loader import init_plugin_loader
48 from ansible.executor import module_common
49 import ansible.constants as C
50 from ansible.module_utils.common.text.converters import to_native, to_text
51 from ansible.template import Templar
52
53 import json
54
55
56 def parse():
57 """parse command line
58
59 :return : (options, args)"""
60 parser = optparse.OptionParser()
61
62 parser.usage = "%prog -[options] (-h for help)"
63
64 parser.add_option('-m', '--module-path', dest='module_path',
65 help="REQUIRED: full path of module source to execute")
66 parser.add_option('-a', '--args', dest='module_args', default="",
67 help="module argument string")
68 parser.add_option('-D', '--debugger', dest='debugger',
69 help="path to python debugger (e.g. /usr/bin/pdb)")
70 parser.add_option('-I', '--interpreter', dest='interpreter',
71 help="path to interpreter to use for this module"
72 " (e.g. ansible_python_interpreter=/usr/bin/python)",
73 metavar='INTERPRETER_TYPE=INTERPRETER_PATH',
74 default="ansible_python_interpreter=%s" %
75 (sys.executable if sys.executable else '/usr/bin/python'))
76 parser.add_option('-c', '--check', dest='check', action='store_true',
77 help="run the module in check mode")
78 parser.add_option('-n', '--noexecute', dest='execute', action='store_false',
79 default=True, help="do not run the resulting module")
80 parser.add_option('-o', '--output', dest='filename',
81 help="Filename for resulting module",
82 default="~/.ansible_module_generated")
83 options, args = parser.parse_args()
84 if not options.module_path:
85 parser.print_help()
86 sys.exit(1)
87 else:
88 return options, args
89
90
91 def jsonify(result, format=False):
92 """ format JSON output (uncompressed or uncompressed) """
93
94 if result is None:
95 return "{}"
96
97 indent = None
98 if format:
99 indent = 4
100
101 try:
102 return json.dumps(result, sort_keys=True, indent=indent, ensure_ascii=False)
103 except UnicodeDecodeError:
104 return json.dumps(result, sort_keys=True, indent=indent)
105
106
107 def write_argsfile(argstring, json=False):
108 """ Write args to a file for old-style module's use. """
109 argspath = Path("~/.ansible_test_module_arguments").expanduser()
110 if json:
111 args = parse_kv(argstring)
112 argstring = jsonify(args)
113 argspath.write_text(argstring)
114 return argspath
115
116
117 def get_interpreters(interpreter):
118 result = dict()
119 if interpreter:
120 if '=' not in interpreter:
121 print("interpreter must by in the form of ansible_python_interpreter=/usr/bin/python")
122 sys.exit(1)
123 interpreter_type, interpreter_path = interpreter.split('=')
124 if not interpreter_type.startswith('ansible_'):
125 interpreter_type = 'ansible_%s' % interpreter_type
126 if not interpreter_type.endswith('_interpreter'):
127 interpreter_type = '%s_interpreter' % interpreter_type
128 result[interpreter_type] = interpreter_path
129 return result
130
131
132 def boilerplate_module(modfile, args, interpreters, check, destfile):
133 """ simulate what ansible does with new style modules """
134
135 # module_fh = open(modfile)
136 # module_data = module_fh.read()
137 # module_fh.close()
138
139 # replacer = module_common.ModuleReplacer()
140 loader = DataLoader()
141
142 # included_boilerplate = module_data.find(module_common.REPLACER) != -1 or module_data.find("import ansible.module_utils") != -1
143
144 complex_args = {}
145
146 # default selinux fs list is pass in as _ansible_selinux_special_fs arg
147 complex_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS
148 complex_args['_ansible_tmpdir'] = C.DEFAULT_LOCAL_TMP
149 complex_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES
150 complex_args['_ansible_version'] = __version__
151
152 if args.startswith("@"):
153 # Argument is a YAML file (JSON is a subset of YAML)
154 complex_args = utils_vars.combine_vars(complex_args, loader.load_from_file(args[1:]))
155 args = ''
156 elif args.startswith("{"):
157 # Argument is a YAML document (not a file)
158 complex_args = utils_vars.combine_vars(complex_args, loader.load(args))
159 args = ''
160
161 if args:
162 parsed_args = parse_kv(args)
163 complex_args = utils_vars.combine_vars(complex_args, parsed_args)
164
165 task_vars = interpreters
166
167 if check:
168 complex_args['_ansible_check_mode'] = True
169
170 modfile = os.path.abspath(modfile)
171 modname = os.path.basename(modfile)
172 modname = os.path.splitext(modname)[0]
173
174 built_module = module_common.modify_module(
175 module_name=modname,
176 module_path=modfile,
177 module_args=complex_args,
178 templar=Templar(loader=loader),
179 task_vars=task_vars
180 )
181
182 module_data, module_style = built_module.b_module_data, built_module.module_style
183
184 if module_style == 'new' and '_ANSIBALLZ_WRAPPER = True' in to_native(module_data):
185 module_style = 'ansiballz'
186
187 modfile2_path = os.path.expanduser(destfile)
188 print("* including generated source, if any, saving to: %s" % modfile2_path)
189 if module_style not in ('ansiballz', 'old'):
190 print("* this may offset any line numbers in tracebacks/debuggers!")
191 with open(modfile2_path, 'wb') as modfile2:
192 modfile2.write(module_data)
193 modfile = modfile2_path
194
195 return (modfile2_path, modname, module_style)
196
197
198 def ansiballz_setup(modfile, modname, interpreters):
199 os.system("chmod +x %s" % modfile)
200
201 if 'ansible_python_interpreter' in interpreters:
202 command = [interpreters['ansible_python_interpreter']]
203 else:
204 command = []
205 command.extend([modfile, 'explode'])
206
207 cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
208 out, err = cmd.communicate()
209 out, err = to_text(out, errors='surrogate_or_strict'), to_text(err)
210 lines = out.splitlines()
211 if len(lines) != 2 or 'Module expanded into' not in lines[0]:
212 print("*" * 35)
213 print("INVALID OUTPUT FROM ANSIBALLZ MODULE WRAPPER")
214 print(out)
215 sys.exit(err)
216 debug_dir = lines[1].strip()
217
218 # All the directories in an AnsiBallZ that modules can live
219 core_dirs = glob.glob(os.path.join(debug_dir, 'ansible/modules'))
220 non_core_dirs = glob.glob(os.path.join(debug_dir, 'ansible/legacy'))
221 collection_dirs = glob.glob(os.path.join(debug_dir, 'ansible_collections/*/*/plugins/modules'))
222
223 # There's only one module in an AnsiBallZ payload so look for the first module and then exit
224 for module_dir in core_dirs + collection_dirs + non_core_dirs:
225 for dirname, directories, filenames in os.walk(module_dir):
226 for filename in filenames:
227 if filename == modname + '.py':
228 modfile = os.path.join(dirname, filename)
229 break
230
231 argsfile = os.path.join(debug_dir, 'args')
232
233 print("* ansiballz module detected; extracted module source to: %s" % debug_dir)
234 return modfile, argsfile
235
236
237 def runtest(modfile, argspath, modname, module_style, interpreters):
238 """Test run a module, piping it's output for reporting."""
239 invoke = ""
240 if module_style == 'ansiballz':
241 modfile, argspath = ansiballz_setup(modfile, modname, interpreters)
242 if 'ansible_python_interpreter' in interpreters:
243 invoke = "%s " % interpreters['ansible_python_interpreter']
244
245 os.system("chmod +x %s" % modfile)
246
247 invoke = "%s%s" % (invoke, modfile)
248 if argspath is not None:
249 invoke = "%s %s" % (invoke, argspath)
250
251 cmd = subprocess.Popen(invoke, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
252 (out, err) = cmd.communicate()
253 out, err = to_text(out), to_text(err)
254
255 try:
256 print("*" * 35)
257 print("RAW OUTPUT")
258 print(out)
259 print(err)
260 results = json.loads(out)
261 except Exception:
262 print("*" * 35)
263 print("INVALID OUTPUT FORMAT")
264 print(out)
265 traceback.print_exc()
266 sys.exit(1)
267
268 print("*" * 35)
269 print("PARSED OUTPUT")
270 print(jsonify(results, format=True))
271
272
273 def rundebug(debugger, modfile, argspath, modname, module_style, interpreters):
274 """Run interactively with console debugger."""
275
276 if module_style == 'ansiballz':
277 modfile, argspath = ansiballz_setup(modfile, modname, interpreters)
278
279 if argspath is not None:
280 subprocess.call("%s %s %s" % (debugger, modfile, argspath), shell=True)
281 else:
282 subprocess.call("%s %s" % (debugger, modfile), shell=True)
283
284
285 def main():
286
287 options, args = parse()
288 init_plugin_loader()
289 interpreters = get_interpreters(options.interpreter)
290 (modfile, modname, module_style) = boilerplate_module(options.module_path, options.module_args, interpreters, options.check, options.filename)
291
292 argspath = None
293 if module_style not in ('new', 'ansiballz'):
294 if module_style in ('non_native_want_json', 'binary'):
295 argspath = write_argsfile(options.module_args, json=True)
296 elif module_style == 'old':
297 argspath = write_argsfile(options.module_args, json=False)
298 else:
299 raise Exception("internal error, unexpected module style: %s" % module_style)
300
301 if options.execute:
302 if options.debugger:
303 rundebug(options.debugger, modfile, argspath, modname, module_style, interpreters)
304 else:
305 runtest(modfile, argspath, modname, module_style, interpreters)
306
307
308 if __name__ == "__main__":
309 try:
310 main()
311 finally:
312 shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)