/
virsh.py
1502 lines (1331 loc) · 52 KB
/
virsh.py
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
# Copyright 2017-2021 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Virsh pod driver."""
from contextlib import suppress
from math import floor
import os
import string
from tempfile import NamedTemporaryFile
from textwrap import dedent
from typing import NamedTuple
from urllib.parse import urlparse
from uuid import uuid4
from lxml import etree
import pexpect
from twisted.internet.defer import inlineCallbacks
from twisted.internet.threads import deferToThread
from provisioningserver.drivers import (
IP_EXTRACTOR_PATTERNS,
make_ip_extractor,
make_setting_field,
SETTING_SCOPE,
)
from provisioningserver.drivers.pod import (
Capabilities,
DiscoveredMachine,
DiscoveredMachineBlockDevice,
DiscoveredMachineInterface,
DiscoveredPod,
DiscoveredPodHints,
DiscoveredPodStoragePool,
InterfaceAttachType,
PodDriver,
)
from provisioningserver.enum import LIBVIRT_NETWORK
from provisioningserver.logger import get_maas_logger
from provisioningserver.path import get_path
from provisioningserver.prometheus.metrics import PROMETHEUS_METRICS
from provisioningserver.rpc.exceptions import PodInvalidResources
from provisioningserver.rpc.utils import commission_node, create_node
from provisioningserver.utils import shell
from provisioningserver.utils.arch import (
debian_to_kernel_architecture,
kernel_to_debian_architecture,
)
from provisioningserver.utils.network import generate_mac_address
from provisioningserver.utils.shell import get_env_with_locale
from provisioningserver.utils.twisted import asynchronous, synchronous
maaslog = get_maas_logger("drivers.pod.virsh")
ADD_DEFAULT_NETWORK = dedent(
"""
Please add a 'default' or 'maas' network whose bridge is
on a MAAS DHCP enabled VLAN. Ensure that libvirt DHCP is
not enabled.
"""
)
XPATH_ARCH = "/domain/os/type/@arch"
XPATH_BOOT = "/domain/os/boot"
XPATH_OS = "/domain/os"
XPATH_POOL_TYPE = "/pool/@type"
XPATH_POOL_AVAILABLE = "/pool/available"
XPATH_POOL_CAPACITY = "/pool/capacity"
XPATH_POOL_PATH = "/pool/target/path"
XPATH_POOL_UUID = "/pool/uuid"
DOM_TEMPLATE_MACVLAN_INTERFACE = dedent(
"""\
<interface type='direct'>
<source dev='{attach_name}' mode='{attach_options}'/>
<mac address='{mac_address}'/>
<model type='virtio'/>
</interface>
"""
)
DOM_TEMPLATE_BRIDGE_INTERFACE = dedent(
"""\
<interface type='bridge'>
<source bridge='{attach_name}'/>
<mac address='{mac_address}'/>
<model type='virtio'/>
</interface>
"""
)
DOM_TEMPLATE_AMD64 = dedent(
"""\
<domain type="{type}">
<name>{name}</name>
<uuid>{uuid}</uuid>
<memory unit="MiB">{memory}</memory>
<vcpu>{cores}</vcpu>
<cpu mode="host-passthrough"/>
<os>
<type arch="{arch}">hvm</type>
</os>
<features>
<acpi/>
<apic/>
</features>
<clock offset="utc"/>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<pm>
<suspend-to-mem enabled="no"/>
<suspend-to-disk enabled="no"/>
</pm>
<devices>
<emulator>{emulator}</emulator>
<controller type="pci" index="0" model="pci-root"/>
<controller type="virtio-serial" index="0">
<address type="pci" domain="0x0000"
bus="0x00" slot="0x05" function="0x0"/>
</controller>
<serial type="pty">
<log file="/var/log/libvirt/qemu/{name}-serial0.log" append="off" />
<target port="0"/>
</serial>
<console type="pty">
<target type="serial" port="0"/>
</console>
<channel type="spicevmc">
<target type="virtio" name="com.redhat.spice.0"/>
<address type="virtio-serial" controller="0" bus="0" port="1"/>
</channel>
<graphics type="spice" autoport="yes">
<image compression="off"/>
</graphics>
<input type="mouse" bus="ps2"/>
<input type="keyboard" bus="ps2"/>
</devices>
</domain>
"""
)
DOM_TEMPLATE_ARM64 = dedent(
"""\
<domain type="{type}">
<name>{name}</name>
<uuid>{uuid}</uuid>
<memory unit="MiB">{memory}</memory>
<vcpu>{cores}</vcpu>
<cpu mode="host-passthrough"/>
<os>
<type arch="{arch}" machine="virt">hvm</type>
<loader readonly="yes" type="pflash">{loader}</loader>
<nvram template="{loader}">{nvram_path}/{name}_VARS.fd</nvram>
</os>
<features>
<acpi/>
<apic/>
<pae/>
<gic version="3"/>
</features>
<clock offset="utc"/>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<devices>
<emulator>{emulator}</emulator>
<controller type="pci" index="0" model="pcie-root"/>
<serial type="pty">
<log file="/var/log/libvirt/qemu/{name}-serial0.log" append="off" />
<target port="0"/>
</serial>
<console type="pty">
<target type="serial" port="0"/>
</console>
<input type="mouse" bus="ps2"/>
<input type="keyboard" bus="ps2"/>
</devices>
</domain>
"""
)
DOM_TEMPLATE_PPC64 = dedent(
"""\
<domain type="{type}">
<name>{name}</name>
<uuid>{uuid}</uuid>
<memory unit="MiB">{memory}</memory>
<vcpu>{cores}</vcpu>
<cpu mode="host-passthrough"/>
<os>
<type arch="{arch}">hvm</type>
</os>
<clock offset="utc"/>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<devices>
<emulator>{emulator}</emulator>
<controller type="pci" index="0" model="pci-root"/>
<serial type="pty">
<log file="/var/log/libvirt/qemu/{name}-serial0.log" append="off" />
<target port="0"/>
</serial>
<console type="pty">
<target type="serial" port="0"/>
</console>
<input type="mouse" bus="ps2"/>
<input type="keyboard" bus="ps2"/>
</devices>
</domain>
"""
)
DOM_TEMPLATE_S390X = dedent(
"""
<domain type="{type}">
<name>{name}</name>
<uuid>{uuid}</uuid>
<memory unit="MiB">{memory}</memory>
<vcpu>{cores}</vcpu>
<cpu mode="host-passthrough"/>
<os>
<type arch="{arch}">hvm</type>
</os>
<features>
<acpi/>
<apic/>
<pae/>
</features>
<devices>
<console type="pty">
<log file="/var/log/libvirt/qemu/{name}-serial0.log" append="off"/>
<target type="sclp" port="0"/>
<alias name="console0"/>
</console>
</devices>
</domain>
"""
)
class InterfaceInfo(NamedTuple):
type: str
source: str
model: str
mac: str
REQUIRED_PACKAGES = [
("virsh", "libvirt-clients"),
]
SUPPORTED_STORAGE_TYPES = ("dir", "logical", "zfs")
class VirshVMState:
OFF = "shut off"
ON = "running"
NO_STATE = "no state"
IDLE = "idle"
PAUSED = "paused"
IN_SHUTDOWN = "in shutdown"
CRASHED = "crashed"
PM_SUSPENDED = "pmsuspended"
VM_STATE_TO_POWER_STATE = {
VirshVMState.OFF: "off",
VirshVMState.ON: "on",
VirshVMState.NO_STATE: "off",
VirshVMState.IDLE: "off",
VirshVMState.PAUSED: "off",
VirshVMState.IN_SHUTDOWN: "on",
VirshVMState.CRASHED: "off",
VirshVMState.PM_SUSPENDED: "off",
}
class VirshError(Exception):
"""Failure communicating to virsh."""
class VirshSSH(pexpect.spawn):
PROMPT = r"virsh \#"
PROMPT_SSHKEY = "(?i)are you sure you want to continue connecting"
PROMPT_PASSWORD = "(?i)(?:password)|(?:passphrase for key)"
PROMPT_DENIED = "(?i)permission denied"
PROMPT_CLOSED = "(?i)connection closed by remote host"
PROMPTS = [
PROMPT_SSHKEY,
PROMPT_PASSWORD,
PROMPT,
PROMPT_DENIED,
PROMPT_CLOSED,
pexpect.TIMEOUT,
pexpect.EOF,
]
I_PROMPT = PROMPTS.index(PROMPT)
I_PROMPT_SSHKEY = PROMPTS.index(PROMPT_SSHKEY)
I_PROMPT_PASSWORD = PROMPTS.index(PROMPT_PASSWORD)
def __init__(self, timeout=30, maxread=2000, dom_prefix=None):
super().__init__(
None, timeout=timeout, maxread=maxread, env=get_env_with_locale()
)
self.name = "<virssh>"
if dom_prefix is None:
self.dom_prefix = ""
else:
self.dom_prefix = dom_prefix
# Store a mapping of { machine_name: xml }.
self.xml = {}
def _execute(self, poweraddr):
"""Spawns the pexpect command."""
self._spawn(f"virsh --connect {poweraddr}")
def get_server_version(self):
output = self.run(["version", "--daemon"])
for line in output.splitlines():
if line.startswith("Running against daemon"):
return line.split()[-1]
def get_network_xml(self, network):
try:
return self.run(["net-dumpxml", network])
except VirshError:
return None
def get_machine_xml(self, machine):
# Check if we have a cached version of the XML.
# This is a short-lived object, so we don't need to worry about
# expiring objects in the cache.
if machine in self.xml:
return self.xml[machine]
# Grab the XML from virsh if we don't have it already.
try:
output = self.run(["dumpxml", machine])
except VirshError:
return None
# Cache the XML, since we'll need it later to reconfigure the VM.
self.xml[machine] = output
return output
def login(self, poweraddr, password=None):
"""Starts connection to virsh."""
# Extra paramaeters are not allowed as this is a security
# hole for allowing a user to run executables.
parsed = urlparse(poweraddr)
if parsed.query:
raise VirshError(
"Supplying extra parameters to the Virsh address"
" is not supported."
)
# Append unverified-ssh command. See,
# https://bugs.launchpad.net/maas/+bug/1807231
# for more details.
poweraddr = (
poweraddr + "?command=" + get_path("/usr/lib/maas/unverified-ssh")
)
self._execute(poweraddr)
i = self.expect(self.PROMPTS, timeout=self.timeout)
if i == self.I_PROMPT_SSHKEY:
# New certificate, lets always accept but if
# it changes it will fail to login.
self.sendline("yes")
i = self.expect(self.PROMPTS)
if i == self.I_PROMPT_PASSWORD:
# Requesting password, give it if available.
if password is None:
self.close()
return False
self.sendline(password)
i = self.expect(self.PROMPTS)
if i != self.I_PROMPT:
# Something bad happened, either disconnect,
# timeout, wrong password.
self.close()
return False
return True
def logout(self):
"""Quits the virsh session."""
self.sendline("quit")
self.close()
def prompt(self, timeout=None):
"""Waits for virsh prompt."""
if timeout is None:
timeout = self.timeout
i = self.expect([self.PROMPT, pexpect.TIMEOUT], timeout=timeout)
if i == 1:
return False
return True
def run(self, args, raise_error=True):
cmd = " ".join(args)
self.sendline(cmd)
self.prompt()
output = self.before.decode("utf-8").strip()
# remove the first line since it containes the issued command
output = "\n".join(output.splitlines()[1:])
if output.startswith("error:"):
message = f"Virsh command {args} failed: {output[7:]}"
maaslog.error(message)
if raise_error:
raise VirshError(message)
return "" # return empty output if something failed
return output
def _get_column_values(self, data, keys):
"""Return tuple of column value tuples based off keys."""
entries = [row.split() for row in data.strip().splitlines()]
columns = entries[0]
indexes = [columns.index(key) for key in keys]
# skip header lines
entries = entries[2:]
return tuple(
tuple(entry[index] for index in indexes) for entry in entries
)
def get_key_value(self, data, key):
"""Return value based off of key."""
if data is not None:
data = data.strip().splitlines()
for d in data:
if key == d.split(":")[0].strip():
return d.split(":")[1].strip()
def get_key_value_unitless(self, data, key):
"""Return value based off of key with unit (if any) stripped off."""
value = self.get_key_value(data, key)
if value:
return value.split()[0]
def create_storage_pool(self):
"""Create a storage pool named `maas`."""
with suppress(VirshError):
self._create_storage_pool()
def list_machines(self):
"""Lists all VMs by name."""
machines = self.run(["list", "--all", "--name"]).splitlines()
return [m for m in machines if m.startswith(self.dom_prefix)]
def list_pools(self):
"""Lists supported pools in the host."""
output = self.run(
["pool-list", "--type", ",".join(SUPPORTED_STORAGE_TYPES)]
)
pools = self._get_column_values(output, ["Name"])
return [p[0] for p in pools]
def list_machine_block_devices(self, machine):
"""Lists all devices for VM."""
output = self.run(["domblklist", machine, "--details"])
devices = self._get_column_values(
output, ["Device", "Target", "Source"]
)
return [(d[1], d[2]) for d in devices if d[0] == "disk"]
def get_machine_state(self, machine):
"""Gets the VM state."""
with suppress(VirshError):
return self._get_machine_state(machine)
def get_machine_interface_info(self, machine):
"""Gets list of mac addressess assigned to the VM."""
with suppress(VirshError):
output = self._get_machine_interface_info(machine)
return [
InterfaceInfo(*entry)
for entry in self._get_column_values(
output, ["Type", "Source", "Model", "MAC"]
)
]
def get_pod_cpu_count(self, nodeinfo):
"""Gets number of CPUs in the pod."""
cpu_count = self.get_key_value(nodeinfo, "CPU(s)")
if cpu_count is None:
maaslog.error("Failed to get pod CPU count")
return 0
return int(cpu_count)
def get_machine_cpu_count(self, machine):
"""Gets the VM CPU count."""
output = self.run(["dominfo", machine])
cpu_count = self.get_key_value(output, "CPU(s)")
if cpu_count is None:
maaslog.error("%s: Failed to get machine CPU count", machine)
return 0
return int(cpu_count)
def get_pod_cpu_speed(self, nodeinfo):
"""Gets CPU speed (MHz) in the pod."""
cpu_speed = self.get_key_value_unitless(nodeinfo, "CPU frequency")
if cpu_speed is None:
maaslog.error("Failed to get pod CPU speed")
return 0
return int(cpu_speed)
def get_pod_memory(self, nodeinfo):
"""Gets the total memory of the pod."""
KiB = self.get_key_value_unitless(nodeinfo, "Memory size")
if KiB is None:
maaslog.error("Failed to get pod memory")
return 0
# Memory in MiB.
return int(int(KiB) / 1024)
def get_machine_memory(self, machine):
"""Gets the VM memory."""
output = self.run(["dominfo", machine])
KiB = self.get_key_value_unitless(output, "Max memory")
if KiB is None:
maaslog.error("%s: Failed to get machine memory", machine)
return 0
# Memory in MiB.
return int(int(KiB) / 1024)
def get_pod_storage_pools(self, with_available=False):
"""Get the storage pools information."""
pools = []
for pool in self.list_pools():
output = self.run(["pool-dumpxml", pool])
if not output:
# Skip if cannot get more information.
continue
doc = etree.XML(output)
evaluator = etree.XPathEvaluator(doc)
pool_capacity = int(evaluator(XPATH_POOL_CAPACITY)[0].text)
pool_path = evaluator(XPATH_POOL_PATH)[0].text
pool_type = evaluator(XPATH_POOL_TYPE)[0]
pool_uuid = evaluator(XPATH_POOL_UUID)[0].text
pool = DiscoveredPodStoragePool(
id=pool_uuid,
name=pool,
path=pool_path,
type=pool_type,
storage=pool_capacity,
)
if with_available:
# Use `setattr` because `DiscoveredPodStoragePool` doesn't have
# an available attribute and its only needed for the driver
# to perform calculations. This prevents this information from
# being sent to the region, which isn't needed.
pool_available = int(evaluator(XPATH_POOL_AVAILABLE)[0].text)
setattr(pool, "available", pool_available)
pools.append(pool)
return pools
def get_pod_available_local_storage(self):
"""Gets the available local storage for the pod."""
pools = self.list_pools()
local_storage = 0
for pool in pools:
output = self.run(["pool-dumpxml", pool]).strip()
if output is None:
maaslog.error("Failed to get available pod local storage")
return None
doc = etree.XML(output)
evaluator = etree.XPathEvaluator(doc)
pool_capacity = int(evaluator(XPATH_POOL_AVAILABLE)[0].text)
local_storage += pool_capacity
# Local storage in bytes.
return local_storage
def get_machine_local_storage(self, machine, device):
"""Gets the VM local storage for device."""
output = self.run(["domblkinfo", machine, device])
if not output:
maaslog.error("Failed to get available pod local storage")
return None
try:
return int(self.get_key_value(output, "Capacity"))
except TypeError:
return None
def get_pod_nodeinfo(self):
"""Gets the general information of the node via 'nodeinfo'"""
return self.run(["nodeinfo"])
def get_pod_arch(self, nodeinfo):
"""Gets architecture of the pod."""
arch = self.get_key_value(nodeinfo, "CPU model")
if arch is None:
maaslog.error("Failed to get pod architecture")
raise PodInvalidResources(
"Pod architecture is not supported: %s" % arch
)
return kernel_to_debian_architecture(arch)
def get_machine_arch(self, machine):
"""Gets the VM architecture."""
output = self.get_machine_xml(machine)
if output is None:
maaslog.error("%s: Failed to get VM architecture", machine)
return None
doc = etree.XML(output)
evaluator = etree.XPathEvaluator(doc)
arch = evaluator(XPATH_ARCH)[0]
# Fix architectures that need to be referenced by a different
# name, that MAAS understands.
return kernel_to_debian_architecture(arch)
def find_storage_pool(self, source, storage_pools):
"""Find the storage pool for `source`."""
for pool in storage_pools:
if source.startswith(pool.path):
return pool
def get_pod_resources(self):
"""Get the pod resources."""
discovered_pod = DiscoveredPod(
architectures=[],
cores=0,
cpu_speed=0,
memory=0,
local_storage=0,
hints=DiscoveredPodHints(
cores=0, cpu_speed=0, memory=0, local_storage=0
),
)
discovered_pod.capabilities = [
Capabilities.COMPOSABLE,
Capabilities.DYNAMIC_LOCAL_STORAGE,
Capabilities.OVER_COMMIT,
Capabilities.STORAGE_POOLS,
]
nodeinfo = self.get_pod_nodeinfo()
discovered_pod.architectures = [self.get_pod_arch(nodeinfo)]
discovered_pod.cores = self.get_pod_cpu_count(nodeinfo)
discovered_pod.cpu_speed = self.get_pod_cpu_speed(nodeinfo)
discovered_pod.memory = self.get_pod_memory(nodeinfo)
discovered_pod.storage_pools = self.get_pod_storage_pools()
discovered_pod.local_storage = sum(
pool.storage for pool in discovered_pod.storage_pools
)
discovered_pod.version = self.get_server_version()
return discovered_pod
def get_pod_hints(self):
"""Gets the discovered pod hints."""
discovered_pod_hints = DiscoveredPodHints(
cores=0, cpu_speed=0, memory=0, local_storage=0
)
# You can always create a domain up to the size of total cores,
# memory, and cpu_speed even if that amount is already in use.
# Not a good idea, but possible.
nodeinfo = self.get_pod_nodeinfo()
discovered_pod_hints.cores = self.get_pod_cpu_count(nodeinfo)
discovered_pod_hints.cpu_speed = self.get_pod_cpu_speed(nodeinfo)
discovered_pod_hints.memory = self.get_pod_memory(nodeinfo)
discovered_pod_hints.local_storage = (
self.get_pod_available_local_storage()
)
return discovered_pod_hints
def get_discovered_machine(
self, machine, request=None, storage_pools=None
):
"""Gets the discovered machine."""
# Discovered machine.
discovered_machine = DiscoveredMachine(
architecture="",
cores=0,
cpu_speed=0,
memory=0,
interfaces=[],
block_devices=[],
tags=[],
)
discovered_machine.hostname = machine
discovered_machine.architecture = self.get_machine_arch(machine)
discovered_machine.cores = self.get_machine_cpu_count(machine)
discovered_machine.memory = self.get_machine_memory(machine)
state = self.get_machine_state(machine)
discovered_machine.power_state = VM_STATE_TO_POWER_STATE[state]
discovered_machine.power_parameters = {"power_id": machine}
# Load storage pools if needed.
if storage_pools is None:
storage_pools = self.get_pod_storage_pools()
# Discover block devices.
block_devices = []
devices = self.list_machine_block_devices(machine)
for idx, (device, source) in enumerate(devices):
# Block device.
# When request is provided map the tags from the request block
# devices to the discovered block devices. This ensures that
# composed machine has the requested tags on the block device.
tags = []
if request is not None:
tags = request.block_devices[idx].tags
size = self.get_machine_local_storage(machine, device)
if size is None:
# Bug lp:1690144 - When a domain has a block device where its
# storage path is no longer available. The domain cannot be
# started when the storage path is missing, so we don't add it
# to MAAS.
maaslog.error(
"Unable to discover machine '%s' in virsh pod: storage "
"device '%s' is missing its storage backing."
% (machine, device)
)
return None
# Find the storage pool for this block device if it belongs to
# a storage pool. Virsh doesn't tell you this information.
storage_pool = self.find_storage_pool(source, storage_pools)
block_devices.append(
DiscoveredMachineBlockDevice(
model=None,
serial=None,
size=size,
id_path="/dev/%s" % device,
tags=tags,
storage_pool=storage_pool.id if storage_pool else None,
)
)
discovered_machine.block_devices = block_devices
# Discover interfaces.
interfaces = []
all_interface_info = self.get_machine_interface_info(machine)
boot = True
for interface_info in all_interface_info:
interfaces.append(
DiscoveredMachineInterface(
mac_address=interface_info.mac,
boot=boot,
attach_type=interface_info.type,
attach_name=interface_info.source,
)
)
boot = False
discovered_machine.interfaces = interfaces
return discovered_machine
def check_machine_can_startup(self, machine):
"""Check the machine for any startup errors
after the domain is created in virsh.
If an error is reported, delete the domain and raise an exception.
If no error is reported, destroy the domain to put it back into a
'shut off' state.
"""
try:
self.run(["start", "--paused", machine])
except VirshError as e:
# Delete the domain.
self.delete_domain(machine)
# Raise the error.
raise VirshError(f"Unable to compose {machine}: {e}")
else:
# No errors, so set machine back to 'shut off' state.
self.run(["destroy", machine])
def set_machine_autostart(self, machine):
"""Set machine to autostart."""
try:
self.run(["autostart", machine])
except VirshError:
return False
return True
def configure_pxe_boot(self, machine):
"""Given the specified machine, reads the XML dump and determines
if the boot order needs to be changed. The boot order needs to be
changed if it isn't (network, hd), and will be changed to that if
it is found to be set to anything else.
"""
xml = self.get_machine_xml(machine)
if xml is None:
return False
doc = etree.XML(xml)
evaluator = etree.XPathEvaluator(doc)
# Remove any existing <boot/> elements under <os/>.
boot_elements = evaluator(XPATH_BOOT)
# Skip this if the boot order is already set up how we want it to be.
if (
len(boot_elements) == 2
and boot_elements[0].attrib["dev"] == "network"
and boot_elements[1].attrib["dev"] == "hd"
):
return True
for element in boot_elements:
element.getparent().remove(element)
# Grab the <os/> element and put the <boot/> element we want in.
os = evaluator(XPATH_OS)[0]
os.append(etree.XML("<boot dev='network'/>"))
os.append(etree.XML("<boot dev='hd'/>"))
# Rewrite the XML in a temporary file to use with 'virsh define'.
with NamedTemporaryFile() as f:
f.write(etree.tostring(doc))
f.write(b"\n")
f.flush()
try:
self.run(["define", f.name])
except VirshError:
return False
return True
def poweron(self, machine):
"""Poweron a VM."""
try:
self.run(["start", machine])
except VirshError:
return False
return True
def poweroff(self, machine):
"""Poweroff a VM."""
try:
self.run(["destroy", machine])
except VirshError:
return False
return True
def get_usable_pool(self, disk, default_pool=None):
"""Return the pool and type that has enough space for `disk.size`."""
pools = self.get_pod_storage_pools(with_available=True)
filtered_pools = [pool for pool in pools if pool.name in disk.tags]
if filtered_pools:
for pool in filtered_pools:
if disk.size <= pool.available:
return pool.type, pool.name
raise PodInvalidResources(
"Not enough storage space on storage pools: %s"
% (", ".join([pool.name for pool in filtered_pools]))
)
if default_pool:
filtered_pools = [
pool for pool in pools if pool.id == default_pool
]
if not filtered_pools:
filtered_pools = [
pool for pool in pools if pool.name == default_pool
]
if filtered_pools:
default_pool = filtered_pools[0]
if disk.size <= default_pool.available:
return default_pool.type, default_pool.name
raise PodInvalidResources(
"Not enough space in default storage pool: %s"
% (default_pool.name)
)
raise VirshError(
"Default storage pool '%s' doesn't exist." % default_pool
)
for pool in pools:
if disk.size <= pool.available:
return pool.type, pool.name
raise PodInvalidResources(
"Not enough storage space on any storage pools: %s"
% (", ".join([pool.name for pool in pools]))
)
def _create_local_volume(self, disk, default_pool=None):
"""Create a local volume with `disk.size`."""
usable_pool_type, usable_pool = self.get_usable_pool(
disk, default_pool
)
if usable_pool is None:
return None
volume = str(uuid4())
disk_size = disk.size
extra_args = []
if usable_pool_type == "dir":
extra_args = [
"--allocation",
"0",
"--format",
"raw",
]
elif usable_pool_type == "zfs":
# LP: #1858201
# Round down to the nearest MiB for zfs.
# See bug comments for more details.
disk_size = int(floor(disk.size / 2**20)) * 2**20
extra_args = [
"--allocation",
"0",
]
self.run(
[
"vol-create-as",
usable_pool,
volume,
str(disk_size),
]
+ extra_args,
)
return usable_pool, volume
def delete_local_volume(self, pool, volume):
"""Delete a local volume from `pool` with `volume`."""
self.run(["vol-delete", volume, "--pool", pool])
def get_volume_path(self, pool, volume):
"""Return the path to the file from `pool` and `volume`."""
return self.run(["vol-path", volume, "--pool", pool])
def attach_local_volume(self, domain, pool, volume, device):
"""Attach `volume` in `pool` to `domain` as `device`."""
vol_path = self.get_volume_path(pool, volume)
serial = os.path.basename(vol_path)
self.run(
[
"attach-disk",
domain,
vol_path,
device,
"--targetbus",
"virtio",
"--sourcetype",
"file",
"--config",
"--serial",
serial,
]
)
def get_network_list(self):
"""Return the list of available networks."""
return self.run(["net-list", "--name"]).splitlines()
def check_network_maas_dhcp_enabled(self, network, host_interfaces):
xml = self.get_network_xml(network)
tree = etree.fromstring(xml)
# Check that libvirt DHCP is not enabled.
if not tree.xpath("//dhcp"):
# Validate that network is attached to a bridge
# whose VLAN is enabled for MAAS DHCP.
bridge_element = tree.xpath("//bridge")[0]
ifname = bridge_element.get("name")
if ifname in host_interfaces and host_interfaces[ifname]:
return ifname
def get_default_interface_attachment(self, known_host_interfaces):
"""Return the interface attachment for the best attachment option
currenlty available for the libvirt networks.
The criteria for retrieving the best possible interface attachments
here is done by:
(1) If a `maas` or `default` network is defined in libvirt, continue
to prefer network attachments in that order of preference However,
DO NOT attach to either network by default if libvirt's DHCP is
enabled (this is virtually guaranteed to break the operation of MAAS).
(2) If a `maas` or `default` network is selected, validate that it is
attached to a bridge whose VLAN is enabled for MAAS DHCP (or DHCP
relay). If no libvirt network is found to be attached to a
DHCP-enabled network in MAAS, skip to (c).
(3) If no MAAS-managed DHCP network was found after checking (1) and
(2), prefer attachments in the following order of precedence:
(3.1) A bridge interface on the pod host whose VLAN is DHCP-enabled.
(3.2) A macvlan attachment on the pod host whose VLAN is
DHCP-enabled.
(4) If known_host_interfaces is None, return interface attachments for
`maas` or `default` network, checked in that order, if they exist
within the available libvirt networks.
"""
networks = self.get_network_list()
# When there are not any known_host_interfaces,
# default to checking for the `maas` and `default` libvirt networks.
if not known_host_interfaces:
if LIBVIRT_NETWORK.MAAS in networks:
return LIBVIRT_NETWORK.MAAS, InterfaceAttachType.NETWORK
elif LIBVIRT_NETWORK.DEFAULT in networks:
return LIBVIRT_NETWORK.DEFAULT, InterfaceAttachType.NETWORK