Debian Codegraph @

test/lib/ansible_test/_internal/payload.py

raw
1 """Payload management for sending Ansible files and test content to other systems (VMs, containers)."""
2
3 from __future__ import annotations
4
5 import os
6 import stat
7 import tarfile
8 import tempfile
9 import time
10 import typing as t
11
12 from .constants import (
13 ANSIBLE_BIN_SYMLINK_MAP,
14 )
15
16 from .config import (
17 IntegrationConfig,
18 ShellConfig,
19 )
20
21 from .util import (
22 display,
23 ANSIBLE_SOURCE_ROOT,
24 remove_tree,
25 is_subdir,
26 )
27
28 from .data import (
29 data_context,
30 PayloadConfig,
31 )
32
33 from .util_common import (
34 CommonConfig,
35 ExitHandler,
36 )
37
38 # improve performance by disabling uid/gid lookups
39 tarfile.pwd = None # type: ignore[attr-defined] # undocumented attribute
40 tarfile.grp = None # type: ignore[attr-defined] # undocumented attribute
41
42
43 def create_payload(args: CommonConfig, dst_path: str) -> None:
44 """Create a payload for delegation."""
45 if args.explain:
46 return
47
48 files = list(data_context().ansible_source)
49 permissions: dict[str, int] = {}
50 filters: dict[str, t.Callable[[tarfile.TarInfo], t.Optional[tarfile.TarInfo]]] = {}
51
52 # Exclude vendored files from the payload.
53 # They may not be compatible with the delegated environment.
54 files = [
55 (abs_path, rel_path) for abs_path, rel_path in files
56 if not rel_path.startswith('lib/ansible/_vendor/')
57 or rel_path == 'lib/ansible/_vendor/__init__.py'
58 ]
59
60 def apply_permissions(tar_info: tarfile.TarInfo, mode: int) -> t.Optional[tarfile.TarInfo]:
61 """
62 Apply the specified permissions to the given file.
63 Existing file type bits are preserved.
64 """
65 tar_info.mode &= ~(stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
66 tar_info.mode |= mode
67
68 return tar_info
69
70 def make_executable(tar_info: tarfile.TarInfo) -> t.Optional[tarfile.TarInfo]:
71 """
72 Make the given file executable and readable by all, and writeable by the owner.
73 Existing file type bits are preserved.
74 This ensures consistency of test results when using unprivileged users.
75 """
76 return apply_permissions(
77 tar_info,
78 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
79 stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH |
80 stat.S_IWUSR
81 ) # fmt: skip
82
83 def make_non_executable(tar_info: tarfile.TarInfo) -> t.Optional[tarfile.TarInfo]:
84 """
85 Make the given file readable by all, and writeable by the owner.
86 Existing file type bits are preserved.
87 This ensures consistency of test results when using unprivileged users.
88 """
89 return apply_permissions(
90 tar_info,
91 stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
92 stat.S_IWUSR
93 ) # fmt: skip
94
95 def detect_permissions(tar_info: tarfile.TarInfo) -> t.Optional[tarfile.TarInfo]:
96 """
97 Detect and apply the appropriate permissions for a file.
98 Existing file type bits are preserved.
99 This ensures consistency of test results when using unprivileged users.
100 """
101 if tar_info.path.startswith('ansible/'):
102 mode = permissions.get(os.path.relpath(tar_info.path, 'ansible'))
103 elif data_context().content.collection and is_subdir(tar_info.path, data_context().content.collection.directory):
104 mode = permissions.get(os.path.relpath(tar_info.path, data_context().content.collection.directory))
105 else:
106 mode = None
107
108 if mode:
109 tar_info = apply_permissions(tar_info, mode)
110 elif tar_info.mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
111 # If any execute bit is set, treat the file as executable.
112 # This ensures that sanity tests which check execute bits behave correctly.
113 tar_info = make_executable(tar_info)
114 else:
115 tar_info = make_non_executable(tar_info)
116
117 return tar_info
118
119 if not ANSIBLE_SOURCE_ROOT:
120 # reconstruct the bin directory which is not available when running from an ansible install
121 files.extend(create_temporary_bin_files(args))
122 filters.update(dict((os.path.join('ansible', path[3:]), make_executable) for path in ANSIBLE_BIN_SYMLINK_MAP.values() if path.startswith('../')))
123
124 if not data_context().content.is_ansible:
125 # exclude unnecessary files when not testing ansible itself
126 files = [f for f in files if
127 is_subdir(f[1], 'bin/') or
128 is_subdir(f[1], 'lib/ansible/') or
129 is_subdir(f[1], 'test/lib/ansible_test/')]
130
131 if not isinstance(args, (ShellConfig, IntegrationConfig)):
132 # exclude built-in ansible modules when they are not needed
133 files = [f for f in files if not is_subdir(f[1], 'lib/ansible/modules/') or f[1] == 'lib/ansible/modules/__init__.py']
134
135 collection_layouts = data_context().create_collection_layouts()
136
137 content_files: list[tuple[str, str]] = []
138 extra_files: list[tuple[str, str]] = []
139
140 for layout in collection_layouts:
141 if layout == data_context().content:
142 # include files from the current collection (layout.collection.directory will be added later)
143 content_files.extend((os.path.join(layout.root, path), path) for path in data_context().content.all_files())
144 else:
145 # include files from each collection in the same collection root as the content being tested
146 extra_files.extend((os.path.join(layout.root, path), os.path.join(layout.collection.directory, path)) for path in layout.all_files())
147 else:
148 # when testing ansible itself the ansible source is the content
149 content_files = files
150 # there are no extra files when testing ansible itself
151 extra_files = []
152
153 payload_config = PayloadConfig(
154 files=content_files,
155 permissions=permissions,
156 )
157
158 for callback in data_context().payload_callbacks:
159 # execute callbacks only on the content paths
160 # this is done before placing them in the appropriate subdirectory (see below)
161 callback(payload_config)
162
163 # place ansible source files under the 'ansible' directory on the delegated host
164 files = [(src, os.path.join('ansible', dst)) for src, dst in files]
165
166 if data_context().content.collection:
167 # place collection files under the 'ansible_collections/{namespace}/{collection}' directory on the delegated host
168 files.extend((src, os.path.join(data_context().content.collection.directory, dst)) for src, dst in content_files)
169 # extra files already have the correct destination path
170 files.extend(extra_files)
171
172 # maintain predictable file order
173 files = sorted(set(files))
174
175 display.info('Creating a payload archive containing %d files...' % len(files), verbosity=1)
176
177 start = time.time()
178
179 with tarfile.open(dst_path, mode='w:gz', compresslevel=4, format=tarfile.GNU_FORMAT) as tar:
180 for src, dst in files:
181 display.info('%s -> %s' % (src, dst), verbosity=4)
182 tar.add(src, dst, filter=filters.get(dst, detect_permissions))
183
184 duration = time.time() - start
185 payload_size_bytes = os.path.getsize(dst_path)
186
187 display.info('Created a %d byte payload archive containing %d files in %d seconds.' % (payload_size_bytes, len(files), duration), verbosity=1)
188
189
190 def create_temporary_bin_files(args: CommonConfig) -> tuple[tuple[str, str], ...]:
191 """Create a temporary ansible bin directory populated using the symlink map."""
192 if args.explain:
193 temp_path = '/tmp/ansible-tmp-bin'
194 else:
195 temp_path = tempfile.mkdtemp(prefix='ansible', suffix='bin')
196 ExitHandler.register(remove_tree, temp_path)
197
198 for name, dest in ANSIBLE_BIN_SYMLINK_MAP.items():
199 path = os.path.join(temp_path, name)
200 os.symlink(dest, path)
201
202 return tuple((os.path.join(temp_path, name), os.path.join('bin', name)) for name in sorted(ANSIBLE_BIN_SYMLINK_MAP))