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.
Files changed (154) hide show
  1. libvirtpy/__init__.py +5 -0
  2. libvirtpy/client/__init__.py +54 -0
  3. libvirtpy/client/_bases.py +326 -0
  4. libvirtpy/client/_runner.py +57 -0
  5. libvirtpy/client/aio.py +5922 -0
  6. libvirtpy/client/client.py +5695 -0
  7. libvirtpy/client/operations/__init__.py +631 -0
  8. libvirtpy/client/operations/_common.py +495 -0
  9. libvirtpy/client/operations/checkpoint.py +196 -0
  10. libvirtpy/client/operations/connection.py +93 -0
  11. libvirtpy/client/operations/connection_extra.py +256 -0
  12. libvirtpy/client/operations/domain.py +306 -0
  13. libvirtpy/client/operations/domain_agent.py +115 -0
  14. libvirtpy/client/operations/domain_block.py +368 -0
  15. libvirtpy/client/operations/domain_info.py +400 -0
  16. libvirtpy/client/operations/domain_lifecycle.py +338 -0
  17. libvirtpy/client/operations/domain_migration.py +164 -0
  18. libvirtpy/client/operations/domain_network.py +113 -0
  19. libvirtpy/client/operations/domain_tuning.py +494 -0
  20. libvirtpy/client/operations/host.py +246 -0
  21. libvirtpy/client/operations/host_interface.py +100 -0
  22. libvirtpy/client/operations/interface_extra.py +45 -0
  23. libvirtpy/client/operations/network.py +135 -0
  24. libvirtpy/client/operations/network_info.py +155 -0
  25. libvirtpy/client/operations/network_port.py +142 -0
  26. libvirtpy/client/operations/node_device.py +76 -0
  27. libvirtpy/client/operations/node_device_info.py +189 -0
  28. libvirtpy/client/operations/nwfilter.py +67 -0
  29. libvirtpy/client/operations/nwfilter_binding.py +74 -0
  30. libvirtpy/client/operations/secret.py +93 -0
  31. libvirtpy/client/operations/secret_extra.py +24 -0
  32. libvirtpy/client/operations/snapshot.py +100 -0
  33. libvirtpy/client/operations/snapshot_tree.py +114 -0
  34. libvirtpy/client/operations/storage.py +267 -0
  35. libvirtpy/client/operations/storage_info.py +188 -0
  36. libvirtpy/client/operations/streams.py +201 -0
  37. libvirtpy/client/references.py +249 -0
  38. libvirtpy/client/subscribing.py +88 -0
  39. libvirtpy/client/testing/__init__.py +24 -0
  40. libvirtpy/client/testing/_common.py +167 -0
  41. libvirtpy/client/testing/_domains.py +294 -0
  42. libvirtpy/client/testing/_objects.py +205 -0
  43. libvirtpy/client/testing/_state.py +246 -0
  44. libvirtpy/client/testing/_storage.py +171 -0
  45. libvirtpy/client/testing/async_transport.py +30 -0
  46. libvirtpy/client/testing/fake.py +81 -0
  47. libvirtpy/client/transport.py +87 -0
  48. libvirtpy/client/types.py +59 -0
  49. libvirtpy/client/wire.py +436 -0
  50. libvirtpy/client/wire_aio.py +348 -0
  51. libvirtpy/errors.py +7 -0
  52. libvirtpy/py.typed +0 -0
  53. libvirtpy/rpc/__init__.py +1 -0
  54. libvirtpy/rpc/aio.py +387 -0
  55. libvirtpy/rpc/cpumap.py +48 -0
  56. libvirtpy/rpc/errors.py +186 -0
  57. libvirtpy/rpc/events.py +259 -0
  58. libvirtpy/rpc/options.py +66 -0
  59. libvirtpy/rpc/procedure.py +27 -0
  60. libvirtpy/rpc/protocol/__init__.py +0 -0
  61. libvirtpy/rpc/protocol/procedures.py +5163 -0
  62. libvirtpy/rpc/protocol/typed_hints.py +210 -0
  63. libvirtpy/rpc/protocol/types.py +9299 -0
  64. libvirtpy/rpc/remote.py +295 -0
  65. libvirtpy/rpc/remote_aio.py +106 -0
  66. libvirtpy/rpc/sasl.py +467 -0
  67. libvirtpy/rpc/session.py +424 -0
  68. libvirtpy/rpc/sockets.py +251 -0
  69. libvirtpy/rpc/stream.py +323 -0
  70. libvirtpy/rpc/subscription.py +451 -0
  71. libvirtpy/rpc/sync.py +460 -0
  72. libvirtpy/rpc/typed_params.py +97 -0
  73. libvirtpy/rpc/uri.py +85 -0
  74. libvirtpy/rpc/xdr.py +552 -0
  75. libvirtpy/xml/__init__.py +49 -0
  76. libvirtpy/xml/_base.py +145 -0
  77. libvirtpy/xml/_shared/__init__.py +1 -0
  78. libvirtpy/xml/_shared/metadata.py +67 -0
  79. libvirtpy/xml/_shared/network.py +108 -0
  80. libvirtpy/xml/_shared/storage.py +131 -0
  81. libvirtpy/xml/_shared/sysinfo.py +83 -0
  82. libvirtpy/xml/_types.py +197 -0
  83. libvirtpy/xml/_xml_element.py +134 -0
  84. libvirtpy/xml/backup/__init__.py +25 -0
  85. libvirtpy/xml/backup/backup.py +89 -0
  86. libvirtpy/xml/backup/checkpoint.py +48 -0
  87. libvirtpy/xml/capabilities/__init__.py +43 -0
  88. libvirtpy/xml/capabilities/domain.py +436 -0
  89. libvirtpy/xml/capabilities/host.py +413 -0
  90. libvirtpy/xml/capabilities/storagepool.py +59 -0
  91. libvirtpy/xml/domain/__init__.py +493 -0
  92. libvirtpy/xml/domain/blkiotune.py +81 -0
  93. libvirtpy/xml/domain/clock.py +79 -0
  94. libvirtpy/xml/domain/cpu.py +265 -0
  95. libvirtpy/xml/domain/devices/__init__.py +495 -0
  96. libvirtpy/xml/domain/devices/address.py +152 -0
  97. libvirtpy/xml/domain/devices/audio.py +204 -0
  98. libvirtpy/xml/domain/devices/chardev.py +197 -0
  99. libvirtpy/xml/domain/devices/common.py +75 -0
  100. libvirtpy/xml/domain/devices/controller.py +262 -0
  101. libvirtpy/xml/domain/devices/devices.py +79 -0
  102. libvirtpy/xml/domain/devices/disk.py +471 -0
  103. libvirtpy/xml/domain/devices/filesystem.py +206 -0
  104. libvirtpy/xml/domain/devices/graphics.py +245 -0
  105. libvirtpy/xml/domain/devices/hostdev.py +221 -0
  106. libvirtpy/xml/domain/devices/input.py +89 -0
  107. libvirtpy/xml/domain/devices/interface.py +459 -0
  108. libvirtpy/xml/domain/devices/iommu.py +54 -0
  109. libvirtpy/xml/domain/devices/memballoon.py +42 -0
  110. libvirtpy/xml/domain/devices/memory_device.py +101 -0
  111. libvirtpy/xml/domain/devices/misc.py +169 -0
  112. libvirtpy/xml/domain/devices/nvram.py +20 -0
  113. libvirtpy/xml/domain/devices/shmem.py +46 -0
  114. libvirtpy/xml/domain/devices/sound.py +42 -0
  115. libvirtpy/xml/domain/devices/tpm.py +103 -0
  116. libvirtpy/xml/domain/devices/usb.py +86 -0
  117. libvirtpy/xml/domain/devices/video.py +101 -0
  118. libvirtpy/xml/domain/domain.py +157 -0
  119. libvirtpy/xml/domain/features.py +312 -0
  120. libvirtpy/xml/domain/iothread.py +41 -0
  121. libvirtpy/xml/domain/launch_security.py +82 -0
  122. libvirtpy/xml/domain/memory.py +149 -0
  123. libvirtpy/xml/domain/misc.py +113 -0
  124. libvirtpy/xml/domain/namespaces.py +96 -0
  125. libvirtpy/xml/domain/numa.py +140 -0
  126. libvirtpy/xml/domain/os.py +267 -0
  127. libvirtpy/xml/domain/qemu.py +102 -0
  128. libvirtpy/xml/domain/seclabel.py +29 -0
  129. libvirtpy/xml/domain/storage_source.py +466 -0
  130. libvirtpy/xml/domain/sysinfo.py +34 -0
  131. libvirtpy/xml/interface/__init__.py +17 -0
  132. libvirtpy/xml/interface/interface.py +153 -0
  133. libvirtpy/xml/network/__init__.py +101 -0
  134. libvirtpy/xml/network/network.py +311 -0
  135. libvirtpy/xml/network/port.py +84 -0
  136. libvirtpy/xml/nodedev/__init__.py +13 -0
  137. libvirtpy/xml/nodedev/nodedev.py +490 -0
  138. libvirtpy/xml/nwfilter/__init__.py +81 -0
  139. libvirtpy/xml/nwfilter/binding.py +51 -0
  140. libvirtpy/xml/nwfilter/filter.py +92 -0
  141. libvirtpy/xml/nwfilter/rules.py +534 -0
  142. libvirtpy/xml/secret/__init__.py +11 -0
  143. libvirtpy/xml/secret/secret.py +36 -0
  144. libvirtpy/xml/snapshot/__init__.py +29 -0
  145. libvirtpy/xml/snapshot/snapshot.py +136 -0
  146. libvirtpy/xml/storage/__init__.py +75 -0
  147. libvirtpy/xml/storage/pool.py +219 -0
  148. libvirtpy/xml/storage/volume.py +102 -0
  149. libvirtpy/xml/sysinfo.py +40 -0
  150. libvirtpy-0.1.0.dist-info/METADATA +109 -0
  151. libvirtpy-0.1.0.dist-info/RECORD +154 -0
  152. libvirtpy-0.1.0.dist-info/WHEEL +4 -0
  153. libvirtpy-0.1.0.dist-info/licenses/LICENSE +501 -0
  154. libvirtpy-0.1.0.dist-info/licenses/NOTICE +23 -0
@@ -0,0 +1,424 @@
1
+ """The libvirt RPC session without any I/O.
2
+
3
+ ``Session`` turns calls into bytes to send and received bytes into results. A
4
+ packet is a 4-byte length (counting itself), a 24-byte header and an XDR
5
+ payload. The sync and the async client only move the bytes.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ from libvirtpy.errors import LibvirtPyError
12
+ from libvirtpy.rpc import xdr
13
+ from libvirtpy.rpc.errors import LibvirtError, error_class_for
14
+ from libvirtpy.rpc.procedure import Procedure
15
+ from libvirtpy.rpc.protocol import types
16
+ from libvirtpy.rpc.protocol.procedures import PROCEDURES
17
+
18
+ __all__ = [
19
+ "CallTimeoutError",
20
+ "Completed",
21
+ "ConnectionLostError",
22
+ "ProtocolError",
23
+ "ServerEvent",
24
+ "Session",
25
+ "StreamEvent",
26
+ ]
27
+
28
+ LENGTH_SIZE = 4
29
+ HEADER_TYPE = xdr.StructType(types.VirNetMessageHeader)
30
+ ERROR_TYPE = xdr.StructType(types.Error)
31
+
32
+
33
+ class ProtocolError(LibvirtPyError):
34
+ """The daemon sent something that is not valid libvirt RPC."""
35
+
36
+
37
+ class ConnectionLostError(ProtocolError, ConnectionError):
38
+ """The connection to the daemon ended (it closed it, or ``ssh`` exited)."""
39
+
40
+
41
+ class CallTimeoutError(ProtocolError, TimeoutError):
42
+ """A call got no reply in time; the connection itself is still usable.
43
+
44
+ The reply may still arrive later: the session drops it.
45
+ """
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Completed:
50
+ """The outcome of a call."""
51
+
52
+ serial: int
53
+ result: Any = None
54
+ error: LibvirtError | None = None
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class StreamEvent:
59
+ """Something that happened on an open data stream."""
60
+
61
+ serial: int
62
+ """The stream, which has the serial of the call that opened it."""
63
+ kind: str
64
+ """``data`` (bytes arrived), ``end`` (the daemon finished sending),
65
+ ``closed`` (the daemon confirmed that we finished) or ``error``. ``end`` does
66
+ not close the stream: finish it to complete the handshake."""
67
+ data: bytes = b""
68
+ error: Exception | None = None
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class ServerEvent:
73
+ """A message the daemon pushed on its own: something happened."""
74
+
75
+ procedure: Procedure[Any, Any]
76
+ """The event's procedure; its ``message`` is the struct below."""
77
+ message: Any
78
+ """The decoded message struct."""
79
+
80
+
81
+ class Session:
82
+ """The state of one RPC connection: serials, pending calls, partial input."""
83
+
84
+ def __init__(self) -> None:
85
+ """Create a session with no calls in flight."""
86
+ self._next_serial = 1
87
+ self._pending: dict[int, Procedure[Any, Any]] = {}
88
+ self._abandoned: set[int] = set()
89
+
90
+ self._buffer = bytearray()
91
+ self._outgoing = bytearray()
92
+ self._events: list[ServerEvent] = []
93
+
94
+ self._streams: dict[int, int] = {}
95
+ self._finishing: set[int] = set()
96
+ self._stream_events: list[StreamEvent] = []
97
+
98
+ def call(
99
+ self,
100
+ procedure: Procedure[Any, Any],
101
+ args: Any = None,
102
+ *,
103
+ stream: bool = False,
104
+ ) -> tuple[int, bytes]:
105
+ """Build the packet of a call.
106
+
107
+ :param procedure: the procedure to call.
108
+ :param args: the arguments struct, or ``None`` if the procedure has none.
109
+ :param stream: the call opens a data stream, which gets the call's serial.
110
+ :returns: the serial of the call and the bytes to send.
111
+ :raises ProtocolError: if the arguments do not match the procedure.
112
+ """
113
+ if (procedure.args is None) != (args is None):
114
+ raise ProtocolError(f"wrong arguments for {procedure.name}")
115
+
116
+ serial = self._next_serial
117
+ self._next_serial += 1
118
+ self._pending[serial] = procedure
119
+ if stream:
120
+ self._streams[serial] = procedure.number
121
+ payload = b"" if args is None else xdr.encode(_arguments_type(procedure), args)
122
+
123
+ header = types.VirNetMessageHeader(
124
+ prog=types.REMOTE_PROGRAM,
125
+ vers=types.REMOTE_PROTOCOL_VERSION,
126
+ proc=procedure.number,
127
+ type=types.VirNetMessageType.CALL,
128
+ serial=serial,
129
+ status=types.VirNetMessageStatus.OK,
130
+ )
131
+ return serial, _packet(header, payload)
132
+
133
+ def feed(self, data: bytes) -> list[Completed]:
134
+ """Add received bytes and collect the calls they finish.
135
+
136
+ Packets that are not replies are handled here: a keepalive ping queues
137
+ a pong (see ``take_outgoing``); events and streams are dropped.
138
+
139
+ :param data: bytes from the socket.
140
+ :returns: the calls that completed, in arrival order.
141
+ :raises ProtocolError: if a packet is malformed.
142
+ """
143
+ self._buffer += data
144
+ completed = []
145
+
146
+ for packet in self._packets():
147
+ reply = self._handle(packet)
148
+ if reply is not None:
149
+ completed.append(reply)
150
+ return completed
151
+
152
+ def abandon(self, serial: int) -> None:
153
+ """Stop waiting for the reply of a call, and drop it if it comes later.
154
+
155
+ :param serial: the call, as returned by ``call``.
156
+ """
157
+ if self._pending.pop(serial, None) is not None:
158
+ self._abandoned.add(serial)
159
+
160
+ def keepalive_ping(self) -> bytes:
161
+ """Build a keepalive ping; a live daemon answers with a pong.
162
+
163
+ :returns: the bytes to send.
164
+ """
165
+ ping = types.VirNetMessageHeader(
166
+ prog=types.KEEPALIVE_PROGRAM,
167
+ vers=types.KEEPALIVE_PROTOCOL_VERSION,
168
+ proc=int(types.KeepaliveProcedure.PING),
169
+ type=types.VirNetMessageType.MESSAGE,
170
+ serial=0,
171
+ status=types.VirNetMessageStatus.OK,
172
+ )
173
+ return _packet(ping, b"")
174
+
175
+ def take_outgoing(self) -> bytes:
176
+ """Take the bytes the session wants sent without being asked (pongs).
177
+
178
+ :returns: the bytes, possibly empty.
179
+ """
180
+ data = bytes(self._outgoing)
181
+ self._outgoing.clear()
182
+ return data
183
+
184
+ def take_events(self) -> list[ServerEvent]:
185
+ """Take the events that arrived since the last call.
186
+
187
+ :returns: the events, oldest first, possibly none.
188
+ """
189
+ events = self._events
190
+ self._events = []
191
+ return events
192
+
193
+ def take_stream_events(self) -> list[StreamEvent]:
194
+ """Take what happened on the open streams since the last call.
195
+
196
+ :returns: the events, oldest first, possibly none.
197
+ """
198
+ events = self._stream_events
199
+ self._stream_events = []
200
+ return events
201
+
202
+ def stream_data(self, serial: int, data: bytes) -> bytes:
203
+ """Build the packet that sends data on a stream.
204
+
205
+ :param serial: the stream.
206
+ :param data: the bytes.
207
+ :returns: the bytes to send; nothing if the stream is already over.
208
+ """
209
+ return self._stream_packet(serial, types.VirNetMessageStatus.CONTINUE, data)
210
+
211
+ def stream_finish(self, serial: int) -> bytes:
212
+ """Build the packet that says we have sent everything.
213
+
214
+ The daemon answers with a ``closed`` stream event.
215
+
216
+ :param serial: the stream.
217
+ :returns: the bytes to send; nothing if the stream is already over.
218
+ """
219
+ if serial in self._streams:
220
+ self._finishing.add(serial)
221
+ return self._stream_packet(serial, types.VirNetMessageStatus.OK, b"")
222
+
223
+ def stream_abort(self, serial: int) -> bytes:
224
+ """Build the packet that gives up on a stream, and forget the stream.
225
+
226
+ :param serial: the stream.
227
+ :returns: the bytes to send; nothing if the stream is already over.
228
+ """
229
+ packet = self._stream_packet(serial, types.VirNetMessageStatus.ERROR, b"")
230
+ self._streams.pop(serial, None)
231
+ return packet
232
+
233
+ def _stream_packet(
234
+ self, serial: int, status: types.VirNetMessageStatus, payload: bytes
235
+ ) -> bytes:
236
+ """Frame a packet of an open stream.
237
+
238
+ :param serial: the stream.
239
+ :param status: continue, ok or error.
240
+ :param payload: the data.
241
+ :returns: the bytes, or nothing if the stream is not open.
242
+ """
243
+ number = self._streams.get(serial)
244
+ if number is None:
245
+ return b""
246
+
247
+ header = types.VirNetMessageHeader(
248
+ prog=types.REMOTE_PROGRAM,
249
+ vers=types.REMOTE_PROTOCOL_VERSION,
250
+ proc=number,
251
+ type=types.VirNetMessageType.STREAM,
252
+ serial=serial,
253
+ status=status,
254
+ )
255
+ return _packet(header, payload)
256
+
257
+ def _record_stream(self, header: types.VirNetMessageHeader, payload: bytes) -> None:
258
+ """Turn a packet of an open stream into a stream event.
259
+
260
+ :param header: the packet's header.
261
+ :param payload: its body.
262
+ """
263
+ serial = header.serial
264
+ if serial not in self._streams:
265
+ return
266
+
267
+ if header.status == types.VirNetMessageStatus.CONTINUE:
268
+ # An empty packet is libvirt's end-of-data marker; the stream stays
269
+ # open until we finish it and the daemon confirms.
270
+ kind = "data" if payload else "end"
271
+ self._stream_events.append(StreamEvent(serial, kind, payload))
272
+ return
273
+
274
+ del self._streams[serial]
275
+ if header.status == types.VirNetMessageStatus.ERROR:
276
+ error = _to_exception(xdr.decode(ERROR_TYPE, payload))
277
+ self._stream_events.append(StreamEvent(serial, "error", error=error))
278
+ return
279
+
280
+ self._finishing.discard(serial)
281
+ self._stream_events.append(StreamEvent(serial, "closed"))
282
+
283
+ def _packets(self) -> list[bytes]:
284
+ """Cut complete packets off the buffer.
285
+
286
+ :returns: the packets, without their length prefix.
287
+ :raises ProtocolError: if a length is impossible.
288
+ """
289
+ packets = []
290
+ while len(self._buffer) >= LENGTH_SIZE:
291
+ length = int.from_bytes(self._buffer[:LENGTH_SIZE], "big")
292
+ if length < LENGTH_SIZE + types.VIR_NET_MESSAGE_HEADER_MAX:
293
+ raise ProtocolError(f"packet length {length} is too small")
294
+ if length > types.VIR_NET_MESSAGE_MAX + LENGTH_SIZE:
295
+ raise ProtocolError(f"packet length {length} is too big")
296
+ if len(self._buffer) < length:
297
+ break
298
+
299
+ packets.append(bytes(self._buffer[LENGTH_SIZE:length]))
300
+ del self._buffer[:length]
301
+ return packets
302
+
303
+ def _handle(self, packet: bytes) -> Completed | None:
304
+ """Process one packet.
305
+
306
+ :param packet: header and payload.
307
+ :returns: the finished call, or ``None`` if the packet was not a reply.
308
+ """
309
+ decoder = xdr.Decoder(packet)
310
+ header = HEADER_TYPE.decode(decoder)
311
+ payload = decoder.read(decoder.remaining)
312
+
313
+ if header.prog == types.KEEPALIVE_PROGRAM:
314
+ self._answer_keepalive(header)
315
+ return None
316
+ if header.prog != types.REMOTE_PROGRAM:
317
+ return None
318
+
319
+ if header.type == types.VirNetMessageType.MESSAGE:
320
+ self._record_event(header, payload)
321
+ return None
322
+ if header.type == types.VirNetMessageType.STREAM:
323
+ self._record_stream(header, payload)
324
+ return None
325
+ if header.type != types.VirNetMessageType.REPLY:
326
+ return None
327
+ return self._complete(header, payload)
328
+
329
+ def _complete(
330
+ self, header: types.VirNetMessageHeader, payload: bytes
331
+ ) -> Completed | None:
332
+ """Match a reply to its call and decode it.
333
+
334
+ :param header: the reply's header.
335
+ :param payload: the reply's body.
336
+ :returns: the outcome, or ``None`` for the late reply of an abandoned call.
337
+ :raises ProtocolError: if no call is waiting for this serial.
338
+ """
339
+ if header.serial in self._abandoned:
340
+ self._abandoned.discard(header.serial)
341
+ return None
342
+
343
+ procedure = self._pending.pop(header.serial, None)
344
+ if procedure is None:
345
+ raise ProtocolError(f"reply to unknown serial {header.serial}")
346
+
347
+ if header.status == types.VirNetMessageStatus.ERROR:
348
+ return Completed(
349
+ header.serial, error=_to_exception(xdr.decode(ERROR_TYPE, payload))
350
+ )
351
+ if procedure.ret is None:
352
+ return Completed(header.serial)
353
+ return Completed(header.serial, xdr.decode(_return_type(procedure), payload))
354
+
355
+ def _record_event(self, header: types.VirNetMessageHeader, payload: bytes) -> None:
356
+ """Decode a pushed event and queue it; unknown events are dropped.
357
+
358
+ :param header: the event's header.
359
+ :param payload: its body.
360
+ """
361
+ procedure = PROCEDURES.get(header.proc)
362
+ if procedure is None or procedure.message is None:
363
+ return
364
+ message = xdr.decode(xdr.StructType(procedure.message), payload)
365
+ self._events.append(ServerEvent(procedure, message))
366
+
367
+ def _answer_keepalive(self, header: types.VirNetMessageHeader) -> None:
368
+ """Queue a pong for a keepalive ping.
369
+
370
+ :param header: the keepalive packet's header.
371
+ """
372
+ if header.proc != types.KeepaliveProcedure.PING:
373
+ return
374
+
375
+ pong = types.VirNetMessageHeader(
376
+ prog=types.KEEPALIVE_PROGRAM,
377
+ vers=types.KEEPALIVE_PROTOCOL_VERSION,
378
+ proc=int(types.KeepaliveProcedure.PONG),
379
+ type=types.VirNetMessageType.MESSAGE,
380
+ serial=header.serial,
381
+ status=types.VirNetMessageStatus.OK,
382
+ )
383
+ self._outgoing += _packet(pong, b"")
384
+
385
+
386
+ def _packet(header: types.VirNetMessageHeader, payload: bytes) -> bytes:
387
+ """Frame a header and a payload.
388
+
389
+ :param header: the message header.
390
+ :param payload: the encoded body.
391
+ :returns: the length prefix, the header and the payload.
392
+ """
393
+ body = xdr.encode(HEADER_TYPE, header) + payload
394
+ return (LENGTH_SIZE + len(body)).to_bytes(LENGTH_SIZE, "big") + body
395
+
396
+
397
+ def _arguments_type(procedure: Procedure[Any, Any]) -> xdr.StructType:
398
+ """Describe a procedure's arguments for the codec.
399
+
400
+ :param procedure: a procedure that has arguments.
401
+ :returns: the codec type.
402
+ """
403
+ assert procedure.args is not None
404
+ return xdr.StructType(procedure.args)
405
+
406
+
407
+ def _return_type(procedure: Procedure[Any, Any]) -> xdr.StructType:
408
+ """Describe a procedure's return value for the codec.
409
+
410
+ :param procedure: a procedure that returns something.
411
+ :returns: the codec type.
412
+ """
413
+ assert procedure.ret is not None
414
+ return xdr.StructType(procedure.ret)
415
+
416
+
417
+ def _to_exception(error: types.Error) -> LibvirtError:
418
+ """Turn the daemon's error struct into an exception.
419
+
420
+ :param error: the decoded ``remote_error``.
421
+ :returns: the exception of the class that fits the error code.
422
+ """
423
+ message = error.message or f"libvirt error {error.code}"
424
+ return error_class_for(error.code)(message, code=error.code, domain=error.domain)
@@ -0,0 +1,251 @@
1
+ """Finding, opening and authenticating the sockets of libvirt daemons."""
2
+
3
+ import os
4
+ from collections.abc import Generator
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from libvirtpy.rpc.errors import AuthFailedError, ErrorNumber
9
+ from libvirtpy.rpc.options import ConnectionOptions
10
+ from libvirtpy.rpc.procedure import Driver
11
+ from libvirtpy.rpc.protocol import procedures, types
12
+ from libvirtpy.rpc.remote import connect_remote
13
+ from libvirtpy.rpc.sasl import SaslCall, SaslCredentials, sasl_exchange
14
+ from libvirtpy.rpc.sync import SyncRpc
15
+ from libvirtpy.rpc.uri import HYPERVISOR_DAEMONS, ConnectionTarget, parse_uri
16
+
17
+ __all__ = [
18
+ "REMOTE_KEY",
19
+ "ConnectionTarget",
20
+ "authentication",
21
+ "open_arguments",
22
+ "open_channel",
23
+ "parse_uri",
24
+ "socket_paths",
25
+ ]
26
+
27
+ SECONDARY_DAEMONS = {
28
+ "interface": ("virtinterfaced", "interface"),
29
+ "network": ("virtnetworkd", "network"),
30
+ "node_device": ("virtnodedevd", "nodedev"),
31
+ "nwfilter": ("virtnwfilterd", "nwfilter"),
32
+ "secret": ("virtsecretd", "secret"),
33
+ "storage": ("virtstoraged", "storage"),
34
+ }
35
+ CONNECT_READ_ONLY = 1
36
+ REMOTE_KEY = "remote"
37
+ """The connection key of a remote target: one connection serves every driver."""
38
+
39
+
40
+ def socket_paths(
41
+ target: ConnectionTarget, driver: Driver, *, read_only: bool
42
+ ) -> list[Path]:
43
+ """List the sockets that may serve a driver, best first.
44
+
45
+ A modular daemon (``virtqemud``) comes first, the monolithic ``libvirtd``
46
+ after it.
47
+
48
+ :param target: what the URI asks for.
49
+ :param driver: the part of libvirt that serves the call.
50
+ :param read_only: use the read-only sockets.
51
+ :returns: the candidate paths.
52
+ """
53
+ directory = _socket_directory(target)
54
+ suffix = "-sock-ro" if read_only else "-sock"
55
+ daemon = (
56
+ HYPERVISOR_DAEMONS[target.driver]
57
+ if driver == "hypervisor"
58
+ else SECONDARY_DAEMONS[driver][0]
59
+ )
60
+ return [directory / f"{daemon}{suffix}", directory / f"libvirt{suffix}"]
61
+
62
+
63
+ def open_channel(
64
+ target: ConnectionTarget,
65
+ driver: Driver,
66
+ *,
67
+ read_only: bool,
68
+ sasl: SaslCredentials | None = None,
69
+ options: ConnectionOptions | None = None,
70
+ ) -> tuple[str, SyncRpc]:
71
+ """Connect to the daemon of a driver, authenticate, and open the connection.
72
+
73
+ For a remote target one connection serves every driver.
74
+
75
+ :param target: what the URI asks for.
76
+ :param driver: the part of libvirt to reach.
77
+ :param read_only: use the read-only sockets and open the connection read-only.
78
+ :param sasl: the user name and password, if the daemon asks for SASL.
79
+ :param options: the call timeout and the keepalive.
80
+ :returns: a key for the connection (its socket path, or ``remote``) and the
81
+ ready channel.
82
+ :raises ConnectionError: if no candidate socket accepts a connection.
83
+ :raises AuthFailedError: if the daemon asks for an unsupported authentication.
84
+ """
85
+ if target.remote:
86
+ key, rpc = REMOTE_KEY, connect_remote(target, options)
87
+ path = None
88
+ else:
89
+ path, rpc = _connect_first(
90
+ socket_paths(target, driver, read_only=read_only), options
91
+ )
92
+ key = str(path)
93
+
94
+ try:
95
+ authenticate(rpc, target, sasl)
96
+ rpc.call(
97
+ procedures.CONNECT_OPEN, open_arguments(target, driver, path, read_only)
98
+ )
99
+ except BaseException:
100
+ rpc.close() # do not leave the reader thread and the ssh process behind
101
+ raise
102
+ return key, rpc
103
+
104
+
105
+ def authenticate(
106
+ rpc: SyncRpc, target: ConnectionTarget, credentials: SaslCredentials | None
107
+ ) -> None:
108
+ """Do the authentication the daemon asks for.
109
+
110
+ :param rpc: a channel that is not opened yet.
111
+ :param target: what the URI asks for.
112
+ :param credentials: the user name and password for SASL, if we have any.
113
+ :raises AuthFailedError: if the daemon asks for something we cannot do.
114
+ """
115
+ offered = rpc.call(procedures.AUTH_LIST).types
116
+ steps = authentication(offered, target, credentials)
117
+
118
+ try:
119
+ call = next(steps)
120
+ while True:
121
+ call = steps.send(rpc.call(*call))
122
+ except StopIteration:
123
+ return
124
+
125
+
126
+ def authentication(
127
+ offered: list[types.AuthType],
128
+ target: ConnectionTarget,
129
+ credentials: SaslCredentials | None,
130
+ ) -> Generator[SaslCall, Any]:
131
+ """Choose and run the authentication, without doing any I/O.
132
+
133
+ :param offered: the methods the daemon accepts.
134
+ :param target: what the URI asks for.
135
+ :param credentials: the user name and password for SASL, if we have any.
136
+ :returns: a generator that yields ``(procedure, arguments)`` and receives the
137
+ reply of each call; it ends at once if no authentication is needed.
138
+ :raises AuthFailedError: if the daemon asks for something we cannot do.
139
+ """
140
+ if types.AuthType.NONE in offered:
141
+ return
142
+ if types.AuthType.POLKIT in offered:
143
+ yield procedures.AUTH_POLKIT, None
144
+ return
145
+ if types.AuthType.SASL in offered:
146
+ yield from _sasl(target, credentials)
147
+ return
148
+ raise _unsupported(offered)
149
+
150
+
151
+ def _sasl(
152
+ target: ConnectionTarget, credentials: SaslCredentials | None
153
+ ) -> Generator[SaslCall, Any]:
154
+ """Run SASL if it is possible and safe.
155
+
156
+ :param target: what the URI asks for.
157
+ :param credentials: the user name and password, if we have any.
158
+ :returns: the SASL conversation.
159
+ :raises AuthFailedError: without credentials, or on a plain TCP connection.
160
+ """
161
+ if credentials is None:
162
+ raise AuthFailedError(
163
+ "the daemon needs SASL credentials: pass sasl=SaslCredentials(...)",
164
+ code=ErrorNumber.AUTH_FAILED,
165
+ )
166
+ if not target.protected:
167
+ raise AuthFailedError(
168
+ "SASL over plain TCP needs a security layer, which is not supported; "
169
+ "use qemu+tls:// or qemu+ssh://",
170
+ code=ErrorNumber.AUTH_FAILED,
171
+ )
172
+ yield from sasl_exchange(credentials, target.host or "localhost")
173
+
174
+
175
+ def _unsupported(offered: list[types.AuthType]) -> AuthFailedError:
176
+ """Make the error for authentication methods we do not know.
177
+
178
+ :param offered: the methods the daemon accepts.
179
+ :returns: the exception.
180
+ """
181
+ names = [kind.name for kind in offered]
182
+ return AuthFailedError(
183
+ f"the daemon asks for {names}, which is not supported",
184
+ code=ErrorNumber.AUTH_FAILED,
185
+ )
186
+
187
+
188
+ def open_arguments(
189
+ target: ConnectionTarget, driver: Driver, path: Path | None, read_only: bool
190
+ ) -> types.ConnectOpenArgs:
191
+ """Build the arguments of ``CONNECT_OPEN`` for a channel.
192
+
193
+ A remote daemon is opened with the URI stripped of transport and host. A
194
+ secondary modular daemon is opened with its own URI scheme
195
+ (``network:///system``); the primary one and ``libvirtd`` with the user's URI.
196
+
197
+ :param target: what the URI asks for.
198
+ :param driver: the part of libvirt the channel serves.
199
+ :param path: the socket the channel is connected to; ``None`` if remote.
200
+ :param read_only: open the connection read-only.
201
+ :returns: the arguments.
202
+ """
203
+ flags = CONNECT_READ_ONLY if read_only else 0
204
+ if path is None:
205
+ return types.ConnectOpenArgs(name=target.open_name, flags=flags)
206
+
207
+ is_secondary = driver != "hypervisor" and not path.name.startswith("libvirt")
208
+ name = _secondary_uri(target, driver) if is_secondary else target.uri
209
+ return types.ConnectOpenArgs(name=name, flags=flags)
210
+
211
+
212
+ def _connect_first(
213
+ paths: list[Path], options: ConnectionOptions | None
214
+ ) -> tuple[Path, SyncRpc]:
215
+ """Connect to the first socket that answers.
216
+
217
+ :param paths: the candidates.
218
+ :param options: the call timeout and the keepalive.
219
+ :returns: the path and the connection.
220
+ :raises ConnectionError: if none could be reached.
221
+ """
222
+ failures = []
223
+ for path in paths:
224
+ try:
225
+ return path, SyncRpc.connect_unix(path, options)
226
+ except OSError as error:
227
+ failures.append(f"{path}: {error.strerror or error}")
228
+ raise ConnectionError("no libvirt socket reachable: " + "; ".join(failures))
229
+
230
+
231
+ def _secondary_uri(target: ConnectionTarget, driver: Driver) -> str:
232
+ """Build the URI a secondary daemon is opened with.
233
+
234
+ :param target: what the URI asks for.
235
+ :param driver: a secondary driver (``network``, ``storage``, ...).
236
+ :returns: e.g. ``network:///system``.
237
+ """
238
+ scheme = SECONDARY_DAEMONS[driver][1]
239
+ return f"{scheme}:///{'session' if target.session else 'system'}"
240
+
241
+
242
+ def _socket_directory(target: ConnectionTarget) -> Path:
243
+ """Find the directory of the daemon sockets.
244
+
245
+ :param target: what the URI asks for.
246
+ :returns: ``/run/libvirt`` or the user's runtime directory.
247
+ """
248
+ if not target.session:
249
+ return Path("/run/libvirt")
250
+ runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
251
+ return Path(runtime) / "libvirt"