Repository navigation
Expand file tree
/
Copy pathlibvirt_provider.py
More file actions
executable file
·1484 lines (1372 loc) · 50.9 KB
/
Copy pathlibvirt_provider.py
File metadata and controls
executable file
·1484 lines (1372 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Guarded local libvirt/QEMU/KVM primitives for platform adapters."""
from __future__ import annotations
import argparse
import base64
from dataclasses import dataclass
import ipaddress
import json
import os
from pathlib import Path, PurePosixPath
import platform
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
from typing import Any, Sequence
import uuid
import xml.etree.ElementTree as ET
HOST_SCHEMA = "machine-control-libvirt-host-doctor/v0"
INSPECT_SCHEMA = "machine-control-libvirt-domain-inspect/v0"
ALLOWED_URI = "qemu:///system"
MACOS_PROFILE = "macos-intel"
QEMU_NAMESPACE = "http://libvirt.org/schemas/domain/qemu/1.0"
MACOS_QEMU_GLOBALS = frozenset({
"kvm-pit.lost_tick_policy=discard",
"ICH9-LPC.disable_s3=1",
"ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off",
"nec-usb-xhci.msi=off",
"driver=cfi.pflash01,property=secure,value=on",
})
class ProviderError(RuntimeError):
def __init__(self, code: str, message: str):
super().__init__(message)
self.code = code
self.message = message
@dataclass(frozen=True)
class Configuration:
uri: str
domain_name: str
expected_uuid: str
network: str
pool: str
virsh: str
qemu: str
boot_timeout: int
shutdown_timeout: int
exec_timeout: int
minimum_free_bytes: int
require_secure_boot: bool
require_tpm2: bool
profile: str = "standard"
@classmethod
def from_environment(cls) -> "Configuration":
return cls(
uri=os.environ.get("MC_LIBVIRT_URI", ALLOWED_URI),
domain_name=os.environ.get("MC_LIBVIRT_DOMAIN_NAME", ""),
expected_uuid=os.environ.get("MC_LIBVIRT_EXPECTED_UUID", ""),
network=os.environ.get("MC_LIBVIRT_NETWORK", "default"),
pool=os.environ.get("MC_LIBVIRT_POOL", "default"),
virsh=os.environ.get("MC_LIBVIRT_VIRSH", "virsh"),
qemu=os.environ.get("MC_LIBVIRT_QEMU", "qemu-system-x86_64"),
boot_timeout=positive_integer("MC_LIBVIRT_BOOT_TIMEOUT", 600),
shutdown_timeout=positive_integer(
"MC_LIBVIRT_SHUTDOWN_TIMEOUT", 180
),
exec_timeout=positive_integer("MC_LIBVIRT_EXEC_TIMEOUT", 300),
minimum_free_bytes=nonnegative_integer(
"MC_LIBVIRT_MIN_FREE_BYTES", 0
),
require_secure_boot=boolean_environment(
"MC_LIBVIRT_REQUIRE_SECURE_BOOT", False
),
require_tpm2=boolean_environment(
"MC_LIBVIRT_REQUIRE_TPM2", False
),
profile=os.environ.get("MC_LIBVIRT_PROFILE", "standard"),
)
def positive_integer(name: str, default: int) -> int:
raw = os.environ.get(name, str(default))
if not raw.isdigit() or int(raw) < 1:
raise ProviderError("configuration_invalid", f"{name} must be positive")
return int(raw)
def nonnegative_integer(name: str, default: int) -> int:
raw = os.environ.get(name, str(default))
if not raw.isdigit():
raise ProviderError(
"configuration_invalid", f"{name} must be nonnegative"
)
return int(raw)
def boolean_environment(name: str, default: bool) -> bool:
raw = os.environ.get(name)
if raw is None:
return default
if raw == "true":
return True
if raw == "false":
return False
raise ProviderError(
"configuration_invalid", f"{name} must be true or false"
)
def run(
arguments: Sequence[str],
*,
input_text: str | None = None,
timeout: int = 30,
check: bool = True,
) -> subprocess.CompletedProcess[str]:
try:
completed = subprocess.run(
list(arguments),
input=input_text,
text=True,
capture_output=True,
timeout=timeout,
check=False,
)
except (OSError, subprocess.TimeoutExpired) as error:
raise ProviderError(
"provider_unavailable", "The local virtualization provider failed"
) from error
if check and completed.returncode != 0:
if os.environ.get("MC_LIBVIRT_DEBUG") == "true":
print(completed.stderr.rstrip(), file=sys.stderr)
raise ProviderError(
"provider_refused", "The local virtualization provider refused the operation"
)
return completed
class Libvirt:
def __init__(self, configuration: Configuration):
self.configuration = configuration
def command(
self,
*arguments: str,
input_text: str | None = None,
timeout: int = 30,
check: bool = True,
) -> subprocess.CompletedProcess[str]:
return run(
[
self.configuration.virsh,
"--connect",
self.configuration.uri,
*arguments,
],
input_text=input_text,
timeout=timeout,
check=check,
)
def text(self, *arguments: str, timeout: int = 30) -> str:
return self.command(*arguments, timeout=timeout).stdout.strip()
def validate_local_host_basics(configuration: Configuration) -> list[str]:
failures: list[str] = []
if platform.system() != "Linux":
failures.append("controller-platform-not-linux")
if platform.machine().lower() not in {"x86_64", "amd64"}:
failures.append("controller-architecture-not-x86_64")
if configuration.uri != ALLOWED_URI:
failures.append("libvirt-uri-not-local-system")
virsh = shutil.which(configuration.virsh)
if virsh is None or not os.access(virsh, os.X_OK):
failures.append("virsh-unavailable")
qemu = shutil.which(configuration.qemu)
if qemu is None or not os.access(qemu, os.X_OK):
failures.append("x86_64-qemu-unavailable")
kvm = Path("/dev/kvm")
try:
mode = kvm.stat().st_mode
if not stat.S_ISCHR(mode) or not os.access(kvm, os.R_OK | os.W_OK):
failures.append("kvm-device-inaccessible")
except OSError:
failures.append("kvm-device-inaccessible")
return failures
def enum_values(root: ET.Element, name: str) -> set[str]:
return {
value.text or ""
for enum in root.findall(f".//enum[@name='{name}']")
for value in enum.findall("value")
}
def host_doctor(configuration: Configuration) -> tuple[dict[str, Any], int]:
failures = validate_local_host_basics(configuration)
acceleration = False
uefi = False
secure_boot = False
tpm2 = False
network_active = False
pool_active = False
free_bytes: int | None = None
if not failures:
provider = Libvirt(configuration)
try:
if provider.text("uri") != ALLOWED_URI:
failures.append("libvirt-uri-mismatch")
capabilities = ET.fromstring(
provider.text(
"domcapabilities",
"--virttype",
"kvm",
"--arch",
"x86_64",
"--machine",
"q35",
)
)
acceleration = (
capabilities.findtext("domain") == "kvm"
and capabilities.findtext("arch") == "x86_64"
and (capabilities.findtext("machine") or "").startswith(
"pc-q35"
)
)
uefi = "efi" in enum_values(capabilities, "firmware")
secure_boot = "yes" in enum_values(capabilities, "secure")
tpm2 = "2.0" in enum_values(capabilities, "backendVersion")
if not acceleration:
failures.append("kvm-domain-unavailable")
if not uefi:
failures.append("q35-uefi-unavailable")
if configuration.require_secure_boot and not secure_boot:
failures.append("secure-boot-unavailable")
if configuration.require_tpm2 and not tpm2:
failures.append("tpm2-unavailable")
accel_help = run(
[configuration.qemu, "-accel", "help"], check=True
).stdout.splitlines()
if "kvm" not in {line.strip() for line in accel_help}:
acceleration = False
failures.append("qemu-kvm-accelerator-unavailable")
network_info = provider.text("net-info", configuration.network)
network_active = bool(
re.search(r"^Active:\s+yes$", network_info, re.MULTILINE)
)
if not network_active:
failures.append("libvirt-network-inactive")
pool_info = provider.text("pool-info", configuration.pool)
pool_active = bool(
re.search(r"^State:\s+running$", pool_info, re.MULTILINE)
)
if not pool_active:
failures.append("libvirt-pool-inactive")
pool_xml = ET.fromstring(
provider.text("pool-dumpxml", configuration.pool)
)
pool_path = pool_xml.findtext("./target/path")
if not pool_path:
failures.append("libvirt-pool-path-unavailable")
else:
stats = os.statvfs(pool_path)
free_bytes = stats.f_bavail * stats.f_frsize
if free_bytes < configuration.minimum_free_bytes:
failures.append("libvirt-pool-capacity-below-reserve")
except (ET.ParseError, OSError, ProviderError):
failures.append("libvirt-capability-probe-failed")
failures = sorted(set(failures))
checks = [
{
"id": "hardware_acceleration",
"status": "pass" if acceleration else "fail",
"summary": "Native x86_64 KVM acceleration is available"
if acceleration
else "Native x86_64 KVM acceleration is unavailable",
},
{
"id": "firmware",
"status": "pass"
if uefi and (secure_boot or not configuration.require_secure_boot)
else "fail",
"summary": "Required Q35 UEFI firmware is available"
if uefi
else "Required Q35 UEFI firmware is unavailable",
},
{
"id": "tpm",
"status": "pass"
if tpm2 or not configuration.require_tpm2
else "fail",
"summary": "Required emulated TPM 2.0 capability is available"
if tpm2
else "Emulated TPM 2.0 capability is unavailable",
},
{
"id": "network",
"status": "pass" if network_active else "fail",
"summary": "Configured libvirt network is active"
if network_active
else "Configured libvirt network is unavailable",
},
{
"id": "storage",
"status": "pass" if pool_active and free_bytes is not None else "fail",
"summary": "Configured libvirt storage is ready"
if pool_active and free_bytes is not None
else "Configured libvirt storage is unavailable",
},
]
value = {
"schema": HOST_SCHEMA,
"ready": not failures,
"architecture": "x86_64",
"acceleration": {"required": "kvm", "available": acceleration},
"firmware": {"uefi": uefi, "secureBoot": secure_boot},
"tpm2": tpm2,
"network": {"active": network_active},
"storage": {
"active": pool_active,
"measurement": "exact" if free_bytes is not None else "unavailable",
"freeBytes": free_bytes,
},
"checks": checks,
"failures": failures,
}
return value, 0 if not failures else 1
def require_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, AttributeError) as error:
raise ProviderError(
"identity_unpinned", "The provider identity is unpinned or invalid"
) from error
def required_element(root: ET.Element, path: str, reason: str) -> ET.Element:
element = root.find(path)
if element is None:
raise ProviderError("domain_incompatible", reason)
return element
def validate_macos_qemu_args(root: ET.Element) -> None:
namespace = f"{{{QEMU_NAMESPACE}}}"
extensions = [element for element in root if element.tag.startswith(namespace)]
if not extensions:
return
command = extensions[0]
args = list(command)
if (
len(extensions) != 1 or command.tag != namespace + "commandline"
or len(args) % 2 or len(args) > 14
or any(arg.tag != namespace + "arg" for arg in args)
):
raise ProviderError("domain_incompatible", "Unexpected macOS QEMU extension")
seen = set()
for option, argument in zip(args[::2], args[1::2]):
name = option.get("value", "")
value = argument.get("value", "")
if name == "-device":
valid = re.fullmatch(r"isa-applesmc,osk=[ -~]{1,128}", value) and "," not in value[17:]
elif name == "-cpu":
model, *features = value.split(",")
valid = model == "Haswell-v2" and all(
word in {"vendor=GenuineIntel", "vmware-cpuid-freq=on"}
or re.fullmatch(r"[+-][a-z0-9_.-]{1,20}", word)
for word in features
)
else:
valid = name == "-global" and value in MACOS_QEMU_GLOBALS
identity = value if name == "-global" else name
if not valid or identity in seen:
raise ProviderError("domain_incompatible", "Unexpected macOS QEMU argument")
seen.add(identity)
def macos_layout(root: ET.Element, disks: list[ET.Element]) -> dict[str, Any]:
"""Check the explicit OpenCore boot disk and writable Tahoe system disk."""
roles = {}
for disk in disks:
target = disk.find("target")
driver = disk.find("driver")
source = disk.find("source")
if target is None or driver is None or source is None:
raise ProviderError("domain_incompatible", "A macOS disk lacks its device definition")
device = (target.get("dev"), target.get("bus"))
role = {("sda", "sata"): "bootDisk", ("vda", "virtio"): "primaryDisk"}.get(device)
path = source.get("file", "")
boot = disk.find("boot")
if (role is None or role in roles or driver.get("type") != "qcow2"
or not PurePosixPath(path).is_absolute() or disk.find("readonly") is not None
or (role == "bootDisk" and (boot is None or boot.get("order") != "1"))
or (role == "primaryDisk" and boot is not None)):
raise ProviderError("domain_incompatible", "A macOS disk does not match its expected role")
roles[role] = {"format": "qcow2", "bus": device[1], "path": path}
if roles.keys() != {"bootDisk", "primaryDisk"}:
raise ProviderError("domain_incompatible", "OpenCore and system disks are required")
loader = required_element(root, "./os/loader", "macOS UEFI firmware is missing")
loader_path = loader.text or ""
nvram = root.findtext("./os/nvram") or ""
paths = [loader_path, nvram, *(device["path"] for device in roles.values())]
if (loader.get("readonly") != "yes" or loader.get("type") != "pflash"
or not all(PurePosixPath(path).is_absolute() for path in paths)
or len({os.path.realpath(path) for path in paths}) != len(paths)):
raise ProviderError("domain_incompatible", "macOS requires distinct firmware and disk files")
network = root.findall("./devices/interface")
if len(network) != 1 or network[0].get("type") != "network":
raise ProviderError("domain_incompatible", "macOS requires one managed network interface")
net_source = network[0].find("source")
if net_source is None or not net_source.get("network"):
raise ProviderError("domain_incompatible", "The macOS managed network is missing")
validate_macos_qemu_args(root)
return {**roles, "nvramPath": nvram, "network": net_source.get("network")}
def validate_domain_xml(
xml_text: str,
*,
expected_uuid: str,
expected_name: str,
require_secure_boot: bool,
require_tpm2: bool,
profile: str = "standard",
) -> dict[str, Any]:
if profile not in {"standard", MACOS_PROFILE}:
raise ProviderError("configuration_invalid", "Unknown libvirt domain profile")
try:
root = ET.fromstring(xml_text)
except ET.ParseError as error:
raise ProviderError(
"domain_xml_invalid", "The provider returned invalid domain XML"
) from error
if root.tag != "domain" or root.get("type") != "kvm":
raise ProviderError(
"hardware_acceleration_required", "The domain type must be KVM"
)
actual_uuid = require_uuid(root.findtext("uuid") or "")
if actual_uuid != require_uuid(expected_uuid):
raise ProviderError(
"identity_mismatch", "The domain UUID does not match private inventory"
)
actual_name = root.findtext("name") or ""
if not expected_name or actual_name != expected_name:
raise ProviderError(
"identity_mismatch", "The domain name does not match private inventory"
)
os_type = required_element(
root, "./os/type", "The domain operating-system type is unavailable"
)
architecture = os_type.get("arch") or ""
machine = os_type.get("machine") or ""
if architecture != "x86_64":
raise ProviderError(
"native_architecture_required", "The domain architecture must be x86_64"
)
if not machine.startswith("pc-q35"):
raise ProviderError(
"domain_incompatible", "The domain machine type must be Q35"
)
emulator = root.findtext("./devices/emulator") or ""
if Path(emulator).name != "qemu-system-x86_64":
raise ProviderError(
"native_architecture_required", "The domain emulator must be x86_64 QEMU"
)
loader = root.find("./os/loader")
secure_boot = loader is not None and loader.get("secure") == "yes"
if require_secure_boot and not secure_boot:
raise ProviderError(
"secure_boot_required", "The domain must use Secure Boot firmware"
)
tpm = root.find("./devices/tpm/backend[@version='2.0']")
tpm2 = tpm is not None
if require_tpm2 and not tpm2:
raise ProviderError("tpm2_required", "The domain must expose TPM 2.0")
guest_agent = any(
target.get("name") == "org.qemu.guest_agent.0"
for target in root.findall("./devices/channel/target")
)
if profile == "standard" and not guest_agent:
raise ProviderError(
"guest_agent_channel_required",
"The domain must expose the QEMU guest-agent channel",
)
disks = root.findall("./devices/disk[@device='disk']")
interface_models = {
model.get("type") for model in root.findall("./devices/interface/model")
}
if "virtio" not in interface_models:
raise ProviderError(
"domain_incompatible", "The domain network must use VirtIO"
)
report = {
"schema": INSPECT_SCHEMA,
"identityVerified": True,
"architecture": architecture,
"domainType": "kvm",
"machine": "q35",
"acceleration": "kvm",
"secureBoot": secure_boot,
"tpm2": tpm2,
"guestAgentChannel": guest_agent,
}
if profile == MACOS_PROFILE:
return {**report, **macos_layout(root, disks), "readinessTransport": "ssh"}
if len(disks) != 1:
raise ProviderError(
"domain_incompatible", "The domain must have one primary system disk"
)
disk = disks[0]
driver = required_element(
disk, "driver", "The primary disk driver is unavailable"
)
target = required_element(
disk, "target", "The primary disk target is unavailable"
)
source = required_element(
disk, "source", "The primary disk source is unavailable"
)
if driver.get("type") != "qcow2" or target.get("bus") != "virtio":
raise ProviderError(
"domain_incompatible", "The primary disk must be QCOW2 over VirtIO"
)
disk_path = source.get("file") or ""
if not disk_path.startswith("/"):
raise ProviderError(
"domain_incompatible", "The primary disk must have an absolute path"
)
return {
**report,
"primaryDisk": {"format": "qcow2", "bus": "virtio", "path": disk_path},
}
def inspect_domain(
configuration: Configuration, provider: Libvirt
) -> dict[str, Any]:
expected_uuid = require_uuid(configuration.expected_uuid)
try:
actual_name = provider.text("domname", expected_uuid)
actual_uuid = require_uuid(provider.text("domuuid", actual_name))
except ProviderError as error:
raise ProviderError(
"identity_unavailable", "The exact provider domain is unavailable"
) from error
if actual_uuid != expected_uuid or actual_name != configuration.domain_name:
raise ProviderError(
"identity_mismatch", "The exact provider identity does not match"
)
xml_text = provider.text("dumpxml", "--inactive", expected_uuid)
value = validate_domain_xml(
xml_text,
expected_uuid=expected_uuid,
expected_name=configuration.domain_name,
require_secure_boot=configuration.require_secure_boot,
require_tpm2=configuration.require_tpm2,
profile=configuration.profile,
)
if configuration.profile == MACOS_PROFILE and value["network"] != configuration.network:
raise ProviderError("identity_mismatch", "The macOS network does not match private inventory")
return value
def resolve_domain_uuid(
configuration: Configuration, provider: Libvirt
) -> str:
if not configuration.domain_name:
raise ProviderError(
"identity_unpinned", "The provider domain name is unconfigured"
)
actual_uuid = require_uuid(
provider.text("domuuid", configuration.domain_name)
)
xml_text = provider.text("dumpxml", "--inactive", actual_uuid)
validate_domain_xml(
xml_text,
expected_uuid=actual_uuid,
expected_name=configuration.domain_name,
require_secure_boot=configuration.require_secure_boot,
require_tpm2=configuration.require_tpm2,
profile=configuration.profile,
)
return actual_uuid
def domain_state(configuration: Configuration, provider: Libvirt) -> str:
inspect_domain(configuration, provider)
raw = provider.text("domstate", configuration.expected_uuid).lower()
if raw == "running":
return "started"
if raw in {"shut off", "shutdown", "crashed", "pmsuspended"}:
return "stopped"
if raw in {"paused", "blocked"}:
return "suspended"
return "unknown"
def query_kvm(configuration: Configuration, provider: Libvirt) -> bool:
result = provider.text(
"qemu-monitor-command",
configuration.expected_uuid,
'{"execute":"query-kvm"}',
)
try:
value = json.loads(result)["return"]
except (json.JSONDecodeError, KeyError, TypeError) as error:
raise ProviderError(
"acceleration_unverified", "The live KVM state could not be verified"
) from error
return value.get("enabled") is True and value.get("present") is True
def require_live_kvm(configuration: Configuration, provider: Libvirt) -> None:
inactive = inspect_domain(configuration, provider)
if domain_state(configuration, provider) != "started":
raise ProviderError("target_not_running", "The domain is not running")
if not query_kvm(configuration, provider):
raise ProviderError(
"hardware_acceleration_required",
"The running domain is not using KVM acceleration",
)
if configuration.profile == MACOS_PROFILE:
live = validate_domain_xml(
provider.text("dumpxml", configuration.expected_uuid),
expected_uuid=configuration.expected_uuid,
expected_name=configuration.domain_name,
require_secure_boot=configuration.require_secure_boot,
require_tpm2=configuration.require_tpm2,
profile=configuration.profile,
)
if live != inactive:
raise ProviderError("identity_mismatch", "Live macOS layout differs from the pinned domain")
def recovery_screenshot(
configuration: Configuration, provider: Libvirt, output_value: str
) -> str:
require_live_kvm(configuration, provider)
output = Path(output_value).expanduser().resolve()
if output.exists() and (not output.is_file() or output.is_symlink()):
raise ProviderError(
"capture_destination_invalid", "The capture destination is invalid"
)
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
descriptor, temporary_value = tempfile.mkstemp(
prefix=".libvirt-capture.", suffix=".ppm", dir=output.parent
)
os.close(descriptor)
temporary = Path(temporary_value)
temporary.unlink()
try:
provider.command(
"screenshot",
configuration.expected_uuid,
"--file",
str(temporary),
"--screen",
"0",
timeout=60,
)
converter = shutil.which("magick") or shutil.which("convert")
if converter is None:
raise ProviderError(
"capture_converter_unavailable",
"The recovery capture converter is unavailable",
)
arguments = [converter]
if Path(converter).name == "magick":
arguments.append("convert")
arguments.append(str(temporary))
if configuration.profile == MACOS_PROFILE:
arguments.append("-strip")
arguments.append(f"png:{output}")
run(arguments, timeout=60)
with output.open("rb") as captured:
header = captured.read(24)
if (
len(header) != 24
or header[:8] != b"\x89PNG\r\n\x1a\n"
or int.from_bytes(header[16:20], "big") < 1
or int.from_bytes(header[20:24], "big") < 1
):
raise ProviderError(
"capture_invalid", "The recovery capture is not a valid PNG"
)
os.chmod(output, 0o600)
return str(output)
except Exception:
output.unlink(missing_ok=True)
raise
finally:
temporary.unlink(missing_ok=True)
def qmp_input_events(
configuration: Configuration,
provider: Libvirt,
events: list[dict[str, Any]],
*,
verify_live: bool = True,
) -> None:
if not events or len(events) > 2048:
raise ProviderError("input_invalid", "The recovery input batch is invalid")
if verify_live:
require_live_kvm(configuration, provider)
payload = json.dumps(
{"execute": "input-send-event", "arguments": {"events": events}},
separators=(",", ":"),
)
response = provider.text(
"qemu-monitor-command", configuration.expected_uuid, payload
)
try:
value = json.loads(response)
except json.JSONDecodeError as error:
raise ProviderError(
"input_unverified", "The recovery input response is invalid"
) from error
if value.get("return") != {}:
raise ProviderError(
"input_refused", "The recovery input provider refused the batch"
)
def qcode_event(qcode: str, down: bool) -> dict[str, Any]:
return {
"type": "key",
"data": {
"down": down,
"key": {"type": "qcode", "data": qcode},
},
}
UNSHIFTED_QCODES = {
" ": "spc",
"-": "minus",
"=": "equal",
"[": "bracket_left",
"]": "bracket_right",
"\\": "backslash",
";": "semicolon",
"'": "apostrophe",
"`": "grave_accent",
",": "comma",
".": "dot",
"/": "slash",
"\n": "ret",
"\r": "ret",
"\t": "tab",
}
SHIFTED_QCODES = {
"!": "1",
"@": "2",
"#": "3",
"$": "4",
"%": "5",
"^": "6",
"&": "7",
"*": "8",
"(": "9",
")": "0",
"_": "minus",
"+": "equal",
"{": "bracket_left",
"}": "bracket_right",
"|": "backslash",
":": "semicolon",
'"': "apostrophe",
"~": "grave_accent",
"<": "comma",
">": "dot",
"?": "slash",
}
def text_input_events(text: str) -> list[dict[str, Any]]:
if not text or len(text) > 512:
raise ProviderError("input_invalid", "Recovery text must be 1-512 characters")
events: list[dict[str, Any]] = []
for character in text:
shifted = False
if "a" <= character <= "z" or "0" <= character <= "9":
qcode = character
elif "A" <= character <= "Z":
qcode = character.lower()
shifted = True
elif character in UNSHIFTED_QCODES:
qcode = UNSHIFTED_QCODES[character]
elif character in SHIFTED_QCODES:
qcode = SHIFTED_QCODES[character]
shifted = True
else:
raise ProviderError(
"input_character_unsupported",
"Recovery typing supports bounded US-ASCII text only",
)
if shifted:
events.append(qcode_event("shift", True))
events.extend([qcode_event(qcode, True), qcode_event(qcode, False)])
if shifted:
events.append(qcode_event("shift", False))
return events
def send_recovery_text(
configuration: Configuration, provider: Libvirt, text: str
) -> None:
if not text or len(text) > 512:
raise ProviderError("input_invalid", "Recovery text must be 1-512 characters")
require_live_kvm(configuration, provider)
for character in text:
qmp_input_events(
configuration,
provider,
text_input_events(character),
verify_live=False,
)
time.sleep(0.03)
NAMED_KEY_CHORDS = {
"enter": ["ret"],
"escape": ["esc"],
"tab": ["tab"],
"backspace": ["backspace"],
"delete": ["delete"],
"left": ["left"],
"right": ["right"],
"up": ["up"],
"down": ["down"],
"home": ["home"],
"end": ["end"],
"page-up": ["pgup"],
"page-down": ["pgdn"],
"ctrl-alt-t": ["ctrl", "alt", "t"],
"super-d": ["meta_l", "d"],
"alt-f4": ["alt", "f4"],
"ctrl-c": ["ctrl", "c"],
"shift-f10": ["shift", "f10"],
"ctrl-alt-delete": ["ctrl", "alt", "delete"],
**{f"f{number}": [f"f{number}"] for number in range(1, 13)},
}
def named_key_events(name: str) -> list[dict[str, Any]]:
chord = NAMED_KEY_CHORDS.get(name)
if chord is None:
raise ProviderError("input_key_unsupported", "Recovery key name is unsupported")
return [qcode_event(key, True) for key in chord] + [
qcode_event(key, False) for key in reversed(chord)
]
def pointer_value(coordinate: int, extent: int) -> int:
if extent < 2 or coordinate < 0 or coordinate >= extent:
raise ProviderError(
"input_coordinate_invalid", "Recovery coordinates are out of bounds"
)
return round(coordinate * 0x7FFF / (extent - 1))
def pointer_events(
width: int,
height: int,
start_x: int,
start_y: int,
button: str,
end_x: int | None = None,
end_y: int | None = None,
) -> list[dict[str, Any]]:
if button not in {"left", "right", "middle"}:
raise ProviderError("input_button_invalid", "Recovery button is invalid")
def move(x: int, y: int) -> list[dict[str, Any]]:
return [
{
"type": "abs",
"data": {"axis": "x", "value": pointer_value(x, width)},
},
{
"type": "abs",
"data": {"axis": "y", "value": pointer_value(y, height)},
},
]
events = move(start_x, start_y)
events.append({"type": "btn", "data": {"down": True, "button": button}})
if end_x is not None and end_y is not None:
events.extend(move(end_x, end_y))
events.append({"type": "btn", "data": {"down": False, "button": button}})
return events
def wait_for_state(
configuration: Configuration,
provider: Libvirt,
expected: str,
timeout: int,
) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if domain_state(configuration, provider) == expected:
return
time.sleep(1)
raise ProviderError(
"lifecycle_timeout", "The domain did not reach the requested state"
)
def start_domain(configuration: Configuration, provider: Libvirt) -> None:
host, host_exit = host_doctor(configuration)
if host_exit != 0:
raise ProviderError(
"host_not_ready", "The KVM controller host is not ready"
)
state = domain_state(configuration, provider)
if state == "started":
if not query_kvm(configuration, provider):
raise ProviderError(
"hardware_acceleration_required",
"The running domain is not using KVM acceleration",
)
return
if state != "stopped":
raise ProviderError(
"lifecycle_state_invalid", "The domain is not in a startable state"
)
provider.command("start", configuration.expected_uuid)
try:
wait_for_state(
configuration, provider, "started", configuration.boot_timeout
)
if not query_kvm(configuration, provider):
raise ProviderError(
"hardware_acceleration_required",
"The started domain did not enable KVM acceleration",
)
except ProviderError:
provider.command("destroy", configuration.expected_uuid, check=False)
raise
def shutdown_domain(configuration: Configuration, provider: Libvirt) -> None:
state = domain_state(configuration, provider)
if state == "stopped":
return
if state != "started":
raise ProviderError(
"lifecycle_state_invalid", "The domain is not in a stoppable state"
)
if configuration.profile == MACOS_PROFILE:
require_live_kvm(configuration, provider)
provider.command(
"shutdown", configuration.expected_uuid, "--mode", "acpi"
)
else:
result = provider.command(
"shutdown", configuration.expected_uuid, "--mode", "agent", check=False
)
if result.returncode != 0:
provider.command(
"shutdown", configuration.expected_uuid, "--mode", "acpi"
)
wait_for_state(
configuration, provider, "stopped", configuration.shutdown_timeout
)
def agent_command(
configuration: Configuration,
provider: Libvirt,
payload: dict[str, Any],
*,
timeout: int | None = None,
) -> Any:
if configuration.profile == MACOS_PROFILE: