Debian Codegraph @

ansible_collections/containers/podman/plugins/connection/podman.py

raw
1 # Based on modern Ansible connection plugin patterns
2 # Copyright (c) 2018 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 #
5 # Connection plugin to interact with existing podman containers.
6 # https://github.com/containers/podman
7 #
8 # Rewritten with modern patterns and enhanced functionality
9
10 from __future__ import absolute_import, division, print_function
11
12 __metaclass__ = type
13
14 DOCUMENTATION = """
15 author: Tomas Tomecek (@TomasTomecek)
16 name: podman
17 short_description: Interact with an existing podman container
18 description:
19 - Run commands or put/fetch files to an existing container using podman tool.
20 - Supports both direct execution and filesystem mounting for optimal performance.
21 options:
22 remote_addr:
23 description:
24 - The ID or name of the container you want to access.
25 default: inventory_hostname
26 vars:
27 - name: inventory_hostname
28 - name: ansible_host
29 - name: ansible_podman_host
30 env:
31 - name: ANSIBLE_PODMAN_HOST
32 ini:
33 - section: defaults
34 key: remote_addr
35 remote_user:
36 description:
37 - User specified via name or UID which is used to execute commands inside the container.
38 - If you specify the user via UID, you must set C(ANSIBLE_REMOTE_TMP) to a path that exists
39 inside the container and is writable by Ansible.
40 ini:
41 - section: defaults
42 key: remote_user
43 env:
44 - name: ANSIBLE_REMOTE_USER
45 vars:
46 - name: ansible_user
47 podman_extra_args:
48 description:
49 - Extra arguments to pass to the podman command line.
50 default: ''
51 type: str
52 ini:
53 - section: defaults
54 key: podman_extra_args
55 vars:
56 - name: ansible_podman_extra_args
57 env:
58 - name: ANSIBLE_PODMAN_EXTRA_ARGS
59 podman_executable:
60 description:
61 - Executable for podman command.
62 default: podman
63 type: str
64 vars:
65 - name: ansible_podman_executable
66 env:
67 - name: ANSIBLE_PODMAN_EXECUTABLE
68 ini:
69 - section: defaults
70 key: podman_executable
71 container_timeout:
72 description:
73 - Timeout in seconds for container operations. 0 means no timeout.
74 default: 0
75 type: int
76 vars:
77 - name: ansible_podman_timeout
78 env:
79 - name: ANSIBLE_PODMAN_TIMEOUT
80 ini:
81 - section: defaults
82 key: podman_timeout
83 mount_detection:
84 description:
85 - Enable automatic detection and use of container mount points for file operations.
86 default: true
87 type: bool
88 vars:
89 - name: ansible_podman_mount_detection
90 env:
91 - name: ANSIBLE_PODMAN_MOUNT_DETECTION
92 ignore_mount_errors:
93 description:
94 - Continue with copy operations even if container mounting fails.
95 default: true
96 type: bool
97 vars:
98 - name: ansible_podman_ignore_mount_errors
99 extra_env_vars:
100 description:
101 - Additional environment variables to set in the container.
102 default: {}
103 type: dict
104 vars:
105 - name: ansible_podman_extra_env
106 privilege_escalation_method:
107 description:
108 - Method to use for privilege escalation inside container.
109 default: 'auto'
110 choices: ['auto', 'sudo', 'su', 'none']
111 type: str
112 vars:
113 - name: ansible_podman_privilege_escalation
114 working_directory:
115 description:
116 - Working directory for commands executed in the container.
117 type: str
118 vars:
119 - name: ansible_podman_working_directory
120 """
121
122 import os
123 import shlex
124 import shutil
125 import subprocess
126
127 from ansible.errors import AnsibleConnectionFailure
128 from ansible.module_utils.common.process import get_bin_path
129 try:
130 from ansible.module_utils.common.text.converters import to_native, to_bytes, to_text # noqa: F402
131 except ImportError:
132 from ansible.module_utils.common.text import to_native, to_bytes, to_text # noqa: F402
133 from ansible.plugins.connection import ConnectionBase, ensure_connect
134 from ansible.utils.display import Display
135
136 display = Display()
137
138
139 class PodmanConnectionError(AnsibleConnectionFailure):
140 """Specific exception for podman connection issues"""
141
142
143 class ContainerNotFoundError(PodmanConnectionError):
144 """Exception for when container cannot be found"""
145
146
147 class Connection(ConnectionBase):
148 """
149 Modern connection plugin for podman with enhanced error handling and performance optimizations
150 """
151
152 transport = "containers.podman.podman"
153 has_pipelining = True
154
155 def __init__(self, play_context, new_stdin, *args, **kwargs):
156 super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
157
158 self._container_id = self._play_context.remote_addr
159 self._connected = False
160 self._container_info = None
161 self._mount_point = None
162 self._executable_path = None
163 self._task_uuid = to_text(kwargs.get("task_uuid", ""))
164
165 # No pre-validation caches to preserve performance
166
167 display.vvvv("Using podman connection from collection", host=self._container_id)
168
169 def _get_podman_executable(self):
170 """Get and cache podman executable path with validation"""
171 if self._executable_path is None:
172 executable = self.get_option("podman_executable")
173 try:
174 self._executable_path = get_bin_path(executable)
175 display.vvvv(f"Found podman executable: {self._executable_path}", host=self._container_id)
176 except ValueError as e:
177 raise PodmanConnectionError(f"Could not find {executable} in PATH: {e}")
178 return self._executable_path
179
180 def _build_podman_command(self, cmd_args, include_container=True):
181 """Build complete podman command with all options"""
182 cmd = [self._get_podman_executable()]
183
184 # Add global options
185 if self.get_option("podman_extra_args"):
186 extra_args = shlex.split(to_native(self.get_option("podman_extra_args"), errors="surrogate_or_strict"))
187 cmd.extend(extra_args)
188
189 # Add subcommand and arguments
190 if isinstance(cmd_args, str):
191 cmd.append(cmd_args)
192 else:
193 cmd.extend(cmd_args)
194
195 # Add container ID if needed
196 if include_container:
197 cmd.append(self._container_id)
198
199 return cmd
200
201 def _run_podman_command(self, cmd_args, input_data=None, check_rc=False, include_container=True):
202 """Execute podman command once with error handling"""
203 cmd = self._build_podman_command(cmd_args, include_container)
204 cmd_bytes = [to_bytes(arg, errors="surrogate_or_strict") for arg in cmd]
205
206 display.vvv(f"PODMAN EXEC: {' '.join(cmd)}", host=self._container_id)
207
208 try:
209 process = subprocess.Popen(
210 cmd_bytes, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False
211 )
212
213 # Only pass timeout if explicitly configured
214 communicate_kwargs = {}
215 container_timeout = self.get_option("container_timeout")
216 if isinstance(container_timeout, int) and container_timeout > 0:
217 communicate_kwargs["timeout"] = container_timeout
218
219 stdout, stderr = process.communicate(input=input_data, **communicate_kwargs)
220
221 display.vvvvv(f"STDOUT: {stdout}", host=self._container_id)
222 display.vvvvv(f"STDERR: {stderr}", host=self._container_id)
223 display.vvvvv(f"RC: {process.returncode}", host=self._container_id)
224
225 if process.returncode != 0:
226 error_msg = to_text(stderr, errors="surrogate_or_strict").strip()
227 lower = error_msg.lower()
228 if "no such container" in lower or "does not exist" in lower or "container not known" in lower:
229 self._connected = False
230 raise ContainerNotFoundError(f"Container '{self._container_id}' not found")
231 if check_rc:
232 raise PodmanConnectionError(f"Command failed (rc={process.returncode}): {error_msg}")
233
234 return process.returncode, stdout, stderr
235
236 except subprocess.TimeoutExpired:
237 process.kill()
238 timeout_val = self.get_option("container_timeout")
239 self._connected = False
240 raise PodmanConnectionError(f"Command timeout after {timeout_val}s")
241 except Exception as e:
242 raise PodmanConnectionError(f"Command execution failed: {e}")
243
244 # No proactive validation; rely on operation failures for performance
245
246 def _setup_mount_point(self):
247 """Attempt to mount container filesystem for direct access (lightweight)"""
248 if not self.get_option("mount_detection"):
249 return
250
251 try:
252 rc, stdout, stderr = self._run_podman_command(["mount"])
253 if rc == 0:
254 mount_point = to_text(stdout, errors="surrogate_or_strict").strip()
255 if mount_point and os.path.isdir(mount_point):
256 self._mount_point = mount_point
257 display.vvv(f"Container mounted at: {self._mount_point}", host=self._container_id)
258 else:
259 display.vvv("Container mount point is invalid", host=self._container_id)
260 else:
261 display.vvv(
262 f"Container mount failed: {to_text(stderr, errors='surrogate_or_strict')}", host=self._container_id
263 )
264 except Exception as e:
265 if not self.get_option("ignore_mount_errors"):
266 raise PodmanConnectionError(f"Mount setup failed: {e}")
267 display.vvv(f"Mount setup failed, continuing without mount: {e}", host=self._container_id)
268
269 def _connect(self):
270 """Establish connection to container with validation and setup"""
271 super(Connection, self)._connect()
272
273 if self._connected:
274 return
275
276 display.vvv(f"Connecting to container: {self._container_id}", host=self._container_id)
277
278 self._connected = True
279 display.vvv("Connection established successfully", host=self._container_id)
280
281 @ensure_connect
282 def exec_command(self, cmd, in_data=None, sudoable=False):
283 """Execute command in container with enhanced error handling"""
284 super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
285
286 display.vvv(f"EXEC: {cmd}", host=self._container_id)
287
288 cmd_args_list = shlex.split(to_native(cmd, errors="surrogate_or_strict"))
289 exec_cmd = ["exec"]
290
291 # Add interactive flag only when input is provided
292 if in_data is not None:
293 exec_cmd.append("-i")
294
295 # Handle user specification
296 if self.get_option("remote_user"):
297 exec_cmd.extend(["--user", self.get_option("remote_user")])
298
299 # Add extra environment variables
300 extra_env = self.get_option("extra_env_vars")
301 if extra_env:
302 for key, value in extra_env.items():
303 exec_cmd.extend(["--env", f"{key}={value}"])
304
305 # Handle privilege escalation only when explicitly requested
306 privilege_method = self.get_option("privilege_escalation_method")
307 if sudoable and privilege_method != "none" and privilege_method != "auto":
308 if privilege_method == "sudo":
309 cmd_args_list = ["sudo", "-n"] + cmd_args_list
310 elif privilege_method == "su":
311 cmd_args_list = ["su", "-c", " ".join(shlex.quote(arg) for arg in cmd_args_list)]
312
313 # Add working directory option
314 workdir = self.get_option("working_directory")
315 if workdir:
316 exec_cmd.extend(["--workdir", workdir])
317
318 # Combine exec command: podman exec [options] container_id command
319 full_cmd = exec_cmd + [self._container_id] + cmd_args_list
320
321 rc, stdout, stderr = self._run_podman_command(full_cmd, input_data=in_data, include_container=False)
322 return rc, stdout, stderr
323
324 def put_file(self, in_path, out_path):
325 """Transfer file to container using optimal method"""
326 super(Connection, self).put_file(in_path, out_path)
327 display.vvv(f"PUT: {in_path} -> {out_path}", host=self._container_id)
328
329 # Lazily prepare mount point if needed
330 if self._mount_point is None and self.get_option("mount_detection"):
331 self._setup_mount_point()
332
333 # Use direct filesystem copy if mount point is available and no user specified
334 if self._mount_point and not self.get_option("remote_user"):
335 try:
336 real_out_path = os.path.join(self._mount_point, out_path.lstrip("/"))
337 os.makedirs(os.path.dirname(real_out_path), exist_ok=True)
338 shutil.copy2(in_path, real_out_path)
339 display.vvvv(f"File copied via mount: {real_out_path}", host=self._container_id)
340 return
341 except Exception as e:
342 display.vvv(f"Mount copy failed, falling back to podman cp: {e}", host=self._container_id)
343
344 # Use podman cp command
345 copy_cmd = ["cp", "--pause=false", in_path, f"{self._container_id}:{out_path}"]
346 self._run_podman_command(copy_cmd, include_container=False, check_rc=True)
347
348 # Change ownership if user specified
349 if self.get_option("remote_user"):
350 chown_cmd = [
351 "exec",
352 "--user",
353 "root",
354 self._container_id,
355 "chown",
356 self.get_option("remote_user"),
357 out_path,
358 ]
359 try:
360 self._run_podman_command(chown_cmd, include_container=False, check_rc=True)
361 except PodmanConnectionError as e:
362 display.warning(f"Failed to change file ownership: {e}")
363
364 def fetch_file(self, in_path, out_path):
365 """Retrieve file from container using optimal method"""
366 super(Connection, self).fetch_file(in_path, out_path)
367 display.vvv(f"FETCH: {in_path} -> {out_path}", host=self._container_id)
368
369 # Lazily prepare mount point if needed
370 if self._mount_point is None and self.get_option("mount_detection"):
371 self._setup_mount_point()
372
373 # Use direct filesystem copy if mount point is available
374 if self._mount_point:
375 try:
376 real_in_path = os.path.join(self._mount_point, in_path.lstrip("/"))
377 if os.path.exists(real_in_path):
378 os.makedirs(os.path.dirname(out_path), exist_ok=True)
379 shutil.copy2(real_in_path, out_path)
380 display.vvvv(f"File fetched via mount: {real_in_path}", host=self._container_id)
381 return
382 except Exception as e:
383 display.vvv(f"Mount fetch failed, falling back to podman cp: {e}", host=self._container_id)
384
385 # Use podman cp command
386 copy_cmd = ["cp", "--pause=false", f"{self._container_id}:{in_path}", out_path]
387 self._run_podman_command(copy_cmd, include_container=False, check_rc=True)
388
389 def close(self):
390 """Close connection and cleanup resources"""
391 super(Connection, self).close()
392
393 if self._mount_point:
394 try:
395 # Attempt to unmount (optional, container keeps mount anyway)
396 self._run_podman_command(["umount"], check_rc=False)
397 display.vvvv("Container unmounted successfully", host=self._container_id)
398 except Exception as e:
399 display.vvvv(f"Unmount failed (this is usually not critical): {e}", host=self._container_id)
400
401 self._connected = False
402 display.vvv("Connection closed", host=self._container_id)