libvirtpy 0.1.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.
- libvirtpy/__init__.py +5 -0
- libvirtpy/client/__init__.py +54 -0
- libvirtpy/client/_bases.py +326 -0
- libvirtpy/client/_runner.py +57 -0
- libvirtpy/client/aio.py +5922 -0
- libvirtpy/client/client.py +5695 -0
- libvirtpy/client/operations/__init__.py +631 -0
- libvirtpy/client/operations/_common.py +495 -0
- libvirtpy/client/operations/checkpoint.py +196 -0
- libvirtpy/client/operations/connection.py +93 -0
- libvirtpy/client/operations/connection_extra.py +256 -0
- libvirtpy/client/operations/domain.py +306 -0
- libvirtpy/client/operations/domain_agent.py +115 -0
- libvirtpy/client/operations/domain_block.py +368 -0
- libvirtpy/client/operations/domain_info.py +400 -0
- libvirtpy/client/operations/domain_lifecycle.py +338 -0
- libvirtpy/client/operations/domain_migration.py +164 -0
- libvirtpy/client/operations/domain_network.py +113 -0
- libvirtpy/client/operations/domain_tuning.py +494 -0
- libvirtpy/client/operations/host.py +246 -0
- libvirtpy/client/operations/host_interface.py +100 -0
- libvirtpy/client/operations/interface_extra.py +45 -0
- libvirtpy/client/operations/network.py +135 -0
- libvirtpy/client/operations/network_info.py +155 -0
- libvirtpy/client/operations/network_port.py +142 -0
- libvirtpy/client/operations/node_device.py +76 -0
- libvirtpy/client/operations/node_device_info.py +189 -0
- libvirtpy/client/operations/nwfilter.py +67 -0
- libvirtpy/client/operations/nwfilter_binding.py +74 -0
- libvirtpy/client/operations/secret.py +93 -0
- libvirtpy/client/operations/secret_extra.py +24 -0
- libvirtpy/client/operations/snapshot.py +100 -0
- libvirtpy/client/operations/snapshot_tree.py +114 -0
- libvirtpy/client/operations/storage.py +267 -0
- libvirtpy/client/operations/storage_info.py +188 -0
- libvirtpy/client/operations/streams.py +201 -0
- libvirtpy/client/references.py +249 -0
- libvirtpy/client/subscribing.py +88 -0
- libvirtpy/client/testing/__init__.py +24 -0
- libvirtpy/client/testing/_common.py +167 -0
- libvirtpy/client/testing/_domains.py +294 -0
- libvirtpy/client/testing/_objects.py +205 -0
- libvirtpy/client/testing/_state.py +246 -0
- libvirtpy/client/testing/_storage.py +171 -0
- libvirtpy/client/testing/async_transport.py +30 -0
- libvirtpy/client/testing/fake.py +81 -0
- libvirtpy/client/transport.py +87 -0
- libvirtpy/client/types.py +59 -0
- libvirtpy/client/wire.py +436 -0
- libvirtpy/client/wire_aio.py +348 -0
- libvirtpy/errors.py +7 -0
- libvirtpy/py.typed +0 -0
- libvirtpy/rpc/__init__.py +1 -0
- libvirtpy/rpc/aio.py +387 -0
- libvirtpy/rpc/cpumap.py +48 -0
- libvirtpy/rpc/errors.py +186 -0
- libvirtpy/rpc/events.py +259 -0
- libvirtpy/rpc/options.py +66 -0
- libvirtpy/rpc/procedure.py +27 -0
- libvirtpy/rpc/protocol/__init__.py +0 -0
- libvirtpy/rpc/protocol/procedures.py +5163 -0
- libvirtpy/rpc/protocol/typed_hints.py +210 -0
- libvirtpy/rpc/protocol/types.py +9299 -0
- libvirtpy/rpc/remote.py +295 -0
- libvirtpy/rpc/remote_aio.py +106 -0
- libvirtpy/rpc/sasl.py +467 -0
- libvirtpy/rpc/session.py +424 -0
- libvirtpy/rpc/sockets.py +251 -0
- libvirtpy/rpc/stream.py +323 -0
- libvirtpy/rpc/subscription.py +451 -0
- libvirtpy/rpc/sync.py +460 -0
- libvirtpy/rpc/typed_params.py +97 -0
- libvirtpy/rpc/uri.py +85 -0
- libvirtpy/rpc/xdr.py +552 -0
- libvirtpy/xml/__init__.py +49 -0
- libvirtpy/xml/_base.py +145 -0
- libvirtpy/xml/_shared/__init__.py +1 -0
- libvirtpy/xml/_shared/metadata.py +67 -0
- libvirtpy/xml/_shared/network.py +108 -0
- libvirtpy/xml/_shared/storage.py +131 -0
- libvirtpy/xml/_shared/sysinfo.py +83 -0
- libvirtpy/xml/_types.py +197 -0
- libvirtpy/xml/_xml_element.py +134 -0
- libvirtpy/xml/backup/__init__.py +25 -0
- libvirtpy/xml/backup/backup.py +89 -0
- libvirtpy/xml/backup/checkpoint.py +48 -0
- libvirtpy/xml/capabilities/__init__.py +43 -0
- libvirtpy/xml/capabilities/domain.py +436 -0
- libvirtpy/xml/capabilities/host.py +413 -0
- libvirtpy/xml/capabilities/storagepool.py +59 -0
- libvirtpy/xml/domain/__init__.py +493 -0
- libvirtpy/xml/domain/blkiotune.py +81 -0
- libvirtpy/xml/domain/clock.py +79 -0
- libvirtpy/xml/domain/cpu.py +265 -0
- libvirtpy/xml/domain/devices/__init__.py +495 -0
- libvirtpy/xml/domain/devices/address.py +152 -0
- libvirtpy/xml/domain/devices/audio.py +204 -0
- libvirtpy/xml/domain/devices/chardev.py +197 -0
- libvirtpy/xml/domain/devices/common.py +75 -0
- libvirtpy/xml/domain/devices/controller.py +262 -0
- libvirtpy/xml/domain/devices/devices.py +79 -0
- libvirtpy/xml/domain/devices/disk.py +471 -0
- libvirtpy/xml/domain/devices/filesystem.py +206 -0
- libvirtpy/xml/domain/devices/graphics.py +245 -0
- libvirtpy/xml/domain/devices/hostdev.py +221 -0
- libvirtpy/xml/domain/devices/input.py +89 -0
- libvirtpy/xml/domain/devices/interface.py +459 -0
- libvirtpy/xml/domain/devices/iommu.py +54 -0
- libvirtpy/xml/domain/devices/memballoon.py +42 -0
- libvirtpy/xml/domain/devices/memory_device.py +101 -0
- libvirtpy/xml/domain/devices/misc.py +169 -0
- libvirtpy/xml/domain/devices/nvram.py +20 -0
- libvirtpy/xml/domain/devices/shmem.py +46 -0
- libvirtpy/xml/domain/devices/sound.py +42 -0
- libvirtpy/xml/domain/devices/tpm.py +103 -0
- libvirtpy/xml/domain/devices/usb.py +86 -0
- libvirtpy/xml/domain/devices/video.py +101 -0
- libvirtpy/xml/domain/domain.py +157 -0
- libvirtpy/xml/domain/features.py +312 -0
- libvirtpy/xml/domain/iothread.py +41 -0
- libvirtpy/xml/domain/launch_security.py +82 -0
- libvirtpy/xml/domain/memory.py +149 -0
- libvirtpy/xml/domain/misc.py +113 -0
- libvirtpy/xml/domain/namespaces.py +96 -0
- libvirtpy/xml/domain/numa.py +140 -0
- libvirtpy/xml/domain/os.py +267 -0
- libvirtpy/xml/domain/qemu.py +102 -0
- libvirtpy/xml/domain/seclabel.py +29 -0
- libvirtpy/xml/domain/storage_source.py +466 -0
- libvirtpy/xml/domain/sysinfo.py +34 -0
- libvirtpy/xml/interface/__init__.py +17 -0
- libvirtpy/xml/interface/interface.py +153 -0
- libvirtpy/xml/network/__init__.py +101 -0
- libvirtpy/xml/network/network.py +311 -0
- libvirtpy/xml/network/port.py +84 -0
- libvirtpy/xml/nodedev/__init__.py +13 -0
- libvirtpy/xml/nodedev/nodedev.py +490 -0
- libvirtpy/xml/nwfilter/__init__.py +81 -0
- libvirtpy/xml/nwfilter/binding.py +51 -0
- libvirtpy/xml/nwfilter/filter.py +92 -0
- libvirtpy/xml/nwfilter/rules.py +534 -0
- libvirtpy/xml/secret/__init__.py +11 -0
- libvirtpy/xml/secret/secret.py +36 -0
- libvirtpy/xml/snapshot/__init__.py +29 -0
- libvirtpy/xml/snapshot/snapshot.py +136 -0
- libvirtpy/xml/storage/__init__.py +75 -0
- libvirtpy/xml/storage/pool.py +219 -0
- libvirtpy/xml/storage/volume.py +102 -0
- libvirtpy/xml/sysinfo.py +40 -0
- libvirtpy-0.1.0.dist-info/METADATA +109 -0
- libvirtpy-0.1.0.dist-info/RECORD +154 -0
- libvirtpy-0.1.0.dist-info/WHEEL +4 -0
- libvirtpy-0.1.0.dist-info/licenses/LICENSE +501 -0
- libvirtpy-0.1.0.dist-info/licenses/NOTICE +23 -0
libvirtpy/rpc/sync.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
"""A blocking connection to one libvirt daemon socket."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import socket
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from concurrent.futures import Future
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
from typing import Any, Protocol, TypeVar
|
|
12
|
+
|
|
13
|
+
from libvirtpy.rpc.options import ConnectionOptions
|
|
14
|
+
from libvirtpy.rpc.procedure import Procedure
|
|
15
|
+
from libvirtpy.rpc.session import (
|
|
16
|
+
CallTimeoutError,
|
|
17
|
+
Completed,
|
|
18
|
+
ConnectionLostError,
|
|
19
|
+
ProtocolError,
|
|
20
|
+
ServerEvent,
|
|
21
|
+
Session,
|
|
22
|
+
StreamEvent,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = ["SocketStream", "Stream", "SyncRpc"]
|
|
26
|
+
|
|
27
|
+
RECEIVE_SIZE = 65536
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class StreamSink(Protocol):
|
|
31
|
+
"""Where the data of an open stream is delivered."""
|
|
32
|
+
|
|
33
|
+
serial: int
|
|
34
|
+
|
|
35
|
+
def deliver(self, event: StreamEvent) -> None:
|
|
36
|
+
"""Receive what the connection read for the stream.
|
|
37
|
+
|
|
38
|
+
:param event: the data, the end, or the error.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
OnResult = Callable[[Any], None]
|
|
43
|
+
EventListener = Callable[[ServerEvent], None]
|
|
44
|
+
SelfT = TypeVar("SelfT", bound="SyncRpc")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Stream(Protocol):
|
|
48
|
+
"""A connected byte stream: a socket, a TLS socket, or an ``ssh`` process."""
|
|
49
|
+
|
|
50
|
+
def send(self, data: bytes) -> None:
|
|
51
|
+
"""Send all of ``data``.
|
|
52
|
+
|
|
53
|
+
:param data: the bytes.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def receive(self) -> bytes:
|
|
57
|
+
"""Wait for bytes.
|
|
58
|
+
|
|
59
|
+
:returns: some bytes, or nothing if the other side closed.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def close(self) -> None:
|
|
63
|
+
"""Close the stream."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class SocketStream:
|
|
67
|
+
"""A ``Stream`` over a connected socket (plain or TLS)."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, connection: socket.socket) -> None:
|
|
70
|
+
"""Wrap a socket.
|
|
71
|
+
|
|
72
|
+
:param connection: a connected stream socket.
|
|
73
|
+
"""
|
|
74
|
+
self._socket = connection
|
|
75
|
+
|
|
76
|
+
def send(self, data: bytes) -> None:
|
|
77
|
+
"""Send all of ``data``.
|
|
78
|
+
|
|
79
|
+
:param data: the bytes.
|
|
80
|
+
"""
|
|
81
|
+
self._socket.sendall(data)
|
|
82
|
+
|
|
83
|
+
def receive(self) -> bytes:
|
|
84
|
+
"""Wait for bytes.
|
|
85
|
+
|
|
86
|
+
:returns: some bytes, or nothing if the other side closed.
|
|
87
|
+
"""
|
|
88
|
+
return self._socket.recv(RECEIVE_SIZE)
|
|
89
|
+
|
|
90
|
+
def close(self) -> None:
|
|
91
|
+
"""Close the socket, waking a thread that waits to read from it."""
|
|
92
|
+
with contextlib.suppress(OSError):
|
|
93
|
+
self._socket.shutdown(socket.SHUT_RDWR)
|
|
94
|
+
self._socket.close()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class SyncRpc:
|
|
98
|
+
"""Calls procedures of one daemon; calls from several threads may overlap.
|
|
99
|
+
|
|
100
|
+
A thread reads everything the daemon sends: replies wake the call that waits
|
|
101
|
+
for them, events go to the listeners, and keepalive pings are answered even
|
|
102
|
+
while no call is running.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self, stream: Stream, options: ConnectionOptions | None = None
|
|
107
|
+
) -> None:
|
|
108
|
+
"""Wrap a connected stream and start reading it.
|
|
109
|
+
|
|
110
|
+
:param stream: a stream to a libvirt daemon.
|
|
111
|
+
:param options: the call timeout and the keepalive; the defaults if left out.
|
|
112
|
+
"""
|
|
113
|
+
self._stream = stream
|
|
114
|
+
self._options = options or ConnectionOptions()
|
|
115
|
+
self._last_received = time.monotonic()
|
|
116
|
+
self._stopped = threading.Event()
|
|
117
|
+
|
|
118
|
+
self._session = Session()
|
|
119
|
+
self._state = threading.Lock()
|
|
120
|
+
self._send = threading.Lock()
|
|
121
|
+
|
|
122
|
+
self._waiting: dict[int, tuple[Future[Completed], OnResult | None]] = {}
|
|
123
|
+
self._listeners: dict[int, EventListener] = {}
|
|
124
|
+
self._on_lost: list[Callable[[Exception], None]] = []
|
|
125
|
+
self._failure: Exception | None = None
|
|
126
|
+
self._streams: dict[int, StreamSink] = {}
|
|
127
|
+
|
|
128
|
+
self._reader = threading.Thread(target=self._read_loop, daemon=True)
|
|
129
|
+
self._reader.start()
|
|
130
|
+
if self._options.keepalive_interval is not None:
|
|
131
|
+
threading.Thread(target=self._keepalive_loop, daemon=True).start()
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def connect_unix(
|
|
135
|
+
cls: type[SelfT], path: Path | str, options: ConnectionOptions | None = None
|
|
136
|
+
) -> SelfT:
|
|
137
|
+
"""Connect to a daemon's UNIX socket.
|
|
138
|
+
|
|
139
|
+
:param path: the socket file, e.g. ``/run/libvirt/virtqemud-sock``.
|
|
140
|
+
:param options: the call timeout and the keepalive.
|
|
141
|
+
:returns: the connection.
|
|
142
|
+
:raises OSError: if the socket cannot be reached.
|
|
143
|
+
"""
|
|
144
|
+
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
145
|
+
try:
|
|
146
|
+
connection.connect(str(path))
|
|
147
|
+
except OSError:
|
|
148
|
+
connection.close()
|
|
149
|
+
raise
|
|
150
|
+
return cls(SocketStream(connection), options)
|
|
151
|
+
|
|
152
|
+
def call(
|
|
153
|
+
self,
|
|
154
|
+
procedure: Procedure[Any, Any],
|
|
155
|
+
args: Any = None,
|
|
156
|
+
*,
|
|
157
|
+
on_result: OnResult | None = None,
|
|
158
|
+
stream: StreamSink | None = None,
|
|
159
|
+
) -> Any:
|
|
160
|
+
"""Call a procedure and wait for its reply.
|
|
161
|
+
|
|
162
|
+
:param procedure: the procedure.
|
|
163
|
+
:param args: its arguments struct, or ``None`` if it has none.
|
|
164
|
+
:param on_result: called with the result by the reading thread as soon as
|
|
165
|
+
the reply arrives, before it handles anything the daemon sent after
|
|
166
|
+
it; a subscription uses it to listen from the first event.
|
|
167
|
+
:param stream: for a call that opens a data stream: where its data goes.
|
|
168
|
+
The call's serial becomes ``stream.serial`` before it is sent.
|
|
169
|
+
:returns: the return struct, or ``None`` if the procedure returns nothing.
|
|
170
|
+
:raises LibvirtError: if the daemon reports an error.
|
|
171
|
+
:raises ConnectionLostError: if the connection ended.
|
|
172
|
+
:raises CallTimeoutError: if there was no reply within the call timeout.
|
|
173
|
+
"""
|
|
174
|
+
future: Future[Completed] = Future()
|
|
175
|
+
with self._state:
|
|
176
|
+
if self._failure is not None:
|
|
177
|
+
raise self._failure
|
|
178
|
+
serial, packet = self._session.call(
|
|
179
|
+
procedure, args, stream=stream is not None
|
|
180
|
+
)
|
|
181
|
+
self._waiting[serial] = (future, on_result)
|
|
182
|
+
if stream is not None:
|
|
183
|
+
stream.serial = serial
|
|
184
|
+
self._streams[serial] = stream
|
|
185
|
+
|
|
186
|
+
self._send_bytes(packet)
|
|
187
|
+
completed = self._wait(future, serial, procedure, stream)
|
|
188
|
+
if completed.error is not None:
|
|
189
|
+
self._forget_stream(stream)
|
|
190
|
+
raise completed.error
|
|
191
|
+
return completed.result
|
|
192
|
+
|
|
193
|
+
def send_stream_data(self, serial: int, data: bytes) -> None:
|
|
194
|
+
"""Send data on an open stream.
|
|
195
|
+
|
|
196
|
+
:param serial: the stream.
|
|
197
|
+
:param data: the bytes.
|
|
198
|
+
"""
|
|
199
|
+
with self._state:
|
|
200
|
+
packet = self._session.stream_data(serial, data)
|
|
201
|
+
if packet:
|
|
202
|
+
self._send_bytes(packet)
|
|
203
|
+
|
|
204
|
+
def finish_stream(self, serial: int) -> None:
|
|
205
|
+
"""Tell the daemon that we have sent everything on a stream.
|
|
206
|
+
|
|
207
|
+
:param serial: the stream.
|
|
208
|
+
"""
|
|
209
|
+
with self._state:
|
|
210
|
+
packet = self._session.stream_finish(serial)
|
|
211
|
+
if packet:
|
|
212
|
+
self._send_bytes(packet)
|
|
213
|
+
|
|
214
|
+
def abort_stream(self, serial: int) -> None:
|
|
215
|
+
"""Give up on a stream.
|
|
216
|
+
|
|
217
|
+
:param serial: the stream.
|
|
218
|
+
"""
|
|
219
|
+
with self._state:
|
|
220
|
+
packet = self._session.stream_abort(serial)
|
|
221
|
+
self._streams.pop(serial, None)
|
|
222
|
+
if packet:
|
|
223
|
+
self._send_bytes(packet)
|
|
224
|
+
|
|
225
|
+
@property
|
|
226
|
+
def failure(self) -> Exception | None:
|
|
227
|
+
"""Why the connection ended.
|
|
228
|
+
|
|
229
|
+
:returns: the error, or ``None`` while the connection is alive.
|
|
230
|
+
"""
|
|
231
|
+
return self._failure
|
|
232
|
+
|
|
233
|
+
def add_listener(self, callback_id: int, listener: EventListener) -> None:
|
|
234
|
+
"""Send the events of a subscription to ``listener``.
|
|
235
|
+
|
|
236
|
+
:param callback_id: the id the daemon gave the subscription.
|
|
237
|
+
:param listener: called in the reading thread with each ``ServerEvent``.
|
|
238
|
+
"""
|
|
239
|
+
with self._state:
|
|
240
|
+
self._listeners[callback_id] = listener
|
|
241
|
+
|
|
242
|
+
def remove_listener(self, callback_id: int) -> None:
|
|
243
|
+
"""Stop sending the events of a subscription.
|
|
244
|
+
|
|
245
|
+
:param callback_id: the id the daemon gave the subscription.
|
|
246
|
+
"""
|
|
247
|
+
with self._state:
|
|
248
|
+
self._listeners.pop(callback_id, None)
|
|
249
|
+
|
|
250
|
+
def when_lost(self, callback: Callable[[Exception], None]) -> None:
|
|
251
|
+
"""Call ``callback`` when the connection ends.
|
|
252
|
+
|
|
253
|
+
:param callback: called in the reading thread with the reason.
|
|
254
|
+
"""
|
|
255
|
+
with self._state:
|
|
256
|
+
lost = self._failure
|
|
257
|
+
if lost is None:
|
|
258
|
+
self._on_lost.append(callback)
|
|
259
|
+
if lost is not None:
|
|
260
|
+
callback(lost)
|
|
261
|
+
|
|
262
|
+
def close(self) -> None:
|
|
263
|
+
"""Close the connection; waiting calls and subscriptions end."""
|
|
264
|
+
self._stream.close()
|
|
265
|
+
self._fail(ConnectionLostError("the connection was closed"))
|
|
266
|
+
if threading.current_thread() is not self._reader:
|
|
267
|
+
self._reader.join(timeout=5)
|
|
268
|
+
|
|
269
|
+
def __enter__(self: SelfT) -> SelfT:
|
|
270
|
+
"""Use the connection in a ``with`` block.
|
|
271
|
+
|
|
272
|
+
:returns: the connection.
|
|
273
|
+
"""
|
|
274
|
+
return self
|
|
275
|
+
|
|
276
|
+
def __exit__(
|
|
277
|
+
self,
|
|
278
|
+
exception_type: type[BaseException] | None,
|
|
279
|
+
exception: BaseException | None,
|
|
280
|
+
traceback: TracebackType | None,
|
|
281
|
+
) -> None:
|
|
282
|
+
"""Close the connection when the ``with`` block ends.
|
|
283
|
+
|
|
284
|
+
:param exception_type: the exception class, if the block raised.
|
|
285
|
+
:param exception: the exception, if the block raised.
|
|
286
|
+
:param traceback: its traceback, if the block raised.
|
|
287
|
+
"""
|
|
288
|
+
self.close()
|
|
289
|
+
|
|
290
|
+
def _keepalive_loop(self) -> None:
|
|
291
|
+
"""Ping the daemon when it is silent, and give up on one that stays silent."""
|
|
292
|
+
interval = self._options.keepalive_interval
|
|
293
|
+
limit = self._options.dead_after
|
|
294
|
+
assert interval is not None and limit is not None
|
|
295
|
+
|
|
296
|
+
while not self._stopped.wait(interval / 2):
|
|
297
|
+
silent_for = time.monotonic() - self._last_received
|
|
298
|
+
if silent_for >= limit:
|
|
299
|
+
self._fail(
|
|
300
|
+
ConnectionLostError(
|
|
301
|
+
f"the daemon has been silent for {silent_for:.0f} seconds"
|
|
302
|
+
)
|
|
303
|
+
)
|
|
304
|
+
return
|
|
305
|
+
if silent_for >= interval:
|
|
306
|
+
try:
|
|
307
|
+
with self._state:
|
|
308
|
+
packet = self._session.keepalive_ping()
|
|
309
|
+
self._send_bytes(packet)
|
|
310
|
+
except ConnectionLostError as error:
|
|
311
|
+
self._fail(error)
|
|
312
|
+
return
|
|
313
|
+
|
|
314
|
+
def _wait(
|
|
315
|
+
self,
|
|
316
|
+
future: Future[Completed],
|
|
317
|
+
serial: int,
|
|
318
|
+
procedure: Procedure[Any, Any],
|
|
319
|
+
stream: StreamSink | None,
|
|
320
|
+
) -> Completed:
|
|
321
|
+
"""Wait for the reply of a call, for at most the call timeout.
|
|
322
|
+
|
|
323
|
+
:param future: completed by the reading thread.
|
|
324
|
+
:param serial: the call.
|
|
325
|
+
:param procedure: the procedure, for the message.
|
|
326
|
+
:param stream: the stream the call opens, if any.
|
|
327
|
+
:returns: the outcome.
|
|
328
|
+
:raises CallTimeoutError: if no reply came in time.
|
|
329
|
+
"""
|
|
330
|
+
timeout = self._options.call_timeout
|
|
331
|
+
try:
|
|
332
|
+
return future.result(timeout)
|
|
333
|
+
except TimeoutError:
|
|
334
|
+
if not future.done():
|
|
335
|
+
with self._state:
|
|
336
|
+
self._waiting.pop(serial, None)
|
|
337
|
+
self._session.abandon(serial)
|
|
338
|
+
self._forget_stream(stream)
|
|
339
|
+
raise CallTimeoutError(
|
|
340
|
+
f"no reply to {procedure.name} within {timeout} seconds"
|
|
341
|
+
) from None
|
|
342
|
+
return future.result()
|
|
343
|
+
|
|
344
|
+
def _read_loop(self) -> None:
|
|
345
|
+
"""Read from the daemon until the connection ends."""
|
|
346
|
+
while True:
|
|
347
|
+
try:
|
|
348
|
+
data = self._stream.receive()
|
|
349
|
+
except (OSError, ValueError) as error:
|
|
350
|
+
self._fail(ConnectionLostError(f"the connection broke: {error}"))
|
|
351
|
+
return
|
|
352
|
+
if not data:
|
|
353
|
+
self._fail(ConnectionLostError("the daemon closed the connection"))
|
|
354
|
+
return
|
|
355
|
+
self._last_received = time.monotonic()
|
|
356
|
+
|
|
357
|
+
try:
|
|
358
|
+
self._handle(data)
|
|
359
|
+
except (ProtocolError, OSError) as error:
|
|
360
|
+
self._fail(error)
|
|
361
|
+
return
|
|
362
|
+
|
|
363
|
+
def _handle(self, data: bytes) -> None:
|
|
364
|
+
"""Process received bytes: finish calls, deliver events, answer pings.
|
|
365
|
+
|
|
366
|
+
:param data: bytes from the daemon.
|
|
367
|
+
"""
|
|
368
|
+
with self._state:
|
|
369
|
+
completed = self._session.feed(data)
|
|
370
|
+
events = self._session.take_events()
|
|
371
|
+
stream_events = self._session.take_stream_events()
|
|
372
|
+
pending = self._session.take_outgoing()
|
|
373
|
+
|
|
374
|
+
ready = [(self._waiting.pop(item.serial), item) for item in completed]
|
|
375
|
+
listeners = dict(self._listeners)
|
|
376
|
+
sinks = dict(self._streams)
|
|
377
|
+
self._forget_finished(stream_events)
|
|
378
|
+
|
|
379
|
+
if pending:
|
|
380
|
+
self._send_bytes(pending)
|
|
381
|
+
for (future, on_result), item in ready:
|
|
382
|
+
if on_result is not None and item.error is None:
|
|
383
|
+
on_result(item.result)
|
|
384
|
+
future.set_result(item)
|
|
385
|
+
for event in events:
|
|
386
|
+
self._deliver(listeners, event)
|
|
387
|
+
for stream_event in stream_events:
|
|
388
|
+
sink = sinks.get(stream_event.serial)
|
|
389
|
+
if sink is not None:
|
|
390
|
+
sink.deliver(stream_event)
|
|
391
|
+
|
|
392
|
+
def _deliver(self, listeners: dict[int, EventListener], event: ServerEvent) -> None:
|
|
393
|
+
"""Give an event to the listener of its subscription.
|
|
394
|
+
|
|
395
|
+
:param listeners: the listeners by subscription id.
|
|
396
|
+
:param event: the event.
|
|
397
|
+
"""
|
|
398
|
+
callback_id = getattr(event.message, "callback_id", None)
|
|
399
|
+
listener = listeners.get(callback_id) if callback_id is not None else None
|
|
400
|
+
if listener is not None:
|
|
401
|
+
listener(event)
|
|
402
|
+
|
|
403
|
+
def _forget_finished(self, events: list[StreamEvent]) -> None:
|
|
404
|
+
"""Stop expecting data for the streams that ended.
|
|
405
|
+
|
|
406
|
+
Call with the state lock held.
|
|
407
|
+
|
|
408
|
+
:param events: the stream events just decoded.
|
|
409
|
+
"""
|
|
410
|
+
for event in events:
|
|
411
|
+
if event.kind in ("closed", "error"):
|
|
412
|
+
self._streams.pop(event.serial, None)
|
|
413
|
+
|
|
414
|
+
def _forget_stream(self, stream: StreamSink | None) -> None:
|
|
415
|
+
"""Stop expecting data for a stream whose call failed.
|
|
416
|
+
|
|
417
|
+
:param stream: the stream, or ``None``.
|
|
418
|
+
"""
|
|
419
|
+
if stream is not None:
|
|
420
|
+
with self._state:
|
|
421
|
+
self._streams.pop(stream.serial, None)
|
|
422
|
+
|
|
423
|
+
def _send_bytes(self, data: bytes) -> None:
|
|
424
|
+
"""Send bytes, one sender at a time.
|
|
425
|
+
|
|
426
|
+
:param data: what to send.
|
|
427
|
+
:raises ConnectionLostError: if the connection is gone.
|
|
428
|
+
"""
|
|
429
|
+
try:
|
|
430
|
+
with self._send:
|
|
431
|
+
self._stream.send(data)
|
|
432
|
+
except OSError as error:
|
|
433
|
+
raise ConnectionLostError(f"cannot send: {error}") from error
|
|
434
|
+
|
|
435
|
+
def _fail(self, error: Exception) -> None:
|
|
436
|
+
"""End the connection: fail the waiting calls and tell the subscriptions.
|
|
437
|
+
|
|
438
|
+
:param error: why it ended.
|
|
439
|
+
"""
|
|
440
|
+
with self._state:
|
|
441
|
+
if self._failure is not None:
|
|
442
|
+
return
|
|
443
|
+
self._failure = error
|
|
444
|
+
self._stopped.set()
|
|
445
|
+
|
|
446
|
+
waiting = list(self._waiting.values())
|
|
447
|
+
self._waiting.clear()
|
|
448
|
+
|
|
449
|
+
lost = list(self._on_lost)
|
|
450
|
+
self._on_lost.clear()
|
|
451
|
+
|
|
452
|
+
sinks = list(self._streams.items())
|
|
453
|
+
self._streams.clear()
|
|
454
|
+
|
|
455
|
+
for serial, sink in sinks:
|
|
456
|
+
sink.deliver(StreamEvent(serial, "error", error=error))
|
|
457
|
+
for future, _ in waiting:
|
|
458
|
+
future.set_exception(error)
|
|
459
|
+
for callback in lost:
|
|
460
|
+
callback(error)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""libvirt's typed parameters: ``dict`` in Python, a list of typed values on the wire.
|
|
2
|
+
|
|
3
|
+
Setters such as ``set_domain_memory_parameters`` take a dict. The daemon needs
|
|
4
|
+
the exact integer width of each named parameter, which libvirt's headers
|
|
5
|
+
document; ``protocol/typed_hints.py`` has them. A name that is not in the table
|
|
6
|
+
is typed from its Python value: ``bool`` boolean, ``float`` double, ``str`` text,
|
|
7
|
+
non-negative ``int`` ullong, negative ``int`` llong.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
|
|
12
|
+
from libvirtpy.rpc.protocol import types
|
|
13
|
+
from libvirtpy.rpc.protocol.typed_hints import TYPED_PARAMETER_HINTS
|
|
14
|
+
|
|
15
|
+
__all__ = ["TypedValue", "from_wire", "to_wire"]
|
|
16
|
+
|
|
17
|
+
TypedValue = int | float | bool | str
|
|
18
|
+
|
|
19
|
+
_INT, _UINT, _LLONG, _ULLONG, _DOUBLE, _BOOLEAN, _STRING = range(1, 8)
|
|
20
|
+
_INTEGER_TYPES = {_INT, _UINT, _LLONG, _ULLONG}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def to_wire(parameters: Mapping[str, TypedValue]) -> list[types.TypedParam]:
|
|
24
|
+
"""Turn a dict into the wire list of typed parameters.
|
|
25
|
+
|
|
26
|
+
:param parameters: parameter name -> value.
|
|
27
|
+
:returns: the typed parameters, in the dict's order.
|
|
28
|
+
:raises TypeError: if a value does not fit the documented type of its name.
|
|
29
|
+
"""
|
|
30
|
+
return [
|
|
31
|
+
types.TypedParam(
|
|
32
|
+
field=name,
|
|
33
|
+
value=types.TypedParamValue(type=code, value=_convert(name, code, value)),
|
|
34
|
+
)
|
|
35
|
+
for name, value in parameters.items()
|
|
36
|
+
for code in [_type_of(name, value)]
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def from_wire(parameters: list[types.TypedParam]) -> dict[str, TypedValue]:
|
|
41
|
+
"""Turn the wire list of typed parameters into a dict.
|
|
42
|
+
|
|
43
|
+
A boolean (wire type 6) becomes ``bool``; the other values keep their Python
|
|
44
|
+
type (``int``, ``float``, ``str``).
|
|
45
|
+
|
|
46
|
+
:param parameters: the typed parameters of a reply.
|
|
47
|
+
:returns: parameter name -> value.
|
|
48
|
+
"""
|
|
49
|
+
values: dict[str, TypedValue] = {}
|
|
50
|
+
for parameter in parameters:
|
|
51
|
+
value = parameter.value.value
|
|
52
|
+
if parameter.value.type == _BOOLEAN:
|
|
53
|
+
value = bool(value)
|
|
54
|
+
values[parameter.field] = value # type: ignore[assignment] # the union holds only TypedValue types
|
|
55
|
+
return values
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _type_of(name: str, value: TypedValue) -> int:
|
|
59
|
+
"""Choose the wire type of a parameter.
|
|
60
|
+
|
|
61
|
+
:param name: the parameter name.
|
|
62
|
+
:param value: the Python value.
|
|
63
|
+
:returns: the wire type code: the documented one, else inferred.
|
|
64
|
+
"""
|
|
65
|
+
if name in TYPED_PARAMETER_HINTS:
|
|
66
|
+
return TYPED_PARAMETER_HINTS[name]
|
|
67
|
+
if isinstance(value, bool):
|
|
68
|
+
return _BOOLEAN
|
|
69
|
+
if isinstance(value, float):
|
|
70
|
+
return _DOUBLE
|
|
71
|
+
if isinstance(value, str):
|
|
72
|
+
return _STRING
|
|
73
|
+
return _ULLONG if value >= 0 else _LLONG
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _convert(name: str, code: int, value: TypedValue) -> int | float | str:
|
|
77
|
+
"""Check a value against its wire type.
|
|
78
|
+
|
|
79
|
+
:param name: the parameter name, for the error message.
|
|
80
|
+
:param code: the wire type code.
|
|
81
|
+
:param value: the Python value.
|
|
82
|
+
:returns: the value for the wire.
|
|
83
|
+
:raises TypeError: if the value cannot be of that type.
|
|
84
|
+
"""
|
|
85
|
+
if code == _STRING and isinstance(value, str):
|
|
86
|
+
return value
|
|
87
|
+
if code == _DOUBLE and isinstance(value, int | float):
|
|
88
|
+
return float(value)
|
|
89
|
+
if code == _BOOLEAN and isinstance(value, bool | int):
|
|
90
|
+
return int(bool(value))
|
|
91
|
+
if (
|
|
92
|
+
code in _INTEGER_TYPES
|
|
93
|
+
and isinstance(value, int)
|
|
94
|
+
and not isinstance(value, bool)
|
|
95
|
+
):
|
|
96
|
+
return value
|
|
97
|
+
raise TypeError(f"parameter {name!r}: {value!r} does not fit wire type {code}")
|
libvirtpy/rpc/uri.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Understanding libvirt URIs: driver, transport, host and parameters."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from urllib.parse import parse_qsl, urlparse
|
|
5
|
+
|
|
6
|
+
__all__ = ["HYPERVISOR_DAEMONS", "ConnectionTarget", "parse_uri"]
|
|
7
|
+
|
|
8
|
+
HYPERVISOR_DAEMONS = {
|
|
9
|
+
"qemu": "virtqemud",
|
|
10
|
+
"lxc": "virtlxcd",
|
|
11
|
+
"xen": "virtxend",
|
|
12
|
+
"vbox": "virtvboxd",
|
|
13
|
+
"ch": "virtchd",
|
|
14
|
+
"bhyve": "virtbhyved",
|
|
15
|
+
"vz": "virtvzd",
|
|
16
|
+
}
|
|
17
|
+
DEFAULT_PORTS = {"tls": 16514, "tcp": 16509}
|
|
18
|
+
LOCAL_TRANSPORTS = ("", "unix")
|
|
19
|
+
REMOTE_TRANSPORTS = ("ssh", "tls", "tcp")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ConnectionTarget:
|
|
24
|
+
"""What a libvirt URI asks for."""
|
|
25
|
+
|
|
26
|
+
uri: str
|
|
27
|
+
driver: str
|
|
28
|
+
"""The hypervisor driver: ``qemu``, ``lxc``, ..."""
|
|
29
|
+
session: bool
|
|
30
|
+
"""``True`` for ``.../session``: the daemon of the user, not of the system."""
|
|
31
|
+
transport: str = ""
|
|
32
|
+
"""``""``/``unix`` for this machine, or ``ssh``, ``tls``, ``tcp``."""
|
|
33
|
+
host: str | None = None
|
|
34
|
+
port: int | None = None
|
|
35
|
+
user: str | None = None
|
|
36
|
+
parameters: dict[str, str] = field(default_factory=dict)
|
|
37
|
+
"""The query of the URI (``keyfile``, ``pkipath``, ``no_verify``, ...)."""
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def remote(self) -> bool:
|
|
41
|
+
"""Whether the daemon runs on another host."""
|
|
42
|
+
return self.transport in REMOTE_TRANSPORTS
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def protected(self) -> bool:
|
|
46
|
+
"""Whether the channel is already private: not plain TCP."""
|
|
47
|
+
return self.transport != "tcp"
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def open_name(self) -> str:
|
|
51
|
+
"""The URI the remote daemon is asked to open: no transport, host or query."""
|
|
52
|
+
scope = "session" if self.session else "system"
|
|
53
|
+
return f"{self.driver}:///{scope}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def parse_uri(uri: str) -> ConnectionTarget:
|
|
57
|
+
"""Understand a libvirt URI such as ``qemu+ssh://user@host/system``.
|
|
58
|
+
|
|
59
|
+
:param uri: the URI.
|
|
60
|
+
:returns: the target.
|
|
61
|
+
:raises NotImplementedError: for a transport other than unix, ssh, tls, tcp.
|
|
62
|
+
:raises ValueError: if the driver is unknown or a remote URI has no host.
|
|
63
|
+
"""
|
|
64
|
+
parsed = urlparse(uri)
|
|
65
|
+
driver, _, transport = parsed.scheme.partition("+")
|
|
66
|
+
|
|
67
|
+
if driver not in HYPERVISOR_DAEMONS:
|
|
68
|
+
raise ValueError(f"unknown libvirt driver {driver!r} in {uri!r}")
|
|
69
|
+
if transport not in (*LOCAL_TRANSPORTS, *REMOTE_TRANSPORTS):
|
|
70
|
+
raise NotImplementedError(f"transport {transport!r} is not supported")
|
|
71
|
+
if transport in REMOTE_TRANSPORTS and not parsed.hostname:
|
|
72
|
+
raise ValueError(f"{uri!r} needs a host for the {transport} transport")
|
|
73
|
+
if transport in LOCAL_TRANSPORTS and parsed.hostname:
|
|
74
|
+
raise ValueError(f"{uri!r} names a host but no remote transport")
|
|
75
|
+
|
|
76
|
+
return ConnectionTarget(
|
|
77
|
+
uri=uri,
|
|
78
|
+
driver=driver,
|
|
79
|
+
session=parsed.path == "/session",
|
|
80
|
+
transport=transport,
|
|
81
|
+
host=parsed.hostname,
|
|
82
|
+
port=parsed.port or DEFAULT_PORTS.get(transport),
|
|
83
|
+
user=parsed.username,
|
|
84
|
+
parameters=dict(parse_qsl(parsed.query)),
|
|
85
|
+
)
|