Debian Codegraph @

lib/ansible/module_utils/facts/collector.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # (c) 2017 Red Hat Inc.
8 #
9 # Redistribution and use in source and binary forms, with or without modification,
10 # are permitted provided that the following conditions are met:
11 #
12 # * Redistributions of source code must retain the above copyright
13 # notice, this list of conditions and the following disclaimer.
14 # * Redistributions in binary form must reproduce the above copyright notice,
15 # this list of conditions and the following disclaimer in the documentation
16 # and/or other materials provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
26 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #
28
29 from __future__ import annotations
30
31 from collections import defaultdict
32
33 import platform
34 import typing as t
35
36 from ansible.module_utils.facts import timeout
37
38
39 class CycleFoundInFactDeps(Exception):
40 """Indicates there is a cycle in fact collector deps
41
42 If collector-B requires collector-A, and collector-A requires
43 collector-B, that is a cycle. In that case, there is no ordering
44 that will satisfy B before A and A and before B. That will cause this
45 error to be raised.
46 """
47 pass
48
49
50 class UnresolvedFactDep(ValueError):
51 pass
52
53
54 class CollectorNotFoundError(KeyError):
55 pass
56
57
58 class BaseFactCollector:
59 _fact_ids = set() # type: t.Set[str]
60
61 _platform = 'Generic'
62 name = None # type: str | None
63 required_facts = set() # type: t.Set[str]
64
65 def __init__(self, collectors=None, namespace=None):
66 """Base class for things that collect facts.
67
68 'collectors' is an optional list of other FactCollectors for composing."""
69 self.collectors = collectors or []
70
71 # self.namespace is a object with a 'transform' method that transforms
72 # the name to indicate the namespace (ie, adds a prefix or suffix).
73 self.namespace = namespace
74
75 self.fact_ids = set([self.name])
76 self.fact_ids.update(self._fact_ids)
77
78 @classmethod
79 def platform_match(cls, platform_info):
80 if platform_info.get('system', None) == cls._platform:
81 return cls
82 return None
83
84 def _transform_name(self, key_name):
85 if self.namespace:
86 return self.namespace.transform(key_name)
87 return key_name
88
89 def _transform_dict_keys(self, fact_dict):
90 """update a dicts keys to use new names as transformed by self._transform_name"""
91
92 if fact_dict is None:
93 return {}
94 for old_key in list(fact_dict.keys()):
95 new_key = self._transform_name(old_key)
96 # pop the item by old_key and replace it using new_key
97 fact_dict[new_key] = fact_dict.pop(old_key)
98 return fact_dict
99
100 # TODO/MAYBE: rename to 'collect' and add 'collect_without_namespace'
101 def collect_with_namespace(self, module=None, collected_facts=None):
102 # collect, then transform the key names if needed
103 facts_dict = self.collect(module=module, collected_facts=collected_facts)
104 if self.namespace:
105 facts_dict = self._transform_dict_keys(facts_dict)
106 return facts_dict
107
108 def collect(self, module=None, collected_facts=None):
109 """do the fact collection
110
111 'collected_facts' is a object (a dict, likely) that holds all previously
112 facts. This is intended to be used if a FactCollector needs to reference
113 another fact (for ex, the system arch) and should not be modified (usually).
114
115 Returns a dict of facts.
116
117 """
118 facts_dict = {}
119 return facts_dict
120
121
122 def get_collector_names(valid_subsets=None,
123 minimal_gather_subset=None,
124 gather_subset=None,
125 aliases_map=None,
126 platform_info=None):
127 """return a set of FactCollector names based on gather_subset spec.
128
129 gather_subset is a spec describing which facts to gather.
130 valid_subsets is a frozenset of potential matches for gather_subset ('all', 'network') etc
131 minimal_gather_subsets is a frozenset of matches to always use, even for gather_subset='!all'
132 """
133
134 # Retrieve module parameters
135 gather_subset = gather_subset or ['all']
136
137 # the list of everything that 'all' expands to
138 valid_subsets = valid_subsets or frozenset()
139
140 # if provided, minimal_gather_subset is always added, even after all negations
141 minimal_gather_subset = minimal_gather_subset or frozenset()
142
143 aliases_map = aliases_map or defaultdict(set)
144
145 # Retrieve all facts elements
146 additional_subsets = set()
147 exclude_subsets = set()
148
149 # total always starts with the min set, then
150 # adds of the additions in gather_subset, then
151 # excludes all of the excludes, then add any explicitly
152 # requested subsets.
153 gather_subset_with_min = ['min']
154 gather_subset_with_min.extend(gather_subset)
155
156 # subsets we mention in gather_subset explicitly, except for 'all'/'min'
157 explicitly_added = set()
158
159 for subset in gather_subset_with_min:
160 subset_id = subset
161 if subset_id == 'min':
162 additional_subsets.update(minimal_gather_subset)
163 continue
164 if subset_id == 'all':
165 additional_subsets.update(valid_subsets)
166 continue
167 if subset_id.startswith('!'):
168 subset = subset[1:]
169 if subset == 'min':
170 exclude_subsets.update(minimal_gather_subset)
171 continue
172 if subset == 'all':
173 exclude_subsets.update(valid_subsets - minimal_gather_subset)
174 continue
175 exclude = True
176 else:
177 exclude = False
178
179 if exclude:
180 # include 'devices', 'dmi' etc for '!hardware'
181 exclude_subsets.update(aliases_map.get(subset, set()))
182 exclude_subsets.add(subset)
183 else:
184 # NOTE: this only considers adding an unknown gather subsetup an error. Asking to
185 # exclude an unknown gather subset is ignored.
186 if subset_id not in valid_subsets:
187 raise TypeError("Bad subset '%s' given to Ansible. gather_subset options allowed: all, %s" %
188 (subset, ", ".join(sorted(valid_subsets))))
189
190 explicitly_added.add(subset)
191 additional_subsets.add(subset)
192
193 if not additional_subsets:
194 additional_subsets.update(valid_subsets)
195
196 additional_subsets.difference_update(exclude_subsets - explicitly_added)
197
198 return additional_subsets
199
200
201 def find_collectors_for_platform(all_collector_classes, compat_platforms):
202 found_collectors = set()
203 found_collectors_names = set()
204
205 # start from specific platform, then try generic
206 for compat_platform in compat_platforms:
207 platform_match = None
208 for all_collector_class in all_collector_classes:
209
210 # ask the class if it is compatible with the platform info
211 platform_match = all_collector_class.platform_match(compat_platform)
212
213 if not platform_match:
214 continue
215
216 primary_name = all_collector_class.name
217
218 if primary_name not in found_collectors_names:
219 found_collectors.add(all_collector_class)
220 found_collectors_names.add(all_collector_class.name)
221
222 return found_collectors
223
224
225 def build_fact_id_to_collector_map(collectors_for_platform):
226 fact_id_to_collector_map = defaultdict(list)
227 aliases_map = defaultdict(set)
228
229 for collector_class in collectors_for_platform:
230 primary_name = collector_class.name
231
232 fact_id_to_collector_map[primary_name].append(collector_class)
233
234 for fact_id in collector_class._fact_ids:
235 fact_id_to_collector_map[fact_id].append(collector_class)
236 aliases_map[primary_name].add(fact_id)
237
238 return fact_id_to_collector_map, aliases_map
239
240
241 def select_collector_classes(collector_names, all_fact_subsets):
242 seen_collector_classes = set()
243
244 selected_collector_classes = []
245
246 for collector_name in collector_names:
247 collector_classes = all_fact_subsets.get(collector_name, [])
248 for collector_class in collector_classes:
249 if collector_class not in seen_collector_classes:
250 selected_collector_classes.append(collector_class)
251 seen_collector_classes.add(collector_class)
252
253 return selected_collector_classes
254
255
256 def _get_requires_by_collector_name(collector_name, all_fact_subsets):
257 required_facts = set()
258
259 try:
260 collector_classes = all_fact_subsets[collector_name]
261 except KeyError:
262 raise CollectorNotFoundError('Fact collector "%s" not found' % collector_name)
263 for collector_class in collector_classes:
264 required_facts.update(collector_class.required_facts)
265 return required_facts
266
267
268 def find_unresolved_requires(collector_names, all_fact_subsets):
269 """Find any collector names that have unresolved requires
270
271 Returns a list of collector names that correspond to collector
272 classes whose .requires_facts() are not in collector_names.
273 """
274 unresolved = set()
275
276 for collector_name in collector_names:
277 required_facts = _get_requires_by_collector_name(collector_name, all_fact_subsets)
278 for required_fact in required_facts:
279 if required_fact not in collector_names:
280 unresolved.add(required_fact)
281
282 return unresolved
283
284
285 def resolve_requires(unresolved_requires, all_fact_subsets):
286 new_names = set()
287 failed = []
288 for unresolved in unresolved_requires:
289 if unresolved in all_fact_subsets:
290 new_names.add(unresolved)
291 else:
292 failed.append(unresolved)
293
294 if failed:
295 raise UnresolvedFactDep('unresolved fact dep %s' % ','.join(failed))
296 return new_names
297
298
299 def build_dep_data(collector_names, all_fact_subsets):
300 dep_map = defaultdict(set)
301 for collector_name in collector_names:
302 collector_deps = set()
303 for collector in all_fact_subsets[collector_name]:
304 for dep in collector.required_facts:
305 collector_deps.add(dep)
306 dep_map[collector_name] = collector_deps
307 return dep_map
308
309
310 def tsort(dep_map):
311 sorted_list = []
312
313 unsorted_map = dep_map.copy()
314
315 while unsorted_map:
316 acyclic = False
317 for node, edges in list(unsorted_map.items()):
318 for edge in edges:
319 if edge in unsorted_map:
320 break
321 else:
322 acyclic = True
323 del unsorted_map[node]
324 sorted_list.append((node, edges))
325
326 if not acyclic:
327 raise CycleFoundInFactDeps('Unable to tsort deps, there was a cycle in the graph. sorted=%s' % sorted_list)
328
329 return sorted_list
330
331
332 def _solve_deps(collector_names, all_fact_subsets):
333 unresolved = collector_names.copy()
334 solutions = collector_names.copy()
335
336 while True:
337 unresolved = find_unresolved_requires(solutions, all_fact_subsets)
338 if unresolved == set():
339 break
340
341 new_names = resolve_requires(unresolved, all_fact_subsets)
342 solutions.update(new_names)
343
344 return solutions
345
346
347 def collector_classes_from_gather_subset(all_collector_classes=None,
348 valid_subsets=None,
349 minimal_gather_subset=None,
350 gather_subset=None,
351 gather_timeout=None,
352 platform_info=None):
353 """return a list of collector classes that match the args"""
354
355 # use gather_name etc to get the list of collectors
356
357 all_collector_classes = all_collector_classes or []
358
359 minimal_gather_subset = minimal_gather_subset or frozenset()
360
361 platform_info = platform_info or {'system': platform.system()}
362
363 gather_timeout = gather_timeout or timeout.DEFAULT_GATHER_TIMEOUT
364
365 # tweak the modules GATHER_TIMEOUT
366 timeout.GATHER_TIMEOUT = gather_timeout
367
368 valid_subsets = valid_subsets or frozenset()
369
370 # maps alias names like 'hardware' to the list of names that are part of hardware
371 # like 'devices' and 'dmi'
372 aliases_map = defaultdict(set)
373
374 compat_platforms = [platform_info, {'system': 'Generic'}]
375
376 collectors_for_platform = find_collectors_for_platform(all_collector_classes, compat_platforms)
377
378 # all_facts_subsets maps the subset name ('hardware') to the class that provides it.
379
380 # TODO: name collisions here? are there facts with the same name as a gather_subset (all, network, hardware, virtual, ohai, facter)
381 all_fact_subsets, aliases_map = build_fact_id_to_collector_map(collectors_for_platform)
382
383 all_valid_subsets = frozenset(all_fact_subsets.keys())
384
385 # expand any fact_id/collectorname/gather_subset term ('all', 'env', etc) to the list of names that represents
386 collector_names = get_collector_names(valid_subsets=all_valid_subsets,
387 minimal_gather_subset=minimal_gather_subset,
388 gather_subset=gather_subset,
389 aliases_map=aliases_map,
390 platform_info=platform_info)
391
392 complete_collector_names = _solve_deps(collector_names, all_fact_subsets)
393
394 dep_map = build_dep_data(complete_collector_names, all_fact_subsets)
395
396 ordered_deps = tsort(dep_map)
397 ordered_collector_names = [x[0] for x in ordered_deps]
398
399 selected_collector_classes = select_collector_classes(ordered_collector_names,
400 all_fact_subsets)
401
402 return selected_collector_classes