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/aio.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"""An asyncio connection to one libvirt daemon socket.
|
|
2
|
+
|
|
3
|
+
A background task reads replies, so many calls may be in flight at once; each
|
|
4
|
+
caller awaits the future of its own serial.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import contextlib
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Awaitable, Callable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from types import TracebackType
|
|
13
|
+
from typing import Any, Protocol, TypeVar
|
|
14
|
+
|
|
15
|
+
from libvirtpy.rpc.options import ConnectionOptions
|
|
16
|
+
from libvirtpy.rpc.procedure import Procedure
|
|
17
|
+
from libvirtpy.rpc.session import (
|
|
18
|
+
CallTimeoutError,
|
|
19
|
+
Completed,
|
|
20
|
+
ConnectionLostError,
|
|
21
|
+
ProtocolError,
|
|
22
|
+
ServerEvent,
|
|
23
|
+
Session,
|
|
24
|
+
StreamEvent,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = ["AsyncRpc"]
|
|
28
|
+
|
|
29
|
+
RECEIVE_SIZE = 65536
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class StreamSink(Protocol):
|
|
33
|
+
"""Where the data of an open stream is delivered."""
|
|
34
|
+
|
|
35
|
+
serial: int
|
|
36
|
+
|
|
37
|
+
def deliver(self, event: StreamEvent) -> None:
|
|
38
|
+
"""Receive what the connection read for the stream.
|
|
39
|
+
|
|
40
|
+
:param event: the data, the end, or the error.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
OnResult = Callable[[Any], None]
|
|
45
|
+
EventListener = Callable[[ServerEvent], None]
|
|
46
|
+
SelfT = TypeVar("SelfT", bound="AsyncRpc")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AsyncRpc:
|
|
50
|
+
"""Calls procedures of one daemon; calls may overlap."""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
reader: asyncio.StreamReader,
|
|
55
|
+
writer: asyncio.StreamWriter,
|
|
56
|
+
on_close: Callable[[], Awaitable[None]] | None = None,
|
|
57
|
+
options: ConnectionOptions | None = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Wrap a connected pair of streams and start reading.
|
|
60
|
+
|
|
61
|
+
:param reader: the receiving side.
|
|
62
|
+
:param writer: the sending side.
|
|
63
|
+
:param on_close: awaited when the connection closes, e.g. to end the
|
|
64
|
+
``ssh`` process behind the streams.
|
|
65
|
+
:param options: the call timeout and the keepalive; the defaults if left out.
|
|
66
|
+
"""
|
|
67
|
+
self._options = options or ConnectionOptions()
|
|
68
|
+
self._last_received = time.monotonic()
|
|
69
|
+
self._reader = reader
|
|
70
|
+
self._writer = writer
|
|
71
|
+
self._on_close = on_close
|
|
72
|
+
|
|
73
|
+
self._session = Session()
|
|
74
|
+
self._waiting: dict[int, asyncio.Future[Completed]] = {}
|
|
75
|
+
self._on_result: dict[int, OnResult] = {}
|
|
76
|
+
|
|
77
|
+
self._listeners: dict[int, EventListener] = {}
|
|
78
|
+
self._on_lost: list[Callable[[Exception], None]] = []
|
|
79
|
+
self._failure: Exception | None = None
|
|
80
|
+
self._streams: dict[int, StreamSink] = {}
|
|
81
|
+
|
|
82
|
+
loop = asyncio.get_running_loop()
|
|
83
|
+
self._reading = loop.create_task(self._read_loop())
|
|
84
|
+
self._watching: asyncio.Task[None] | None = None
|
|
85
|
+
if self._options.keepalive_interval is not None:
|
|
86
|
+
self._watching = loop.create_task(self._keepalive_loop())
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
async def connect_unix(
|
|
90
|
+
cls: type[SelfT], path: Path | str, options: ConnectionOptions | None = None
|
|
91
|
+
) -> SelfT:
|
|
92
|
+
"""Connect to a daemon's UNIX socket.
|
|
93
|
+
|
|
94
|
+
:param path: the socket file, e.g. ``/run/libvirt/virtqemud-sock``.
|
|
95
|
+
:param options: the call timeout and the keepalive.
|
|
96
|
+
:returns: the connection.
|
|
97
|
+
:raises OSError: if the socket cannot be reached.
|
|
98
|
+
"""
|
|
99
|
+
reader, writer = await asyncio.open_unix_connection(str(path))
|
|
100
|
+
return cls(reader, writer, options=options)
|
|
101
|
+
|
|
102
|
+
async def call(
|
|
103
|
+
self,
|
|
104
|
+
procedure: Procedure[Any, Any],
|
|
105
|
+
args: Any = None,
|
|
106
|
+
*,
|
|
107
|
+
on_result: OnResult | None = None,
|
|
108
|
+
stream: StreamSink | None = None,
|
|
109
|
+
) -> Any:
|
|
110
|
+
"""Call a procedure and wait for its reply.
|
|
111
|
+
|
|
112
|
+
:param procedure: the procedure.
|
|
113
|
+
:param args: its arguments struct, or ``None`` if it has none.
|
|
114
|
+
:param on_result: called with the result as soon as the reply is read,
|
|
115
|
+
before anything the daemon sent after it is handled; a subscription
|
|
116
|
+
uses it to listen from the first event.
|
|
117
|
+
:param stream: for a call that opens a data stream: where its data goes.
|
|
118
|
+
The call's serial becomes ``stream.serial`` before it is sent.
|
|
119
|
+
:returns: the return struct, or ``None`` if the procedure returns nothing.
|
|
120
|
+
:raises LibvirtError: if the daemon reports an error.
|
|
121
|
+
:raises ConnectionLostError: if the connection ended.
|
|
122
|
+
:raises CallTimeoutError: if there was no reply within the call timeout.
|
|
123
|
+
"""
|
|
124
|
+
if self._failure is not None:
|
|
125
|
+
raise self._failure
|
|
126
|
+
|
|
127
|
+
serial, packet = self._session.call(procedure, args, stream=stream is not None)
|
|
128
|
+
if stream is not None:
|
|
129
|
+
stream.serial = serial
|
|
130
|
+
self._streams[serial] = stream
|
|
131
|
+
future: asyncio.Future[Completed] = asyncio.get_running_loop().create_future()
|
|
132
|
+
self._waiting[serial] = future
|
|
133
|
+
if on_result is not None:
|
|
134
|
+
self._on_result[serial] = on_result
|
|
135
|
+
|
|
136
|
+
self._writer.write(packet)
|
|
137
|
+
await self._writer.drain()
|
|
138
|
+
|
|
139
|
+
completed = await self._wait(future, serial, procedure, stream)
|
|
140
|
+
if completed.error is not None:
|
|
141
|
+
if stream is not None:
|
|
142
|
+
self._streams.pop(stream.serial, None)
|
|
143
|
+
raise completed.error
|
|
144
|
+
return completed.result
|
|
145
|
+
|
|
146
|
+
async def send_stream_data(self, serial: int, data: bytes) -> None:
|
|
147
|
+
"""Send data on an open stream.
|
|
148
|
+
|
|
149
|
+
:param serial: the stream.
|
|
150
|
+
:param data: the bytes.
|
|
151
|
+
"""
|
|
152
|
+
await self._write(self._session.stream_data(serial, data))
|
|
153
|
+
|
|
154
|
+
async def finish_stream(self, serial: int) -> None:
|
|
155
|
+
"""Tell the daemon that we have sent everything on a stream.
|
|
156
|
+
|
|
157
|
+
:param serial: the stream.
|
|
158
|
+
"""
|
|
159
|
+
await self._write(self._session.stream_finish(serial))
|
|
160
|
+
|
|
161
|
+
async def abort_stream(self, serial: int) -> None:
|
|
162
|
+
"""Give up on a stream.
|
|
163
|
+
|
|
164
|
+
:param serial: the stream.
|
|
165
|
+
"""
|
|
166
|
+
packet = self._session.stream_abort(serial)
|
|
167
|
+
self._streams.pop(serial, None)
|
|
168
|
+
await self._write(packet)
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def failure(self) -> Exception | None:
|
|
172
|
+
"""Why the connection ended.
|
|
173
|
+
|
|
174
|
+
:returns: the error, or ``None`` while the connection is alive.
|
|
175
|
+
"""
|
|
176
|
+
return self._failure
|
|
177
|
+
|
|
178
|
+
def add_listener(self, callback_id: int, listener: EventListener) -> None:
|
|
179
|
+
"""Send the events of a subscription to ``listener``.
|
|
180
|
+
|
|
181
|
+
:param callback_id: the id the daemon gave the subscription.
|
|
182
|
+
:param listener: called with each ``ServerEvent``, in the event loop.
|
|
183
|
+
"""
|
|
184
|
+
self._listeners[callback_id] = listener
|
|
185
|
+
|
|
186
|
+
def remove_listener(self, callback_id: int) -> None:
|
|
187
|
+
"""Stop sending the events of a subscription.
|
|
188
|
+
|
|
189
|
+
:param callback_id: the id the daemon gave the subscription.
|
|
190
|
+
"""
|
|
191
|
+
self._listeners.pop(callback_id, None)
|
|
192
|
+
|
|
193
|
+
def when_lost(self, callback: Callable[[Exception], None]) -> None:
|
|
194
|
+
"""Call ``callback`` when the connection ends.
|
|
195
|
+
|
|
196
|
+
:param callback: called with the reason, in the event loop.
|
|
197
|
+
"""
|
|
198
|
+
if self._failure is not None:
|
|
199
|
+
callback(self._failure)
|
|
200
|
+
return
|
|
201
|
+
self._on_lost.append(callback)
|
|
202
|
+
|
|
203
|
+
async def close(self) -> None:
|
|
204
|
+
"""Close the connection and stop reading."""
|
|
205
|
+
self._reading.cancel()
|
|
206
|
+
if self._watching is not None:
|
|
207
|
+
self._watching.cancel()
|
|
208
|
+
self._writer.close()
|
|
209
|
+
with contextlib.suppress(OSError):
|
|
210
|
+
await self._writer.wait_closed()
|
|
211
|
+
|
|
212
|
+
self._fail_waiting(ConnectionLostError("the connection was closed"))
|
|
213
|
+
if self._on_close is not None:
|
|
214
|
+
await self._on_close()
|
|
215
|
+
|
|
216
|
+
async def __aenter__(self: SelfT) -> SelfT:
|
|
217
|
+
"""Use the connection in an ``async with`` block.
|
|
218
|
+
|
|
219
|
+
:returns: the connection.
|
|
220
|
+
"""
|
|
221
|
+
return self
|
|
222
|
+
|
|
223
|
+
async def __aexit__(
|
|
224
|
+
self,
|
|
225
|
+
exception_type: type[BaseException] | None,
|
|
226
|
+
exception: BaseException | None,
|
|
227
|
+
traceback: TracebackType | None,
|
|
228
|
+
) -> None:
|
|
229
|
+
"""Close the connection when the block ends.
|
|
230
|
+
|
|
231
|
+
:param exception_type: the exception class, if the block raised.
|
|
232
|
+
:param exception: the exception, if the block raised.
|
|
233
|
+
:param traceback: its traceback, if the block raised.
|
|
234
|
+
"""
|
|
235
|
+
await self.close()
|
|
236
|
+
|
|
237
|
+
async def _wait(
|
|
238
|
+
self,
|
|
239
|
+
future: asyncio.Future[Completed],
|
|
240
|
+
serial: int,
|
|
241
|
+
procedure: Procedure[Any, Any],
|
|
242
|
+
stream: StreamSink | None,
|
|
243
|
+
) -> Completed:
|
|
244
|
+
"""Wait for the reply of a call, for at most the call timeout.
|
|
245
|
+
|
|
246
|
+
A call that is cancelled or times out is abandoned: its late reply is dropped
|
|
247
|
+
instead of being taken for a protocol error.
|
|
248
|
+
|
|
249
|
+
:param future: completed by the reading task.
|
|
250
|
+
:param serial: the call.
|
|
251
|
+
:param procedure: the procedure, for the message.
|
|
252
|
+
:param stream: the stream the call opens, if any.
|
|
253
|
+
:returns: the outcome.
|
|
254
|
+
:raises CallTimeoutError: if no reply came in time.
|
|
255
|
+
"""
|
|
256
|
+
timeout = self._options.call_timeout
|
|
257
|
+
try:
|
|
258
|
+
return await asyncio.wait_for(asyncio.shield(future), timeout)
|
|
259
|
+
except (TimeoutError, asyncio.CancelledError) as error:
|
|
260
|
+
self._waiting.pop(serial, None)
|
|
261
|
+
self._on_result.pop(serial, None)
|
|
262
|
+
self._session.abandon(serial)
|
|
263
|
+
|
|
264
|
+
if stream is not None:
|
|
265
|
+
self._streams.pop(serial, None)
|
|
266
|
+
future.cancel()
|
|
267
|
+
|
|
268
|
+
if isinstance(error, asyncio.CancelledError):
|
|
269
|
+
raise
|
|
270
|
+
raise CallTimeoutError(
|
|
271
|
+
f"no reply to {procedure.name} within {timeout} seconds"
|
|
272
|
+
) from None
|
|
273
|
+
|
|
274
|
+
async def _keepalive_loop(self) -> None:
|
|
275
|
+
"""Ping the daemon when it is silent, and give up on one that stays silent."""
|
|
276
|
+
interval = self._options.keepalive_interval
|
|
277
|
+
limit = self._options.dead_after
|
|
278
|
+
assert interval is not None and limit is not None
|
|
279
|
+
|
|
280
|
+
while True:
|
|
281
|
+
await asyncio.sleep(interval / 2)
|
|
282
|
+
silent_for = time.monotonic() - self._last_received
|
|
283
|
+
if silent_for >= limit:
|
|
284
|
+
self._fail_waiting(
|
|
285
|
+
ConnectionLostError(
|
|
286
|
+
f"the daemon has been silent for {silent_for:.0f} seconds"
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
self._writer.close()
|
|
290
|
+
return
|
|
291
|
+
if silent_for >= interval:
|
|
292
|
+
try:
|
|
293
|
+
await self._write(self._session.keepalive_ping())
|
|
294
|
+
except OSError as error:
|
|
295
|
+
self._fail_waiting(ConnectionLostError(f"cannot send: {error}"))
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
async def _read_loop(self) -> None:
|
|
299
|
+
"""Feed received bytes to the session and wake the callers."""
|
|
300
|
+
try:
|
|
301
|
+
while True:
|
|
302
|
+
data = await self._reader.read(RECEIVE_SIZE)
|
|
303
|
+
if not data:
|
|
304
|
+
raise ConnectionLostError("the daemon closed the connection")
|
|
305
|
+
self._last_received = time.monotonic()
|
|
306
|
+
self._deliver(self._session.feed(data))
|
|
307
|
+
|
|
308
|
+
self._dispatch_events(self._session.take_events())
|
|
309
|
+
self._dispatch_stream(self._session.take_stream_events())
|
|
310
|
+
await self._send_pending()
|
|
311
|
+
except (ProtocolError, OSError) as error:
|
|
312
|
+
self._fail_waiting(error)
|
|
313
|
+
|
|
314
|
+
def _deliver(self, completed: list[Completed]) -> None:
|
|
315
|
+
"""Hand finished calls to the callers waiting for them.
|
|
316
|
+
|
|
317
|
+
:param completed: the outcomes, from the session.
|
|
318
|
+
"""
|
|
319
|
+
for item in completed:
|
|
320
|
+
future = self._waiting.pop(item.serial, None)
|
|
321
|
+
on_result = self._on_result.pop(item.serial, None)
|
|
322
|
+
if on_result is not None and item.error is None:
|
|
323
|
+
on_result(item.result)
|
|
324
|
+
if future is not None and not future.done():
|
|
325
|
+
future.set_result(item)
|
|
326
|
+
|
|
327
|
+
async def _write(self, packet: bytes) -> None:
|
|
328
|
+
"""Send a packet, if there is one.
|
|
329
|
+
|
|
330
|
+
:param packet: the bytes; empty means nothing to send.
|
|
331
|
+
"""
|
|
332
|
+
if packet:
|
|
333
|
+
self._writer.write(packet)
|
|
334
|
+
await self._writer.drain()
|
|
335
|
+
|
|
336
|
+
def _dispatch_stream(self, events: list[StreamEvent]) -> None:
|
|
337
|
+
"""Give each stream event to its stream.
|
|
338
|
+
|
|
339
|
+
:param events: what the session decoded for the open streams.
|
|
340
|
+
"""
|
|
341
|
+
for event in events:
|
|
342
|
+
sink = self._streams.get(event.serial)
|
|
343
|
+
if event.kind in ("closed", "error"):
|
|
344
|
+
self._streams.pop(event.serial, None)
|
|
345
|
+
if sink is not None:
|
|
346
|
+
sink.deliver(event)
|
|
347
|
+
|
|
348
|
+
def _dispatch_events(self, events: list[ServerEvent]) -> None:
|
|
349
|
+
"""Give each event to the listener of its subscription.
|
|
350
|
+
|
|
351
|
+
:param events: the events the session decoded.
|
|
352
|
+
"""
|
|
353
|
+
for event in events:
|
|
354
|
+
callback_id = getattr(event.message, "callback_id", None)
|
|
355
|
+
listener = (
|
|
356
|
+
self._listeners.get(callback_id) if callback_id is not None else None
|
|
357
|
+
)
|
|
358
|
+
if listener is not None:
|
|
359
|
+
listener(event)
|
|
360
|
+
|
|
361
|
+
async def _send_pending(self) -> None:
|
|
362
|
+
"""Send what the session queued by itself (keepalive pongs)."""
|
|
363
|
+
pending = self._session.take_outgoing()
|
|
364
|
+
if pending:
|
|
365
|
+
self._writer.write(pending)
|
|
366
|
+
await self._writer.drain()
|
|
367
|
+
|
|
368
|
+
def _fail_waiting(self, error: Exception) -> None:
|
|
369
|
+
"""Make every waiting call fail.
|
|
370
|
+
|
|
371
|
+
:param error: the reason.
|
|
372
|
+
"""
|
|
373
|
+
if self._failure is None:
|
|
374
|
+
self._failure = error
|
|
375
|
+
for future in self._waiting.values():
|
|
376
|
+
if not future.done():
|
|
377
|
+
future.set_exception(error)
|
|
378
|
+
self._waiting.clear()
|
|
379
|
+
self._on_result.clear()
|
|
380
|
+
|
|
381
|
+
sinks, self._streams = self._streams, {}
|
|
382
|
+
for serial, sink in sinks.items():
|
|
383
|
+
sink.deliver(StreamEvent(serial, "error", error=error))
|
|
384
|
+
|
|
385
|
+
lost, self._on_lost = self._on_lost, []
|
|
386
|
+
for callback in lost:
|
|
387
|
+
callback(error)
|
libvirtpy/rpc/cpumap.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""CPU bitmaps: the wire form of "these host CPUs" (bit ``n`` of byte ``n // 8``)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
|
|
5
|
+
__all__ = ["from_cpumap", "map_length", "to_cpumap"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def to_cpumap(cpus: Iterable[int], length: int = 0) -> bytes:
|
|
9
|
+
"""Make the bitmap of a set of CPU numbers.
|
|
10
|
+
|
|
11
|
+
:param cpus: the CPU numbers.
|
|
12
|
+
:param length: the least number of bytes of the bitmap; it grows to hold the
|
|
13
|
+
highest CPU.
|
|
14
|
+
:returns: the bitmap.
|
|
15
|
+
:raises ValueError: if a CPU number is negative.
|
|
16
|
+
"""
|
|
17
|
+
wanted = sorted(set(cpus))
|
|
18
|
+
if wanted and wanted[0] < 0:
|
|
19
|
+
raise ValueError(f"CPU numbers are not negative: {wanted[0]}")
|
|
20
|
+
|
|
21
|
+
size = max(length, (wanted[-1] // 8 + 1) if wanted else 1)
|
|
22
|
+
bitmap = bytearray(size)
|
|
23
|
+
for cpu in wanted:
|
|
24
|
+
bitmap[cpu // 8] |= 1 << (cpu % 8)
|
|
25
|
+
return bytes(bitmap)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def from_cpumap(bitmap: bytes) -> list[int]:
|
|
29
|
+
"""List the CPU numbers of a bitmap.
|
|
30
|
+
|
|
31
|
+
:param bitmap: the bitmap.
|
|
32
|
+
:returns: the CPU numbers that are set, ascending.
|
|
33
|
+
"""
|
|
34
|
+
return [
|
|
35
|
+
index * 8 + bit
|
|
36
|
+
for index, byte in enumerate(bitmap)
|
|
37
|
+
for bit in range(8)
|
|
38
|
+
if byte >> bit & 1
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def map_length(cpu_count: int) -> int:
|
|
43
|
+
"""Return the bytes needed for a bitmap of ``cpu_count`` CPUs.
|
|
44
|
+
|
|
45
|
+
:param cpu_count: the number of CPUs of the host.
|
|
46
|
+
:returns: ``ceil(cpu_count / 8)``, at least 1.
|
|
47
|
+
"""
|
|
48
|
+
return max(1, (cpu_count + 7) // 8)
|
libvirtpy/rpc/errors.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Errors raised by the client.
|
|
2
|
+
|
|
3
|
+
A libvirt daemon reports a failure as a numeric ``code`` (``virErrorNumber``) and
|
|
4
|
+
a ``domain`` (the part of libvirt that failed). ``LibvirtError`` carries both,
|
|
5
|
+
and the common codes have their own subclass so callers can write
|
|
6
|
+
``except NoDomainError``.
|
|
7
|
+
|
|
8
|
+
``ErrorNumber`` lists the codes the prototype knows; the full list will be
|
|
9
|
+
generated from ``include/libvirt/virterror.h``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from enum import IntEnum
|
|
13
|
+
|
|
14
|
+
from libvirtpy.errors import LibvirtPyError
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"AuthFailedError",
|
|
18
|
+
"ErrorNumber",
|
|
19
|
+
"ExistsError",
|
|
20
|
+
"InvalidArgumentError",
|
|
21
|
+
"LibvirtError",
|
|
22
|
+
"NoCheckpointError",
|
|
23
|
+
"NoDomainError",
|
|
24
|
+
"NoFilterBindingError",
|
|
25
|
+
"NoFilterError",
|
|
26
|
+
"NoInterfaceError",
|
|
27
|
+
"NoNetworkError",
|
|
28
|
+
"NoNetworkPortError",
|
|
29
|
+
"NoNodeDeviceError",
|
|
30
|
+
"NoSecretError",
|
|
31
|
+
"NoSnapshotError",
|
|
32
|
+
"NoStoragePoolError",
|
|
33
|
+
"NoStorageVolumeError",
|
|
34
|
+
"NotSupportedError",
|
|
35
|
+
"OperationInvalidError",
|
|
36
|
+
"error_class_for",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ErrorNumber(IntEnum):
|
|
41
|
+
"""The libvirt error codes (``virErrorNumber``) that have a dedicated class."""
|
|
42
|
+
|
|
43
|
+
OK = 0
|
|
44
|
+
INTERNAL_ERROR = 1
|
|
45
|
+
NO_SUPPORT = 3
|
|
46
|
+
INVALID_ARG = 8
|
|
47
|
+
OPERATION_FAILED = 9
|
|
48
|
+
XML_ERROR = 27
|
|
49
|
+
DOM_EXIST = 28
|
|
50
|
+
OPERATION_DENIED = 29
|
|
51
|
+
NETWORK_EXIST = 37
|
|
52
|
+
NO_DOMAIN = 42
|
|
53
|
+
NO_NETWORK = 43
|
|
54
|
+
AUTH_FAILED = 45
|
|
55
|
+
NO_STORAGE_POOL = 49
|
|
56
|
+
NO_STORAGE_VOL = 50
|
|
57
|
+
NO_NODE_DEVICE = 53
|
|
58
|
+
OPERATION_INVALID = 55
|
|
59
|
+
NO_INTERFACE = 57
|
|
60
|
+
NO_NWFILTER = 62
|
|
61
|
+
NO_SECRET = 66
|
|
62
|
+
NO_DOMAIN_SNAPSHOT = 72
|
|
63
|
+
NO_NWFILTER_BINDING = 101
|
|
64
|
+
NO_DOMAIN_CHECKPOINT = 103
|
|
65
|
+
NO_NETWORK_PORT = 107
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LibvirtError(LibvirtPyError):
|
|
69
|
+
"""A libvirt daemon reported an error."""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
message: str,
|
|
74
|
+
*,
|
|
75
|
+
code: int = ErrorNumber.INTERNAL_ERROR,
|
|
76
|
+
domain: int = 0,
|
|
77
|
+
) -> None:
|
|
78
|
+
"""Create the error.
|
|
79
|
+
|
|
80
|
+
:param message: the daemon's description of the failure.
|
|
81
|
+
:param code: the ``virErrorNumber`` of the failure.
|
|
82
|
+
:param domain: the ``virErrorDomain``: the part of libvirt that failed.
|
|
83
|
+
"""
|
|
84
|
+
super().__init__(message)
|
|
85
|
+
self.message = message
|
|
86
|
+
self.code = code
|
|
87
|
+
self.domain = domain
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class NoDomainError(LibvirtError):
|
|
91
|
+
"""The domain does not exist."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class NoNetworkError(LibvirtError):
|
|
95
|
+
"""The network does not exist."""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class NoStoragePoolError(LibvirtError):
|
|
99
|
+
"""The storage pool does not exist."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class NoStorageVolumeError(LibvirtError):
|
|
103
|
+
"""The storage volume does not exist."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class NoSecretError(LibvirtError):
|
|
107
|
+
"""The secret does not exist."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class NoNodeDeviceError(LibvirtError):
|
|
111
|
+
"""The host device does not exist."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class NoInterfaceError(LibvirtError):
|
|
115
|
+
"""The host interface does not exist."""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class NoFilterError(LibvirtError):
|
|
119
|
+
"""The network filter does not exist."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class NoSnapshotError(LibvirtError):
|
|
123
|
+
"""The domain snapshot does not exist."""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class NoCheckpointError(LibvirtError):
|
|
127
|
+
"""The domain checkpoint does not exist."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class NoNetworkPortError(LibvirtError):
|
|
131
|
+
"""The network port does not exist."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class NoFilterBindingError(LibvirtError):
|
|
135
|
+
"""The network filter binding does not exist."""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class OperationInvalidError(LibvirtError):
|
|
139
|
+
"""The operation does not apply in the object's current state."""
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class ExistsError(LibvirtError):
|
|
143
|
+
"""An object with that name or UUID already exists."""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class InvalidArgumentError(LibvirtError):
|
|
147
|
+
"""An argument is invalid."""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class NotSupportedError(LibvirtError):
|
|
151
|
+
"""The hypervisor does not support the operation."""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class AuthFailedError(LibvirtError):
|
|
155
|
+
"""Authentication failed."""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_CLASSES: dict[int, type[LibvirtError]] = {
|
|
159
|
+
ErrorNumber.NO_DOMAIN: NoDomainError,
|
|
160
|
+
ErrorNumber.NO_NETWORK: NoNetworkError,
|
|
161
|
+
ErrorNumber.NO_STORAGE_POOL: NoStoragePoolError,
|
|
162
|
+
ErrorNumber.NO_STORAGE_VOL: NoStorageVolumeError,
|
|
163
|
+
ErrorNumber.NO_SECRET: NoSecretError,
|
|
164
|
+
ErrorNumber.NO_NODE_DEVICE: NoNodeDeviceError,
|
|
165
|
+
ErrorNumber.NO_INTERFACE: NoInterfaceError,
|
|
166
|
+
ErrorNumber.NO_NWFILTER: NoFilterError,
|
|
167
|
+
ErrorNumber.NO_DOMAIN_SNAPSHOT: NoSnapshotError,
|
|
168
|
+
ErrorNumber.NO_DOMAIN_CHECKPOINT: NoCheckpointError,
|
|
169
|
+
ErrorNumber.NO_NETWORK_PORT: NoNetworkPortError,
|
|
170
|
+
ErrorNumber.NO_NWFILTER_BINDING: NoFilterBindingError,
|
|
171
|
+
ErrorNumber.OPERATION_INVALID: OperationInvalidError,
|
|
172
|
+
ErrorNumber.DOM_EXIST: ExistsError,
|
|
173
|
+
ErrorNumber.NETWORK_EXIST: ExistsError,
|
|
174
|
+
ErrorNumber.INVALID_ARG: InvalidArgumentError,
|
|
175
|
+
ErrorNumber.NO_SUPPORT: NotSupportedError,
|
|
176
|
+
ErrorNumber.AUTH_FAILED: AuthFailedError,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def error_class_for(code: int) -> type[LibvirtError]:
|
|
181
|
+
"""Return the exception class for a ``virErrorNumber``.
|
|
182
|
+
|
|
183
|
+
:param code: the error code reported by the daemon.
|
|
184
|
+
:returns: the dedicated subclass, or ``LibvirtError`` for other codes.
|
|
185
|
+
"""
|
|
186
|
+
return _CLASSES.get(code, LibvirtError)
|