Debian Codegraph @

ansible_collections/community/general/plugins/connection/lxc.py

raw
1 # (c) 2015, Joerg Thalheim <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 author: Joerg Thalheim (!UNKNOWN) <[email protected]>
10 name: lxc
11 short_description: Run tasks in LXC containers using lxc python library
12 description:
13 - Run commands or put/fetch files to an existing LXC container using lxc python library.
14 options:
15 remote_addr:
16 description:
17 - Container identifier.
18 type: string
19 default: inventory_hostname
20 vars:
21 - name: inventory_hostname
22 - name: ansible_host
23 - name: ansible_lxc_host
24 executable:
25 default: /bin/sh
26 description:
27 - Shell executable.
28 type: string
29 vars:
30 - name: ansible_executable
31 - name: ansible_lxc_executable
32 """
33
34 import errno
35 import fcntl
36 import os
37 import select
38 import shutil
39 import traceback
40
41 HAS_LIBLXC = False
42 try:
43 import lxc as _lxc
44
45 HAS_LIBLXC = True
46 except ImportError:
47 pass
48
49 from ansible import errors
50 from ansible.module_utils.common.text.converters import to_bytes, to_native
51 from ansible.plugins.connection import ConnectionBase
52
53
54 class Connection(ConnectionBase):
55 """Local lxc based connections"""
56
57 transport = "community.general.lxc"
58 has_pipelining = True
59 default_user = "root"
60
61 def __init__(self, play_context, new_stdin, *args, **kwargs):
62 super().__init__(play_context, new_stdin, *args, **kwargs)
63
64 self.container_name = None
65 self.container = None
66
67 def _connect(self):
68 """connect to the lxc; nothing to do here"""
69 super()._connect()
70
71 if not HAS_LIBLXC:
72 msg = "lxc python bindings are not installed"
73 raise errors.AnsibleError(msg)
74
75 container_name = self.get_option("remote_addr")
76 if self.container and self.container_name == container_name:
77 return
78
79 self.container_name = container_name
80
81 self._display.vvv("THIS IS A LOCAL LXC DIR", host=self.container_name)
82 self.container = _lxc.Container(self.container_name)
83 if self.container.state == "STOPPED":
84 raise errors.AnsibleError(f"{self.container_name} is not running")
85
86 @staticmethod
87 def _communicate(pid, in_data, stdin, stdout, stderr):
88 buf = {stdout: [], stderr: []}
89 read_fds = [stdout, stderr]
90 if in_data:
91 write_fds = [stdin]
92 else:
93 write_fds = []
94 while len(read_fds) > 0 or len(write_fds) > 0:
95 try:
96 ready_reads, ready_writes, dummy = select.select(read_fds, write_fds, [])
97 except OSError as e:
98 if e.args[0] == errno.EINTR:
99 continue
100 raise
101 for fd in ready_writes:
102 in_data = in_data[os.write(fd, in_data) :]
103 if len(in_data) == 0:
104 write_fds.remove(fd)
105 for fd in ready_reads:
106 data = os.read(fd, 32768)
107 if not data:
108 read_fds.remove(fd)
109 buf[fd].append(data)
110
111 (pid, returncode) = os.waitpid(pid, 0)
112
113 return returncode, b"".join(buf[stdout]), b"".join(buf[stderr])
114
115 def _set_nonblocking(self, fd):
116 flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
117 fcntl.fcntl(fd, fcntl.F_SETFL, flags)
118 return fd
119
120 def exec_command(self, cmd, in_data=None, sudoable=False):
121 """run a command on the chroot"""
122 super().exec_command(cmd, in_data=in_data, sudoable=sudoable)
123
124 # python2-lxc needs bytes. python3-lxc needs text.
125 executable = to_native(self.get_option("executable"), errors="surrogate_or_strict")
126 local_cmd = [executable, "-c", to_native(cmd, errors="surrogate_or_strict")]
127
128 read_stdout, write_stdout = None, None
129 read_stderr, write_stderr = None, None
130 read_stdin, write_stdin = None, None
131
132 try:
133 read_stdout, write_stdout = os.pipe()
134 read_stderr, write_stderr = os.pipe()
135
136 kwargs = {
137 "stdout": self._set_nonblocking(write_stdout),
138 "stderr": self._set_nonblocking(write_stderr),
139 "env_policy": _lxc.LXC_ATTACH_CLEAR_ENV,
140 }
141
142 if in_data:
143 read_stdin, write_stdin = os.pipe()
144 kwargs["stdin"] = self._set_nonblocking(read_stdin)
145
146 self._display.vvv(f"EXEC {local_cmd}", host=self.container_name)
147 pid = self.container.attach(_lxc.attach_run_command, local_cmd, **kwargs)
148 if pid == -1:
149 msg = f"failed to attach to container {self.container_name}"
150 raise errors.AnsibleError(msg)
151
152 write_stdout = os.close(write_stdout)
153 write_stderr = os.close(write_stderr)
154 if read_stdin:
155 read_stdin = os.close(read_stdin)
156
157 return self._communicate(pid, in_data, write_stdin, read_stdout, read_stderr)
158 finally:
159 fds = [read_stdout, write_stdout, read_stderr, write_stderr, read_stdin, write_stdin]
160 for fd in fds:
161 if fd:
162 os.close(fd)
163
164 def put_file(self, in_path, out_path):
165 """transfer a file from local to lxc"""
166 super().put_file(in_path, out_path)
167 self._display.vvv(f"PUT {in_path} TO {out_path}", host=self.container_name)
168 in_path = to_bytes(in_path, errors="surrogate_or_strict")
169 out_path = to_bytes(out_path, errors="surrogate_or_strict")
170
171 if not os.path.exists(in_path):
172 msg = f"file or module does not exist: {in_path}"
173 raise errors.AnsibleFileNotFound(msg)
174 try:
175 src_file = open(in_path, "rb")
176 except OSError as e:
177 traceback.print_exc()
178 raise errors.AnsibleError(f"failed to open input file to {in_path}") from e
179 try:
180
181 def write_file(args):
182 with open(out_path, "wb+") as dst_file:
183 shutil.copyfileobj(src_file, dst_file)
184
185 try:
186 self.container.attach_wait(write_file, None)
187 except OSError as e:
188 traceback.print_exc()
189 msg = f"failed to transfer file to {out_path}"
190 raise errors.AnsibleError(msg) from e
191 finally:
192 src_file.close()
193
194 def fetch_file(self, in_path, out_path):
195 """fetch a file from lxc to local"""
196 super().fetch_file(in_path, out_path)
197 self._display.vvv(f"FETCH {in_path} TO {out_path}", host=self.container_name)
198 in_path = to_bytes(in_path, errors="surrogate_or_strict")
199 out_path = to_bytes(out_path, errors="surrogate_or_strict")
200
201 try:
202 dst_file = open(out_path, "wb")
203 except OSError as e:
204 traceback.print_exc()
205 msg = f"failed to open output file {out_path}"
206 raise errors.AnsibleError(msg) from e
207 try:
208
209 def write_file(args):
210 try:
211 with open(in_path, "rb") as src_file:
212 shutil.copyfileobj(src_file, dst_file)
213 finally:
214 # this is needed in the lxc child process
215 # to flush internal python buffers
216 dst_file.close()
217
218 try:
219 self.container.attach_wait(write_file, None)
220 except OSError as e:
221 traceback.print_exc()
222 msg = f"failed to transfer file from {in_path} to {out_path}"
223 raise errors.AnsibleError(msg) from e
224 finally:
225 dst_file.close()
226
227 def close(self):
228 """terminate the connection; nothing to do here"""
229 super().close()
230 self._connected = False