Debian Codegraph @

lib/ansible/plugins/action/gather_facts.py

raw
1 # Copyright (c) 2017 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 annotations
5
6 import os
7 import time
8 import typing as t
9
10 from ansible import constants as C
11 from ansible.errors import AnsibleActionFail
12 from ansible.executor.module_common import _apply_action_arg_defaults
13 from ansible.module_utils.parsing.convert_bool import boolean
14 from ansible.plugins.action import ActionBase
15 from ansible.utils.vars import merge_hash
16 from ansible._internal._errors import _error_utils
17
18
19 class ActionModule(ActionBase):
20
21 _supports_check_mode = True
22
23 def _get_module_args(self, fact_module: str, task_vars: dict[str, t.Any]) -> dict[str, t.Any]:
24
25 mod_args = self._task.args.copy()
26
27 # deal with 'setup specific arguments'
28 if fact_module not in C._ACTION_SETUP:
29
30 # TODO: remove in favor of controller side argspec detecting valid arguments
31 # network facts modules must support gather_subset
32 name = self._connection.ansible_name.removeprefix('ansible.netcommon.')
33
34 if name not in ('network_cli', 'httpapi', 'netconf'):
35 subset = mod_args.pop('gather_subset', None)
36 if subset not in ('all', ['all'], None):
37 self._display.warning('Not passing subset(%s) to %s' % (subset, fact_module))
38
39 timeout = mod_args.pop('gather_timeout', None)
40 if timeout is not None:
41 self._display.warning('Not passing timeout(%s) to %s' % (timeout, fact_module))
42
43 fact_filter = mod_args.pop('filter', None)
44 if fact_filter is not None:
45 self._display.warning('Not passing filter(%s) to %s' % (fact_filter, fact_module))
46
47 # Strip out keys with ``None`` values, effectively mimicking ``omit`` behavior
48 # This ensures we don't pass a ``None`` value as an argument expecting a specific type
49 mod_args = dict((k, v) for k, v in mod_args.items() if v is not None)
50
51 # handle module defaults
52 resolved_fact_module = self._shared_loader_obj.module_loader.find_plugin_with_context(
53 fact_module, collection_list=self._task.collections
54 ).resolved_fqcn
55
56 mod_args = _apply_action_arg_defaults(resolved_fact_module, self._task, mod_args, self._templar)
57
58 return mod_args
59
60 def _combine_task_result(self, result: dict[str, t.Any], task_result: dict[str, t.Any]) -> dict[str, t.Any]:
61 """ builds the final result to return """
62 filtered_res = {
63 'ansible_facts': task_result.get('ansible_facts', {}),
64 'warnings': task_result.get('warnings', []),
65 'deprecations': task_result.get('deprecations', []),
66 }
67
68 # on conflict the last plugin processed wins, but try to do deep merge and append to lists.
69 return merge_hash(result, filtered_res, list_merge='append_rp')
70
71 def _handle_smart(self, modules: list, task_vars: dict[str, t.Any]):
72 """ Updates the module list when 'smart' is used, lookup network os mappings or use setup, warn when things seem inconsistent """
73
74 if 'smart' not in modules:
75 return
76
77 modules.pop(modules.index('smart')) # remove as this will cause 'module not found' errors
78 network_os = self._task.args.get('network_os', task_vars.get('ansible_network_os', task_vars.get('ansible_facts', {}).get('network_os')))
79
80 if network_os:
81
82 connection_map = C.config.get_config_value('CONNECTION_FACTS_MODULES', variables=task_vars)
83 if network_os in connection_map:
84 modules.append(connection_map[network_os])
85 elif not modules:
86 raise AnsibleActionFail(f"No fact modules available and we could not find a fact module for your network OS ({network_os}), "
87 "try setting one via the `FACTS_MODULES` configuration.")
88
89 if set(modules).intersection(set(C._ACTION_SETUP)):
90 # most don't realize how setup works with networking connection plugins (forced_local)
91 self._display.warning("Detected 'setup' module and a network OS is set, the output when running it will reflect 'localhost'"
92 " and not the target when a networking connection plugin is used.")
93
94 elif not set(modules).intersection(set(C._ACTION_SETUP)):
95 # no network OS and setup not in list, add setup by default since 'smart'
96 modules.append('ansible.legacy.setup')
97
98 def run(self, tmp: t.Optional[str] = None, task_vars: t.Optional[dict[str, t.Any]] = None) -> dict[str, t.Any]:
99
100 result = super(ActionModule, self).run(tmp, task_vars)
101 result['ansible_facts'] = {}
102
103 # copy the value with list() so we don't mutate the config
104 modules = list(C.config.get_config_value('FACTS_MODULES', variables=task_vars))
105 self._handle_smart(modules, task_vars)
106
107 parallel = task_vars.pop('ansible_facts_parallel', self._task.args.pop('parallel', None))
108
109 failed: dict[str, t.Any] = {}
110 skipped: dict[str, t.Any] = {}
111
112 if parallel is None:
113 if len(modules) > 1:
114 parallel = True
115 else:
116 parallel = False
117 else:
118 parallel = boolean(parallel)
119
120 timeout = self._task.args.get('gather_timeout', None)
121 async_val = self._task.async_val
122
123 if not parallel:
124 # serially execute each module
125 for fact_module in modules:
126 # just one module, no need for fancy async
127 mod_args = self._get_module_args(fact_module, task_vars)
128 # TODO: use gather_timeout to cut module execution if module itself does not support gather_timeout
129 res = self._execute_module(module_name=fact_module, module_args=mod_args, task_vars=task_vars, wrap_async=False)
130 if res.get('failed', False):
131 failed[fact_module] = res
132 elif res.get('skipped', False):
133 skipped[fact_module] = res
134 else:
135 result = self._combine_task_result(result, res)
136
137 self._remove_tmp_path(self._connection._shell.tmpdir)
138 else:
139 # do it async, aka parallel
140 jobs: dict[str, t.Any] = {}
141
142 for fact_module in modules:
143 mod_args = self._get_module_args(fact_module, task_vars)
144
145 # if module does not handle timeout, use timeout to handle module, hijack async_val as this is what async_wrapper uses
146 # TODO: make this action complain about async/async settings, use parallel option instead .. or remove parallel in favor of async settings?
147 if timeout and 'gather_timeout' not in mod_args:
148 self._task.async_val = int(timeout)
149 elif async_val != 0:
150 self._task.async_val = async_val
151 else:
152 self._task.async_val = 0
153
154 self._display.vvvv("Running %s" % fact_module)
155 jobs[fact_module] = (self._execute_module(module_name=fact_module, module_args=mod_args, task_vars=task_vars, wrap_async=True))
156
157 while jobs:
158 for module in jobs:
159 poll_args = {'jid': jobs[module]['ansible_job_id'], '_async_dir': os.path.dirname(jobs[module]['results_file'])}
160 res = self._execute_module(module_name='ansible.legacy.async_status', module_args=poll_args, task_vars=task_vars, wrap_async=False)
161 if res.get('finished', False):
162 if res.get('failed', False):
163 failed[module] = res
164 elif res.get('skipped', False):
165 skipped[module] = res
166 else:
167 result = self._combine_task_result(result, res)
168 del jobs[module]
169 break
170 else:
171 time.sleep(0.1)
172 else:
173 time.sleep(0.5)
174
175 # restore value for post processing
176 if self._task.async_val != async_val:
177 self._task.async_val = async_val
178
179 if skipped:
180 result['msg'] = f"The following modules were skipped: {', '.join(skipped.keys())}."
181 result['skipped_modules'] = skipped
182 if len(skipped) == len(modules):
183 result['skipped'] = True # deprecated: description='returning skipped from actions/modules' core_version='2.25'
184 result['changed'] = False
185
186 if failed:
187 result['failed_modules'] = failed
188
189 result.update(_error_utils.result_dict_from_captured_errors(
190 msg=f"The following modules failed to execute: {', '.join(failed.keys())}.",
191 errors=[r['exception'] for r in failed.values()],
192 ))
193
194 # tell executor facts were gathered
195 result['ansible_facts']['_ansible_facts_gathered'] = True
196
197 # hack to keep --verbose from showing all the setup module result
198 result['_ansible_verbose_override'] = True
199
200 return result