Debian Codegraph @

lib/ansible/inventory/group.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
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 typing as t
7
8 from collections.abc import Mapping, MutableMapping
9 from enum import Enum
10 from itertools import chain
11
12 from ansible import constants as C
13 from ansible.errors import AnsibleError
14 from ansible.module_utils.common.text.converters import to_native, to_text
15 from ansible.utils.display import Display
16 from ansible.utils.vars import combine_vars, validate_variable_name
17
18 from . import helpers # this is left as a module import to facilitate easier unit test patching
19
20 display = Display()
21
22 if t.TYPE_CHECKING:
23 from .host import Host
24
25
26 def to_safe_group_name(name, replacer="_", force=False, silent=False):
27 # Converts 'bad' characters in a string to underscores (or provided replacer) so they can be used as Ansible hosts or groups
28
29 warn = ''
30 if name: # when deserializing we might not have name yet
31 invalid_chars = C.INVALID_VARIABLE_NAMES.findall(name)
32 if invalid_chars:
33 msg = 'invalid character(s) "%s" in group name (%s)' % (to_text(set(invalid_chars)), to_text(name))
34 if C.TRANSFORM_INVALID_GROUP_CHARS not in ('never', 'ignore') or force:
35 name = C.INVALID_VARIABLE_NAMES.sub(replacer, name)
36 if not (silent or C.TRANSFORM_INVALID_GROUP_CHARS == 'silently'):
37 display.vvvv('Replacing ' + msg)
38 warn = 'Invalid characters were found in group names and automatically replaced, use -vvvv to see details'
39 else:
40 if C.TRANSFORM_INVALID_GROUP_CHARS == 'never':
41 display.vvvv('Not replacing %s' % msg)
42 warn = 'Invalid characters were found in group names but not replaced, use -vvvv to see details'
43
44 if warn:
45 display.warning(warn)
46
47 return name
48
49
50 class InventoryObjectType(Enum):
51 HOST = 0
52 GROUP = 1
53
54
55 class Group:
56 """A group of ansible hosts."""
57 base_type = InventoryObjectType.GROUP
58
59 # __slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ]
60
61 def __init__(self, name: str) -> None:
62 name = helpers.remove_trust(name)
63
64 self.depth: int = 0
65 self.name: str = to_safe_group_name(name)
66 self.hosts: list[Host] = []
67 self._hosts: set[str] | None = None
68 self.vars: dict[str, t.Any] = {}
69 self.child_groups: list[Group] = []
70 self.parent_groups: list[Group] = []
71 self._hosts_cache: list[Host] | None = None
72 self.priority: int = 1
73
74 def __repr__(self):
75 return self.get_name()
76
77 def __str__(self):
78 return self.get_name()
79
80 def _walk_relationship(self, rel, include_self=False, preserve_ordering=False) -> set[Group] | list[Group]:
81 """
82 Given `rel` that is an iterable property of Group,
83 consitituting a directed acyclic graph among all groups,
84 Returns a set of all groups in full tree
85 A B C
86 | / | /
87 | / | /
88 D -> E
89 | / vertical connections
90 | / are directed upward
91 F
92 Called on F, returns set of (A, B, C, D, E)
93 """
94 seen: set[Group] = set([])
95 unprocessed = set(getattr(self, rel))
96 if include_self:
97 unprocessed.add(self)
98 if preserve_ordering:
99 ordered: list[Group] = [self] if include_self else []
100 ordered.extend(getattr(self, rel))
101
102 while unprocessed:
103 seen.update(unprocessed)
104 new_unprocessed = set([])
105
106 for new_item in chain.from_iterable(getattr(g, rel) for g in unprocessed):
107 new_unprocessed.add(new_item)
108 if preserve_ordering:
109 if new_item not in seen:
110 ordered.append(new_item)
111
112 new_unprocessed.difference_update(seen)
113 unprocessed = new_unprocessed
114
115 if preserve_ordering:
116 return ordered
117 return seen
118
119 def get_ancestors(self) -> set[Group]:
120 return t.cast(set, self._walk_relationship('parent_groups'))
121
122 def get_descendants(self, **kwargs) -> set[Group] | list[Group]:
123 return self._walk_relationship('child_groups', **kwargs)
124
125 @property
126 def host_names(self) -> set[str]:
127 if self._hosts is None:
128 self._hosts = {h.name for h in self.hosts}
129 return self._hosts
130
131 def get_name(self) -> str:
132 return self.name
133
134 def add_child_group(self, group: Group) -> bool:
135 added = False
136 if self == group:
137 raise Exception("can't add group to itself")
138
139 # don't add if it's already there
140 if group not in self.child_groups:
141
142 # prepare list of group's new ancestors this edge creates
143 start_ancestors = group.get_ancestors()
144 new_ancestors = self.get_ancestors()
145 if group in new_ancestors:
146 raise AnsibleError("Adding group '%s' as child to '%s' creates a recursive dependency loop." % (to_native(group.name), to_native(self.name)))
147 new_ancestors.add(self)
148 new_ancestors.difference_update(start_ancestors)
149
150 added = True
151 self.child_groups.append(group)
152
153 # update the depth of the child
154 group.depth = max([self.depth + 1, group.depth])
155
156 # update the depth of the grandchildren
157 group._check_children_depth()
158
159 # now add self to child's parent_groups list, but only if there
160 # isn't already a group with the same name
161 if self.name not in [g.name for g in group.parent_groups]:
162 group.parent_groups.append(self)
163 for h in group.get_hosts():
164 h.populate_ancestors(additions=new_ancestors)
165
166 self.clear_hosts_cache()
167 return added
168
169 def _check_children_depth(self) -> None:
170
171 depth = self.depth
172 start_depth = self.depth # self.depth could change over loop
173 seen = set([])
174 unprocessed = set(self.child_groups)
175
176 while unprocessed:
177 seen.update(unprocessed)
178 depth += 1
179 to_process = unprocessed.copy()
180 unprocessed = set([])
181 for g in to_process:
182 if g.depth < depth:
183 g.depth = depth
184 unprocessed.update(g.child_groups)
185 if depth - start_depth > len(seen):
186 raise AnsibleError("The group named '%s' has a recursive dependency loop." % to_native(self.name))
187
188 def add_host(self, host: Host) -> bool:
189 added = False
190 if host.name not in self.host_names:
191 self.hosts.append(host)
192 self._hosts.add(host.name)
193 host.add_group(self)
194 self.clear_hosts_cache()
195 added = True
196 return added
197
198 def remove_host(self, host: Host) -> bool:
199 removed = False
200 if host.name in self.host_names:
201 self.hosts.remove(host)
202 self._hosts.remove(host.name)
203 host.remove_group(self)
204 self.clear_hosts_cache()
205 removed = True
206 return removed
207
208 def set_variable(self, key: str, value: t.Any) -> None:
209 key = helpers.remove_trust(key)
210
211 try:
212 validate_variable_name(key)
213 except AnsibleError as ex:
214 Display().deprecated(msg=f'Accepting inventory variable with invalid name {key!r}.', version='2.23', help_text=ex._help_text, obj=ex.obj)
215
216 if key == 'ansible_group_priority':
217 self.set_priority(value)
218 else:
219 if key in self.vars and isinstance(self.vars[key], MutableMapping) and isinstance(value, Mapping):
220 self.vars = combine_vars(self.vars, {key: value})
221 else:
222 self.vars[key] = value
223
224 def clear_hosts_cache(self) -> None:
225
226 self._hosts_cache = None
227 for g in self.get_ancestors():
228 g._hosts_cache = None
229
230 def get_hosts(self) -> list[Host]:
231
232 if self._hosts_cache is None:
233 self._hosts_cache = self._get_hosts()
234 return self._hosts_cache
235
236 def _get_hosts(self) -> list[Host]:
237
238 hosts: list[Host] = []
239 seen: set[Host] = set()
240 for kid in self.get_descendants(include_self=True, preserve_ordering=True):
241 kid_hosts = kid.hosts
242 for kk in kid_hosts:
243 if kk not in seen:
244 seen.add(kk)
245 if self.name == 'all' and kk.implicit:
246 continue
247 hosts.append(kk)
248 return hosts
249
250 def get_vars(self) -> dict[str, t.Any]:
251 return self.vars.copy()
252
253 def set_priority(self, priority: int | str) -> None:
254 try:
255 self.priority = int(priority)
256 except (TypeError, ValueError) as e:
257 display.error_as_warning(
258 msg=f"Invalid priority value '{priority}' for group '{self.name}'."
259 "Setting priority to default value.",
260 exception=e,
261 )
262 # Keep the existing priority value when conversion fails