pyinfra-incus-kit 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,69 @@
1
+ """
2
+ Addressing another Incus server than the local one.
3
+
4
+ The incus CLI picks its server from the ``<remote>:`` prefix on the object it is given,
5
+ then from ``INCUS_REMOTE``, then from the client's configured default remote. Facts and
6
+ operations here emit the prefix, so a deploy file can drive a remote daemon from a machine
7
+ that holds nothing but the client — no daemon, no SSH.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+
15
+ def qualify(name: str, remote: str | None) -> str:
16
+ """
17
+ Return ``<remote>:<name>``, or ``name`` unchanged when there is no remote to add.
18
+
19
+ A name that already carries a remote (``"lx4:container"``) is left alone: the caller was
20
+ explicit, and prefixing again would address a remote that does not exist.
21
+
22
+ + param name: instance, project, pool, profile, network or image name.
23
+ + param remote: remote to address it on, if any.
24
+ """
25
+ if not remote or ":" in name:
26
+ return name
27
+
28
+ return f"{remote}:{name}"
29
+
30
+
31
+ def remote_arg(remote: str | None) -> list[str]:
32
+ """
33
+ Return ``["<remote>:"]`` for the commands that take the server as their own argument.
34
+
35
+ Listing commands (``incus list``, ``incus network list``, ``incus config trust list``) take a
36
+ bare ``<remote>:`` rather than a prefix on an object name, and so does
37
+ ``incus config trust add-certificate``.
38
+
39
+ + param remote: remote to address, if any.
40
+ """
41
+ return [f"{remote}:"] if remote else []
42
+
43
+
44
+ def resolve_remote(remote: str | None = None) -> str | None:
45
+ """
46
+ Return the remote a fact or operation should address, or ``None`` for the default one.
47
+
48
+ An explicit argument wins. Otherwise ``incus_remote`` from the host data, so a deploy running
49
+ on a machine with only a client can name the server once, in its inventory. ``INCUS_REMOTE``
50
+ comes last: the incus CLI reads it too, but naming the remote in the inventory is what makes
51
+ the emitted commands readable and keeps one fact per remote.
52
+
53
+ + param remote: remote given by the caller, if any.
54
+ """
55
+ if remote:
56
+ return remote
57
+
58
+ from pyinfra import host
59
+
60
+ try:
61
+ from_data = host.data.get("incus_remote")
62
+ except (AttributeError, ValueError):
63
+ # No host context: outside a deploy there is no inventory to read a remote from.
64
+ from_data = None
65
+
66
+ if from_data:
67
+ return str(from_data)
68
+
69
+ return os.environ.get("INCUS_REMOTE") or None
File without changes
@@ -0,0 +1,371 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ from tempfile import mkstemp
8
+ from typing import TYPE_CHECKING
9
+
10
+ from pyinfra import local, logger
11
+ from pyinfra.api.command import QuoteString, StringCommand
12
+ from pyinfra.api.output import echo
13
+ from pyinfra.api.util import get_file_io
14
+ from pyinfra.connectors.base import BaseConnector, DataMeta
15
+ from pyinfra.connectors.local import LocalConnector
16
+ from pyinfra.connectors.util import (
17
+ CommandOutput,
18
+ extract_control_arguments,
19
+ make_unix_command_for_host,
20
+ )
21
+ from typing_extensions import TypedDict, Unpack, override
22
+
23
+ from .._remote import qualify
24
+
25
+ if TYPE_CHECKING:
26
+ from pyinfra.api.arguments import ConnectorArguments
27
+ from pyinfra.api.host import Host
28
+ from pyinfra.api.state import State
29
+
30
+
31
+ class ConnectorData(TypedDict):
32
+ incus_name: str
33
+ incus_project: str
34
+ incus_remote: str | None
35
+
36
+
37
+ connector_data_meta: dict[str, DataMeta] = {
38
+ "incus_name": DataMeta("Incus instance name"),
39
+ "incus_project": DataMeta("Incus project name", None),
40
+ "incus_remote": DataMeta("Incus remote name", None),
41
+ }
42
+
43
+
44
+ def _list_instances(cmd: str, name: str | None) -> list[str]:
45
+ if not name:
46
+ command = f"{cmd} list --format=json"
47
+ output = local.shell(command)
48
+ return [row["name"] for row in json.loads(output)]
49
+
50
+ # A bare remote (`remote:`) filters the listing to that remote: its instances have to be
51
+ # yielded qualified, or they cannot be targeted afterwards.
52
+ remote_prefix = ""
53
+ if ":" in name:
54
+ remote_prefix = name.split(":", 1)[0] + ":"
55
+
56
+ command = f"{cmd} list --format=json {shlex.quote(name)}"
57
+ output = local.shell(command)
58
+
59
+ return [f"{remote_prefix}{row['name']}" for row in json.loads(output)]
60
+
61
+
62
+ def _make_names_data(cmd: str, prefix: str, name: str | None):
63
+ # A name ending in `:` is a remote and nothing else, so it lists that remote's instances, as
64
+ # the incus CLI does. Any other name is a single instance, targeted without listing - which is
65
+ # also what lets a chain layer expand to exactly one host, without a local incus binary.
66
+ if name and not name.endswith(":"):
67
+ yield (f"{prefix}/{name}", {"incus_name": name}, [prefix])
68
+ return
69
+
70
+ for instance_name in _list_instances(cmd, name):
71
+ yield (f"{prefix}/{instance_name}", {"incus_name": instance_name}, [prefix])
72
+
73
+
74
+ class IncusConnector(BaseConnector):
75
+ """
76
+ Target Incus instances as inventory, running the ``incus`` CLI locally.
77
+
78
+ To run it on a remote host instead - without exposing the Incus API or installing the client
79
+ locally - use it as a layer of the ``@chain`` connector: ``@ssh/<host>/@incus/<instance>``.
80
+
81
+ You can use the inventory syntax:
82
+
83
+ + ``@incus``: every instance of the local daemon
84
+ + ``@incus/<remote>:``: every instance of a remote
85
+ + ``@incus/<name>``: a single instance
86
+ + ``@incus/<remote>:<name>``: a single instance of a remote
87
+
88
+ Optional inventory data:
89
+
90
+ + ``incus_project``: project name for the instance
91
+ + ``incus_remote``: remote name to prefix instance with (if not already set)
92
+
93
+ A chain segment is a host rather than a URL, and the layers share that host's data: the SSH
94
+ user goes through ``--data ssh_user=<user>``, not through a ``user@`` prefix.
95
+
96
+ Example:
97
+
98
+ .. code:: shell
99
+
100
+ # Local instance
101
+ pyinfra @incus/my-instance exec -- echo "hello"
102
+
103
+ # Instance on a remote incus server (configured in local incus)
104
+ pyinfra @incus/remote:my-instance exec -- echo "hello"
105
+
106
+ # Same instance, with `incus` running on the other end of an SSH connection
107
+ pyinfra @ssh/myserver.net/@incus/remote:my-instance exec -- echo "hello"
108
+ """
109
+
110
+ cmd = "incus"
111
+ name_prefix = "@incus"
112
+
113
+ handles_execution = True
114
+
115
+ data_cls = ConnectorData
116
+ data_meta = connector_data_meta
117
+ data: ConnectorData
118
+
119
+ local: LocalConnector
120
+
121
+ def __init__(self, state: "State", host: "Host"):
122
+ super().__init__(state, host)
123
+ self.local = LocalConnector(state, host)
124
+
125
+ @override
126
+ @staticmethod
127
+ def make_names_data(name: str | None = None):
128
+ """
129
+ Inventory can target a single instance, or list instances.
130
+
131
+ + None: list every instance of the local daemon
132
+ + <remote>: list every instance of a remote
133
+ + <name> or <remote>:<name>: target a single instance
134
+ """
135
+ yield from _make_names_data(IncusConnector.cmd, IncusConnector.name_prefix, name)
136
+
137
+ def _get_instance_name(self) -> str:
138
+ """
139
+ The instance as the incus CLI expects it: ``<remote>:<name>`` when the remote was
140
+ given as connector data rather than as part of the name.
141
+
142
+ Only the connector's own data is consulted. Host data and ``INCUS_REMOTE`` are deliberately
143
+ ignored here: as a chain layer this connector already runs against the server it is meant
144
+ to, and honouring a remote from the inventory would send its commands to a second one.
145
+ """
146
+ return qualify(self.data["incus_name"], self.data.get("incus_remote"))
147
+
148
+ def _get_project_args(self) -> list[str | QuoteString]:
149
+ project = self.data.get("incus_project")
150
+
151
+ if project:
152
+ return ["--project", QuoteString(project)]
153
+
154
+ return []
155
+
156
+ @override
157
+ def connect(self) -> None:
158
+ self.local.connect()
159
+
160
+ @override
161
+ def disconnect(self) -> None:
162
+ self.local.disconnect()
163
+
164
+ # Not @override: public pyinfra 3.11 has no chain hooks yet
165
+ # (pyinfra-dev/pyinfra#1780). The fork's @chain connector calls these by duck typing.
166
+ def get_runtime_id(self) -> str:
167
+ return self._get_instance_name()
168
+
169
+ def wrap_exec_command(self, command: StringCommand, container_id: str) -> StringCommand:
170
+ # `container_id` is this layer's runtime identifier, resolved by the chain through
171
+ # get_runtime_id(): use it rather than resolving the instance name a second time.
172
+ # Instances inherit stdin from the parent process, so a file uploaded through a chain
173
+ # (streamed into a `cat` in the target) needs no extra flag.
174
+ return StringCommand(
175
+ self.cmd,
176
+ "exec",
177
+ *self._get_project_args(),
178
+ QuoteString(container_id),
179
+ "--",
180
+ "sh",
181
+ "-c",
182
+ QuoteString(command),
183
+ )
184
+
185
+ @override
186
+ def run_shell_command(
187
+ self,
188
+ command: StringCommand,
189
+ print_output: bool = False,
190
+ print_input: bool = False,
191
+ **arguments: Unpack["ConnectorArguments"],
192
+ ) -> tuple[bool, CommandOutput]:
193
+ local_arguments = extract_control_arguments(arguments)
194
+
195
+ command = make_unix_command_for_host(self.state, self.host, command, **arguments)
196
+ command = StringCommand(QuoteString(command))
197
+
198
+ incus_command = StringCommand(
199
+ self.cmd,
200
+ "exec",
201
+ *self._get_project_args(),
202
+ QuoteString(self._get_instance_name()),
203
+ "--",
204
+ "sh",
205
+ "-c",
206
+ command,
207
+ )
208
+
209
+ logger.debug("--> Running command via incus: %s", incus_command)
210
+
211
+ return self.local.run_shell_command(
212
+ incus_command,
213
+ print_output=print_output,
214
+ print_input=print_input,
215
+ **local_arguments,
216
+ )
217
+
218
+ @override
219
+ def put_file(
220
+ self,
221
+ filename_or_io,
222
+ remote_filename,
223
+ remote_temp_filename=None, # ignored
224
+ print_output=False,
225
+ print_input=False,
226
+ **kwargs, # ignored (sudo/etc)
227
+ ) -> bool:
228
+ """
229
+ Upload a file/IO object to the target instance using ``incus file push``.
230
+ """
231
+ remote_path = f"{self._get_instance_name()}/{remote_filename}"
232
+
233
+ # A path is a file on disk already: hand it to `incus file push` as it is. Staging a copy
234
+ # would read the whole payload through this process - fatal for a database archive, whose
235
+ # size has nothing to do with the memory a runner has.
236
+ if isinstance(filename_or_io, str):
237
+ return self._push_path(
238
+ filename_or_io,
239
+ remote_path,
240
+ remote_filename=remote_filename,
241
+ print_output=print_output,
242
+ print_input=print_input,
243
+ )
244
+
245
+ fd, temp_filename = mkstemp()
246
+ try:
247
+ # copyfileobj streams in bounded chunks where `read()` would hold the whole file.
248
+ with (
249
+ get_file_io(filename_or_io) as file_io,
250
+ open(temp_filename, "wb") as temp_f,
251
+ ):
252
+ shutil.copyfileobj(file_io, temp_f)
253
+
254
+ return self._push_path(
255
+ temp_filename,
256
+ remote_path,
257
+ remote_filename=remote_filename,
258
+ print_output=print_output,
259
+ print_input=print_input,
260
+ )
261
+ finally:
262
+ os.close(fd)
263
+ os.remove(temp_filename)
264
+
265
+ def _push_path(
266
+ self,
267
+ local_path: str,
268
+ remote_path: str,
269
+ *,
270
+ remote_filename: str,
271
+ print_output: bool,
272
+ print_input: bool,
273
+ ) -> bool:
274
+ """
275
+ Run ``incus file push`` for one already-materialised local path.
276
+ """
277
+ incus_command = StringCommand(
278
+ self.cmd,
279
+ "file",
280
+ "push",
281
+ *self._get_project_args(),
282
+ QuoteString(local_path),
283
+ QuoteString(remote_path),
284
+ )
285
+
286
+ status, output = self.local.run_shell_command(
287
+ incus_command,
288
+ print_output=print_output,
289
+ print_input=print_input,
290
+ )
291
+
292
+ if not status:
293
+ raise IOError(output.stderr)
294
+
295
+ if print_output:
296
+ echo(
297
+ f"{self.host.print_prefix}file uploaded to instance: {remote_filename}",
298
+ err=True,
299
+ )
300
+
301
+ return status
302
+
303
+ @override
304
+ def get_file(
305
+ self,
306
+ remote_filename,
307
+ filename_or_io,
308
+ remote_temp_filename=None, # ignored
309
+ print_output=False,
310
+ print_input=False,
311
+ **kwargs, # ignored (sudo/etc)
312
+ ) -> bool:
313
+ """
314
+ Download a file from the target instance using ``incus file pull``.
315
+ """
316
+ fd, temp_filename = mkstemp()
317
+
318
+ try:
319
+ remote_path = f"{self._get_instance_name()}/{remote_filename}"
320
+
321
+ incus_command = StringCommand(
322
+ self.cmd,
323
+ "file",
324
+ "pull",
325
+ *self._get_project_args(),
326
+ QuoteString(remote_path),
327
+ QuoteString(temp_filename),
328
+ )
329
+
330
+ status, output = self.local.run_shell_command(
331
+ incus_command,
332
+ print_output=print_output,
333
+ print_input=print_input,
334
+ )
335
+
336
+ if not status:
337
+ raise IOError(output.stderr)
338
+
339
+ # Write the destination only once the pull is known to have succeeded: a failed pull
340
+ # must not truncate it. copyfileobj streams in bounded chunks, where reading the
341
+ # pulled file back whole would hold it in memory - fatal for a database archive.
342
+ with (
343
+ open(temp_filename, "rb") as temp_f,
344
+ get_file_io(filename_or_io, "wb") as file_io,
345
+ ):
346
+ shutil.copyfileobj(temp_f, file_io)
347
+ finally:
348
+ os.close(fd)
349
+ os.remove(temp_filename)
350
+
351
+ if print_output:
352
+ echo(
353
+ f"{self.host.print_prefix}file downloaded from instance: {remote_filename}",
354
+ err=True,
355
+ )
356
+
357
+ return status
358
+
359
+
360
+ class LXCConnector(IncusConnector):
361
+ """
362
+ The LXC connector is compatible with LXC/LXD CLI (same interface as Incus).
363
+ """
364
+
365
+ cmd = "lxc"
366
+ name_prefix = "@lxc"
367
+
368
+ @override
369
+ @staticmethod
370
+ def make_names_data(name: str | None = None):
371
+ yield from _make_names_data(LXCConnector.cmd, LXCConnector.name_prefix, name)