]> git.proxmox.com Git - qemu-server.git/blame - PVE/QemuServer.pm
config: add new meta property with the VM creation time
[qemu-server.git] / PVE / QemuServer.pm
CommitLineData
1e3baf05
DM
1package PVE::QemuServer;
2
3use strict;
990fc5e2 4use warnings;
3ff84d6f 5
5da072fb
TL
6use Cwd 'abs_path';
7use Digest::SHA;
8use Fcntl ':flock';
9use Fcntl;
1e3baf05 10use File::Basename;
5da072fb 11use File::Copy qw(copy);
1e3baf05
DM
12use File::Path;
13use File::stat;
14use Getopt::Long;
5da072fb
TL
15use IO::Dir;
16use IO::File;
17use IO::Handle;
18use IO::Select;
19use IO::Socket::UNIX;
1e3baf05 20use IPC::Open3;
c971c4f2 21use JSON;
1f30ac3a 22use MIME::Base64;
5da072fb
TL
23use POSIX;
24use Storable qw(dclone);
f85951dc 25use Time::HiRes qw(gettimeofday usleep);
5da072fb 26use URI::Escape;
425441e6 27use UUID;
5da072fb 28
82841214 29use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file);
5b65b00d 30use PVE::CGroup;
48cf040f 31use PVE::DataCenterConfig;
5da072fb 32use PVE::Exception qw(raise raise_param_exc);
3b56383b 33use PVE::Format qw(render_duration render_bytes);
81d6e4e1 34use PVE::GuestHelpers qw(safe_string_ne safe_num_ne safe_boolean_ne);
1e3baf05 35use PVE::INotify;
4df98f2f 36use PVE::JSONSchema qw(get_standard_option parse_property_string);
1e3baf05 37use PVE::ProcFSTools;
fbec3f89 38use PVE::PBSClient;
91bd6c90 39use PVE::RPCEnvironment;
5da072fb 40use PVE::Storage;
b71351a7 41use PVE::SysFSTools;
d04d6af1 42use PVE::Systemd;
82841214 43use PVE::Tools qw(run_command file_read_firstline file_get_contents dir_glob_foreach get_host_arch $IPV6RE);
5da072fb
TL
44
45use PVE::QMPClient;
46use PVE::QemuConfig;
2f18c84d 47use PVE::QemuServer::Helpers qw(min_version config_aware_timeout);
5da072fb 48use PVE::QemuServer::Cloudinit;
5b65b00d 49use PVE::QemuServer::CGroup;
d786a274 50use PVE::QemuServer::CPUConfig qw(print_cpu_device get_cpu_options);
75748d44 51use PVE::QemuServer::Drive qw(is_valid_drivename drive_is_cloudinit drive_is_cdrom drive_is_read_only parse_drive print_drive);
2ea5fb7e 52use PVE::QemuServer::Machine;
5da072fb 53use PVE::QemuServer::Memory;
0a13e08e 54use PVE::QemuServer::Monitor qw(mon_cmd);
74c17b7a 55use PVE::QemuServer::PCI qw(print_pci_addr print_pcie_addr print_pcie_root_port parse_hostpci);
5da072fb 56use PVE::QemuServer::USB qw(parse_usb_device);
1e3baf05 57
28e129cc
AD
58my $have_sdn;
59eval {
60 require PVE::Network::SDN::Zones;
61 $have_sdn = 1;
62};
63
102cf9d8 64my $EDK2_FW_BASE = '/usr/share/pve-edk2-firmware/';
96ed3574 65my $OVMF = {
b5099b4f 66 x86_64 => {
90b20b15
DC
67 '4m-no-smm' => [
68 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
69 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
70 ],
71 '4m-no-smm-ms' => [
72 "$EDK2_FW_BASE/OVMF_CODE_4M.fd",
73 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
74 ],
b5099b4f
SR
75 '4m' => [
76 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
77 "$EDK2_FW_BASE/OVMF_VARS_4M.fd",
78 ],
79 '4m-ms' => [
80 "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd",
81 "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd",
82 ],
83 default => [
84 "$EDK2_FW_BASE/OVMF_CODE.fd",
85 "$EDK2_FW_BASE/OVMF_VARS.fd",
86 ],
87 },
88 aarch64 => {
89 default => [
90 "$EDK2_FW_BASE/AAVMF_CODE.fd",
91 "$EDK2_FW_BASE/AAVMF_VARS.fd",
92 ],
93 },
96ed3574 94};
2ddc0a5c 95
7f0b5beb 96my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
1e3baf05 97
8d88a594
TL
98# Note about locking: we use flock on the config file protect against concurent actions.
99# Aditionaly, we have a 'lock' setting in the config file. This can be set to 'migrate',
100# 'backup', 'snapshot' or 'rollback'. Most actions are not allowed when such lock is set.
101# But you can ignore this kind of lock with the --skiplock flag.
1e3baf05 102
97d62eb7 103cfs_register_file('/qemu-server/',
1858638f
DM
104 \&parse_vm_config,
105 \&write_vm_config);
1e3baf05 106
3ea94c60
DM
107PVE::JSONSchema::register_standard_option('pve-qm-stateuri', {
108 description => "Some command save/restore state from this location.",
109 type => 'string',
110 maxLength => 128,
111 optional => 1,
112});
113
c6737ef1
DC
114PVE::JSONSchema::register_standard_option('pve-qemu-machine', {
115 description => "Specifies the Qemu machine type.",
116 type => 'string',
9471e48b 117 pattern => '(pc|pc(-i440fx)?-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|q35|pc-q35-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|virt(?:-\d+(\.\d+)+)?(\+pve\d+)?)',
c6737ef1
DC
118 maxLength => 40,
119 optional => 1,
120});
121
bf8fc5a3
FG
122
123sub map_storage {
124 my ($map, $source) = @_;
125
126 return $source if !defined($map);
127
128 return $map->{entries}->{$source}
b6d9b54b 129 if $map->{entries} && defined($map->{entries}->{$source});
bf8fc5a3
FG
130
131 return $map->{default} if $map->{default};
132
133 # identity (fallback)
134 return $source;
135}
136
137PVE::JSONSchema::register_standard_option('pve-targetstorage', {
138 description => "Mapping from source to target storages. Providing only a single storage ID maps all source storages to that storage. Providing the special value '1' will map each source storage to itself.",
139 type => 'string',
140 format => 'storagepair-list',
141 optional => 1,
142});
143
1e3baf05
DM
144#no warnings 'redefine';
145
38277afc
TL
146my $nodename_cache;
147sub nodename {
148 $nodename_cache //= PVE::INotify::nodename();
149 return $nodename_cache;
150}
1e3baf05 151
ec3582b5
WB
152my $watchdog_fmt = {
153 model => {
154 default_key => 1,
155 type => 'string',
156 enum => [qw(i6300esb ib700)],
157 description => "Watchdog type to emulate.",
158 default => 'i6300esb',
159 optional => 1,
160 },
161 action => {
162 type => 'string',
163 enum => [qw(reset shutdown poweroff pause debug none)],
164 description => "The action to perform if after activation the guest fails to poll the watchdog in time.",
165 optional => 1,
166 },
167};
168PVE::JSONSchema::register_format('pve-qm-watchdog', $watchdog_fmt);
169
9d66b397
SI
170my $agent_fmt = {
171 enabled => {
8d88a594 172 description => "Enable/disable communication with a Qemu Guest Agent (QGA) running in the VM.",
9d66b397
SI
173 type => 'boolean',
174 default => 0,
175 default_key => 1,
176 },
177 fstrim_cloned_disks => {
0a4aff09 178 description => "Run fstrim after moving a disk or migrating the VM.",
9d66b397
SI
179 type => 'boolean',
180 optional => 1,
181 default => 0
182 },
48657158
MD
183 type => {
184 description => "Select the agent type",
185 type => 'string',
186 default => 'virtio',
187 optional => 1,
188 enum => [qw(virtio isa)],
189 },
9d66b397
SI
190};
191
55655ebc
DC
192my $vga_fmt = {
193 type => {
194 description => "Select the VGA type.",
195 type => 'string',
196 default => 'std',
197 optional => 1,
198 default_key => 1,
7c954c42 199 enum => [qw(cirrus qxl qxl2 qxl3 qxl4 none serial0 serial1 serial2 serial3 std virtio vmware)],
55655ebc
DC
200 },
201 memory => {
202 description => "Sets the VGA memory (in MiB). Has no effect with serial display.",
203 type => 'integer',
204 optional => 1,
205 minimum => 4,
206 maximum => 512,
207 },
208};
209
6dbcb073
DC
210my $ivshmem_fmt = {
211 size => {
212 type => 'integer',
213 minimum => 1,
214 description => "The size of the file in MB.",
215 },
216 name => {
217 type => 'string',
218 pattern => '[a-zA-Z0-9\-]+',
219 optional => 1,
220 format_description => 'string',
221 description => "The name of the file. Will be prefixed with 'pve-shm-'. Default is the VMID. Will be deleted when the VM is stopped.",
222 },
223};
224
1448547f
AL
225my $audio_fmt = {
226 device => {
227 type => 'string',
228 enum => [qw(ich9-intel-hda intel-hda AC97)],
229 description => "Configure an audio device."
230 },
231 driver => {
232 type => 'string',
211785ee 233 enum => ['spice', 'none'],
1448547f
AL
234 default => 'spice',
235 optional => 1,
236 description => "Driver backend for the audio device."
237 },
238};
239
c4df18db
AL
240my $spice_enhancements_fmt = {
241 foldersharing => {
242 type => 'boolean',
243 optional => 1,
d282a24d 244 default => '0',
c4df18db
AL
245 description => "Enable folder sharing via SPICE. Needs Spice-WebDAV daemon installed in the VM."
246 },
247 videostreaming => {
248 type => 'string',
249 enum => ['off', 'all', 'filter'],
d282a24d 250 default => 'off',
c4df18db
AL
251 optional => 1,
252 description => "Enable video streaming. Uses compression for detected video streams."
253 },
254};
255
2cf61f33
SR
256my $rng_fmt = {
257 source => {
258 type => 'string',
259 enum => ['/dev/urandom', '/dev/random', '/dev/hwrng'],
260 default_key => 1,
8d88a594
TL
261 description => "The file on the host to gather entropy from. In most cases '/dev/urandom'"
262 ." should be preferred over '/dev/random' to avoid entropy-starvation issues on the"
263 ." host. Using urandom does *not* decrease security in any meaningful way, as it's"
264 ." still seeded from real entropy, and the bytes provided will most likely be mixed"
265 ." with real entropy on the guest as well. '/dev/hwrng' can be used to pass through"
266 ." a hardware RNG from the host.",
2cf61f33
SR
267 },
268 max_bytes => {
269 type => 'integer',
8d88a594
TL
270 description => "Maximum bytes of entropy allowed to get injected into the guest every"
271 ." 'period' milliseconds. Prefer a lower value when using '/dev/random' as source. Use"
272 ." `0` to disable limiting (potentially dangerous!).",
2cf61f33
SR
273 optional => 1,
274
8d88a594
TL
275 # default is 1 KiB/s, provides enough entropy to the guest to avoid boot-starvation issues
276 # (e.g. systemd etc...) while allowing no chance of overwhelming the host, provided we're
277 # reading from /dev/urandom
2cf61f33
SR
278 default => 1024,
279 },
280 period => {
281 type => 'integer',
8d88a594
TL
282 description => "Every 'period' milliseconds the entropy-injection quota is reset, allowing"
283 ." the guest to retrieve another 'max_bytes' of entropy.",
2cf61f33
SR
284 optional => 1,
285 default => 1000,
286 },
287};
288
26b443c8
TL
289my $meta_info_fmt = {
290 'ctime' => {
291 type => 'integer',
292 description => "The guest creation timestamp as UNIX epoch time",
293 minimum => 0,
294 optional => 1,
295 },
296};
297
1e3baf05
DM
298my $confdesc = {
299 onboot => {
300 optional => 1,
301 type => 'boolean',
302 description => "Specifies whether a VM will be started during system bootup.",
303 default => 0,
304 },
305 autostart => {
306 optional => 1,
307 type => 'boolean',
308 description => "Automatic restart after crash (currently ignored).",
309 default => 0,
310 },
2ff09f52 311 hotplug => {
483ceeab
TL
312 optional => 1,
313 type => 'string', format => 'pve-hotplug-features',
314 description => "Selectively enable hotplug features. This is a comma separated list of"
8d88a594
TL
315 ." hotplug features: 'network', 'disk', 'cpu', 'memory' and 'usb'. Use '0' to disable"
316 ." hotplug completely. Using '1' as value is an alias for the default `network,disk,usb`.",
b3c2bdd1 317 default => 'network,disk,usb',
2ff09f52 318 },
1e3baf05
DM
319 reboot => {
320 optional => 1,
321 type => 'boolean',
322 description => "Allow reboot. If set to '0' the VM exit on reboot.",
323 default => 1,
324 },
325 lock => {
326 optional => 1,
327 type => 'string',
328 description => "Lock/unlock the VM.",
159719e5 329 enum => [qw(backup clone create migrate rollback snapshot snapshot-delete suspending suspended)],
1e3baf05
DM
330 },
331 cpulimit => {
332 optional => 1,
c6f773b8 333 type => 'number',
52261945 334 description => "Limit of CPU usage.",
8d88a594
TL
335 verbose_description => "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has"
336 ." total of '2' CPU time. Value '0' indicates no CPU limit.",
1e3baf05 337 minimum => 0,
c6f773b8 338 maximum => 128,
483ceeab 339 default => 0,
1e3baf05
DM
340 },
341 cpuunits => {
342 optional => 1,
343 type => 'integer',
483ceeab 344 description => "CPU weight for a VM, will be clamped to [1, 10000] in cgroup v2.",
67498860
TL
345 verbose_description => "CPU weight for a VM. Argument is used in the kernel fair scheduler."
346 ." The larger the number is, the more CPU time this VM gets. Number is relative to"
347 ." weights of all the other running VMs.",
237239bf
PA
348 minimum => 2,
349 maximum => 262144,
67498860 350 default => 'cgroup v1: 1024, cgroup v2: 100',
1e3baf05
DM
351 },
352 memory => {
353 optional => 1,
354 type => 'integer',
8d88a594
TL
355 description => "Amount of RAM for the VM in MB. This is the maximum available memory when"
356 ." you use the balloon device.",
1e3baf05
DM
357 minimum => 16,
358 default => 512,
359 },
13a48620 360 balloon => {
483ceeab
TL
361 optional => 1,
362 type => 'integer',
363 description => "Amount of target RAM for the VM in MB. Using zero disables the ballon driver.",
8b1accf7
DM
364 minimum => 0,
365 },
366 shares => {
483ceeab
TL
367 optional => 1,
368 type => 'integer',
369 description => "Amount of memory shares for auto-ballooning. The larger the number is, the"
8d88a594
TL
370 ." more memory this VM gets. Number is relative to weights of all other running VMs."
371 ." Using zero disables auto-ballooning. Auto-ballooning is done by pvestatd.",
8b1accf7
DM
372 minimum => 0,
373 maximum => 50000,
374 default => 1000,
13a48620 375 },
1e3baf05
DM
376 keyboard => {
377 optional => 1,
378 type => 'string',
8d88a594
TL
379 description => "Keyboard layout for VNC server. The default is read from the"
380 ."'/etc/pve/datacenter.cfg' configuration file. It should not be necessary to set it.",
e95fe75f 381 enum => PVE::Tools::kvmkeymaplist(),
aea47dd6 382 default => undef,
1e3baf05
DM
383 },
384 name => {
385 optional => 1,
7fabe17d 386 type => 'string', format => 'dns-name',
1e3baf05
DM
387 description => "Set a name for the VM. Only used on the configuration web interface.",
388 },
cdd20088
AD
389 scsihw => {
390 optional => 1,
391 type => 'string',
52261945 392 description => "SCSI controller model",
6731a4cf 393 enum => [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)],
cdd20088
AD
394 default => 'lsi',
395 },
1e3baf05
DM
396 description => {
397 optional => 1,
398 type => 'string',
a200af10
TL
399 description => "Description for the VM. Shown in the web-interface VM's summary."
400 ." This is saved as comment inside the configuration file.",
401 maxLength => 1024 * 8,
1e3baf05
DM
402 },
403 ostype => {
404 optional => 1,
405 type => 'string',
483ceeab 406 enum => [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 win11 l24 l26 solaris)],
52261945
DM
407 description => "Specify guest operating system.",
408 verbose_description => <<EODESC,
409Specify guest operating system. This is used to enable special
410optimization/features for specific operating systems:
411
412[horizontal]
413other;; unspecified OS
414wxp;; Microsoft Windows XP
415w2k;; Microsoft Windows 2000
416w2k3;; Microsoft Windows 2003
417w2k8;; Microsoft Windows 2008
418wvista;; Microsoft Windows Vista
419win7;; Microsoft Windows 7
44c2a647 420win8;; Microsoft Windows 8/2012/2012r2
1f5828f2 421win10;; Microsoft Windows 10/2016/2019
179b9f1b 422win11;; Microsoft Windows 11/2022
52261945 423l24;; Linux 2.4 Kernel
a5269260 424l26;; Linux 2.6 - 5.X Kernel
52261945 425solaris;; Solaris/OpenSolaris/OpenIndiania kernel
1e3baf05
DM
426EODESC
427 },
428 boot => {
429 optional => 1,
2141a802 430 type => 'string', format => 'pve-qm-boot',
483ceeab
TL
431 description => "Specify guest boot order. Use the 'order=' sub-property as usage with no"
432 ." key or 'legacy=' is deprecated.",
1e3baf05
DM
433 },
434 bootdisk => {
435 optional => 1,
436 type => 'string', format => 'pve-qm-bootdisk',
2141a802 437 description => "Enable booting from specified disk. Deprecated: Use 'boot: order=foo;bar' instead.",
03e480fc 438 pattern => '(ide|sata|scsi|virtio)\d+',
1e3baf05
DM
439 },
440 smp => {
441 optional => 1,
442 type => 'integer',
443 description => "The number of CPUs. Please use option -sockets instead.",
444 minimum => 1,
445 default => 1,
446 },
447 sockets => {
448 optional => 1,
449 type => 'integer',
450 description => "The number of CPU sockets.",
451 minimum => 1,
452 default => 1,
453 },
454 cores => {
455 optional => 1,
456 type => 'integer',
457 description => "The number of cores per socket.",
458 minimum => 1,
459 default => 1,
460 },
8a010eae
AD
461 numa => {
462 optional => 1,
463 type => 'boolean',
1917695c 464 description => "Enable/disable NUMA.",
8a010eae
AD
465 default => 0,
466 },
7023f3ea
AD
467 hugepages => {
468 optional => 1,
469 type => 'string',
470 description => "Enable/disable hugepages memory.",
471 enum => [qw(any 2 1024)],
472 },
f36e9894
SR
473 keephugepages => {
474 optional => 1,
475 type => 'boolean',
476 default => 0,
4df98f2f
TL
477 description => "Use together with hugepages. If enabled, hugepages will not not be deleted"
478 ." after VM shutdown and can be used for subsequent starts.",
f36e9894 479 },
de9d1e55 480 vcpus => {
3bd18e48
AD
481 optional => 1,
482 type => 'integer',
de9d1e55 483 description => "Number of hotplugged vcpus.",
3bd18e48 484 minimum => 1,
de9d1e55 485 default => 0,
3bd18e48 486 },
1e3baf05
DM
487 acpi => {
488 optional => 1,
489 type => 'boolean',
490 description => "Enable/disable ACPI.",
491 default => 1,
492 },
bc84dcca 493 agent => {
ab6a046f 494 optional => 1,
8d88a594 495 description => "Enable/disable communication with the Qemu Guest Agent and its properties.",
9d66b397
SI
496 type => 'string',
497 format => $agent_fmt,
ab6a046f 498 },
1e3baf05
DM
499 kvm => {
500 optional => 1,
501 type => 'boolean',
502 description => "Enable/disable KVM hardware virtualization.",
503 default => 1,
504 },
505 tdf => {
506 optional => 1,
507 type => 'boolean',
8c559505
DM
508 description => "Enable/disable time drift fix.",
509 default => 0,
1e3baf05 510 },
19672434 511 localtime => {
1e3baf05
DM
512 optional => 1,
513 type => 'boolean',
8d88a594
TL
514 description => "Set the real time clock (RTC) to local time. This is enabled by default if"
515 ." the `ostype` indicates a Microsoft Windows OS.",
1e3baf05
DM
516 },
517 freeze => {
518 optional => 1,
519 type => 'boolean',
520 description => "Freeze CPU at startup (use 'c' monitor command to start execution).",
521 },
522 vga => {
523 optional => 1,
55655ebc
DC
524 type => 'string', format => $vga_fmt,
525 description => "Configure the VGA hardware.",
4df98f2f
TL
526 verbose_description => "Configure the VGA Hardware. If you want to use high resolution"
527 ." modes (>= 1280x1024x16) you may need to increase the vga memory option. Since QEMU"
528 ." 2.9 the default VGA display type is 'std' for all OS types besides some Windows"
529 ." versions (XP and older) which use 'cirrus'. The 'qxl' option enables the SPICE"
530 ." display server. For win* OS you can select how many independent displays you want,"
531 ." Linux guests can add displays them self.\nYou can also run without any graphic card,"
532 ." using a serial device as terminal.",
1e3baf05 533 },
0ea9541d
DM
534 watchdog => {
535 optional => 1,
536 type => 'string', format => 'pve-qm-watchdog',
52261945 537 description => "Create a virtual hardware watchdog device.",
4df98f2f
TL
538 verbose_description => "Create a virtual hardware watchdog device. Once enabled (by a guest"
539 ." action), the watchdog must be periodically polled by an agent inside the guest or"
540 ." else the watchdog will reset the guest (or execute the respective action specified)",
0ea9541d 541 },
1e3baf05
DM
542 startdate => {
543 optional => 1,
19672434 544 type => 'string',
1e3baf05 545 typetext => "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)",
4df98f2f
TL
546 description => "Set the initial date of the real time clock. Valid format for date are:"
547 ."'now' or '2006-06-17T16:01:21' or '2006-06-17'.",
1e3baf05
DM
548 pattern => '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)',
549 default => 'now',
550 },
43574f73 551 startup => get_standard_option('pve-startup-order'),
68eda3ab
AD
552 template => {
553 optional => 1,
554 type => 'boolean',
555 description => "Enable/disable Template.",
556 default => 0,
557 },
1e3baf05
DM
558 args => {
559 optional => 1,
560 type => 'string',
52261945
DM
561 description => "Arbitrary arguments passed to kvm.",
562 verbose_description => <<EODESCR,
c7a8aad6 563Arbitrary arguments passed to kvm, for example:
1e3baf05
DM
564
565args: -no-reboot -no-hpet
c7a8aad6
FG
566
567NOTE: this option is for experts only.
1e3baf05
DM
568EODESCR
569 },
570 tablet => {
571 optional => 1,
572 type => 'boolean',
573 default => 1,
52261945 574 description => "Enable/disable the USB tablet device.",
4df98f2f
TL
575 verbose_description => "Enable/disable the USB tablet device. This device is usually needed"
576 ." to allow absolute mouse positioning with VNC. Else the mouse runs out of sync with"
577 ." normal VNC clients. If you're running lots of console-only guests on one host, you"
578 ." may consider disabling this to save some context switches. This is turned off by"
579 ." default if you use spice (`qm set <vmid> --vga qxl`).",
1e3baf05
DM
580 },
581 migrate_speed => {
582 optional => 1,
583 type => 'integer',
584 description => "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.",
585 minimum => 0,
586 default => 0,
587 },
588 migrate_downtime => {
589 optional => 1,
04432191 590 type => 'number',
1e3baf05
DM
591 description => "Set maximum tolerated downtime (in seconds) for migrations.",
592 minimum => 0,
04432191 593 default => 0.1,
1e3baf05
DM
594 },
595 cdrom => {
596 optional => 1,
b799312f 597 type => 'string', format => 'pve-qm-ide',
8485b9ba 598 typetext => '<volume>',
1e3baf05
DM
599 description => "This is an alias for option -ide2",
600 },
601 cpu => {
602 optional => 1,
603 description => "Emulated CPU type.",
604 type => 'string',
5d008ad3 605 format => 'pve-vm-cpu-conf',
1e3baf05 606 },
b7ba6b79
DM
607 parent => get_standard_option('pve-snapshot-name', {
608 optional => 1,
609 description => "Parent snapshot name. This is used internally, and should not be modified.",
610 }),
982c7f12
DM
611 snaptime => {
612 optional => 1,
613 description => "Timestamp for snapshots.",
614 type => 'integer',
615 minimum => 0,
616 },
18bfb361
DM
617 vmstate => {
618 optional => 1,
619 type => 'string', format => 'pve-volume-id',
4df98f2f
TL
620 description => "Reference to a volume which stores the VM state. This is used internally"
621 ." for snapshots.",
18bfb361 622 },
253624c7
FG
623 vmstatestorage => get_standard_option('pve-storage-id', {
624 description => "Default storage for VM state volumes/files.",
625 optional => 1,
626 }),
c6737ef1 627 runningmachine => get_standard_option('pve-qemu-machine', {
4df98f2f
TL
628 description => "Specifies the QEMU machine type of the running vm. This is used internally"
629 ." for snapshots.",
c6737ef1 630 }),
ea1c2110 631 runningcpu => {
4df98f2f
TL
632 description => "Specifies the QEMU '-cpu' parameter of the running vm. This is used"
633 ." internally for snapshots.",
ea1c2110
SR
634 optional => 1,
635 type => 'string',
636 pattern => $PVE::QemuServer::CPUConfig::qemu_cmdline_cpu_re,
637 format_description => 'QEMU -cpu parameter'
638 },
c6737ef1 639 machine => get_standard_option('pve-qemu-machine'),
d731ecbe
WB
640 arch => {
641 description => "Virtual processor architecture. Defaults to the host.",
642 optional => 1,
643 type => 'string',
644 enum => [qw(x86_64 aarch64)],
645 },
2796e7d5
DM
646 smbios1 => {
647 description => "Specify SMBIOS type 1 fields.",
648 type => 'string', format => 'pve-qm-smbios1',
5d004b00 649 maxLength => 512,
2796e7d5
DM
650 optional => 1,
651 },
cb0e4540
AG
652 protection => {
653 optional => 1,
654 type => 'boolean',
4df98f2f
TL
655 description => "Sets the protection flag of the VM. This will disable the remove VM and"
656 ." remove disk operations.",
cb0e4540
AG
657 default => 0,
658 },
3edb45e7 659 bios => {
a783c78e 660 optional => 1,
3edb45e7
DM
661 type => 'string',
662 enum => [ qw(seabios ovmf) ],
663 description => "Select BIOS implementation.",
664 default => 'seabios',
a783c78e 665 },
6ee499ff
DC
666 vmgenid => {
667 type => 'string',
668 pattern => '(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}|[01])',
669 format_description => 'UUID',
4df98f2f
TL
670 description => "Set VM Generation ID. Use '1' to autogenerate on create or update, pass '0'"
671 ." to disable explicitly.",
672 verbose_description => "The VM generation ID (vmgenid) device exposes a 128-bit integer"
673 ." value identifier to the guest OS. This allows to notify the guest operating system"
674 ." when the virtual machine is executed with a different configuration (e.g. snapshot"
675 ." execution or creation from a template). The guest operating system notices the"
676 ." change, and is then able to react as appropriate by marking its copies of"
677 ." distributed databases as dirty, re-initializing its random number generator, etc.\n"
678 ."Note that auto-creation only works when done through API/CLI create or update methods"
679 .", but not when manually editing the config file.",
f7ed64e7 680 default => "1 (autogenerated)",
6ee499ff
DC
681 optional => 1,
682 },
9e784b11
DC
683 hookscript => {
684 type => 'string',
685 format => 'pve-volume-id',
686 optional => 1,
687 description => "Script that will be executed during various steps in the vms lifetime.",
688 },
6dbcb073
DC
689 ivshmem => {
690 type => 'string',
691 format => $ivshmem_fmt,
4df98f2f
TL
692 description => "Inter-VM shared memory. Useful for direct communication between VMs, or to"
693 ." the host.",
6dbcb073 694 optional => 1,
2e7b5925
AL
695 },
696 audio0 => {
697 type => 'string',
1448547f 698 format => $audio_fmt,
194b65f1 699 description => "Configure a audio device, useful in combination with QXL/Spice.",
2e7b5925
AL
700 optional => 1
701 },
c4df18db
AL
702 spice_enhancements => {
703 type => 'string',
704 format => $spice_enhancements_fmt,
705 description => "Configure additional enhancements for SPICE.",
706 optional => 1
707 },
b8e7068a
DC
708 tags => {
709 type => 'string', format => 'pve-tag-list',
710 description => 'Tags of the VM. This is only meta information.',
711 optional => 1,
712 },
2cf61f33
SR
713 rng0 => {
714 type => 'string',
715 format => $rng_fmt,
716 description => "Configure a VirtIO-based Random Number Generator.",
717 optional => 1,
718 },
26b443c8
TL
719 meta => {
720 type => 'string',
721 format => $meta_info_fmt,
722 description => "Some (read-only) meta-information about this guest.",
723 optional => 1,
724 },
9ed7a77c
WB
725};
726
cb702ebe
DL
727my $cicustom_fmt = {
728 meta => {
729 type => 'string',
730 optional => 1,
4df98f2f
TL
731 description => 'Specify a custom file containing all meta data passed to the VM via"
732 ." cloud-init. This is provider specific meaning configdrive2 and nocloud differ.',
cb702ebe
DL
733 format => 'pve-volume-id',
734 format_description => 'volume',
735 },
736 network => {
737 type => 'string',
738 optional => 1,
4df98f2f
TL
739 description => 'Specify a custom file containing all network data passed to the VM via'
740 .' cloud-init.',
cb702ebe
DL
741 format => 'pve-volume-id',
742 format_description => 'volume',
743 },
744 user => {
745 type => 'string',
746 optional => 1,
4df98f2f
TL
747 description => 'Specify a custom file containing all user data passed to the VM via'
748 .' cloud-init.',
cb702ebe
DL
749 format => 'pve-volume-id',
750 format_description => 'volume',
751 },
101beafe
CH
752 vendor => {
753 type => 'string',
754 optional => 1,
755 description => 'Specify a custom file containing all vendor data passed to the VM via'
756 .' cloud-init.',
757 format => 'pve-volume-id',
758 format_description => 'volume',
759 },
cb702ebe
DL
760};
761PVE::JSONSchema::register_format('pve-qm-cicustom', $cicustom_fmt);
762
9ed7a77c 763my $confdesc_cloudinit = {
41cd94a0
WB
764 citype => {
765 optional => 1,
766 type => 'string',
4df98f2f
TL
767 description => 'Specifies the cloud-init configuration format. The default depends on the'
768 .' configured operating system type (`ostype`. We use the `nocloud` format for Linux,'
769 .' and `configdrive2` for windows.',
545eec65 770 enum => ['configdrive2', 'nocloud', 'opennebula'],
41cd94a0 771 },
7b42f951
WB
772 ciuser => {
773 optional => 1,
774 type => 'string',
4df98f2f
TL
775 description => "cloud-init: User name to change ssh keys and password for instead of the"
776 ." image's configured default user.",
7b42f951
WB
777 },
778 cipassword => {
779 optional => 1,
780 type => 'string',
4df98f2f
TL
781 description => 'cloud-init: Password to assign the user. Using this is generally not'
782 .' recommended. Use ssh keys instead. Also note that older cloud-init versions do not'
783 .' support hashed passwords.',
7b42f951 784 },
cb702ebe
DL
785 cicustom => {
786 optional => 1,
787 type => 'string',
4df98f2f
TL
788 description => 'cloud-init: Specify custom files to replace the automatically generated'
789 .' ones at start.',
cb702ebe
DL
790 format => 'pve-qm-cicustom',
791 },
0c9a7596
AD
792 searchdomain => {
793 optional => 1,
794 type => 'string',
4df98f2f
TL
795 description => "cloud-init: Sets DNS search domains for a container. Create will'
796 .' automatically use the setting from the host if neither searchdomain nor nameserver'
797 .' are set.",
0c9a7596
AD
798 },
799 nameserver => {
800 optional => 1,
801 type => 'string', format => 'address-list',
4df98f2f
TL
802 description => "cloud-init: Sets DNS server IP address for a container. Create will'
803 .' automatically use the setting from the host if neither searchdomain nor nameserver'
804 .' are set.",
0c9a7596
AD
805 },
806 sshkeys => {
807 optional => 1,
808 type => 'string',
809 format => 'urlencoded',
1d1c4e1c 810 description => "cloud-init: Setup public SSH keys (one key per line, OpenSSH format).",
0c9a7596 811 },
1e3baf05
DM
812};
813
814# what about other qemu settings ?
815#cpu => 'string',
816#machine => 'string',
817#fda => 'file',
818#fdb => 'file',
819#mtdblock => 'file',
820#sd => 'file',
821#pflash => 'file',
822#snapshot => 'bool',
823#bootp => 'file',
824##tftp => 'dir',
825##smb => 'dir',
826#kernel => 'file',
827#append => 'string',
828#initrd => 'file',
829##soundhw => 'string',
830
831while (my ($k, $v) = each %$confdesc) {
832 PVE::JSONSchema::register_standard_option("pve-qm-$k", $v);
833}
834
1e3baf05 835my $MAX_USB_DEVICES = 5;
5bdcf937 836my $MAX_NETS = 32;
bae179aa 837my $MAX_SERIAL_PORTS = 4;
1989a89c 838my $MAX_PARALLEL_PORTS = 3;
2ed5d572
AD
839my $MAX_NUMA = 8;
840
ffc0d8c7
WB
841my $numa_fmt = {
842 cpus => {
843 type => "string",
844 pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
52261945 845 description => "CPUs accessing this NUMA node.",
ffc0d8c7
WB
846 format_description => "id[-id];...",
847 },
848 memory => {
849 type => "number",
52261945 850 description => "Amount of memory this NUMA node provides.",
ffc0d8c7
WB
851 optional => 1,
852 },
853 hostnodes => {
854 type => "string",
855 pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
52261945 856 description => "Host NUMA nodes to use.",
ffc0d8c7
WB
857 format_description => "id[-id];...",
858 optional => 1,
859 },
860 policy => {
861 type => 'string',
862 enum => [qw(preferred bind interleave)],
52261945 863 description => "NUMA allocation policy.",
ffc0d8c7
WB
864 optional => 1,
865 },
866};
867PVE::JSONSchema::register_format('pve-qm-numanode', $numa_fmt);
2ed5d572
AD
868my $numadesc = {
869 optional => 1,
ffc0d8c7 870 type => 'string', format => $numa_fmt,
52261945 871 description => "NUMA topology.",
2ed5d572
AD
872};
873PVE::JSONSchema::register_standard_option("pve-qm-numanode", $numadesc);
874
875for (my $i = 0; $i < $MAX_NUMA; $i++) {
876 $confdesc->{"numa$i"} = $numadesc;
877}
1e3baf05 878
f7bc17ca
TL
879my $nic_model_list = [
880 'e1000',
881 'e1000-82540em',
882 'e1000-82544gc',
883 'e1000-82545em',
e83dd50a 884 'e1000e',
f7bc17ca
TL
885 'i82551',
886 'i82557b',
887 'i82559er',
888 'ne2k_isa',
889 'ne2k_pci',
890 'pcnet',
891 'rtl8139',
892 'virtio',
893 'vmxnet3',
894];
6b64503e 895my $nic_model_list_txt = join(' ', sort @$nic_model_list);
1e3baf05 896
52261945
DM
897my $net_fmt_bridge_descr = <<__EOD__;
898Bridge to attach the network device to. The Proxmox VE standard bridge
899is called 'vmbr0'.
900
901If you do not specify a bridge, we create a kvm user (NATed) network
902device, which provides DHCP and DNS services. The following addresses
903are used:
904
905 10.0.2.2 Gateway
906 10.0.2.3 DNS Server
907 10.0.2.4 SMB Server
908
909The DHCP server assign addresses to the guest starting from 10.0.2.15.
910__EOD__
911
cd9c34d1 912my $net_fmt = {
399d96db 913 macaddr => get_standard_option('mac-addr', {
4df98f2f
TL
914 description => "MAC address. That address must be unique withing your network. This is"
915 ." automatically generated if not specified.",
399d96db 916 }),
7f694a71
DM
917 model => {
918 type => 'string',
4df98f2f
TL
919 description => "Network Card Model. The 'virtio' model provides the best performance with"
920 ." very low CPU overhead. If your guest does not support this driver, it is usually"
921 ." best to use 'e1000'.",
7f694a71
DM
922 enum => $nic_model_list,
923 default_key => 1,
924 },
925 (map { $_ => { keyAlias => 'model', alias => 'macaddr' }} @$nic_model_list),
cd9c34d1
WB
926 bridge => {
927 type => 'string',
52261945 928 description => $net_fmt_bridge_descr,
cd9c34d1 929 format_description => 'bridge',
e1cfa02e 930 pattern => '[-_.\w\d]+',
cd9c34d1
WB
931 optional => 1,
932 },
933 queues => {
934 type => 'integer',
935 minimum => 0, maximum => 16,
936 description => 'Number of packet queues to be used on the device.',
cd9c34d1
WB
937 optional => 1,
938 },
939 rate => {
940 type => 'number',
941 minimum => 0,
52261945 942 description => "Rate limit in mbps (megabytes per second) as floating point number.",
cd9c34d1
WB
943 optional => 1,
944 },
945 tag => {
946 type => 'integer',
9f41a659 947 minimum => 1, maximum => 4094,
cd9c34d1 948 description => 'VLAN tag to apply to packets on this interface.',
cd9c34d1
WB
949 optional => 1,
950 },
951 trunks => {
952 type => 'string',
953 pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
954 description => 'VLAN trunks to pass through this interface.',
7f694a71 955 format_description => 'vlanid[;vlanid...]',
cd9c34d1
WB
956 optional => 1,
957 },
958 firewall => {
959 type => 'boolean',
960 description => 'Whether this interface should be protected by the firewall.',
cd9c34d1
WB
961 optional => 1,
962 },
963 link_down => {
964 type => 'boolean',
52261945 965 description => 'Whether this interface should be disconnected (like pulling the plug).',
cd9c34d1
WB
966 optional => 1,
967 },
61a14cde
AD
968 mtu => {
969 type => 'integer',
970 minimum => 1, maximum => 65520,
0530177b 971 description => "Force MTU, for VirtIO only. Set to '1' to use the bridge MTU",
61a14cde
AD
972 optional => 1,
973 },
cd9c34d1 974};
52261945 975
1e3baf05
DM
976my $netdesc = {
977 optional => 1,
7f694a71 978 type => 'string', format => $net_fmt,
52261945 979 description => "Specify network devices.",
1e3baf05 980};
52261945 981
1e3baf05
DM
982PVE::JSONSchema::register_standard_option("pve-qm-net", $netdesc);
983
0c9a7596
AD
984my $ipconfig_fmt = {
985 ip => {
986 type => 'string',
987 format => 'pve-ipv4-config',
988 format_description => 'IPv4Format/CIDR',
989 description => 'IPv4 address in CIDR format.',
990 optional => 1,
991 default => 'dhcp',
992 },
993 gw => {
994 type => 'string',
995 format => 'ipv4',
996 format_description => 'GatewayIPv4',
997 description => 'Default gateway for IPv4 traffic.',
998 optional => 1,
999 requires => 'ip',
1000 },
1001 ip6 => {
1002 type => 'string',
1003 format => 'pve-ipv6-config',
1004 format_description => 'IPv6Format/CIDR',
1005 description => 'IPv6 address in CIDR format.',
1006 optional => 1,
1007 default => 'dhcp',
1008 },
1009 gw6 => {
1010 type => 'string',
1011 format => 'ipv6',
1012 format_description => 'GatewayIPv6',
1013 description => 'Default gateway for IPv6 traffic.',
1014 optional => 1,
1015 requires => 'ip6',
1016 },
1017};
1018PVE::JSONSchema::register_format('pve-qm-ipconfig', $ipconfig_fmt);
1019my $ipconfigdesc = {
1020 optional => 1,
1021 type => 'string', format => 'pve-qm-ipconfig',
1022 description => <<'EODESCR',
1023cloud-init: Specify IP addresses and gateways for the corresponding interface.
1024
1025IP addresses use CIDR notation, gateways are optional but need an IP of the same type specified.
1026
4df98f2f
TL
1027The special string 'dhcp' can be used for IP addresses to use DHCP, in which case no explicit
1028gateway should be provided.
988be8d0
ML
1029For IPv6 the special string 'auto' can be used to use stateless autoconfiguration. This requires
1030cloud-init 19.4 or newer.
0c9a7596 1031
4df98f2f
TL
1032If cloud-init is enabled and neither an IPv4 nor an IPv6 address is specified, it defaults to using
1033dhcp on IPv4.
0c9a7596
AD
1034EODESCR
1035};
1036PVE::JSONSchema::register_standard_option("pve-qm-ipconfig", $netdesc);
1037
1e3baf05
DM
1038for (my $i = 0; $i < $MAX_NETS; $i++) {
1039 $confdesc->{"net$i"} = $netdesc;
9ed7a77c
WB
1040 $confdesc_cloudinit->{"ipconfig$i"} = $ipconfigdesc;
1041}
1042
1043foreach my $key (keys %$confdesc_cloudinit) {
1044 $confdesc->{$key} = $confdesc_cloudinit->{$key};
1e3baf05
DM
1045}
1046
ffa42b86
DC
1047PVE::JSONSchema::register_format('pve-volume-id-or-qm-path', \&verify_volume_id_or_qm_path);
1048sub verify_volume_id_or_qm_path {
822c8a07
WB
1049 my ($volid, $noerr) = @_;
1050
ffa42b86
DC
1051 if ($volid eq 'none' || $volid eq 'cdrom' || $volid =~ m|^/|) {
1052 return $volid;
1053 }
1054
1055 # if its neither 'none' nor 'cdrom' nor a path, check if its a volume-id
822c8a07
WB
1056 $volid = eval { PVE::JSONSchema::check_format('pve-volume-id', $volid, '') };
1057 if ($@) {
d1c1af4b 1058 return if $noerr;
822c8a07
WB
1059 die $@;
1060 }
1061 return $volid;
1062}
1063
ff6ffe20 1064my $usb_fmt = {
a6b9aee4
DC
1065 host => {
1066 default_key => 1,
1067 type => 'string', format => 'pve-qm-usb-device',
1068 format_description => 'HOSTUSBDEVICE|spice',
52261945
DM
1069 description => <<EODESCR,
1070The Host USB device or port or the value 'spice'. HOSTUSBDEVICE syntax is:
1071
1072 'bus-port(.port)*' (decimal numbers) or
1073 'vendor_id:product_id' (hexadeciaml numbers) or
1074 'spice'
1075
1076You can use the 'lsusb -t' command to list existing usb devices.
1077
4df98f2f
TL
1078NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such
1079machines - use with special care.
52261945
DM
1080
1081The value 'spice' can be used to add a usb redirection devices for spice.
1082EODESCR
a6b9aee4
DC
1083 },
1084 usb3 => {
1085 optional => 1,
1086 type => 'boolean',
97ef5356 1087 description => "Specifies whether if given host option is a USB3 device or port.",
52261945 1088 default => 0,
a6b9aee4
DC
1089 },
1090};
1091
1e3baf05
DM
1092my $usbdesc = {
1093 optional => 1,
ff6ffe20 1094 type => 'string', format => $usb_fmt,
52261945 1095 description => "Configure an USB device (n is 0 to 4).",
1e3baf05
DM
1096};
1097PVE::JSONSchema::register_standard_option("pve-qm-usb", $usbdesc);
1098
bae179aa
DA
1099my $serialdesc = {
1100 optional => 1,
ca0cef26 1101 type => 'string',
1b0b51ed 1102 pattern => '(/dev/.+|socket)',
52261945
DM
1103 description => "Create a serial device inside the VM (n is 0 to 3)",
1104 verbose_description => <<EODESCR,
52261945
DM
1105Create a serial device inside the VM (n is 0 to 3), and pass through a
1106host serial device (i.e. /dev/ttyS0), or create a unix socket on the
1107host side (use 'qm terminal' to open a terminal connection).
bae179aa 1108
4df98f2f
TL
1109NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines -
1110use with special care.
bae179aa 1111
52261945 1112CAUTION: Experimental! User reported problems with this option.
bae179aa
DA
1113EODESCR
1114};
bae179aa 1115
1989a89c
DA
1116my $paralleldesc= {
1117 optional => 1,
ca0cef26 1118 type => 'string',
9ecc8431 1119 pattern => '/dev/parport\d+|/dev/usb/lp\d+',
52261945
DM
1120 description => "Map host parallel devices (n is 0 to 2).",
1121 verbose_description => <<EODESCR,
19672434 1122Map host parallel devices (n is 0 to 2).
1989a89c 1123
4df98f2f
TL
1124NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such
1125machines - use with special care.
1989a89c 1126
52261945 1127CAUTION: Experimental! User reported problems with this option.
1989a89c
DA
1128EODESCR
1129};
1989a89c
DA
1130
1131for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
1132 $confdesc->{"parallel$i"} = $paralleldesc;
1133}
1134
bae179aa
DA
1135for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
1136 $confdesc->{"serial$i"} = $serialdesc;
1137}
1138
74c17b7a
SR
1139for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) {
1140 $confdesc->{"hostpci$i"} = $PVE::QemuServer::PCI::hostpcidesc;
040b06b7 1141}
1e3baf05 1142
e0fd2b2f
FE
1143for my $key (keys %{$PVE::QemuServer::Drive::drivedesc_hash}) {
1144 $confdesc->{$key} = $PVE::QemuServer::Drive::drivedesc_hash->{$key};
cdb0931f
DA
1145}
1146
1e3baf05
DM
1147for (my $i = 0; $i < $MAX_USB_DEVICES; $i++) {
1148 $confdesc->{"usb$i"} = $usbdesc;
1149}
1150
5cfa9f5f
SR
1151my $boot_fmt = {
1152 legacy => {
1153 optional => 1,
1154 default_key => 1,
1155 type => 'string',
1156 description => "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)."
1157 . " Deprecated, use 'order=' instead.",
1158 pattern => '[acdn]{1,4}',
1159 format_description => "[acdn]{1,4}",
1160
1161 # note: this is also the fallback if boot: is not given at all
1162 default => 'cdn',
1163 },
1164 order => {
1165 optional => 1,
1166 type => 'string',
1167 format => 'pve-qm-bootdev-list',
1168 format_description => "device[;device...]",
1169 description => <<EODESC,
1170The guest will attempt to boot from devices in the order they appear here.
1171
1172Disks, optical drives and passed-through storage USB devices will be directly
1173booted from, NICs will load PXE, and PCIe devices will either behave like disks
1174(e.g. NVMe) or load an option ROM (e.g. RAID controller, hardware NIC).
1175
1176Note that only devices in this list will be marked as bootable and thus loaded
1177by the guest firmware (BIOS/UEFI). If you require multiple disks for booting
1178(e.g. software-raid), you need to specify all of them here.
1179
1180Overrides the deprecated 'legacy=[acdn]*' value when given.
1181EODESC
1182 },
1183};
1184PVE::JSONSchema::register_format('pve-qm-boot', $boot_fmt);
1185
1186PVE::JSONSchema::register_format('pve-qm-bootdev', \&verify_bootdev);
1187sub verify_bootdev {
1188 my ($dev, $noerr) = @_;
1189
f9dde219
SR
1190 my $special = $dev =~ m/^efidisk/ || $dev =~ m/^tpmstate/;
1191 return $dev if PVE::QemuServer::Drive::is_valid_drivename($dev) && !$special;
5cfa9f5f
SR
1192
1193 my $check = sub {
1194 my ($base) = @_;
1195 return 0 if $dev !~ m/^$base\d+$/;
1196 return 0 if !$confdesc->{$dev};
1197 return 1;
1198 };
1199
1200 return $dev if $check->("net");
1201 return $dev if $check->("usb");
1202 return $dev if $check->("hostpci");
1203
d1c1af4b 1204 return if $noerr;
5cfa9f5f
SR
1205 die "invalid boot device '$dev'\n";
1206}
1207
1208sub print_bootorder {
1209 my ($devs) = @_;
4c27b18c 1210 return "" if !@$devs;
5cfa9f5f
SR
1211 my $data = { order => join(';', @$devs) };
1212 return PVE::JSONSchema::print_property_string($data, $boot_fmt);
1213}
1214
1e3baf05
DM
1215my $kvm_api_version = 0;
1216
1217sub kvm_version {
1e3baf05
DM
1218 return $kvm_api_version if $kvm_api_version;
1219
808a65b5 1220 open my $fh, '<', '/dev/kvm' or return;
1e3baf05 1221
646f2df4
WB
1222 # 0xae00 => KVM_GET_API_VERSION
1223 $kvm_api_version = ioctl($fh, 0xae00, 0);
808a65b5 1224 close($fh);
1e3baf05 1225
646f2df4 1226 return $kvm_api_version;
1e3baf05
DM
1227}
1228
1476b99f
DC
1229my $kvm_user_version = {};
1230my $kvm_mtime = {};
1e3baf05
DM
1231
1232sub kvm_user_version {
1476b99f 1233 my ($binary) = @_;
1e3baf05 1234
1476b99f
DC
1235 $binary //= get_command_for_arch(get_host_arch()); # get the native arch by default
1236 my $st = stat($binary);
1e3baf05 1237
1476b99f
DC
1238 my $cachedmtime = $kvm_mtime->{$binary} // -1;
1239 return $kvm_user_version->{$binary} if $kvm_user_version->{$binary} &&
1240 $cachedmtime == $st->mtime;
1241
1242 $kvm_user_version->{$binary} = 'unknown';
1243 $kvm_mtime->{$binary} = $st->mtime;
1e3baf05 1244
09b11429
TL
1245 my $code = sub {
1246 my $line = shift;
1247 if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) {
1476b99f 1248 $kvm_user_version->{$binary} = $2;
09b11429
TL
1249 }
1250 };
19672434 1251
1476b99f 1252 eval { run_command([$binary, '--version'], outfunc => $code); };
09b11429 1253 warn $@ if $@;
1e3baf05 1254
1476b99f 1255 return $kvm_user_version->{$binary};
1e3baf05
DM
1256
1257}
4df98f2f
TL
1258my sub extract_version {
1259 my ($machine_type, $version) = @_;
1260 $version = kvm_user_version() if !defined($version);
8eb73377 1261 return PVE::QemuServer::Machine::extract_version($machine_type, $version)
4df98f2f 1262}
1e3baf05 1263
db70021b
TL
1264sub kernel_has_vhost_net {
1265 return -c '/dev/vhost-net';
1266}
1e3baf05 1267
1e3baf05
DM
1268sub option_exists {
1269 my $key = shift;
1270 return defined($confdesc->{$key});
19672434 1271}
1e3baf05 1272
1e3baf05 1273my $cdrom_path;
1e3baf05
DM
1274sub get_cdrom_path {
1275
1276 return $cdrom_path if $cdrom_path;
1277
1278 return $cdrom_path = "/dev/cdrom" if -l "/dev/cdrom";
1279 return $cdrom_path = "/dev/cdrom1" if -l "/dev/cdrom1";
1280 return $cdrom_path = "/dev/cdrom2" if -l "/dev/cdrom2";
1281}
1282
1283sub get_iso_path {
1284 my ($storecfg, $vmid, $cdrom) = @_;
1285
1286 if ($cdrom eq 'cdrom') {
1287 return get_cdrom_path();
1288 } elsif ($cdrom eq 'none') {
1289 return '';
1290 } elsif ($cdrom =~ m|^/|) {
1291 return $cdrom;
1292 } else {
6b64503e 1293 return PVE::Storage::path($storecfg, $cdrom);
1e3baf05
DM
1294 }
1295}
1296
1297# try to convert old style file names to volume IDs
1298sub filename_to_volume_id {
1299 my ($vmid, $file, $media) = @_;
1300
0c9a7596 1301 if (!($file eq 'none' || $file eq 'cdrom' ||
1e3baf05 1302 $file =~ m|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) {
19672434 1303
d1c1af4b 1304 return if $file =~ m|/|;
19672434 1305
1e3baf05
DM
1306 if ($media && $media eq 'cdrom') {
1307 $file = "local:iso/$file";
1308 } else {
1309 $file = "local:$vmid/$file";
1310 }
1311 }
1312
1313 return $file;
1314}
1315
1316sub verify_media_type {
1317 my ($opt, $vtype, $media) = @_;
1318
1319 return if !$media;
1320
1321 my $etype;
1322 if ($media eq 'disk') {
a125592c 1323 $etype = 'images';
1e3baf05
DM
1324 } elsif ($media eq 'cdrom') {
1325 $etype = 'iso';
1326 } else {
1327 die "internal error";
1328 }
1329
1330 return if ($vtype eq $etype);
19672434 1331
1e3baf05
DM
1332 raise_param_exc({ $opt => "unexpected media type ($vtype != $etype)" });
1333}
1334
1335sub cleanup_drive_path {
1336 my ($opt, $storecfg, $drive) = @_;
1337
1338 # try to convert filesystem paths to volume IDs
1339
1340 if (($drive->{file} !~ m/^(cdrom|none)$/) &&
1341 ($drive->{file} !~ m|^/dev/.+|) &&
1342 ($drive->{file} !~ m/^([^:]+):(.+)$/) &&
19672434 1343 ($drive->{file} !~ m/^\d+$/)) {
1e3baf05 1344 my ($vtype, $volid) = PVE::Storage::path_to_volume_id($storecfg, $drive->{file});
4df98f2f
TL
1345 raise_param_exc({ $opt => "unable to associate path '$drive->{file}' to any storage"})
1346 if !$vtype;
1e3baf05
DM
1347 $drive->{media} = 'cdrom' if !$drive->{media} && $vtype eq 'iso';
1348 verify_media_type($opt, $vtype, $drive->{media});
1349 $drive->{file} = $volid;
1350 }
1351
1352 $drive->{media} = 'cdrom' if !$drive->{media} && $drive->{file} =~ m/^(cdrom|none)$/;
1353}
1354
b3c2bdd1
DM
1355sub parse_hotplug_features {
1356 my ($data) = @_;
1357
1358 my $res = {};
1359
1360 return $res if $data eq '0';
a1b7d579 1361
b3c2bdd1
DM
1362 $data = $confdesc->{hotplug}->{default} if $data eq '1';
1363
45827685 1364 foreach my $feature (PVE::Tools::split_list($data)) {
b3c2bdd1
DM
1365 if ($feature =~ m/^(network|disk|cpu|memory|usb)$/) {
1366 $res->{$1} = 1;
1367 } else {
596a0a20 1368 die "invalid hotplug feature '$feature'\n";
b3c2bdd1
DM
1369 }
1370 }
1371 return $res;
1372}
1373
1374PVE::JSONSchema::register_format('pve-hotplug-features', \&pve_verify_hotplug_features);
1375sub pve_verify_hotplug_features {
1376 my ($value, $noerr) = @_;
1377
1378 return $value if parse_hotplug_features($value);
1379
d1c1af4b 1380 return if $noerr;
b3c2bdd1
DM
1381
1382 die "unable to parse hotplug option\n";
1383}
1384
28ef82d3
DM
1385sub scsi_inquiry {
1386 my($fh, $noerr) = @_;
1387
1388 my $SG_IO = 0x2285;
1389 my $SG_GET_VERSION_NUM = 0x2282;
1390
1391 my $versionbuf = "\x00" x 8;
1392 my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
1393 if (!$ret) {
1394 die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
d1c1af4b 1395 return;
28ef82d3 1396 }
97d62eb7 1397 my $version = unpack("I", $versionbuf);
28ef82d3
DM
1398 if ($version < 30000) {
1399 die "scsi generic interface too old\n" if !$noerr;
d1c1af4b 1400 return;
28ef82d3 1401 }
97d62eb7 1402
28ef82d3
DM
1403 my $buf = "\x00" x 36;
1404 my $sensebuf = "\x00" x 8;
f334aa3e 1405 my $cmd = pack("C x3 C x1", 0x12, 36);
97d62eb7 1406
28ef82d3
DM
1407 # see /usr/include/scsi/sg.h
1408 my $sg_io_hdr_t = "i i C C s I P P P I I i P C C C C S S i I I";
1409
f606d5bd
TL
1410 my $packet = pack(
1411 $sg_io_hdr_t, ord('S'), -3, length($cmd), length($sensebuf), 0, length($buf), $buf, $cmd, $sensebuf, 6000
1412 );
28ef82d3
DM
1413
1414 $ret = ioctl($fh, $SG_IO, $packet);
1415 if (!$ret) {
1416 die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
d1c1af4b 1417 return;
28ef82d3 1418 }
97d62eb7 1419
28ef82d3
DM
1420 my @res = unpack($sg_io_hdr_t, $packet);
1421 if ($res[17] || $res[18]) {
1422 die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
d1c1af4b 1423 return;
28ef82d3
DM
1424 }
1425
1426 my $res = {};
f606d5bd 1427 $res->@{qw(type removable vendor product revision)} = unpack("C C x6 A8 A16 A4", $buf);
28ef82d3 1428
f606d5bd
TL
1429 $res->{removable} = $res->{removable} & 128 ? 1 : 0;
1430 $res->{type} &= 0x1F;
09984754 1431
28ef82d3
DM
1432 return $res;
1433}
1434
1435sub path_is_scsi {
1436 my ($path) = @_;
1437
d1c1af4b 1438 my $fh = IO::File->new("+<$path") || return;
28ef82d3
DM
1439 my $res = scsi_inquiry($fh, 1);
1440 close($fh);
1441
1442 return $res;
1443}
1444
db656e5f 1445sub print_tabletdevice_full {
d559309f 1446 my ($conf, $arch) = @_;
b467f79a 1447
3392d6ca 1448 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f
DM
1449
1450 # we use uhci for old VMs because tablet driver was buggy in older qemu
d559309f 1451 my $usbbus;
3392d6ca 1452 if (PVE::QemuServer::Machine::machine_type_is_q35($conf) || $arch eq 'aarch64') {
d559309f
WB
1453 $usbbus = 'ehci';
1454 } else {
1455 $usbbus = 'uhci';
1456 }
b467f79a 1457
db656e5f
DM
1458 return "usb-tablet,id=tablet,bus=$usbbus.0,port=1";
1459}
1460
d559309f 1461sub print_keyboarddevice_full {
6971c38e 1462 my ($conf, $arch) = @_;
d559309f 1463
d1c1af4b 1464 return if $arch ne 'aarch64';
d559309f
WB
1465
1466 return "usb-kbd,id=keyboard,bus=ehci.0,port=2";
1467}
1468
a183df68
TL
1469my sub get_drive_id {
1470 my ($drive) = @_;
1471 return "$drive->{interface}$drive->{index}";
1472}
1473
ca916ecc 1474sub print_drivedevice_full {
d559309f 1475 my ($storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type) = @_;
ca916ecc
DA
1476
1477 my $device = '';
1478 my $maxdev = 0;
19672434 1479
a183df68 1480 my $drive_id = get_drive_id($drive);
ca916ecc 1481 if ($drive->{interface} eq 'virtio') {
4df98f2f
TL
1482 my $pciaddr = print_pci_addr("$drive_id", $bridges, $arch, $machine_type);
1483 $device = "virtio-blk-pci,drive=drive-$drive_id,id=${drive_id}${pciaddr}";
1484 $device .= ",iothread=iothread-$drive_id" if $drive->{iothread};
2ed36a41 1485 } elsif ($drive->{interface} eq 'scsi') {
6731a4cf 1486
ee034f5c 1487 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
2ed36a41
DM
1488 my $unit = $drive->{index} % $maxdev;
1489 my $devicetype = 'hd';
69bcf246
WB
1490 my $path = '';
1491 if (drive_is_cdrom($drive)) {
1492 $devicetype = 'cd';
29b19529 1493 } else {
69bcf246
WB
1494 if ($drive->{file} =~ m|^/|) {
1495 $path = $drive->{file};
1496 if (my $info = path_is_scsi($path)) {
8e3c33ab 1497 if ($info->{type} == 0 && $drive->{scsiblock}) {
69bcf246
WB
1498 $devicetype = 'block';
1499 } elsif ($info->{type} == 1) { # tape
1500 $devicetype = 'generic';
1501 }
1502 }
1503 } else {
1504 $path = PVE::Storage::path($storecfg, $drive->{file});
1505 }
1506
a034e3d6 1507 # for compatibility only, we prefer scsi-hd (#2408, #2355, #2380)
4df98f2f 1508 my $version = extract_version($machine_type, kvm_user_version());
a034e3d6 1509 if ($path =~ m/^iscsi\:\/\// &&
2ea5fb7e 1510 !min_version($version, 4, 1)) {
69bcf246
WB
1511 $devicetype = 'generic';
1512 }
1513 }
1514
ef88eaaa 1515 if (!$conf->{scsihw} || $conf->{scsihw} =~ m/^lsi/ || $conf->{scsihw} eq 'pvscsi') {
4df98f2f 1516 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit";
69bcf246 1517 } else {
4df98f2f
TL
1518 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,channel=0,scsi-id=0"
1519 .",lun=$drive->{index}";
69bcf246 1520 }
4df98f2f 1521 $device .= ",drive=drive-$drive_id,id=$drive_id";
cdd20088 1522
6c875f9f
NC
1523 if ($drive->{ssd} && ($devicetype eq 'block' || $devicetype eq 'hd')) {
1524 $device .= ",rotation_rate=1";
1525 }
e741c516 1526 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
6c875f9f
NC
1527
1528 } elsif ($drive->{interface} eq 'ide' || $drive->{interface} eq 'sata') {
e0fd2b2f 1529 my $maxdev = ($drive->{interface} eq 'sata') ? $PVE::QemuServer::Drive::MAX_SATA_DISKS : 2;
2ed36a41
DM
1530 my $controller = int($drive->{index} / $maxdev);
1531 my $unit = $drive->{index} % $maxdev;
1532 my $devicetype = ($drive->{media} && $drive->{media} eq 'cdrom') ? "cd" : "hd";
1533
6c875f9f
NC
1534 $device = "ide-$devicetype";
1535 if ($drive->{interface} eq 'ide') {
1536 $device .= ",bus=ide.$controller,unit=$unit";
1537 } else {
1538 $device .= ",bus=ahci$controller.$unit";
1539 }
4df98f2f 1540 $device .= ",drive=drive-$drive_id,id=$drive_id";
6c875f9f
NC
1541
1542 if ($devicetype eq 'hd') {
1543 if (my $model = $drive->{model}) {
1544 $model = URI::Escape::uri_unescape($model);
1545 $device .= ",model=$model";
1546 }
1547 if ($drive->{ssd}) {
1548 $device .= ",rotation_rate=1";
1549 }
0f2812c2 1550 }
e741c516 1551 $device .= ",wwn=$drive->{wwn}" if $drive->{wwn};
2ed36a41
DM
1552 } elsif ($drive->{interface} eq 'usb') {
1553 die "implement me";
1554 # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
1555 } else {
1556 die "unsupported interface type";
ca916ecc
DA
1557 }
1558
3b408e82
DM
1559 $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex};
1560
a70e7e6c
TL
1561 if (my $serial = $drive->{serial}) {
1562 $serial = URI::Escape::uri_unescape($serial);
1563 $device .= ",serial=$serial";
1564 }
1565
1566
ca916ecc
DA
1567 return $device;
1568}
1569
15b21acc 1570sub get_initiator_name {
46f58b5f 1571 my $initiator;
15b21acc 1572
d1c1af4b 1573 my $fh = IO::File->new('/etc/iscsi/initiatorname.iscsi') || return;
46f58b5f
DM
1574 while (defined(my $line = <$fh>)) {
1575 next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/;
15b21acc
MR
1576 $initiator = $1;
1577 last;
1578 }
46f58b5f
DM
1579 $fh->close();
1580
15b21acc
MR
1581 return $initiator;
1582}
1583
776c5f50 1584sub print_drive_commandline_full {
6d5673c3 1585 my ($storecfg, $vmid, $drive, $pbs_name, $io_uring) = @_;
1e3baf05 1586
d81f0f09
DM
1587 my $path;
1588 my $volid = $drive->{file};
5921764c 1589 my $format = $drive->{format};
a183df68 1590 my $drive_id = get_drive_id($drive);
370b05e7 1591
0fe779a6
WB
1592 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1593 my $scfg = $storeid ? PVE::Storage::storage_config($storecfg, $storeid) : undef;
1594
d81f0f09
DM
1595 if (drive_is_cdrom($drive)) {
1596 $path = get_iso_path($storecfg, $vmid, $volid);
a183df68 1597 die "$drive_id: cannot back cdrom drive with PBS snapshot\n" if $pbs_name;
d81f0f09 1598 } else {
d81f0f09
DM
1599 if ($storeid) {
1600 $path = PVE::Storage::path($storecfg, $volid);
5921764c 1601 $format //= qemu_img_format($scfg, $volname);
d81f0f09
DM
1602 } else {
1603 $path = $volid;
5921764c 1604 $format //= "raw";
d81f0f09
DM
1605 }
1606 }
1607
5921764c
SR
1608 my $is_rbd = $path =~ m/^rbd:/;
1609
1e3baf05 1610 my $opts = '';
5921764c 1611 my @qemu_drive_options = qw(heads secs cyls trans media cache rerror werror aio discard);
1e3baf05 1612 foreach my $o (@qemu_drive_options) {
5fc74861 1613 $opts .= ",$o=$drive->{$o}" if defined($drive->{$o});
19672434 1614 }
8a267708
DC
1615
1616 # snapshot only accepts on|off
1617 if (defined($drive->{snapshot})) {
1618 my $v = $drive->{snapshot} ? 'on' : 'off';
1619 $opts .= ",snapshot=$v";
1620 }
1621
1f91f7b4
TL
1622 if (defined($drive->{ro})) { # ro maps to QEMUs `readonly`, which accepts `on` or `off` only
1623 $opts .= ",readonly=" . ($drive->{ro} ? 'on' : 'off');
12e1d472
DC
1624 }
1625
fb8e95a2
WB
1626 foreach my $type (['', '-total'], [_rd => '-read'], [_wr => '-write']) {
1627 my ($dir, $qmpname) = @$type;
1628 if (my $v = $drive->{"mbps$dir"}) {
1629 $opts .= ",throttling.bps$qmpname=".int($v*1024*1024);
1630 }
1631 if (my $v = $drive->{"mbps${dir}_max"}) {
1632 $opts .= ",throttling.bps$qmpname-max=".int($v*1024*1024);
1633 }
1634 if (my $v = $drive->{"bps${dir}_max_length"}) {
1635 $opts .= ",throttling.bps$qmpname-max-length=$v";
1636 }
1637 if (my $v = $drive->{"iops${dir}"}) {
1638 $opts .= ",throttling.iops$qmpname=$v";
1639 }
1640 if (my $v = $drive->{"iops${dir}_max"}) {
8aca1654 1641 $opts .= ",throttling.iops$qmpname-max=$v";
fb8e95a2
WB
1642 }
1643 if (my $v = $drive->{"iops${dir}_max_length"}) {
8aca1654 1644 $opts .= ",throttling.iops$qmpname-max-length=$v";
fb8e95a2
WB
1645 }
1646 }
1647
5921764c
SR
1648 if ($pbs_name) {
1649 $format = "rbd" if $is_rbd;
a183df68
TL
1650 die "$drive_id: Proxmox Backup Server backed drive cannot auto-detect the format\n"
1651 if !$format;
5921764c
SR
1652 $opts .= ",format=alloc-track,file.driver=$format";
1653 } elsif ($format) {
1654 $opts .= ",format=$format";
1655 }
d81f0f09 1656
b2ee900e
WB
1657 my $cache_direct = 0;
1658
1659 if (my $cache = $drive->{cache}) {
1660 $cache_direct = $cache =~ /^(?:off|none|directsync)$/;
0fe779a6 1661 } elsif (!drive_is_cdrom($drive) && !($scfg && $scfg->{type} eq 'btrfs' && !$scfg->{nocow})) {
b2ee900e
WB
1662 $opts .= ",cache=none";
1663 $cache_direct = 1;
1664 }
1665
628937f5
SR
1666 # io_uring with cache mode writeback or writethrough on krbd will hang...
1667 my $rbd_no_io_uring = $scfg && $scfg->{type} eq 'rbd' && $scfg->{krbd} && !$cache_direct;
1668
78a3ada7
TL
1669 # io_uring with cache mode writeback or writethrough on LVM will hang, without cache only
1670 # sometimes, just plain disable...
1671 my $lvm_no_io_uring = $scfg && $scfg->{type} eq 'lvm';
ec5d198e 1672
b2ee900e 1673 if (!$drive->{aio}) {
ec5d198e 1674 if ($io_uring && !$rbd_no_io_uring && !$lvm_no_io_uring) {
6d5673c3
SR
1675 # io_uring supports all cache modes
1676 $opts .= ",aio=io_uring";
b2ee900e 1677 } else {
6d5673c3
SR
1678 # aio native works only with O_DIRECT
1679 if($cache_direct) {
1680 $opts .= ",aio=native";
1681 } else {
1682 $opts .= ",aio=threads";
1683 }
b2ee900e
WB
1684 }
1685 }
11490cf2 1686
6e47c3b4
WB
1687 if (!drive_is_cdrom($drive)) {
1688 my $detectzeroes;
7d4e30f3 1689 if (defined($drive->{detect_zeroes}) && !$drive->{detect_zeroes}) {
6e47c3b4
WB
1690 $detectzeroes = 'off';
1691 } elsif ($drive->{discard}) {
1692 $detectzeroes = $drive->{discard} eq 'on' ? 'unmap' : 'on';
1693 } else {
1694 # This used to be our default with discard not being specified:
1695 $detectzeroes = 'on';
1696 }
5921764c
SR
1697
1698 # note: 'detect-zeroes' works per blockdev and we want it to persist
1699 # after the alloc-track is removed, so put it on 'file' directly
1700 my $dz_param = $pbs_name ? "file.detect-zeroes" : "detect-zeroes";
1701 $opts .= ",$dz_param=$detectzeroes" if $detectzeroes;
6e47c3b4 1702 }
f1e05305 1703
5921764c
SR
1704 if ($pbs_name) {
1705 $opts .= ",backing=$pbs_name";
1706 $opts .= ",auto-remove=on";
1707 }
1708
1709 # my $file_param = $pbs_name ? "file.file.filename" : "file";
1710 my $file_param = "file";
1711 if ($pbs_name) {
1712 # non-rbd drivers require the underlying file to be a seperate block
1713 # node, so add a second .file indirection
1714 $file_param .= ".file" if !$is_rbd;
1715 $file_param .= ".filename";
1716 }
1717 my $pathinfo = $path ? "$file_param=$path," : '';
1e3baf05 1718
3ebfcc86 1719 return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts";
1e3baf05
DM
1720}
1721
5921764c
SR
1722sub print_pbs_blockdev {
1723 my ($pbs_conf, $pbs_name) = @_;
1724 my $blockdev = "driver=pbs,node-name=$pbs_name,read-only=on";
1725 $blockdev .= ",repository=$pbs_conf->{repository}";
1726 $blockdev .= ",snapshot=$pbs_conf->{snapshot}";
1727 $blockdev .= ",archive=$pbs_conf->{archive}";
1728 $blockdev .= ",keyfile=$pbs_conf->{keyfile}" if $pbs_conf->{keyfile};
1729 return $blockdev;
1730}
1731
cc4d6182 1732sub print_netdevice_full {
d559309f 1733 my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files, $arch, $machine_type) = @_;
cc4d6182 1734
cc4d6182
DA
1735 my $device = $net->{model};
1736 if ($net->{model} eq 'virtio') {
1737 $device = 'virtio-net-pci';
1738 };
1739
d559309f 1740 my $pciaddr = print_pci_addr("$netid", $bridges, $arch, $machine_type);
5e2068d2 1741 my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid";
a9410357 1742 if ($net->{queues} && $net->{queues} > 1 && $net->{model} eq 'virtio'){
4df98f2f
TL
1743 # Consider we have N queues, the number of vectors needed is 2 * N + 2, i.e., one per in
1744 # and out of each queue plus one config interrupt and control vector queue
a9410357
AD
1745 my $vectors = $net->{queues} * 2 + 2;
1746 $tmpstr .= ",vectors=$vectors,mq=on";
1747 }
cc4d6182 1748 $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex} ;
ba9e1000 1749
0530177b
TL
1750 if (my $mtu = $net->{mtu}) {
1751 if ($net->{model} eq 'virtio' && $net->{bridge}) {
1752 my $bridge_mtu = PVE::Network::read_bridge_mtu($net->{bridge});
1753 if ($mtu == 1) {
1754 $mtu = $bridge_mtu;
1755 } elsif ($mtu < 576) {
1756 die "netdev $netid: MTU '$mtu' is smaller than the IP minimum MTU '576'\n";
1757 } elsif ($mtu > $bridge_mtu) {
1758 die "netdev $netid: MTU '$mtu' is bigger than the bridge MTU '$bridge_mtu'\n";
1759 }
1760 $tmpstr .= ",host_mtu=$mtu";
1761 } else {
1762 warn "WARN: netdev $netid: ignoring MTU '$mtu', not using VirtIO or no bridge configured.\n";
61a14cde 1763 }
61a14cde
AD
1764 }
1765
ba9e1000
DM
1766 if ($use_old_bios_files) {
1767 my $romfile;
1768 if ($device eq 'virtio-net-pci') {
1769 $romfile = 'pxe-virtio.rom';
1770 } elsif ($device eq 'e1000') {
1771 $romfile = 'pxe-e1000.rom';
e83dd50a
TL
1772 } elsif ($device eq 'e1000e') {
1773 $romfile = 'pxe-e1000e.rom';
ba9e1000
DM
1774 } elsif ($device eq 'ne2k') {
1775 $romfile = 'pxe-ne2k_pci.rom';
1776 } elsif ($device eq 'pcnet') {
1777 $romfile = 'pxe-pcnet.rom';
1778 } elsif ($device eq 'rtl8139') {
1779 $romfile = 'pxe-rtl8139.rom';
1780 }
1781 $tmpstr .= ",romfile=$romfile" if $romfile;
1782 }
1783
cc4d6182
DA
1784 return $tmpstr;
1785}
1786
1787sub print_netdev_full {
d559309f 1788 my ($vmid, $conf, $arch, $net, $netid, $hotplug) = @_;
cc4d6182
DA
1789
1790 my $i = '';
1791 if ($netid =~ m/^net(\d+)$/) {
1792 $i = int($1);
1793 }
1794
1795 die "got strange net id '$i'\n" if $i >= ${MAX_NETS};
1796
1797 my $ifname = "tap${vmid}i$i";
1798
1799 # kvm uses TUNSETIFF ioctl, and that limits ifname length
1800 die "interface name '$ifname' is too long (max 15 character)\n"
1801 if length($ifname) >= 16;
1802
1803 my $vhostparam = '';
6f0cb675 1804 if (is_native($arch)) {
db70021b 1805 $vhostparam = ',vhost=on' if kernel_has_vhost_net() && $net->{model} eq 'virtio';
6f0cb675 1806 }
cc4d6182
DA
1807
1808 my $vmname = $conf->{name} || "vm$vmid";
1809
a9410357 1810 my $netdev = "";
208ba94e 1811 my $script = $hotplug ? "pve-bridge-hotplug" : "pve-bridge";
a9410357 1812
cc4d6182 1813 if ($net->{bridge}) {
4df98f2f
TL
1814 $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script"
1815 .",downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam";
cc4d6182 1816 } else {
a9410357 1817 $netdev = "type=user,id=$netid,hostname=$vmname";
cc4d6182 1818 }
a9410357
AD
1819
1820 $netdev .= ",queues=$net->{queues}" if ($net->{queues} && $net->{model} eq 'virtio');
1821
1822 return $netdev;
cc4d6182 1823}
1e3baf05 1824
55655ebc
DC
1825my $vga_map = {
1826 'cirrus' => 'cirrus-vga',
1827 'std' => 'VGA',
1828 'vmware' => 'vmware-svga',
1829 'virtio' => 'virtio-vga',
1830};
1831
1832sub print_vga_device {
2ea5fb7e 1833 my ($conf, $vga, $arch, $machine_version, $machine, $id, $qxlnum, $bridges) = @_;
55655ebc
DC
1834
1835 my $type = $vga_map->{$vga->{type}};
86c9fafe 1836 if ($arch eq 'aarch64' && defined($type) && $type eq 'virtio-vga') {
d559309f
WB
1837 $type = 'virtio-gpu';
1838 }
55655ebc 1839 my $vgamem_mb = $vga->{memory};
6021c7a5
AL
1840
1841 my $max_outputs = '';
55655ebc
DC
1842 if ($qxlnum) {
1843 $type = $id ? 'qxl' : 'qxl-vga';
6021c7a5 1844
c5a4c92c 1845 if (!$conf->{ostype} || $conf->{ostype} =~ m/^(?:l\d\d)|(?:other)$/) {
6021c7a5 1846 # set max outputs so linux can have up to 4 qxl displays with one device
2ea5fb7e 1847 if (min_version($machine_version, 4, 1)) {
9e8976ea
TL
1848 $max_outputs = ",max_outputs=4";
1849 }
6021c7a5 1850 }
55655ebc 1851 }
6021c7a5 1852
55655ebc
DC
1853 die "no devicetype for $vga->{type}\n" if !$type;
1854
1855 my $memory = "";
1856 if ($vgamem_mb) {
1857 if ($vga->{type} eq 'virtio') {
1858 my $bytes = PVE::Tools::convert_size($vgamem_mb, "mb" => "b");
1859 $memory = ",max_hostmem=$bytes";
1860 } elsif ($qxlnum) {
1861 # from https://www.spice-space.org/multiple-monitors.html
1862 $memory = ",vgamem_mb=$vga->{memory}";
1863 my $ram = $vgamem_mb * 4;
1864 my $vram = $vgamem_mb * 2;
1865 $memory .= ",ram_size_mb=$ram,vram_size_mb=$vram";
1866 } else {
1867 $memory = ",vgamem_mb=$vga->{memory}";
1868 }
1869 } elsif ($qxlnum && $id) {
1870 $memory = ",ram_size=67108864,vram_size=33554432";
1871 }
1872
789fe8e8
AL
1873 my $edidoff = "";
1874 if ($type eq 'VGA' && windows_version($conf->{ostype})) {
b5d32c6b 1875 $edidoff=",edid=off" if (!defined($conf->{bios}) || $conf->{bios} ne 'ovmf');
789fe8e8
AL
1876 }
1877
3392d6ca 1878 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
55655ebc
DC
1879 my $vgaid = "vga" . ($id // '');
1880 my $pciaddr;
1881 if ($q35 && $vgaid eq 'vga') {
daadd5a4 1882 # the first display uses pcie.0 bus on q35 machines
d559309f 1883 $pciaddr = print_pcie_addr($vgaid, $bridges, $arch, $machine);
55655ebc 1884 } else {
d559309f 1885 $pciaddr = print_pci_addr($vgaid, $bridges, $arch, $machine);
55655ebc
DC
1886 }
1887
789fe8e8 1888 return "$type,id=${vgaid}${memory}${max_outputs}${pciaddr}${edidoff}";
55655ebc
DC
1889}
1890
ffc0d8c7
WB
1891sub parse_number_sets {
1892 my ($set) = @_;
1893 my $res = [];
1894 foreach my $part (split(/;/, $set)) {
1895 if ($part =~ /^\s*(\d+)(?:-(\d+))?\s*$/) {
1896 die "invalid range: $part ($2 < $1)\n" if defined($2) && $2 < $1;
1897 push @$res, [ $1, $2 ];
2ed5d572 1898 } else {
ffc0d8c7 1899 die "invalid range: $part\n";
2ed5d572
AD
1900 }
1901 }
ffc0d8c7
WB
1902 return $res;
1903}
2ed5d572 1904
ffc0d8c7
WB
1905sub parse_numa {
1906 my ($data) = @_;
1907
4df98f2f 1908 my $res = parse_property_string($numa_fmt, $data);
ffc0d8c7
WB
1909 $res->{cpus} = parse_number_sets($res->{cpus}) if defined($res->{cpus});
1910 $res->{hostnodes} = parse_number_sets($res->{hostnodes}) if defined($res->{hostnodes});
2ed5d572
AD
1911 return $res;
1912}
1913
1e3baf05
DM
1914# netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps>
1915sub parse_net {
1916 my ($data) = @_;
1917
4df98f2f 1918 my $res = eval { parse_property_string($net_fmt, $data) };
cd9c34d1
WB
1919 if ($@) {
1920 warn $@;
d1c1af4b 1921 return;
1e3baf05 1922 }
b5b99790
WB
1923 if (!defined($res->{macaddr})) {
1924 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1925 $res->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1926 }
0c9a7596
AD
1927 return $res;
1928}
1929
1930# ipconfigX ip=cidr,gw=ip,ip6=cidr,gw6=ip
1931sub parse_ipconfig {
1932 my ($data) = @_;
1933
4df98f2f 1934 my $res = eval { parse_property_string($ipconfig_fmt, $data) };
0c9a7596
AD
1935 if ($@) {
1936 warn $@;
d1c1af4b 1937 return;
0c9a7596
AD
1938 }
1939
1940 if ($res->{gw} && !$res->{ip}) {
1941 warn 'gateway specified without specifying an IP address';
d1c1af4b 1942 return;
0c9a7596
AD
1943 }
1944 if ($res->{gw6} && !$res->{ip6}) {
1945 warn 'IPv6 gateway specified without specifying an IPv6 address';
d1c1af4b 1946 return;
0c9a7596
AD
1947 }
1948 if ($res->{gw} && $res->{ip} eq 'dhcp') {
1949 warn 'gateway specified together with DHCP';
d1c1af4b 1950 return;
0c9a7596
AD
1951 }
1952 if ($res->{gw6} && $res->{ip6} !~ /^$IPV6RE/) {
1953 # gw6 + auto/dhcp
1954 warn "IPv6 gateway specified together with $res->{ip6} address";
d1c1af4b 1955 return;
0c9a7596
AD
1956 }
1957
1958 if (!$res->{ip} && !$res->{ip6}) {
1959 return { ip => 'dhcp', ip6 => 'dhcp' };
1960 }
1961
1e3baf05
DM
1962 return $res;
1963}
1964
1965sub print_net {
1966 my $net = shift;
1967
cd9c34d1 1968 return PVE::JSONSchema::print_property_string($net, $net_fmt);
1e3baf05
DM
1969}
1970
1971sub add_random_macs {
1972 my ($settings) = @_;
1973
1974 foreach my $opt (keys %$settings) {
1975 next if $opt !~ m/^net(\d+)$/;
1976 my $net = parse_net($settings->{$opt});
1977 next if !$net;
1978 $settings->{$opt} = print_net($net);
1979 }
1980}
1981
055d554d
DM
1982sub vm_is_volid_owner {
1983 my ($storecfg, $vmid, $volid) = @_;
1984
1985 if ($volid !~ m|^/|) {
1986 my ($path, $owner);
1987 eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); };
1988 if ($owner && ($owner == $vmid)) {
1989 return 1;
1990 }
1991 }
1992
d1c1af4b 1993 return;
055d554d
DM
1994}
1995
055d554d
DM
1996sub vmconfig_register_unused_drive {
1997 my ($storecfg, $vmid, $conf, $drive) = @_;
1998
2d9ddec5
WB
1999 if (drive_is_cloudinit($drive)) {
2000 eval { PVE::Storage::vdisk_free($storecfg, $drive->{file}) };
2001 warn $@ if $@;
2002 } elsif (!drive_is_cdrom($drive)) {
055d554d
DM
2003 my $volid = $drive->{file};
2004 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
8793d495 2005 PVE::QemuConfig->add_unused_volume($conf, $volid, $vmid);
055d554d
DM
2006 }
2007 }
2008}
2009
1f30ac3a 2010# smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str][,base64=bool]
ff6ffe20 2011my $smbios1_fmt = {
bd27e851
WB
2012 uuid => {
2013 type => 'string',
2014 pattern => '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}',
2015 format_description => 'UUID',
52261945 2016 description => "Set SMBIOS1 UUID.",
bd27e851
WB
2017 optional => 1,
2018 },
2019 version => {
2020 type => 'string',
1f30ac3a
CE
2021 pattern => '[A-Za-z0-9+\/]+={0,2}',
2022 format_description => 'Base64 encoded string',
52261945 2023 description => "Set SMBIOS1 version.",
bd27e851
WB
2024 optional => 1,
2025 },
2026 serial => {
2027 type => 'string',
1f30ac3a
CE
2028 pattern => '[A-Za-z0-9+\/]+={0,2}',
2029 format_description => 'Base64 encoded string',
52261945 2030 description => "Set SMBIOS1 serial number.",
bd27e851
WB
2031 optional => 1,
2032 },
2033 manufacturer => {
2034 type => 'string',
1f30ac3a
CE
2035 pattern => '[A-Za-z0-9+\/]+={0,2}',
2036 format_description => 'Base64 encoded string',
52261945 2037 description => "Set SMBIOS1 manufacturer.",
bd27e851
WB
2038 optional => 1,
2039 },
2040 product => {
2041 type => 'string',
1f30ac3a
CE
2042 pattern => '[A-Za-z0-9+\/]+={0,2}',
2043 format_description => 'Base64 encoded string',
52261945 2044 description => "Set SMBIOS1 product ID.",
bd27e851
WB
2045 optional => 1,
2046 },
2047 sku => {
2048 type => 'string',
1f30ac3a
CE
2049 pattern => '[A-Za-z0-9+\/]+={0,2}',
2050 format_description => 'Base64 encoded string',
52261945 2051 description => "Set SMBIOS1 SKU string.",
bd27e851
WB
2052 optional => 1,
2053 },
2054 family => {
2055 type => 'string',
1f30ac3a
CE
2056 pattern => '[A-Za-z0-9+\/]+={0,2}',
2057 format_description => 'Base64 encoded string',
52261945 2058 description => "Set SMBIOS1 family string.",
bd27e851
WB
2059 optional => 1,
2060 },
1f30ac3a
CE
2061 base64 => {
2062 type => 'boolean',
2063 description => 'Flag to indicate that the SMBIOS values are base64 encoded',
2064 optional => 1,
2065 },
2796e7d5
DM
2066};
2067
2796e7d5
DM
2068sub parse_smbios1 {
2069 my ($data) = @_;
2070
4df98f2f 2071 my $res = eval { parse_property_string($smbios1_fmt, $data) };
bd27e851 2072 warn $@ if $@;
2796e7d5
DM
2073 return $res;
2074}
2075
cd11416f
DM
2076sub print_smbios1 {
2077 my ($smbios1) = @_;
ff6ffe20 2078 return PVE::JSONSchema::print_property_string($smbios1, $smbios1_fmt);
cd11416f
DM
2079}
2080
ff6ffe20 2081PVE::JSONSchema::register_format('pve-qm-smbios1', $smbios1_fmt);
2796e7d5 2082
0ea9541d
DM
2083sub parse_watchdog {
2084 my ($value) = @_;
2085
d1c1af4b 2086 return if !$value;
0ea9541d 2087
4df98f2f 2088 my $res = eval { parse_property_string($watchdog_fmt, $value) };
ec3582b5 2089 warn $@ if $@;
0ea9541d
DM
2090 return $res;
2091}
2092
9d66b397 2093sub parse_guest_agent {
a2af1bbe 2094 my ($conf) = @_;
9d66b397 2095
a2af1bbe 2096 return {} if !defined($conf->{agent});
9d66b397 2097
a2af1bbe 2098 my $res = eval { parse_property_string($agent_fmt, $conf->{agent}) };
9d66b397
SI
2099 warn $@ if $@;
2100
2101 # if the agent is disabled ignore the other potentially set properties
2102 return {} if !$res->{enabled};
2103 return $res;
2104}
2105
a2af1bbe
TL
2106sub get_qga_key {
2107 my ($conf, $key) = @_;
2108 return undef if !defined($conf->{agent});
2109
2110 my $agent = parse_guest_agent($conf);
2111 return $agent->{$key};
2112}
2113
55655ebc
DC
2114sub parse_vga {
2115 my ($value) = @_;
2116
2117 return {} if !$value;
4df98f2f 2118 my $res = eval { parse_property_string($vga_fmt, $value) };
55655ebc
DC
2119 warn $@ if $@;
2120 return $res;
2121}
2122
2cf61f33
SR
2123sub parse_rng {
2124 my ($value) = @_;
2125
d1c1af4b 2126 return if !$value;
2cf61f33 2127
4df98f2f 2128 my $res = eval { parse_property_string($rng_fmt, $value) };
2cf61f33
SR
2129 warn $@ if $@;
2130 return $res;
2131}
2132
26b443c8
TL
2133sub parse_meta_info {
2134 my ($value) = @_;
2135
2136 return if !$value;
2137
2138 my $res = eval { parse_property_string($meta_info_fmt, $value) };
2139 warn $@ if $@;
2140 return $res;
2141}
2142
2143sub new_meta_info_string {
2144 my () = @_; # for now do not allow to override any value
2145
2146 return PVE::JSONSchema::print_property_string(
2147 {
2148 ctime => "". int(time()),
2149 },
2150 $meta_info_fmt
2151 );
2152}
2153
1e3baf05
DM
2154PVE::JSONSchema::register_format('pve-qm-usb-device', \&verify_usb_device);
2155sub verify_usb_device {
2156 my ($value, $noerr) = @_;
2157
2158 return $value if parse_usb_device($value);
2159
d1c1af4b 2160 return if $noerr;
19672434 2161
1e3baf05
DM
2162 die "unable to parse usb device\n";
2163}
2164
1e3baf05
DM
2165# add JSON properties for create and set function
2166sub json_config_properties {
2167 my $prop = shift;
2168
5a08fb9c
TL
2169 my $skip_json_config_opts = {
2170 parent => 1,
2171 snaptime => 1,
2172 vmstate => 1,
2173 runningmachine => 1,
2174 runningcpu => 1,
26b443c8 2175 meta => 1,
5a08fb9c
TL
2176 };
2177
1e3baf05 2178 foreach my $opt (keys %$confdesc) {
5a08fb9c 2179 next if $skip_json_config_opts->{$opt};
1e3baf05
DM
2180 $prop->{$opt} = $confdesc->{$opt};
2181 }
2182
2183 return $prop;
2184}
2185
d41121fd
DM
2186# return copy of $confdesc_cloudinit to generate documentation
2187sub cloudinit_config_properties {
2188
2189 return dclone($confdesc_cloudinit);
2190}
2191
1e3baf05
DM
2192sub check_type {
2193 my ($key, $value) = @_;
2194
2195 die "unknown setting '$key'\n" if !$confdesc->{$key};
2196
2197 my $type = $confdesc->{$key}->{type};
2198
6b64503e 2199 if (!defined($value)) {
1e3baf05
DM
2200 die "got undefined value\n";
2201 }
2202
2203 if ($value =~ m/[\n\r]/) {
2204 die "property contains a line feed\n";
2205 }
2206
2207 if ($type eq 'boolean') {
19672434
DM
2208 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
2209 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
2210 die "type check ('boolean') failed - got '$value'\n";
1e3baf05
DM
2211 } elsif ($type eq 'integer') {
2212 return int($1) if $value =~ m/^(\d+)$/;
2213 die "type check ('integer') failed - got '$value'\n";
04432191
AD
2214 } elsif ($type eq 'number') {
2215 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
2216 die "type check ('number') failed - got '$value'\n";
1e3baf05
DM
2217 } elsif ($type eq 'string') {
2218 if (my $fmt = $confdesc->{$key}->{format}) {
1e3baf05 2219 PVE::JSONSchema::check_format($fmt, $value);
19672434
DM
2220 return $value;
2221 }
1e3baf05 2222 $value =~ s/^\"(.*)\"$/$1/;
19672434 2223 return $value;
1e3baf05
DM
2224 } else {
2225 die "internal error"
2226 }
2227}
2228
1e3baf05 2229sub destroy_vm {
75854662 2230 my ($storecfg, $vmid, $skiplock, $replacement_conf, $purge_unreferenced) = @_;
1e3baf05 2231
ffda963f 2232 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2233
ffda963f 2234 PVE::QemuConfig->check_lock($conf) if !$skiplock;
1e3baf05 2235
5e67a2d2
DC
2236 if ($conf->{template}) {
2237 # check if any base image is still used by a linked clone
3ab0f925 2238 PVE::QemuConfig->foreach_volume_full($conf, { include_unused => 1 }, sub {
5e67a2d2 2239 my ($ds, $drive) = @_;
5e67a2d2
DC
2240 return if drive_is_cdrom($drive);
2241
2242 my $volid = $drive->{file};
5e67a2d2
DC
2243 return if !$volid || $volid =~ m|^/|;
2244
2245 die "base volume '$volid' is still in use by linked cloned\n"
2246 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
2247
2248 });
2249 }
2250
3e07c6d5 2251 my $volids = {};
ba1a1984 2252 my $remove_owned_drive = sub {
1e3baf05 2253 my ($ds, $drive) = @_;
9c52f5ed 2254 return if drive_is_cdrom($drive, 1);
1e3baf05
DM
2255
2256 my $volid = $drive->{file};
ff1a2432 2257 return if !$volid || $volid =~ m|^/|;
3e07c6d5 2258 return if $volids->{$volid};
1e3baf05 2259
6b64503e 2260 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
ff1a2432 2261 return if !$path || !$owner || ($owner != $vmid);
1e3baf05 2262
3e07c6d5 2263 $volids->{$volid} = 1;
a2f50f01 2264 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
31b52247 2265 warn "Could not remove disk '$volid', check manually: $@" if $@;
ba1a1984
FE
2266 };
2267
2268 # only remove disks owned by this VM (referenced in the config)
2269 my $include_opts = {
2270 include_unused => 1,
2271 extra_keys => ['vmstate'],
2272 };
2273 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $remove_owned_drive);
2274
2275 for my $snap (values %{$conf->{snapshots}}) {
2276 next if !defined($snap->{vmstate});
2277 my $drive = PVE::QemuConfig->parse_volume('vmstate', $snap->{vmstate}, 1);
2278 next if !defined($drive);
2279 $remove_owned_drive->('vmstate', $drive);
2280 }
19672434 2281
3e07c6d5
FG
2282 PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $remove_owned_drive);
2283
75854662 2284 if ($purge_unreferenced) { # also remove unreferenced disk
d0ff75d9 2285 my $vmdisks = PVE::Storage::vdisk_list($storecfg, undef, $vmid, undef, 'images');
75854662
TL
2286 PVE::Storage::foreach_volid($vmdisks, sub {
2287 my ($volid, $sid, $volname, $d) = @_;
2288 eval { PVE::Storage::vdisk_free($storecfg, $volid) };
2289 warn $@ if $@;
2290 });
2291 }
dfda979e 2292
b04ea584 2293 if (defined $replacement_conf) {
8baf8bc7 2294 PVE::QemuConfig->write_config($vmid, $replacement_conf);
dfda979e
DJ
2295 } else {
2296 PVE::QemuConfig->destroy_config($vmid);
2297 }
1e3baf05
DM
2298}
2299
1e3baf05
DM
2300sub parse_vm_config {
2301 my ($filename, $raw) = @_;
2302
d1c1af4b 2303 return if !defined($raw);
1e3baf05 2304
554ac7e7 2305 my $res = {
fc1ddcdc 2306 digest => Digest::SHA::sha1_hex($raw),
0d18dcfc 2307 snapshots => {},
0d732d16 2308 pending => {},
554ac7e7 2309 };
1e3baf05 2310
19672434 2311 $filename =~ m|/qemu-server/(\d+)\.conf$|
1e3baf05
DM
2312 || die "got strange filename '$filename'";
2313
2314 my $vmid = $1;
2315
0d18dcfc 2316 my $conf = $res;
b0ec896e 2317 my $descr;
e297c490 2318 my $section = '';
0581fe4f 2319
0d18dcfc
DM
2320 my @lines = split(/\n/, $raw);
2321 foreach my $line (@lines) {
1e3baf05 2322 next if $line =~ m/^\s*$/;
be190583 2323
eab09f4e 2324 if ($line =~ m/^\[PENDING\]\s*$/i) {
e297c490 2325 $section = 'pending';
b0ec896e
DM
2326 if (defined($descr)) {
2327 $descr =~ s/\s+$//;
2328 $conf->{description} = $descr;
2329 }
2330 $descr = undef;
e297c490 2331 $conf = $res->{$section} = {};
eab09f4e
AD
2332 next;
2333
0d732d16 2334 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
e297c490 2335 $section = $1;
b0ec896e
DM
2336 if (defined($descr)) {
2337 $descr =~ s/\s+$//;
2338 $conf->{description} = $descr;
2339 }
2340 $descr = undef;
e297c490 2341 $conf = $res->{snapshots}->{$section} = {};
0d18dcfc
DM
2342 next;
2343 }
1e3baf05 2344
0581fe4f 2345 if ($line =~ m/^\#(.*)\s*$/) {
b0ec896e 2346 $descr = '' if !defined($descr);
0581fe4f
DM
2347 $descr .= PVE::Tools::decode_text($1) . "\n";
2348 next;
2349 }
2350
1e3baf05 2351 if ($line =~ m/^(description):\s*(.*\S)\s*$/) {
b0ec896e 2352 $descr = '' if !defined($descr);
0581fe4f 2353 $descr .= PVE::Tools::decode_text($2);
0d18dcfc
DM
2354 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
2355 $conf->{snapstate} = $1;
1e3baf05
DM
2356 } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) {
2357 my $key = $1;
2358 my $value = $2;
0d18dcfc 2359 $conf->{$key} = $value;
ef824322 2360 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
e297c490 2361 my $value = $1;
ef824322
DM
2362 if ($section eq 'pending') {
2363 $conf->{delete} = $value; # we parse this later
2364 } else {
2365 warn "vm $vmid - propertry 'delete' is only allowed in [PENDING]\n";
eab09f4e 2366 }
15cf7698 2367 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(.+?)\s*$/) {
1e3baf05
DM
2368 my $key = $1;
2369 my $value = $2;
2370 eval { $value = check_type($key, $value); };
2371 if ($@) {
2372 warn "vm $vmid - unable to parse value of '$key' - $@";
2373 } else {
b799312f 2374 $key = 'ide2' if $key eq 'cdrom';
1e3baf05 2375 my $fmt = $confdesc->{$key}->{format};
b799312f 2376 if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) {
1e3baf05
DM
2377 my $v = parse_drive($key, $value);
2378 if (my $volid = filename_to_volume_id($vmid, $v->{file}, $v->{media})) {
2379 $v->{file} = $volid;
71c58bb7 2380 $value = print_drive($v);
1e3baf05
DM
2381 } else {
2382 warn "vm $vmid - unable to parse value of '$key'\n";
2383 next;
2384 }
2385 }
2386
b799312f 2387 $conf->{$key} = $value;
1e3baf05 2388 }
f8d2a1ce
FE
2389 } else {
2390 warn "vm $vmid - unable to parse config: $line\n";
1e3baf05
DM
2391 }
2392 }
2393
b0ec896e
DM
2394 if (defined($descr)) {
2395 $descr =~ s/\s+$//;
2396 $conf->{description} = $descr;
2397 }
0d18dcfc 2398 delete $res->{snapstate}; # just to be sure
1e3baf05
DM
2399
2400 return $res;
2401}
2402
1858638f
DM
2403sub write_vm_config {
2404 my ($filename, $conf) = @_;
1e3baf05 2405
0d18dcfc
DM
2406 delete $conf->{snapstate}; # just to be sure
2407
1858638f
DM
2408 if ($conf->{cdrom}) {
2409 die "option ide2 conflicts with cdrom\n" if $conf->{ide2};
2410 $conf->{ide2} = $conf->{cdrom};
2411 delete $conf->{cdrom};
2412 }
1e3baf05
DM
2413
2414 # we do not use 'smp' any longer
1858638f
DM
2415 if ($conf->{sockets}) {
2416 delete $conf->{smp};
2417 } elsif ($conf->{smp}) {
2418 $conf->{sockets} = $conf->{smp};
2419 delete $conf->{cores};
2420 delete $conf->{smp};
1e3baf05
DM
2421 }
2422
ee2f90b1 2423 my $used_volids = {};
0d18dcfc 2424
ee2f90b1 2425 my $cleanup_config = sub {
ef824322 2426 my ($cref, $pending, $snapname) = @_;
1858638f 2427
ee2f90b1
DM
2428 foreach my $key (keys %$cref) {
2429 next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' ||
ef824322 2430 $key eq 'snapstate' || $key eq 'pending';
ee2f90b1 2431 my $value = $cref->{$key};
ef824322
DM
2432 if ($key eq 'delete') {
2433 die "propertry 'delete' is only allowed in [PENDING]\n"
2434 if !$pending;
2435 # fixme: check syntax?
2436 next;
2437 }
ee2f90b1
DM
2438 eval { $value = check_type($key, $value); };
2439 die "unable to parse value of '$key' - $@" if $@;
1858638f 2440
ee2f90b1
DM
2441 $cref->{$key} = $value;
2442
74479ee9 2443 if (!$snapname && is_valid_drivename($key)) {
ed221350 2444 my $drive = parse_drive($key, $value);
ee2f90b1
DM
2445 $used_volids->{$drive->{file}} = 1 if $drive && $drive->{file};
2446 }
1e3baf05 2447 }
ee2f90b1
DM
2448 };
2449
2450 &$cleanup_config($conf);
ef824322
DM
2451
2452 &$cleanup_config($conf->{pending}, 1);
2453
ee2f90b1 2454 foreach my $snapname (keys %{$conf->{snapshots}}) {
15c6e277 2455 die "internal error: snapshot name '$snapname' is forbidden" if lc($snapname) eq 'pending';
ef824322 2456 &$cleanup_config($conf->{snapshots}->{$snapname}, undef, $snapname);
1e3baf05
DM
2457 }
2458
1858638f
DM
2459 # remove 'unusedX' settings if we re-add a volume
2460 foreach my $key (keys %$conf) {
2461 my $value = $conf->{$key};
ee2f90b1 2462 if ($key =~ m/^unused/ && $used_volids->{$value}) {
1858638f 2463 delete $conf->{$key};
1e3baf05 2464 }
1858638f 2465 }
be190583 2466
0d18dcfc 2467 my $generate_raw_config = sub {
b0ec896e 2468 my ($conf, $pending) = @_;
0581fe4f 2469
0d18dcfc
DM
2470 my $raw = '';
2471
2472 # add description as comment to top of file
b0ec896e
DM
2473 if (defined(my $descr = $conf->{description})) {
2474 if ($descr) {
2475 foreach my $cl (split(/\n/, $descr)) {
2476 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
2477 }
2478 } else {
2479 $raw .= "#\n" if $pending;
2480 }
0d18dcfc
DM
2481 }
2482
2483 foreach my $key (sort keys %$conf) {
4df98f2f 2484 next if $key =~ /^(digest|description|pending|snapshots)$/;
0d18dcfc
DM
2485 $raw .= "$key: $conf->{$key}\n";
2486 }
2487 return $raw;
2488 };
0581fe4f 2489
0d18dcfc 2490 my $raw = &$generate_raw_config($conf);
ef824322
DM
2491
2492 if (scalar(keys %{$conf->{pending}})){
2493 $raw .= "\n[PENDING]\n";
b0ec896e 2494 $raw .= &$generate_raw_config($conf->{pending}, 1);
ef824322
DM
2495 }
2496
0d18dcfc
DM
2497 foreach my $snapname (sort keys %{$conf->{snapshots}}) {
2498 $raw .= "\n[$snapname]\n";
2499 $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname});
1858638f 2500 }
1e3baf05 2501
1858638f
DM
2502 return $raw;
2503}
1e3baf05 2504
19672434 2505sub load_defaults {
1e3baf05
DM
2506
2507 my $res = {};
2508
2509 # we use static defaults from our JSON schema configuration
2510 foreach my $key (keys %$confdesc) {
2511 if (defined(my $default = $confdesc->{$key}->{default})) {
2512 $res->{$key} = $default;
2513 }
2514 }
19672434 2515
1e3baf05
DM
2516 return $res;
2517}
2518
2519sub config_list {
2520 my $vmlist = PVE::Cluster::get_vmlist();
2521 my $res = {};
2522 return $res if !$vmlist || !$vmlist->{ids};
2523 my $ids = $vmlist->{ids};
38277afc 2524 my $nodename = nodename();
1e3baf05 2525
1e3baf05
DM
2526 foreach my $vmid (keys %$ids) {
2527 my $d = $ids->{$vmid};
2528 next if !$d->{node} || $d->{node} ne $nodename;
5ee957cc 2529 next if !$d->{type} || $d->{type} ne 'qemu';
1e3baf05
DM
2530 $res->{$vmid}->{exists} = 1;
2531 }
2532 return $res;
2533}
2534
64e13401
DM
2535# test if VM uses local resources (to prevent migration)
2536sub check_local_resources {
2537 my ($conf, $noerr) = @_;
2538
ca6abacf 2539 my @loc_res = ();
19672434 2540
ca6abacf
TM
2541 push @loc_res, "hostusb" if $conf->{hostusb}; # old syntax
2542 push @loc_res, "hostpci" if $conf->{hostpci}; # old syntax
64e13401 2543
ca6abacf 2544 push @loc_res, "ivshmem" if $conf->{ivshmem};
6dbcb073 2545
0d29ab3b 2546 foreach my $k (keys %$conf) {
a9ce7583 2547 next if $k =~ m/^usb/ && ($conf->{$k} =~ m/^spice(?![^,])/);
d44712fc
EK
2548 # sockets are safe: they will recreated be on the target side post-migrate
2549 next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket');
ca6abacf 2550 push @loc_res, $k if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/;
64e13401
DM
2551 }
2552
ca6abacf 2553 die "VM uses local resources\n" if scalar @loc_res && !$noerr;
64e13401 2554
ca6abacf 2555 return \@loc_res;
64e13401
DM
2556}
2557
719893a9 2558# check if used storages are available on all nodes (use by migrate)
47152e2e
DM
2559sub check_storage_availability {
2560 my ($storecfg, $conf, $node) = @_;
2561
912792e2 2562 PVE::QemuConfig->foreach_volume($conf, sub {
47152e2e
DM
2563 my ($ds, $drive) = @_;
2564
2565 my $volid = $drive->{file};
2566 return if !$volid;
2567
2568 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2569 return if !$sid;
2570
2571 # check if storage is available on both nodes
0d2db084
FE
2572 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
2573 PVE::Storage::storage_check_enabled($storecfg, $sid, $node);
24b84b47 2574
3148f0b0
TL
2575 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
2576
2577 die "$volid: content type '$vtype' is not available on storage '$sid'\n"
2578 if !$scfg->{content}->{$vtype};
47152e2e
DM
2579 });
2580}
2581
719893a9
DM
2582# list nodes where all VM images are available (used by has_feature API)
2583sub shared_nodes {
2584 my ($conf, $storecfg) = @_;
2585
2586 my $nodelist = PVE::Cluster::get_nodelist();
2587 my $nodehash = { map { $_ => 1 } @$nodelist };
38277afc 2588 my $nodename = nodename();
be190583 2589
912792e2 2590 PVE::QemuConfig->foreach_volume($conf, sub {
719893a9
DM
2591 my ($ds, $drive) = @_;
2592
2593 my $volid = $drive->{file};
2594 return if !$volid;
2595
2596 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2597 if ($storeid) {
2598 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2599 if ($scfg->{disable}) {
2600 $nodehash = {};
2601 } elsif (my $avail = $scfg->{nodes}) {
2602 foreach my $node (keys %$nodehash) {
2603 delete $nodehash->{$node} if !$avail->{$node};
2604 }
2605 } elsif (!$scfg->{shared}) {
2606 foreach my $node (keys %$nodehash) {
2607 delete $nodehash->{$node} if $node ne $nodename
2608 }
2609 }
2610 }
2611 });
2612
2613 return $nodehash
2614}
2615
f25852c2
TM
2616sub check_local_storage_availability {
2617 my ($conf, $storecfg) = @_;
2618
2619 my $nodelist = PVE::Cluster::get_nodelist();
2620 my $nodehash = { map { $_ => {} } @$nodelist };
2621
912792e2 2622 PVE::QemuConfig->foreach_volume($conf, sub {
f25852c2
TM
2623 my ($ds, $drive) = @_;
2624
2625 my $volid = $drive->{file};
2626 return if !$volid;
2627
2628 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2629 if ($storeid) {
2630 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
2631
2632 if ($scfg->{disable}) {
2633 foreach my $node (keys %$nodehash) {
32075a2c 2634 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2635 }
2636 } elsif (my $avail = $scfg->{nodes}) {
2637 foreach my $node (keys %$nodehash) {
2638 if (!$avail->{$node}) {
32075a2c 2639 $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1;
f25852c2
TM
2640 }
2641 }
2642 }
2643 }
2644 });
2645
32075a2c
TL
2646 foreach my $node (values %$nodehash) {
2647 if (my $unavail = $node->{unavailable_storages}) {
2648 $node->{unavailable_storages} = [ sort keys %$unavail ];
2649 }
2650 }
2651
f25852c2
TM
2652 return $nodehash
2653}
2654
babf613a 2655# Compat only, use assert_config_exists_on_node and vm_running_locally where possible
1e3baf05 2656sub check_running {
7e8dcf2c 2657 my ($vmid, $nocheck, $node) = @_;
1e3baf05 2658
babf613a
SR
2659 PVE::QemuConfig::assert_config_exists_on_node($vmid, $node) if !$nocheck;
2660 return PVE::QemuServer::Helpers::vm_running_locally($vmid);
1e3baf05
DM
2661}
2662
2663sub vzlist {
19672434 2664
1e3baf05
DM
2665 my $vzlist = config_list();
2666
d036e418 2667 my $fd = IO::Dir->new($PVE::QemuServer::Helpers::var_run_tmpdir) || return $vzlist;
1e3baf05 2668
19672434 2669 while (defined(my $de = $fd->read)) {
1e3baf05
DM
2670 next if $de !~ m/^(\d+)\.pid$/;
2671 my $vmid = $1;
6b64503e
DM
2672 next if !defined($vzlist->{$vmid});
2673 if (my $pid = check_running($vmid)) {
1e3baf05
DM
2674 $vzlist->{$vmid}->{pid} = $pid;
2675 }
2676 }
2677
2678 return $vzlist;
2679}
2680
b1a70cab
DM
2681our $vmstatus_return_properties = {
2682 vmid => get_standard_option('pve-vmid'),
2683 status => {
2684 description => "Qemu process status.",
2685 type => 'string',
2686 enum => ['stopped', 'running'],
2687 },
2688 maxmem => {
2689 description => "Maximum memory in bytes.",
2690 type => 'integer',
2691 optional => 1,
2692 renderer => 'bytes',
2693 },
2694 maxdisk => {
2695 description => "Root disk size in bytes.",
2696 type => 'integer',
2697 optional => 1,
2698 renderer => 'bytes',
2699 },
2700 name => {
2701 description => "VM name.",
2702 type => 'string',
2703 optional => 1,
2704 },
2705 qmpstatus => {
2706 description => "Qemu QMP agent status.",
2707 type => 'string',
2708 optional => 1,
2709 },
2710 pid => {
2711 description => "PID of running qemu process.",
2712 type => 'integer',
2713 optional => 1,
2714 },
2715 uptime => {
2716 description => "Uptime.",
2717 type => 'integer',
2718 optional => 1,
2719 renderer => 'duration',
2720 },
2721 cpus => {
2722 description => "Maximum usable CPUs.",
2723 type => 'number',
2724 optional => 1,
2725 },
e6ed61b4 2726 lock => {
11efdfa5 2727 description => "The current config lock, if any.",
e6ed61b4
DC
2728 type => 'string',
2729 optional => 1,
b8e7068a
DC
2730 },
2731 tags => {
2732 description => "The current configured tags, if any",
2733 type => 'string',
2734 optional => 1,
2735 },
949112c3
FE
2736 'running-machine' => {
2737 description => "The currently running machine type (if running).",
2738 type => 'string',
2739 optional => 1,
2740 },
2741 'running-qemu' => {
2742 description => "The currently running QEMU version (if running).",
2743 type => 'string',
2744 optional => 1,
2745 },
b1a70cab
DM
2746};
2747
1e3baf05
DM
2748my $last_proc_pid_stat;
2749
03a33f30
DM
2750# get VM status information
2751# This must be fast and should not block ($full == false)
2752# We only query KVM using QMP if $full == true (this can be slow)
1e3baf05 2753sub vmstatus {
03a33f30 2754 my ($opt_vmid, $full) = @_;
1e3baf05
DM
2755
2756 my $res = {};
2757
19672434 2758 my $storecfg = PVE::Storage::config();
1e3baf05
DM
2759
2760 my $list = vzlist();
3618ee99
EK
2761 my $defaults = load_defaults();
2762
694fcad4 2763 my ($uptime) = PVE::ProcFSTools::read_proc_uptime(1);
1e3baf05 2764
ae4915a2
DM
2765 my $cpucount = $cpuinfo->{cpus} || 1;
2766
1e3baf05
DM
2767 foreach my $vmid (keys %$list) {
2768 next if $opt_vmid && ($vmid ne $opt_vmid);
2769
9f78b695 2770 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 2771
ad2cad72 2772 my $d = { vmid => int($vmid) };
8a0addab 2773 $d->{pid} = int($list->{$vmid}->{pid}) if $list->{$vmid}->{pid};
1e3baf05
DM
2774
2775 # fixme: better status?
2776 $d->{status} = $list->{$vmid}->{pid} ? 'running' : 'stopped';
2777
776c5f50 2778 my $size = PVE::QemuServer::Drive::bootdisk_size($storecfg, $conf);
af990afe
DM
2779 if (defined($size)) {
2780 $d->{disk} = 0; # no info available
1e3baf05
DM
2781 $d->{maxdisk} = $size;
2782 } else {
2783 $d->{disk} = 0;
2784 $d->{maxdisk} = 0;
2785 }
2786
3618ee99
EK
2787 $d->{cpus} = ($conf->{sockets} || $defaults->{sockets})
2788 * ($conf->{cores} || $defaults->{cores});
ae4915a2 2789 $d->{cpus} = $cpucount if $d->{cpus} > $cpucount;
d7c8364b 2790 $d->{cpus} = $conf->{vcpus} if $conf->{vcpus};
ae4915a2 2791
1e3baf05 2792 $d->{name} = $conf->{name} || "VM $vmid";
3618ee99
EK
2793 $d->{maxmem} = $conf->{memory} ? $conf->{memory}*(1024*1024)
2794 : $defaults->{memory}*(1024*1024);
1e3baf05 2795
8b1accf7 2796 if ($conf->{balloon}) {
4bdb0514 2797 $d->{balloon_min} = $conf->{balloon}*(1024*1024);
3618ee99
EK
2798 $d->{shares} = defined($conf->{shares}) ? $conf->{shares}
2799 : $defaults->{shares};
8b1accf7
DM
2800 }
2801
1e3baf05
DM
2802 $d->{uptime} = 0;
2803 $d->{cpu} = 0;
1e3baf05
DM
2804 $d->{mem} = 0;
2805
2806 $d->{netout} = 0;
2807 $d->{netin} = 0;
2808
2809 $d->{diskread} = 0;
2810 $d->{diskwrite} = 0;
2811
75a2a423 2812 $d->{template} = 1 if PVE::QemuConfig->is_template($conf);
4d8c851b 2813
8107b378 2814 $d->{serial} = 1 if conf_has_serial($conf);
e6ed61b4 2815 $d->{lock} = $conf->{lock} if $conf->{lock};
b8e7068a 2816 $d->{tags} = $conf->{tags} if defined($conf->{tags});
8107b378 2817
1e3baf05
DM
2818 $res->{$vmid} = $d;
2819 }
2820
2821 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
2822 foreach my $dev (keys %$netdev) {
2823 next if $dev !~ m/^tap([1-9]\d*)i/;
2824 my $vmid = $1;
2825 my $d = $res->{$vmid};
2826 next if !$d;
19672434 2827
1e3baf05
DM
2828 $d->{netout} += $netdev->{$dev}->{receive};
2829 $d->{netin} += $netdev->{$dev}->{transmit};
604ea644
AD
2830
2831 if ($full) {
ad2cad72
FE
2832 $d->{nics}->{$dev}->{netout} = int($netdev->{$dev}->{receive});
2833 $d->{nics}->{$dev}->{netin} = int($netdev->{$dev}->{transmit});
604ea644
AD
2834 }
2835
1e3baf05
DM
2836 }
2837
1e3baf05
DM
2838 my $ctime = gettimeofday;
2839
2840 foreach my $vmid (keys %$list) {
2841
2842 my $d = $res->{$vmid};
2843 my $pid = $d->{pid};
2844 next if !$pid;
2845
694fcad4
DM
2846 my $pstat = PVE::ProcFSTools::read_proc_pid_stat($pid);
2847 next if !$pstat; # not running
19672434 2848
694fcad4 2849 my $used = $pstat->{utime} + $pstat->{stime};
1e3baf05 2850
694fcad4 2851 $d->{uptime} = int(($uptime - $pstat->{starttime})/$cpuinfo->{user_hz});
1e3baf05 2852
694fcad4 2853 if ($pstat->{vsize}) {
6b64503e 2854 $d->{mem} = int(($pstat->{rss}/$pstat->{vsize})*$d->{maxmem});
1e3baf05
DM
2855 }
2856
2857 my $old = $last_proc_pid_stat->{$pid};
2858 if (!$old) {
19672434
DM
2859 $last_proc_pid_stat->{$pid} = {
2860 time => $ctime,
1e3baf05
DM
2861 used => $used,
2862 cpu => 0,
1e3baf05
DM
2863 };
2864 next;
2865 }
2866
7f0b5beb 2867 my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
1e3baf05
DM
2868
2869 if ($dtime > 1000) {
2870 my $dutime = $used - $old->{used};
2871
ae4915a2 2872 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
1e3baf05 2873 $last_proc_pid_stat->{$pid} = {
19672434 2874 time => $ctime,
1e3baf05
DM
2875 used => $used,
2876 cpu => $d->{cpu},
1e3baf05
DM
2877 };
2878 } else {
2879 $d->{cpu} = $old->{cpu};
1e3baf05
DM
2880 }
2881 }
2882
f5eb281a 2883 return $res if !$full;
03a33f30
DM
2884
2885 my $qmpclient = PVE::QMPClient->new();
2886
64e7fcf2
DM
2887 my $ballooncb = sub {
2888 my ($vmid, $resp) = @_;
2889
2890 my $info = $resp->{'return'};
38babf81
DM
2891 return if !$info->{max_mem};
2892
64e7fcf2
DM
2893 my $d = $res->{$vmid};
2894
38babf81
DM
2895 # use memory assigned to VM
2896 $d->{maxmem} = $info->{max_mem};
2897 $d->{balloon} = $info->{actual};
2898
2899 if (defined($info->{total_mem}) && defined($info->{free_mem})) {
2900 $d->{mem} = $info->{total_mem} - $info->{free_mem};
2901 $d->{freemem} = $info->{free_mem};
64e7fcf2
DM
2902 }
2903
604ea644 2904 $d->{ballooninfo} = $info;
64e7fcf2
DM
2905 };
2906
03a33f30
DM
2907 my $blockstatscb = sub {
2908 my ($vmid, $resp) = @_;
2909 my $data = $resp->{'return'} || [];
2910 my $totalrdbytes = 0;
2911 my $totalwrbytes = 0;
604ea644 2912
03a33f30
DM
2913 for my $blockstat (@$data) {
2914 $totalrdbytes = $totalrdbytes + $blockstat->{stats}->{rd_bytes};
2915 $totalwrbytes = $totalwrbytes + $blockstat->{stats}->{wr_bytes};
604ea644
AD
2916
2917 $blockstat->{device} =~ s/drive-//;
2918 $res->{$vmid}->{blockstat}->{$blockstat->{device}} = $blockstat->{stats};
03a33f30
DM
2919 }
2920 $res->{$vmid}->{diskread} = $totalrdbytes;
2921 $res->{$vmid}->{diskwrite} = $totalwrbytes;
2922 };
2923
949112c3
FE
2924 my $machinecb = sub {
2925 my ($vmid, $resp) = @_;
2926 my $data = $resp->{'return'} || [];
2927
2928 $res->{$vmid}->{'running-machine'} =
2929 PVE::QemuServer::Machine::current_from_query_machines($data);
2930 };
2931
2932 my $versioncb = sub {
2933 my ($vmid, $resp) = @_;
2934 my $data = $resp->{'return'} // {};
2935 my $version = 'unknown';
2936
2937 if (my $v = $data->{qemu}) {
2938 $version = $v->{major} . "." . $v->{minor} . "." . $v->{micro};
2939 }
2940
2941 $res->{$vmid}->{'running-qemu'} = $version;
2942 };
2943
03a33f30
DM
2944 my $statuscb = sub {
2945 my ($vmid, $resp) = @_;
64e7fcf2 2946
03a33f30 2947 $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats');
949112c3
FE
2948 $qmpclient->queue_cmd($vmid, $machinecb, 'query-machines');
2949 $qmpclient->queue_cmd($vmid, $versioncb, 'query-version');
64e7fcf2
DM
2950 # this fails if ballon driver is not loaded, so this must be
2951 # the last commnand (following command are aborted if this fails).
38babf81 2952 $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon');
03a33f30
DM
2953
2954 my $status = 'unknown';
2955 if (!defined($status = $resp->{'return'}->{status})) {
2956 warn "unable to get VM status\n";
2957 return;
2958 }
2959
2960 $res->{$vmid}->{qmpstatus} = $resp->{'return'}->{status};
2961 };
2962
2963 foreach my $vmid (keys %$list) {
2964 next if $opt_vmid && ($vmid ne $opt_vmid);
2965 next if !$res->{$vmid}->{pid}; # not running
2966 $qmpclient->queue_cmd($vmid, $statuscb, 'query-status');
2967 }
2968
b017fbda 2969 $qmpclient->queue_execute(undef, 2);
03a33f30 2970
6891fd70
SR
2971 foreach my $vmid (keys %$list) {
2972 next if $opt_vmid && ($vmid ne $opt_vmid);
e5b18771
FG
2973 next if !$res->{$vmid}->{pid}; #not running
2974
6891fd70
SR
2975 # we can't use the $qmpclient since it might have already aborted on
2976 # 'query-balloon', but this might also fail for older versions...
2977 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
2978 $res->{$vmid}->{'proxmox-support'} = $qemu_support // {};
2979 }
2980
03a33f30
DM
2981 foreach my $vmid (keys %$list) {
2982 next if $opt_vmid && ($vmid ne $opt_vmid);
2983 $res->{$vmid}->{qmpstatus} = $res->{$vmid}->{status} if !$res->{$vmid}->{qmpstatus};
2984 }
2985
1e3baf05
DM
2986 return $res;
2987}
2988
8107b378
DC
2989sub conf_has_serial {
2990 my ($conf) = @_;
2991
2992 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
2993 if ($conf->{"serial$i"}) {
2994 return 1;
2995 }
2996 }
2997
2998 return 0;
2999}
3000
d5535a00
TL
3001sub conf_has_audio {
3002 my ($conf, $id) = @_;
3003
3004 $id //= 0;
3005 my $audio = $conf->{"audio$id"};
d1c1af4b 3006 return if !defined($audio);
d5535a00 3007
4df98f2f 3008 my $audioproperties = parse_property_string($audio_fmt, $audio);
d5535a00
TL
3009 my $audiodriver = $audioproperties->{driver} // 'spice';
3010
3011 return {
3012 dev => $audioproperties->{device},
b0f96836 3013 dev_id => "audiodev$id",
d5535a00
TL
3014 backend => $audiodriver,
3015 backend_id => "$audiodriver-backend${id}",
3016 };
3017}
3018
b01de199 3019sub audio_devs {
1cc5ed1b 3020 my ($audio, $audiopciaddr, $machine_version) = @_;
b01de199
TL
3021
3022 my $devs = [];
3023
3024 my $id = $audio->{dev_id};
1cc5ed1b
AL
3025 my $audiodev = "";
3026 if (min_version($machine_version, 4, 2)) {
3027 $audiodev = ",audiodev=$audio->{backend_id}";
3028 }
b01de199
TL
3029
3030 if ($audio->{dev} eq 'AC97') {
1cc5ed1b 3031 push @$devs, '-device', "AC97,id=${id}${audiopciaddr}$audiodev";
b01de199
TL
3032 } elsif ($audio->{dev} =~ /intel\-hda$/) {
3033 push @$devs, '-device', "$audio->{dev},id=${id}${audiopciaddr}";
1cc5ed1b
AL
3034 push @$devs, '-device', "hda-micro,id=${id}-codec0,bus=${id}.0,cad=0$audiodev";
3035 push @$devs, '-device', "hda-duplex,id=${id}-codec1,bus=${id}.0,cad=1$audiodev";
b01de199
TL
3036 } else {
3037 die "unkown audio device '$audio->{dev}', implement me!";
3038 }
3039
3040 push @$devs, '-audiodev', "$audio->{backend},id=$audio->{backend_id}";
3041
3042 return $devs;
3043}
3044
f9dde219
SR
3045sub get_tpm_paths {
3046 my ($vmid) = @_;
3047 return {
3048 socket => "/var/run/qemu-server/$vmid.swtpm",
3049 pid => "/var/run/qemu-server/$vmid.swtpm.pid",
3050 };
3051}
3052
3053sub add_tpm_device {
3054 my ($vmid, $devices, $conf) = @_;
3055
3056 return if !$conf->{tpmstate0};
3057
3058 my $paths = get_tpm_paths($vmid);
3059
3060 push @$devices, "-chardev", "socket,id=tpmchar,path=$paths->{socket}";
3061 push @$devices, "-tpmdev", "emulator,id=tpmdev,chardev=tpmchar";
3062 push @$devices, "-device", "tpm-tis,tpmdev=tpmdev";
3063}
3064
3065sub start_swtpm {
3066 my ($storecfg, $vmid, $tpmdrive, $migration) = @_;
3067
3068 return if !$tpmdrive;
3069
3070 my $state;
3071 my $tpm = parse_drive("tpmstate0", $tpmdrive);
3072 my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1);
3073 if ($storeid) {
3074 $state = PVE::Storage::map_volume($storecfg, $tpm->{file});
3075 } else {
3076 $state = $tpm->{file};
3077 }
3078
3079 my $paths = get_tpm_paths($vmid);
3080
3081 # during migration, we will get state from remote
3082 #
3083 if (!$migration) {
3084 # run swtpm_setup to create a new TPM state if it doesn't exist yet
3085 my $setup_cmd = [
3086 "swtpm_setup",
3087 "--tpmstate",
3088 "file://$state",
3089 "--createek",
3090 "--create-ek-cert",
3091 "--create-platform-cert",
3092 "--lock-nvram",
3093 "--config",
3094 "/etc/swtpm_setup.conf", # do not use XDG configs
3095 "--runas",
3096 "0", # force creation as root, error if not possible
3097 "--not-overwrite", # ignore existing state, do not modify
3098 ];
3099
3100 push @$setup_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3101 # TPM 2.0 supports ECC crypto, use if possible
3102 push @$setup_cmd, "--ecc" if $tpm->{version} eq 'v2.0';
3103
3104 run_command($setup_cmd, outfunc => sub {
3105 print "swtpm_setup: $1\n";
3106 });
3107 }
3108
3109 my $emulator_cmd = [
3110 "swtpm",
3111 "socket",
3112 "--tpmstate",
3113 "backend-uri=file://$state,mode=0600",
3114 "--ctrl",
3115 "type=unixio,path=$paths->{socket},mode=0600",
3116 "--pid",
3117 "file=$paths->{pid}",
3118 "--terminate", # terminate on QEMU disconnect
3119 "--daemon",
3120 ];
3121 push @$emulator_cmd, "--tpm2" if $tpm->{version} eq 'v2.0';
3122 run_command($emulator_cmd, outfunc => sub { print $1; });
3123
6bbcd71f 3124 my $tries = 100; # swtpm may take a bit to start before daemonizing, wait up to 5s for pid
f85951dc 3125 while (! -e $paths->{pid}) {
90c41bac 3126 die "failed to start swtpm: pid file '$paths->{pid}' wasn't created.\n" if --$tries == 0;
6bbcd71f 3127 usleep(50_000);
f85951dc
SR
3128 }
3129
f9dde219
SR
3130 # return untainted PID of swtpm daemon so it can be killed on error
3131 file_read_firstline($paths->{pid}) =~ m/(\d+)/;
3132 return $1;
3133}
3134
86b8228b
DM
3135sub vga_conf_has_spice {
3136 my ($vga) = @_;
3137
55655ebc
DC
3138 my $vgaconf = parse_vga($vga);
3139 my $vgatype = $vgaconf->{type};
3140 return 0 if !$vgatype || $vgatype !~ m/^qxl([234])?$/;
590e698c
DM
3141
3142 return $1 || 1;
86b8228b
DM
3143}
3144
d731ecbe
WB
3145sub is_native($) {
3146 my ($arch) = @_;
3147 return get_host_arch() eq $arch;
3148}
3149
045749f2
TL
3150sub get_vm_arch {
3151 my ($conf) = @_;
3152 return $conf->{arch} // get_host_arch();
3153}
3154
d731ecbe
WB
3155my $default_machines = {
3156 x86_64 => 'pc',
3157 aarch64 => 'virt',
3158};
3159
0761e619
TL
3160sub get_installed_machine_version {
3161 my ($kvmversion) = @_;
3162 $kvmversion = kvm_user_version() if !defined($kvmversion);
3163 $kvmversion =~ m/^(\d+\.\d+)/;
3164 return $1;
3165}
3166
3167sub windows_get_pinned_machine_version {
3168 my ($machine, $base_version, $kvmversion) = @_;
3169
3170 my $pin_version = $base_version;
3171 if (!defined($base_version) ||
3172 !PVE::QemuServer::Machine::can_run_pve_machine_version($base_version, $kvmversion)
3173 ) {
3174 $pin_version = get_installed_machine_version($kvmversion);
3175 }
3176 if (!$machine || $machine eq 'pc') {
3177 $machine = "pc-i440fx-$pin_version";
3178 } elsif ($machine eq 'q35') {
3179 $machine = "pc-q35-$pin_version";
3180 } elsif ($machine eq 'virt') {
3181 $machine = "virt-$pin_version";
3182 } else {
3183 warn "unknown machine type '$machine', not touching that!\n";
3184 }
3185
3186 return $machine;
3187}
3188
045749f2 3189sub get_vm_machine {
ac0077cc 3190 my ($conf, $forcemachine, $arch, $add_pve_version, $kvmversion) = @_;
045749f2
TL
3191
3192 my $machine = $forcemachine || $conf->{machine};
d731ecbe 3193
9471e48b 3194 if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) {
4dd1e83c
TL
3195 $kvmversion //= kvm_user_version();
3196 # we must pin Windows VMs without a specific version to 5.1, as 5.2 fixed a bug in ACPI
3197 # layout which confuses windows quite a bit and may result in various regressions..
3198 # see: https://lists.gnu.org/archive/html/qemu-devel/2021-02/msg08484.html
3199 if (windows_version($conf->{ostype})) {
0761e619 3200 $machine = windows_get_pinned_machine_version($machine, '5.1', $kvmversion);
4dd1e83c 3201 }
045749f2
TL
3202 $arch //= 'x86_64';
3203 $machine ||= $default_machines->{$arch};
ac0077cc 3204 if ($add_pve_version) {
ac0077cc
SR
3205 my $pvever = PVE::QemuServer::Machine::get_pve_version($kvmversion);
3206 $machine .= "+pve$pvever";
3207 }
3208 }
3209
d4be7f31
SR
3210 if ($add_pve_version && $machine !~ m/\+pve\d+?(?:\.pxe)?$/) {
3211 my $is_pxe = $machine =~ m/^(.*?)\.pxe$/;
3212 $machine = $1 if $is_pxe;
3213
ac0077cc
SR
3214 # for version-pinned machines that do not include a pve-version (e.g.
3215 # pc-q35-4.1), we assume 0 to keep them stable in case we bump
3216 $machine .= '+pve0';
d4be7f31
SR
3217
3218 $machine .= '.pxe' if $is_pxe;
045749f2
TL
3219 }
3220
3221 return $machine;
d731ecbe
WB
3222}
3223
90b20b15
DC
3224sub get_ovmf_files($$$) {
3225 my ($arch, $efidisk, $smm) = @_;
96ed3574 3226
b5099b4f 3227 my $types = $OVMF->{$arch}
96ed3574
WB
3228 or die "no OVMF images known for architecture '$arch'\n";
3229
b5099b4f
SR
3230 my $type = 'default';
3231 if (defined($efidisk->{efitype}) && $efidisk->{efitype} eq '4m') {
90b20b15
DC
3232 $type = $smm ? "4m" : "4m-no-smm";
3233 $type .= '-ms' if $efidisk->{'pre-enrolled-keys'};
b5099b4f
SR
3234 }
3235
3236 return $types->{$type}->@*;
96ed3574
WB
3237}
3238
6908fd9b
WB
3239my $Arch2Qemu = {
3240 aarch64 => '/usr/bin/qemu-system-aarch64',
3241 x86_64 => '/usr/bin/qemu-system-x86_64',
3242};
3243sub get_command_for_arch($) {
3244 my ($arch) = @_;
3245 return '/usr/bin/kvm' if is_native($arch);
3246
3247 my $cmd = $Arch2Qemu->{$arch}
3248 or die "don't know how to emulate architecture '$arch'\n";
3249 return $cmd;
3250}
3251
05a4c550
SR
3252# To use query_supported_cpu_flags and query_understood_cpu_flags to get flags
3253# to use in a QEMU command line (-cpu element), first array_intersect the result
3254# of query_supported_ with query_understood_. This is necessary because:
3255#
3256# a) query_understood_ returns flags the host cannot use and
3257# b) query_supported_ (rather the QMP call) doesn't actually return CPU
3258# flags, but CPU settings - with most of them being flags. Those settings
3259# (and some flags, curiously) cannot be specified as a "-cpu" argument.
3260#
3261# query_supported_ needs to start up to 2 temporary VMs and is therefore rather
3262# expensive. If you need the value returned from this, you can get it much
3263# cheaper from pmxcfs using PVE::Cluster::get_node_kv('cpuflags-$accel') with
3264# $accel being 'kvm' or 'tcg'.
3265#
3266# pvestatd calls this function on startup and whenever the QEMU/KVM version
3267# changes, automatically populating pmxcfs.
3268#
3269# Returns: { kvm => [ flagX, flagY, ... ], tcg => [ flag1, flag2, ... ] }
3270# since kvm and tcg machines support different flags
3271#
3272sub query_supported_cpu_flags {
52cffab6 3273 my ($arch) = @_;
05a4c550 3274
52cffab6
SR
3275 $arch //= get_host_arch();
3276 my $default_machine = $default_machines->{$arch};
3277
3278 my $flags = {};
05a4c550
SR
3279
3280 # FIXME: Once this is merged, the code below should work for ARM as well:
3281 # https://lists.nongnu.org/archive/html/qemu-devel/2019-06/msg04947.html
3282 die "QEMU/KVM cannot detect CPU flags on ARM (aarch64)\n" if
3283 $arch eq "aarch64";
3284
3285 my $kvm_supported = defined(kvm_version());
3286 my $qemu_cmd = get_command_for_arch($arch);
3287 my $fakevmid = -1;
3288 my $pidfile = PVE::QemuServer::Helpers::pidfile_name($fakevmid);
3289
3290 # Start a temporary (frozen) VM with vmid -1 to allow sending a QMP command
3291 my $query_supported_run_qemu = sub {
3292 my ($kvm) = @_;
3293
3294 my $flags = {};
3295 my $cmd = [
3296 $qemu_cmd,
3297 '-machine', $default_machine,
3298 '-display', 'none',
378ad769 3299 '-chardev', "socket,id=qmp,path=/var/run/qemu-server/$fakevmid.qmp,server=on,wait=off",
05a4c550
SR
3300 '-mon', 'chardev=qmp,mode=control',
3301 '-pidfile', $pidfile,
3302 '-S', '-daemonize'
3303 ];
3304
3305 if (!$kvm) {
3306 push @$cmd, '-accel', 'tcg';
3307 }
3308
3309 my $rc = run_command($cmd, noerr => 1, quiet => 0);
3310 die "QEMU flag querying VM exited with code " . $rc if $rc;
3311
3312 eval {
3313 my $cmd_result = mon_cmd(
3314 $fakevmid,
3315 'query-cpu-model-expansion',
3316 type => 'full',
3317 model => { name => 'host' }
3318 );
3319
3320 my $props = $cmd_result->{model}->{props};
3321 foreach my $prop (keys %$props) {
3322 next if $props->{$prop} ne '1';
3323 # QEMU returns some flags multiple times, with '_', '.' or '-'
3324 # (e.g. lahf_lm and lahf-lm; sse4.2, sse4-2 and sse4_2; ...).
3325 # We only keep those with underscores, to match /proc/cpuinfo
3326 $prop =~ s/\.|-/_/g;
3327 $flags->{$prop} = 1;
3328 }
3329 };
3330 my $err = $@;
3331
6bbcd71f 3332 # force stop with 10 sec timeout and 'nocheck', always stop, even if QMP failed
05a4c550
SR
3333 vm_stop(undef, $fakevmid, 1, 1, 10, 0, 1);
3334
3335 die $err if $err;
3336
3337 return [ sort keys %$flags ];
3338 };
3339
3340 # We need to query QEMU twice, since KVM and TCG have different supported flags
3341 PVE::QemuConfig->lock_config($fakevmid, sub {
3342 $flags->{tcg} = eval { $query_supported_run_qemu->(0) };
3343 warn "warning: failed querying supported tcg flags: $@\n" if $@;
3344
3345 if ($kvm_supported) {
3346 $flags->{kvm} = eval { $query_supported_run_qemu->(1) };
3347 warn "warning: failed querying supported kvm flags: $@\n" if $@;
3348 }
3349 });
3350
3351 return $flags;
3352}
3353
3354# Understood CPU flags are written to a file at 'pve-qemu' compile time
3355my $understood_cpu_flag_dir = "/usr/share/kvm";
3356sub query_understood_cpu_flags {
3357 my $arch = get_host_arch();
3358 my $filepath = "$understood_cpu_flag_dir/recognized-CPUID-flags-$arch";
3359
3360 die "Cannot query understood QEMU CPU flags for architecture: $arch (file not found)\n"
3361 if ! -e $filepath;
3362
3363 my $raw = file_get_contents($filepath);
3364 $raw =~ s/^\s+|\s+$//g;
3365 my @flags = split(/\s+/, $raw);
3366
3367 return \@flags;
3368}
3369
d3f9db4d
TL
3370my sub get_cpuunits {
3371 my ($conf) = @_;
3372 return $conf->{cpuunits} // (PVE::CGroup::cgroup_mode() == 2 ? 100 : 1024);
3373}
1e3baf05 3374sub config_to_command {
5921764c
SR
3375 my ($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu,
3376 $pbs_backing) = @_;
1e3baf05
DM
3377
3378 my $cmd = [];
3326ae19 3379 my ($globalFlags, $machineFlags, $rtcFlags) = ([], [], []);
5bdcf937 3380 my $devices = [];
5bdcf937 3381 my $bridges = {};
b42d3cf9 3382 my $ostype = $conf->{ostype};
4317f69f 3383 my $winversion = windows_version($ostype);
d731ecbe 3384 my $kvm = $conf->{kvm};
38277afc 3385 my $nodename = nodename();
d731ecbe 3386
045749f2 3387 my $arch = get_vm_arch($conf);
1476b99f
DC
3388 my $kvm_binary = get_command_for_arch($arch);
3389 my $kvmver = kvm_user_version($kvm_binary);
045749f2 3390
a04dd5c4
SR
3391 if (!$kvmver || $kvmver !~ m/^(\d+)\.(\d+)/ || $1 < 3) {
3392 $kvmver //= "undefined";
3393 die "Detected old QEMU binary ('$kvmver', at least 3.0 is required)\n";
3394 }
3395
9471e48b
TL
3396 my $add_pve_version = min_version($kvmver, 4, 1);
3397
3398 my $machine_type = get_vm_machine($conf, $forcemachine, $arch, $add_pve_version);
4df98f2f 3399 my $machine_version = extract_version($machine_type, $kvmver);
d731ecbe 3400 $kvm //= 1 if is_native($arch);
4317f69f 3401
a77a53ae 3402 $machine_version =~ m/(\d+)\.(\d+)/;
ac0077cc 3403 my ($machine_major, $machine_minor) = ($1, $2);
ac0077cc 3404
b516c848
SR
3405 if ($kvmver =~ m/^\d+\.\d+\.(\d+)/ && $1 >= 90) {
3406 warn "warning: Installed QEMU version ($kvmver) is a release candidate, ignoring version checks\n";
3407 } elsif (!min_version($kvmver, $machine_major, $machine_minor)) {
4df98f2f
TL
3408 die "Installed QEMU version '$kvmver' is too old to run machine type '$machine_type',"
3409 ." please upgrade node '$nodename'\n"
b516c848 3410 } elsif (!PVE::QemuServer::Machine::can_run_pve_machine_version($machine_version, $kvmver)) {
ac0077cc 3411 my $max_pve_version = PVE::QemuServer::Machine::get_pve_version($machine_version);
4df98f2f
TL
3412 die "Installed qemu-server (max feature level for $machine_major.$machine_minor is"
3413 ." pve$max_pve_version) is too old to run machine type '$machine_type', please upgrade"
3414 ." node '$nodename'\n";
ac0077cc
SR
3415 }
3416
3417 # if a specific +pve version is required for a feature, use $version_guard
3418 # instead of min_version to allow machines to be run with the minimum
3419 # required version
3420 my $required_pve_version = 0;
3421 my $version_guard = sub {
3422 my ($major, $minor, $pve) = @_;
3423 return 0 if !min_version($machine_version, $major, $minor, $pve);
47f35977
SR
3424 my $max_pve = PVE::QemuServer::Machine::get_pve_version("$major.$minor");
3425 return 1 if min_version($machine_version, $major, $minor, $max_pve+1);
ac0077cc
SR
3426 $required_pve_version = $pve if $pve && $pve > $required_pve_version;
3427 return 1;
3428 };
a77a53ae 3429
4df98f2f
TL
3430 if ($kvm && !defined kvm_version()) {
3431 die "KVM virtualisation configured, but not available. Either disable in VM configuration"
3432 ." or enable in BIOS.\n";
d731ecbe 3433 }
bfcd9b7e 3434
3392d6ca 3435 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
4d3f29ed 3436 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
249c4a6c
AD
3437 my $use_old_bios_files = undef;
3438 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
db656e5f 3439
d3f9db4d 3440 my $cpuunits = get_cpuunits($conf);
f08e17c7 3441
1476b99f 3442 push @$cmd, $kvm_binary;
1e3baf05
DM
3443
3444 push @$cmd, '-id', $vmid;
3445
e4d4cda1
HR
3446 my $vmname = $conf->{name} || "vm$vmid";
3447
3448 push @$cmd, '-name', $vmname;
3449
27b25d03
SR
3450 push @$cmd, '-no-shutdown';
3451
1e3baf05
DM
3452 my $use_virtio = 0;
3453
d036e418 3454 my $qmpsocket = PVE::QemuServer::Helpers::qmp_socket($vmid);
378ad769 3455 push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server=on,wait=off";
c971c4f2
AD
3456 push @$cmd, '-mon', "chardev=qmp,mode=control";
3457
2ea5fb7e 3458 if (min_version($machine_version, 2, 12)) {
b4496b9e 3459 push @$cmd, '-chardev', "socket,id=qmp-event,path=/var/run/qmeventd.sock,reconnect=5";
71bd73b5
DC
3460 push @$cmd, '-mon', "chardev=qmp-event,mode=control";
3461 }
1e3baf05 3462
d036e418 3463 push @$cmd, '-pidfile' , PVE::QemuServer::Helpers::pidfile_name($vmid);
19672434 3464
1e3baf05
DM
3465 push @$cmd, '-daemonize';
3466
2796e7d5 3467 if ($conf->{smbios1}) {
1f30ac3a
CE
3468 my $smbios_conf = parse_smbios1($conf->{smbios1});
3469 if ($smbios_conf->{base64}) {
3470 # Do not pass base64 flag to qemu
3471 delete $smbios_conf->{base64};
3472 my $smbios_string = "";
3473 foreach my $key (keys %$smbios_conf) {
3474 my $value;
3475 if ($key eq "uuid") {
3476 $value = $smbios_conf->{uuid}
3477 } else {
3478 $value = decode_base64($smbios_conf->{$key});
3479 }
3480 # qemu accepts any binary data, only commas need escaping by double comma
3481 $value =~ s/,/,,/g;
3482 $smbios_string .= "," . $key . "=" . $value if $value;
3483 }
3484 push @$cmd, '-smbios', "type=1" . $smbios_string;
3485 } else {
3486 push @$cmd, '-smbios', "type=1,$conf->{smbios1}";
3487 }
2796e7d5
DM
3488 }
3489
3edb45e7 3490 if ($conf->{bios} && $conf->{bios} eq 'ovmf') {
b5099b4f
SR
3491 my $d;
3492 if (my $efidisk = $conf->{efidisk0}) {
3493 $d = parse_drive('efidisk0', $efidisk);
3494 }
3495
90b20b15 3496 my ($ovmf_code, $ovmf_vars) = get_ovmf_files($arch, $d, $q35);
818c3b8d 3497 die "uefi base image '$ovmf_code' not found\n" if ! -f $ovmf_code;
2ddc0a5c 3498
818c3b8d 3499 my ($path, $format);
b4dc6475 3500 my $read_only_str = '';
b5099b4f 3501 if ($d) {
2ddc0a5c 3502 my ($storeid, $volname) = PVE::Storage::parse_volume_id($d->{file}, 1);
13bca7b4 3503 $format = $d->{format};
2ddc0a5c
DC
3504 if ($storeid) {
3505 $path = PVE::Storage::path($storecfg, $d->{file});
13bca7b4
WB
3506 if (!defined($format)) {
3507 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
3508 $format = qemu_img_format($scfg, $volname);
3509 }
2ddc0a5c
DC
3510 } else {
3511 $path = $d->{file};
13bca7b4
WB
3512 die "efidisk format must be specified\n"
3513 if !defined($format);
2ddc0a5c 3514 }
b4dc6475
FG
3515
3516 $read_only_str = ',readonly=on' if drive_is_read_only($conf, $d);
2ddc0a5c 3517 } else {
4dcce9ee
TL
3518 warn "no efidisk configured! Using temporary efivars disk.\n";
3519 $path = "/tmp/$vmid-ovmf.fd";
96ed3574 3520 PVE::Tools::file_copy($ovmf_vars, $path, -s $ovmf_vars);
13bca7b4 3521 $format = 'raw';
2ddc0a5c 3522 }
4dcce9ee 3523
818ce80e
DC
3524 my $size_str = "";
3525
3526 if ($format eq 'raw' && $version_guard->(4, 1, 2)) {
3527 $size_str = ",size=" . (-s $ovmf_vars);
3528 }
3529
738dc81c
TL
3530 # SPI flash does lots of read-modify-write OPs, without writeback this gets really slow #3329
3531 my $cache = "";
3532 if ($path =~ m/^rbd:/) {
3533 $cache = ',cache=writeback';
3534 $path .= ':rbd_cache_policy=writeback'; # avoid write-around, we *need* to cache writes too
3535 }
6aaad230 3536
378ad769 3537 push @$cmd, '-drive', "if=pflash,unit=0,format=raw,readonly=on,file=$ovmf_code";
b4dc6475 3538 push @$cmd, '-drive', "if=pflash,unit=1$cache,format=$format,id=drive-efidisk0$size_str,file=${path}${read_only_str}";
a783c78e
AD
3539 }
3540
483ceeab 3541 if ($q35) { # tell QEMU to load q35 config early
7583d156 3542 # we use different pcie-port hardware for qemu >= 4.0 for passthrough
2ea5fb7e 3543 if (min_version($machine_version, 4, 0)) {
7583d156
DC
3544 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35-4.0.cfg';
3545 } else {
3546 push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35.cfg';
3547 }
3548 }
da8b4189 3549
844d8fa6
DC
3550 if ($conf->{vmgenid}) {
3551 push @$devices, '-device', 'vmgenid,guid='.$conf->{vmgenid};
3552 }
3553
d40e5e18 3554 # add usb controllers
4df98f2f
TL
3555 my @usbcontrollers = PVE::QemuServer::USB::get_usb_controllers(
3556 $conf, $bridges, $arch, $machine_type, $usbdesc->{format}, $MAX_USB_DEVICES);
d40e5e18 3557 push @$devices, @usbcontrollers if @usbcontrollers;
55655ebc 3558 my $vga = parse_vga($conf->{vga});
2fa3151e 3559
55655ebc
DC
3560 my $qxlnum = vga_conf_has_spice($conf->{vga});
3561 $vga->{type} = 'qxl' if $qxlnum;
2fa3151e 3562
55655ebc 3563 if (!$vga->{type}) {
869ad4a7
WB
3564 if ($arch eq 'aarch64') {
3565 $vga->{type} = 'virtio';
2ea5fb7e 3566 } elsif (min_version($machine_version, 2, 9)) {
55655ebc 3567 $vga->{type} = (!$winversion || $winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3568 } else {
55655ebc 3569 $vga->{type} = ($winversion >= 6) ? 'std' : 'cirrus';
a2a5cd64 3570 }
5acbfe9e
DM
3571 }
3572
1e3baf05 3573 # enable absolute mouse coordinates (needed by vnc)
fa3b3ce0
TL
3574 my $tablet = $conf->{tablet};
3575 if (!defined($tablet)) {
5acbfe9e 3576 $tablet = $defaults->{tablet};
590e698c 3577 $tablet = 0 if $qxlnum; # disable for spice because it is not needed
55655ebc 3578 $tablet = 0 if $vga->{type} =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card)
5acbfe9e
DM
3579 }
3580
d559309f
WB
3581 if ($tablet) {
3582 push @$devices, '-device', print_tabletdevice_full($conf, $arch) if $tablet;
3583 my $kbd = print_keyboarddevice_full($conf, $arch);
3584 push @$devices, '-device', $kbd if defined($kbd);
3585 }
b467f79a 3586
e5d611c3 3587 my $bootorder = device_bootorder($conf);
2141a802 3588
74c17b7a 3589 # host pci device passthrough
13d68979 3590 my ($kvm_off, $gpu_passthrough, $legacy_igd) = PVE::QemuServer::PCI::print_hostpci_devices(
41af2dfc 3591 $vmid, $conf, $devices, $vga, $winversion, $q35, $bridges, $arch, $machine_type, $bootorder);
1e3baf05
DM
3592
3593 # usb devices
ae36393d 3594 my $usb_dev_features = {};
2ea5fb7e 3595 $usb_dev_features->{spice_usb3} = 1 if min_version($machine_version, 4, 0);
ae36393d 3596
4df98f2f 3597 my @usbdevices = PVE::QemuServer::USB::get_usb_devices(
2141a802 3598 $conf, $usbdesc->{format}, $MAX_USB_DEVICES, $usb_dev_features, $bootorder);
d40e5e18 3599 push @$devices, @usbdevices if @usbdevices;
2141a802 3600
1e3baf05 3601 # serial devices
bae179aa 3602 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
fa3b3ce0
TL
3603 my $path = $conf->{"serial$i"} or next;
3604 if ($path eq 'socket') {
3605 my $socket = "/var/run/qemu-server/${vmid}.serial$i";
3606 push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server=on,wait=off";
3607 # On aarch64, serial0 is the UART device. Qemu only allows
3608 # connecting UART devices via the '-serial' command line, as
3609 # the device has a fixed slot on the hardware...
3610 if ($arch eq 'aarch64' && $i == 0) {
3611 push @$devices, '-serial', "chardev:serial$i";
9f9d2fb2 3612 } else {
9f9d2fb2
DM
3613 push @$devices, '-device', "isa-serial,chardev=serial$i";
3614 }
fa3b3ce0
TL
3615 } else {
3616 die "no such serial device\n" if ! -c $path;
3617 push @$devices, '-chardev', "tty,id=serial$i,path=$path";
3618 push @$devices, '-device', "isa-serial,chardev=serial$i";
34978be3 3619 }
1e3baf05
DM
3620 }
3621
3622 # parallel devices
1989a89c 3623 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
34978be3 3624 if (my $path = $conf->{"parallel$i"}) {
19672434 3625 die "no such parallel device\n" if ! -c $path;
32e69805 3626 my $devtype = $path =~ m!^/dev/usb/lp! ? 'tty' : 'parport';
4c5dbaf6 3627 push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path";
5bdcf937 3628 push @$devices, '-device', "isa-parallel,chardev=parallel$i";
34978be3 3629 }
1e3baf05
DM
3630 }
3631
b01de199 3632 if (min_version($machine_version, 4, 0) && (my $audio = conf_has_audio($conf))) {
2e7b5925 3633 my $audiopciaddr = print_pci_addr("audio0", $bridges, $arch, $machine_type);
1cc5ed1b 3634 my $audio_devs = audio_devs($audio, $audiopciaddr, $machine_version);
b01de199 3635 push @$devices, @$audio_devs;
2e7b5925 3636 }
19672434 3637
f9dde219
SR
3638 add_tpm_device($vmid, $devices, $conf);
3639
1e3baf05
DM
3640 my $sockets = 1;
3641 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
3642 $sockets = $conf->{sockets} if $conf->{sockets};
3643
3644 my $cores = $conf->{cores} || 1;
3bd18e48 3645
de9d1e55 3646 my $maxcpus = $sockets * $cores;
76267728 3647
de9d1e55 3648 my $vcpus = $conf->{vcpus} ? $conf->{vcpus} : $maxcpus;
76267728 3649
de9d1e55
AD
3650 my $allowed_vcpus = $cpuinfo->{cpus};
3651
483ceeab 3652 die "MAX $allowed_vcpus vcpus allowed per VM on this node\n" if ($allowed_vcpus < $maxcpus);
1e3baf05 3653
483ceeab 3654 if ($hotplug_features->{cpu} && min_version($machine_version, 2, 7)) {
69c81430
AD
3655 push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3656 for (my $i = 2; $i <= $vcpus; $i++) {
3657 my $cpustr = print_cpu_device($conf,$i);
3658 push @$cmd, '-device', $cpustr;
3659 }
3660
3661 } else {
3662
3663 push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3664 }
1e3baf05
DM
3665 push @$cmd, '-nodefaults';
3666
dbea4415 3667 push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg";
1e3baf05 3668
6b64503e 3669 push @$cmd, '-no-acpi' if defined($conf->{acpi}) && $conf->{acpi} == 0;
1e3baf05 3670
6b64503e 3671 push @$cmd, '-no-reboot' if defined($conf->{reboot}) && $conf->{reboot} == 0;
1e3baf05 3672
84902837 3673 if ($vga->{type} && $vga->{type} !~ m/^serial\d+$/ && $vga->{type} ne 'none'){
4df98f2f
TL
3674 push @$devices, '-device', print_vga_device(
3675 $conf, $vga, $arch, $machine_version, $machine_type, undef, $qxlnum, $bridges);
d036e418 3676 my $socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
378ad769 3677 push @$cmd, '-vnc', "unix:$socket,password=on";
b7be4ba9 3678 } else {
55655ebc 3679 push @$cmd, '-vga', 'none' if $vga->{type} eq 'none';
b7be4ba9
AD
3680 push @$cmd, '-nographic';
3681 }
3682
1e3baf05 3683 # time drift fix
6b64503e 3684 my $tdf = defined($conf->{tdf}) ? $conf->{tdf} : $defaults->{tdf};
8c559505 3685 my $useLocaltime = $conf->{localtime};
1e3baf05 3686
4317f69f
AD
3687 if ($winversion >= 5) { # windows
3688 $useLocaltime = 1 if !defined($conf->{localtime});
7a131888 3689
4317f69f
AD
3690 # use time drift fix when acpi is enabled
3691 if (!(defined($conf->{acpi}) && $conf->{acpi} == 0)) {
3692 $tdf = 1 if !defined($conf->{tdf});
462e8d19 3693 }
4317f69f 3694 }
462e8d19 3695
4317f69f
AD
3696 if ($winversion >= 6) {
3697 push @$globalFlags, 'kvm-pit.lost_tick_policy=discard';
3698 push @$cmd, '-no-hpet';
1e3baf05
DM
3699 }
3700
8c559505
DM
3701 push @$rtcFlags, 'driftfix=slew' if $tdf;
3702
2f6f002c 3703 if ($conf->{startdate} && $conf->{startdate} ne 'now') {
8c559505
DM
3704 push @$rtcFlags, "base=$conf->{startdate}";
3705 } elsif ($useLocaltime) {
3706 push @$rtcFlags, 'base=localtime';
3707 }
1e3baf05 3708
58c64ad5
SR
3709 if ($forcecpu) {
3710 push @$cmd, '-cpu', $forcecpu;
3711 } else {
2f6f002c 3712 push @$cmd, get_cpu_options($conf, $arch, $kvm, $kvm_off, $machine_version, $winversion, $gpu_passthrough);
58c64ad5 3713 }
519ed28c 3714
0567a4d5 3715 PVE::QemuServer::Memory::config($conf, $vmid, $sockets, $cores, $defaults, $hotplug_features, $cmd);
370b05e7 3716
1e3baf05
DM
3717 push @$cmd, '-S' if $conf->{freeze};
3718
b20df606 3719 push @$cmd, '-k', $conf->{keyboard} if defined($conf->{keyboard});
1e3baf05 3720
48657158
MD
3721 my $guest_agent = parse_guest_agent($conf);
3722
3723 if ($guest_agent->{enabled}) {
d036e418 3724 my $qgasocket = PVE::QemuServer::Helpers::qmp_socket($vmid, 1);
378ad769 3725 push @$devices, '-chardev', "socket,path=$qgasocket,server=on,wait=off,id=qga0";
48657158 3726
60f03a11 3727 if (!$guest_agent->{type} || $guest_agent->{type} eq 'virtio') {
48657158
MD
3728 my $pciaddr = print_pci_addr("qga0", $bridges, $arch, $machine_type);
3729 push @$devices, '-device', "virtio-serial,id=qga0$pciaddr";
3730 push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0';
3731 } elsif ($guest_agent->{type} eq 'isa') {
3732 push @$devices, '-device', "isa-serial,chardev=qga0";
3733 }
ab6a046f
AD
3734 }
3735
e5d611c3
TL
3736 my $rng = $conf->{rng0} ? parse_rng($conf->{rng0}) : undef;
3737 if ($rng && $version_guard->(4, 1, 2)) {
05853188
SR
3738 check_rng_source($rng->{source});
3739
2cf61f33
SR
3740 my $max_bytes = $rng->{max_bytes} // $rng_fmt->{max_bytes}->{default};
3741 my $period = $rng->{period} // $rng_fmt->{period}->{default};
2cf61f33
SR
3742 my $limiter_str = "";
3743 if ($max_bytes) {
3744 $limiter_str = ",max-bytes=$max_bytes,period=$period";
3745 }
3746
2cf61f33 3747 my $rng_addr = print_pci_addr("rng0", $bridges, $arch, $machine_type);
2cf61f33
SR
3748 push @$devices, '-object', "rng-random,filename=$rng->{source},id=rng0";
3749 push @$devices, '-device', "virtio-rng-pci,rng=rng0$limiter_str$rng_addr";
3750 }
3751
1d794448 3752 my $spice_port;
2fa3151e 3753
590e698c
DM
3754 if ($qxlnum) {
3755 if ($qxlnum > 1) {
ac087616 3756 if ($winversion){
2f6f002c 3757 for (my $i = 1; $i < $qxlnum; $i++){
4df98f2f
TL
3758 push @$devices, '-device', print_vga_device(
3759 $conf, $vga, $arch, $machine_version, $machine_type, $i, $qxlnum, $bridges);
590e698c
DM
3760 }
3761 } else {
3762 # assume other OS works like Linux
55655ebc
DC
3763 my ($ram, $vram) = ("134217728", "67108864");
3764 if ($vga->{memory}) {
3765 $ram = PVE::Tools::convert_size($qxlnum*4*$vga->{memory}, 'mb' => 'b');
3766 $vram = PVE::Tools::convert_size($qxlnum*2*$vga->{memory}, 'mb' => 'b');
3767 }
3768 push @$cmd, '-global', "qxl-vga.ram_size=$ram";
3769 push @$cmd, '-global', "qxl-vga.vram_size=$vram";
2fa3151e
AD
3770 }
3771 }
3772
d559309f 3773 my $pciaddr = print_pci_addr("spice", $bridges, $arch, $machine_type);
95a4b4a9 3774
af0eba7e 3775 my $pfamily = PVE::Tools::get_host_address_family($nodename);
91152441
WB
3776 my @nodeaddrs = PVE::Tools::getaddrinfo_all('localhost', family => $pfamily);
3777 die "failed to get an ip address of type $pfamily for 'localhost'\n" if !@nodeaddrs;
4d316a63
AL
3778
3779 push @$devices, '-device', "virtio-serial,id=spice$pciaddr";
3780 push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent";
3781 push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0";
3782
91152441
WB
3783 my $localhost = PVE::Network::addr_to_ip($nodeaddrs[0]->{addr});
3784 $spice_port = PVE::Tools::next_spice_port($pfamily, $localhost);
943340a6 3785
4df98f2f
TL
3786 my $spice_enhancement_str = $conf->{spice_enhancements} // '';
3787 my $spice_enhancement = parse_property_string($spice_enhancements_fmt, $spice_enhancement_str);
caab114a
TL
3788 if ($spice_enhancement->{foldersharing}) {
3789 push @$devices, '-chardev', "spiceport,id=foldershare,name=org.spice-space.webdav.0";
3790 push @$devices, '-device', "virtserialport,chardev=foldershare,name=org.spice-space.webdav.0";
3791 }
c4df18db 3792
caab114a 3793 my $spice_opts = "tls-port=${spice_port},addr=$localhost,tls-ciphers=HIGH,seamless-migration=on";
4df98f2f
TL
3794 $spice_opts .= ",streaming-video=$spice_enhancement->{videostreaming}"
3795 if $spice_enhancement->{videostreaming};
3796
caab114a 3797 push @$devices, '-spice', "$spice_opts";
1011b570
DM
3798 }
3799
8d9ae0d2
DM
3800 # enable balloon by default, unless explicitly disabled
3801 if (!defined($conf->{balloon}) || $conf->{balloon}) {
3326ae19 3802 my $pciaddr = print_pci_addr("balloon0", $bridges, $arch, $machine_type);
8d9ae0d2
DM
3803 push @$devices, '-device', "virtio-balloon-pci,id=balloon0$pciaddr";
3804 }
1e3baf05 3805
0ea9541d
DM
3806 if ($conf->{watchdog}) {
3807 my $wdopts = parse_watchdog($conf->{watchdog});
3326ae19 3808 my $pciaddr = print_pci_addr("watchdog", $bridges, $arch, $machine_type);
0a40e8ea 3809 my $watchdog = $wdopts->{model} || 'i6300esb';
5bdcf937
AD
3810 push @$devices, '-device', "$watchdog$pciaddr";
3811 push @$devices, '-watchdog-action', $wdopts->{action} if $wdopts->{action};
0ea9541d
DM
3812 }
3813
1e3baf05 3814 my $vollist = [];
941e0c42 3815 my $scsicontroller = {};
26ee04b6 3816 my $ahcicontroller = {};
cdd20088 3817 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : $defaults->{scsihw};
1e3baf05 3818
5881b913
DM
3819 # Add iscsi initiator name if available
3820 if (my $initiator = get_initiator_name()) {
3821 push @$devices, '-iscsi', "initiator-name=$initiator";
3822 }
3823
912792e2 3824 PVE::QemuConfig->foreach_volume($conf, sub {
1e3baf05
DM
3825 my ($ds, $drive) = @_;
3826
ff1a2432 3827 if (PVE::Storage::parse_volume_id($drive->{file}, 1)) {
3f11f0d7 3828 check_volume_storage_type($storecfg, $drive->{file});
1e3baf05 3829 push @$vollist, $drive->{file};
ff1a2432 3830 }
afdb31d5 3831
4dcce9ee
TL
3832 # ignore efidisk here, already added in bios/fw handling code above
3833 return if $drive->{interface} eq 'efidisk';
f9dde219
SR
3834 # similar for TPM
3835 return if $drive->{interface} eq 'tpmstate';
4dcce9ee 3836
1e3baf05 3837 $use_virtio = 1 if $ds =~ m/^virtio/;
3b408e82 3838
2141a802 3839 $drive->{bootindex} = $bootorder->{$ds} if $bootorder->{$ds};
3b408e82 3840
2f6f002c 3841 if ($drive->{interface} eq 'virtio'){
51f492cd
AD
3842 push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread};
3843 }
3844
2f6f002c 3845 if ($drive->{interface} eq 'scsi') {
cdd20088 3846
ee034f5c 3847 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive);
6731a4cf 3848
b8fb1c03
SR
3849 die "scsi$drive->{index}: machine version 4.1~pve2 or higher is required to use more than 14 SCSI disks\n"
3850 if $drive->{index} > 13 && !&$version_guard(4, 1, 2);
3851
3326ae19 3852 my $pciaddr = print_pci_addr("$controller_prefix$controller", $bridges, $arch, $machine_type);
a1b7d579 3853 my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ? "virtio-scsi-pci" : $scsihw;
fc8b40fd
AD
3854
3855 my $iothread = '';
3856 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{iothread}){
3857 $iothread .= ",iothread=iothread-$controller_prefix$controller";
3858 push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller";
e7a5104d
DC
3859 } elsif ($drive->{iothread}) {
3860 warn "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n";
fc8b40fd
AD
3861 }
3862
6e11f143
AD
3863 my $queues = '';
3864 if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{queues}){
3865 $queues = ",num_queues=$drive->{queues}";
370b05e7 3866 }
6e11f143 3867
4df98f2f
TL
3868 push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues"
3869 if !$scsicontroller->{$controller};
cdd20088 3870 $scsicontroller->{$controller}=1;
2f6f002c 3871 }
3b408e82 3872
26ee04b6 3873 if ($drive->{interface} eq 'sata') {
2f6f002c 3874 my $controller = int($drive->{index} / $PVE::QemuServer::Drive::MAX_SATA_DISKS);
3326ae19 3875 my $pciaddr = print_pci_addr("ahci$controller", $bridges, $arch, $machine_type);
4df98f2f
TL
3876 push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr"
3877 if !$ahcicontroller->{$controller};
2f6f002c 3878 $ahcicontroller->{$controller}=1;
26ee04b6 3879 }
46f58b5f 3880
5921764c
SR
3881 my $pbs_conf = $pbs_backing->{$ds};
3882 my $pbs_name = undef;
3883 if ($pbs_conf) {
3884 $pbs_name = "drive-$ds-pbs";
3885 push @$devices, '-blockdev', print_pbs_blockdev($pbs_conf, $pbs_name);
3886 }
3887
6d5673c3
SR
3888 my $drive_cmd = print_drive_commandline_full(
3889 $storecfg, $vmid, $drive, $pbs_name, min_version($kvmver, 6, 0));
3dc33a72
FG
3890
3891 # extra protection for templates, but SATA and IDE don't support it..
75748d44 3892 $drive_cmd .= ',readonly=on' if drive_is_read_only($conf, $drive);
4ef13a7f 3893
15b21acc 3894 push @$devices, '-drive',$drive_cmd;
4df98f2f
TL
3895 push @$devices, '-device', print_drivedevice_full(
3896 $storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type);
1e3baf05
DM
3897 });
3898
cc4d6182 3899 for (my $i = 0; $i < $MAX_NETS; $i++) {
2141a802
SR
3900 my $netname = "net$i";
3901
3902 next if !$conf->{$netname};
3903 my $d = parse_net($conf->{$netname});
d0a86b24 3904 next if !$d;
1e3baf05 3905
d0a86b24 3906 $use_virtio = 1 if $d->{model} eq 'virtio';
1e3baf05 3907
2141a802 3908 $d->{bootindex} = $bootorder->{$netname} if $bootorder->{$netname};
1e3baf05 3909
2141a802 3910 my $netdevfull = print_netdev_full($vmid, $conf, $arch, $d, $netname);
d0a86b24 3911 push @$devices, '-netdev', $netdevfull;
5bdcf937 3912
d0a86b24 3913 my $netdevicefull = print_netdevice_full(
2141a802 3914 $vmid, $conf, $d, $netname, $bridges, $use_old_bios_files, $arch, $machine_type);
4df98f2f 3915
d0a86b24 3916 push @$devices, '-device', $netdevicefull;
5bdcf937 3917 }
1e3baf05 3918
6dbcb073 3919 if ($conf->{ivshmem}) {
4df98f2f 3920 my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem});
e3c27a6a 3921
6dbcb073
DC
3922 my $bus;
3923 if ($q35) {
3924 $bus = print_pcie_addr("ivshmem");
3925 } else {
3926 $bus = print_pci_addr("ivshmem", $bridges, $arch, $machine_type);
3927 }
e3c27a6a
TL
3928
3929 my $ivshmem_name = $ivshmem->{name} // $vmid;
3930 my $path = '/dev/shm/pve-shm-' . $ivshmem_name;
3931
6dbcb073 3932 push @$devices, '-device', "ivshmem-plain,memdev=ivshmem$bus,";
4df98f2f
TL
3933 push @$devices, '-object', "memory-backend-file,id=ivshmem,share=on,mem-path=$path"
3934 .",size=$ivshmem->{size}M";
6dbcb073
DC
3935 }
3936
2513b862
DC
3937 # pci.4 is nested in pci.1
3938 $bridges->{1} = 1 if $bridges->{4};
3939
3326ae19
TL
3940 if (!$q35) { # add pci bridges
3941 if (min_version($machine_version, 2, 3)) {
fc79e813
AD
3942 $bridges->{1} = 1;
3943 $bridges->{2} = 1;
3944 }
6731a4cf 3945 $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/;
2513b862
DC
3946 }
3947
3948 for my $k (sort {$b cmp $a} keys %$bridges) {
3949 next if $q35 && $k < 4; # q35.cfg already includes bridges up to 3
13d68979
SR
3950
3951 my $k_name = $k;
3952 if ($k == 2 && $legacy_igd) {
3953 $k_name = "$k-igd";
3954 }
3326ae19 3955 my $pciaddr = print_pci_addr("pci.$k_name", undef, $arch, $machine_type);
2513b862 3956 my $devstr = "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr";
3326ae19
TL
3957
3958 if ($q35) { # add after -readconfig pve-q35.cfg
2513b862
DC
3959 splice @$devices, 2, 0, '-device', $devstr;
3960 } else {
3961 unshift @$devices, '-device', $devstr if $k > 0;
f8e83f05 3962 }
19672434
DM
3963 }
3964
ac0077cc
SR
3965 if (!$kvm) {
3966 push @$machineFlags, 'accel=tcg';
3967 }
3968
3969 my $machine_type_min = $machine_type;
3970 if ($add_pve_version) {
3971 $machine_type_min =~ s/\+pve\d+$//;
3972 $machine_type_min .= "+pve$required_pve_version";
3973 }
3974 push @$machineFlags, "type=${machine_type_min}";
3975
5bdcf937 3976 push @$cmd, @$devices;
2f6f002c
TL
3977 push @$cmd, '-rtc', join(',', @$rtcFlags) if scalar(@$rtcFlags);
3978 push @$cmd, '-machine', join(',', @$machineFlags) if scalar(@$machineFlags);
3979 push @$cmd, '-global', join(',', @$globalFlags) if scalar(@$globalFlags);
8c559505 3980
7ceade4c
DC
3981 if (my $vmstate = $conf->{vmstate}) {
3982 my $statepath = PVE::Storage::path($storecfg, $vmstate);
24d1f93a 3983 push @$vollist, $vmstate;
7ceade4c 3984 push @$cmd, '-loadstate', $statepath;
b85666cf 3985 print "activating and using '$vmstate' as vmstate\n";
7ceade4c
DC
3986 }
3987
85fcf79e
FG
3988 if (PVE::QemuConfig->is_template($conf)) {
3989 # needed to workaround base volumes being read-only
3990 push @$cmd, '-snapshot';
3991 }
3992
76350670
DC
3993 # add custom args
3994 if ($conf->{args}) {
3995 my $aa = PVE::Tools::split_args($conf->{args});
3996 push @$cmd, @$aa;
3997 }
3998
1d794448 3999 return wantarray ? ($cmd, $vollist, $spice_port) : $cmd;
1e3baf05 4000}
19672434 4001
05853188
SR
4002sub check_rng_source {
4003 my ($source) = @_;
4004
4005 # mostly relevant for /dev/hwrng, but doesn't hurt to check others too
4006 die "cannot create VirtIO RNG device: source file '$source' doesn't exist\n"
4007 if ! -e $source;
4008
4009 my $rng_current = '/sys/devices/virtual/misc/hw_random/rng_current';
4010 if ($source eq '/dev/hwrng' && file_read_firstline($rng_current) eq 'none') {
4df98f2f
TL
4011 # Needs to abort, otherwise QEMU crashes on first rng access. Note that rng_current cannot
4012 # be changed to 'none' manually, so once the VM is past this point, it's no longer an issue.
4013 die "Cannot start VM with passed-through RNG device: '/dev/hwrng' exists, but"
4014 ." '$rng_current' is set to 'none'. Ensure that a compatible hardware-RNG is attached"
4015 ." to the host.\n";
05853188
SR
4016 }
4017}
4018
943340a6 4019sub spice_port {
1011b570 4020 my ($vmid) = @_;
943340a6 4021
0a13e08e 4022 my $res = mon_cmd($vmid, 'query-spice');
943340a6
DM
4023
4024 return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n";
1011b570
DM
4025}
4026
86fdcfb2
DA
4027sub vm_devices_list {
4028 my ($vmid) = @_;
4029
0a13e08e 4030 my $res = mon_cmd($vmid, 'query-pci');
f721624b 4031 my $devices_to_check = [];
ceea9078
DM
4032 my $devices = {};
4033 foreach my $pcibus (@$res) {
f721624b
DC
4034 push @$devices_to_check, @{$pcibus->{devices}},
4035 }
4036
4037 while (@$devices_to_check) {
4038 my $to_check = [];
4039 for my $d (@$devices_to_check) {
4040 $devices->{$d->{'qdev_id'}} = 1 if $d->{'qdev_id'};
4041 next if !$d->{'pci_bridge'};
4042
4043 $devices->{$d->{'qdev_id'}} += scalar(@{$d->{'pci_bridge'}->{devices}});
4044 push @$to_check, @{$d->{'pci_bridge'}->{devices}};
f78cc802 4045 }
f721624b 4046 $devices_to_check = $to_check;
f78cc802
AD
4047 }
4048
0a13e08e 4049 my $resblock = mon_cmd($vmid, 'query-block');
f78cc802
AD
4050 foreach my $block (@$resblock) {
4051 if($block->{device} =~ m/^drive-(\S+)/){
4052 $devices->{$1} = 1;
1dc4f496
DM
4053 }
4054 }
86fdcfb2 4055
0a13e08e 4056 my $resmice = mon_cmd($vmid, 'query-mice');
3d7389fe
DM
4057 foreach my $mice (@$resmice) {
4058 if ($mice->{name} eq 'QEMU HID Tablet') {
4059 $devices->{tablet} = 1;
4060 last;
4061 }
4062 }
4063
deb091c5
DC
4064 # for usb devices there is no query-usb
4065 # but we can iterate over the entries in
4066 # qom-list path=/machine/peripheral
0a13e08e 4067 my $resperipheral = mon_cmd($vmid, 'qom-list', path => '/machine/peripheral');
deb091c5
DC
4068 foreach my $per (@$resperipheral) {
4069 if ($per->{name} =~ m/^usb\d+$/) {
4070 $devices->{$per->{name}} = 1;
4071 }
4072 }
4073
1dc4f496 4074 return $devices;
86fdcfb2
DA
4075}
4076
ec21aa11 4077sub vm_deviceplug {
d559309f 4078 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
ae57f6b3 4079
3392d6ca 4080 my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf);
db656e5f 4081
95d6343b
DA
4082 my $devices_list = vm_devices_list($vmid);
4083 return 1 if defined($devices_list->{$deviceid});
4084
4df98f2f
TL
4085 # add PCI bridge if we need it for the device
4086 qemu_add_pci_bridge($storecfg, $conf, $vmid, $deviceid, $arch, $machine_type);
fee46675 4087
3d7389fe 4088 if ($deviceid eq 'tablet') {
d559309f 4089 qemu_deviceadd($vmid, print_tabletdevice_full($conf, $arch));
d559309f 4090 } elsif ($deviceid eq 'keyboard') {
d559309f 4091 qemu_deviceadd($vmid, print_keyboarddevice_full($conf, $arch));
4eb68604 4092 } elsif ($deviceid =~ m/^usb(\d+)$/) {
f745762b 4093 die "usb hotplug currently not reliable\n";
50bbe377
TL
4094 # since we can't reliably hot unplug all added usb devices and usb
4095 # passthrough breaks live migration we disable usb hotplugging for now
4096 #qemu_deviceadd($vmid, PVE::QemuServer::USB::print_usbdevice_full($conf, $deviceid, $device));
fee46675 4097 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
22de899a
AD
4098 qemu_iothread_add($vmid, $deviceid, $device);
4099
3326ae19
TL
4100 qemu_driveadd($storecfg, $vmid, $device);
4101 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675 4102
3326ae19 4103 qemu_deviceadd($vmid, $devicefull);
fee46675
DM
4104 eval { qemu_deviceaddverify($vmid, $deviceid); };
4105 if (my $err = $@) {
63c2da2f
DM
4106 eval { qemu_drivedel($vmid, $deviceid); };
4107 warn $@ if $@;
fee46675 4108 die $err;
5e5dcb73 4109 }
2733141c 4110 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3326ae19
TL
4111 my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : "lsi";
4112 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
a1b7d579 4113 my $scsihw_type = $scsihw eq 'virtio-scsi-single' ? "virtio-scsi-pci" : $scsihw;
2733141c 4114
3326ae19 4115 my $devicefull = "$scsihw_type,id=$deviceid$pciaddr";
fee46675 4116
fc8b40fd
AD
4117 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread}) {
4118 qemu_iothread_add($vmid, $deviceid, $device);
4119 $devicefull .= ",iothread=iothread-$deviceid";
4120 }
4121
6e11f143
AD
4122 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues}) {
4123 $devicefull .= ",num_queues=$device->{queues}";
4124 }
4125
3326ae19
TL
4126 qemu_deviceadd($vmid, $devicefull);
4127 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4128 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
d559309f 4129 qemu_findorcreatescsihw($storecfg,$conf, $vmid, $device, $arch, $machine_type);
fee46675 4130 qemu_driveadd($storecfg, $vmid, $device);
a1b7d579 4131
acfc6ef8 4132 my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type);
fee46675
DM
4133 eval { qemu_deviceadd($vmid, $devicefull); };
4134 if (my $err = $@) {
63c2da2f
DM
4135 eval { qemu_drivedel($vmid, $deviceid); };
4136 warn $@ if $@;
fee46675 4137 die $err;
a4f091a0 4138 }
fee46675 4139 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
d1c1af4b 4140 return if !qemu_netdevadd($vmid, $conf, $arch, $device, $deviceid);
8718099c 4141
3392d6ca 4142 my $machine_type = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
95d3be58
DC
4143 my $use_old_bios_files = undef;
4144 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type);
8718099c 4145
4df98f2f
TL
4146 my $netdevicefull = print_netdevice_full(
4147 $vmid, $conf, $device, $deviceid, undef, $use_old_bios_files, $arch, $machine_type);
95d3be58 4148 qemu_deviceadd($vmid, $netdevicefull);
79046fd1
DC
4149 eval {
4150 qemu_deviceaddverify($vmid, $deviceid);
4151 qemu_set_link_status($vmid, $deviceid, !$device->{link_down});
4152 };
fee46675
DM
4153 if (my $err = $@) {
4154 eval { qemu_netdevdel($vmid, $deviceid); };
4155 warn $@ if $@;
4156 die $err;
95d3be58 4157 }
fee46675 4158 } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) {
40f28a9f 4159 my $bridgeid = $2;
d559309f 4160 my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type);
40f28a9f 4161 my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr";
a1b7d579 4162
40f28a9f 4163 qemu_deviceadd($vmid, $devicefull);
fee46675 4164 qemu_deviceaddverify($vmid, $deviceid);
fee46675 4165 } else {
a1b7d579 4166 die "can't hotplug device '$deviceid'\n";
40f28a9f
AD
4167 }
4168
5e5dcb73 4169 return 1;
a4dea331
DA
4170}
4171
3eec5767 4172# fixme: this should raise exceptions on error!
ec21aa11 4173sub vm_deviceunplug {
f19d1c47 4174 my ($vmid, $conf, $deviceid) = @_;
873c2d69 4175
95d6343b
DA
4176 my $devices_list = vm_devices_list($vmid);
4177 return 1 if !defined($devices_list->{$deviceid});
4178
2141a802
SR
4179 my $bootdisks = PVE::QemuServer::Drive::get_bootdisks($conf);
4180 die "can't unplug bootdisk '$deviceid'\n" if grep {$_ eq $deviceid} @$bootdisks;
63c2da2f 4181
d559309f 4182 if ($deviceid eq 'tablet' || $deviceid eq 'keyboard') {
3d7389fe 4183 qemu_devicedel($vmid, $deviceid);
4eb68604 4184 } elsif ($deviceid =~ m/^usb\d+$/) {
f745762b 4185 die "usb hotplug currently not reliable\n";
50bbe377
TL
4186 # when unplugging usb devices this way, there may be remaining usb
4187 # controllers/hubs so we disable it for now
4188 #qemu_devicedel($vmid, $deviceid);
4189 #qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4190 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
9a66c311 4191 my $device = parse_drive($deviceid, $conf->{$deviceid});
f19d1c47 4192
a8d0fec3
TL
4193 qemu_devicedel($vmid, $deviceid);
4194 qemu_devicedelverify($vmid, $deviceid);
4195 qemu_drivedel($vmid, $deviceid);
9a66c311 4196 qemu_iothread_del($vmid, $deviceid, $device);
2733141c 4197 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
63c2da2f 4198 qemu_devicedel($vmid, $deviceid);
8ce30dde 4199 qemu_devicedelverify($vmid, $deviceid);
63c2da2f 4200 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
9a66c311 4201 my $device = parse_drive($deviceid, $conf->{$deviceid});
cfc817c7 4202
a8d0fec3
TL
4203 qemu_devicedel($vmid, $deviceid);
4204 qemu_drivedel($vmid, $deviceid);
a1b7d579 4205 qemu_deletescsihw($conf, $vmid, $deviceid);
8ce30dde 4206
9a66c311
FG
4207 qemu_iothread_del($vmid, "virtioscsi$device->{index}", $device)
4208 if $conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single');
63c2da2f 4209 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
a8d0fec3
TL
4210 qemu_devicedel($vmid, $deviceid);
4211 qemu_devicedelverify($vmid, $deviceid);
4212 qemu_netdevdel($vmid, $deviceid);
63c2da2f
DM
4213 } else {
4214 die "can't unplug device '$deviceid'\n";
2630d2a9
DA
4215 }
4216
5e5dcb73
DA
4217 return 1;
4218}
4219
4220sub qemu_deviceadd {
4221 my ($vmid, $devicefull) = @_;
873c2d69 4222
d695b5b7
AD
4223 $devicefull = "driver=".$devicefull;
4224 my %options = split(/[=,]/, $devicefull);
f19d1c47 4225
0a13e08e 4226 mon_cmd($vmid, "device_add" , %options);
5e5dcb73 4227}
afdb31d5 4228
5e5dcb73 4229sub qemu_devicedel {
fee46675 4230 my ($vmid, $deviceid) = @_;
63c2da2f 4231
0a13e08e 4232 my $ret = mon_cmd($vmid, "device_del", id => $deviceid);
5e5dcb73
DA
4233}
4234
22de899a 4235sub qemu_iothread_add {
a8d0fec3 4236 my ($vmid, $deviceid, $device) = @_;
22de899a
AD
4237
4238 if ($device->{iothread}) {
4239 my $iothreads = vm_iothreads_list($vmid);
4240 qemu_objectadd($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"};
4241 }
4242}
4243
4244sub qemu_iothread_del {
a8d0fec3 4245 my ($vmid, $deviceid, $device) = @_;
22de899a 4246
22de899a
AD
4247 if ($device->{iothread}) {
4248 my $iothreads = vm_iothreads_list($vmid);
4249 qemu_objectdel($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"};
4250 }
4251}
4252
4d3f29ed 4253sub qemu_objectadd {
a8d0fec3 4254 my ($vmid, $objectid, $qomtype) = @_;
4d3f29ed 4255
0a13e08e 4256 mon_cmd($vmid, "object-add", id => $objectid, "qom-type" => $qomtype);
4d3f29ed
AD
4257
4258 return 1;
4259}
4260
4261sub qemu_objectdel {
a8d0fec3 4262 my ($vmid, $objectid) = @_;
4d3f29ed 4263
0a13e08e 4264 mon_cmd($vmid, "object-del", id => $objectid);
4d3f29ed
AD
4265
4266 return 1;
4267}
4268
5e5dcb73 4269sub qemu_driveadd {
fee46675 4270 my ($storecfg, $vmid, $device) = @_;
5e5dcb73 4271
6d5673c3
SR
4272 my $kvmver = get_running_qemu_version($vmid);
4273 my $io_uring = min_version($kvmver, 6, 0);
4274 my $drive = print_drive_commandline_full($storecfg, $vmid, $device, undef, $io_uring);
7a69fc3c 4275 $drive =~ s/\\/\\\\/g;
0a13e08e 4276 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_add auto \"$drive\"");
fee46675 4277
5e5dcb73 4278 # If the command succeeds qemu prints: "OK"
fee46675
DM
4279 return 1 if $ret =~ m/OK/s;
4280
4281 die "adding drive failed: $ret\n";
5e5dcb73 4282}
afdb31d5 4283
5e5dcb73 4284sub qemu_drivedel {
a8d0fec3 4285 my ($vmid, $deviceid) = @_;
873c2d69 4286
0a13e08e 4287 my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_del drive-$deviceid");
5e5dcb73 4288 $ret =~ s/^\s+//;
a1b7d579 4289
63c2da2f 4290 return 1 if $ret eq "";
a1b7d579 4291
63c2da2f 4292 # NB: device not found errors mean the drive was auto-deleted and we ignore the error
a1b7d579
DM
4293 return 1 if $ret =~ m/Device \'.*?\' not found/s;
4294
63c2da2f 4295 die "deleting drive $deviceid failed : $ret\n";
5e5dcb73 4296}
f19d1c47 4297
5e5dcb73 4298sub qemu_deviceaddverify {
fee46675 4299 my ($vmid, $deviceid) = @_;
873c2d69 4300
5e5dcb73
DA
4301 for (my $i = 0; $i <= 5; $i++) {
4302 my $devices_list = vm_devices_list($vmid);
4303 return 1 if defined($devices_list->{$deviceid});
4304 sleep 1;
afdb31d5 4305 }
fee46675
DM
4306
4307 die "error on hotplug device '$deviceid'\n";
5e5dcb73 4308}
afdb31d5 4309
5e5dcb73
DA
4310
4311sub qemu_devicedelverify {
63c2da2f
DM
4312 my ($vmid, $deviceid) = @_;
4313
a1b7d579 4314 # need to verify that the device is correctly removed as device_del
63c2da2f 4315 # is async and empty return is not reliable
5e5dcb73 4316
5e5dcb73
DA
4317 for (my $i = 0; $i <= 5; $i++) {
4318 my $devices_list = vm_devices_list($vmid);
4319 return 1 if !defined($devices_list->{$deviceid});
4320 sleep 1;
afdb31d5 4321 }
63c2da2f
DM
4322
4323 die "error on hot-unplugging device '$deviceid'\n";
873c2d69
DA
4324}
4325
cdd20088 4326sub qemu_findorcreatescsihw {
d559309f 4327 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
cfc817c7 4328
ee034f5c 4329 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
2733141c
AD
4330
4331 my $scsihwid="$controller_prefix$controller";
cfc817c7
DA
4332 my $devices_list = vm_devices_list($vmid);
4333
a8d0fec3 4334 if (!defined($devices_list->{$scsihwid})) {
d559309f 4335 vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device, $arch, $machine_type);
cfc817c7 4336 }
fee46675 4337
cfc817c7
DA
4338 return 1;
4339}
4340
8ce30dde
AD
4341sub qemu_deletescsihw {
4342 my ($conf, $vmid, $opt) = @_;
4343
4344 my $device = parse_drive($opt, $conf->{$opt});
4345
a1511b3c 4346 if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
2733141c
AD
4347 vm_deviceunplug($vmid, $conf, "virtioscsi$device->{index}");
4348 return 1;
4349 }
4350
ee034f5c 4351 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
8ce30dde
AD
4352
4353 my $devices_list = vm_devices_list($vmid);
4354 foreach my $opt (keys %{$devices_list}) {
e0fd2b2f
FE
4355 if (is_valid_drivename($opt)) {
4356 my $drive = parse_drive($opt, $conf->{$opt});
a8d0fec3 4357 if ($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) {
8ce30dde
AD
4358 return 1;
4359 }
4360 }
4361 }
4362
4363 my $scsihwid="scsihw$controller";
4364
4365 vm_deviceunplug($vmid, $conf, $scsihwid);
4366
4367 return 1;
4368}
4369
281fedb3 4370sub qemu_add_pci_bridge {
d559309f 4371 my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_;
40f28a9f
AD
4372
4373 my $bridges = {};
281fedb3
DM
4374
4375 my $bridgeid;
4376
d559309f 4377 print_pci_addr($device, $bridges, $arch, $machine_type);
40f28a9f
AD
4378
4379 while (my ($k, $v) = each %$bridges) {
4380 $bridgeid = $k;
4381 }
fee46675 4382 return 1 if !defined($bridgeid) || $bridgeid < 1;
281fedb3 4383
40f28a9f
AD
4384 my $bridge = "pci.$bridgeid";
4385 my $devices_list = vm_devices_list($vmid);
4386
281fedb3 4387 if (!defined($devices_list->{$bridge})) {
d559309f 4388 vm_deviceplug($storecfg, $conf, $vmid, $bridge, $arch, $machine_type);
40f28a9f 4389 }
281fedb3 4390
40f28a9f
AD
4391 return 1;
4392}
4393
25088687
DM
4394sub qemu_set_link_status {
4395 my ($vmid, $device, $up) = @_;
4396
0a13e08e 4397 mon_cmd($vmid, "set_link", name => $device,
25088687
DM
4398 up => $up ? JSON::true : JSON::false);
4399}
4400
2630d2a9 4401sub qemu_netdevadd {
d559309f 4402 my ($vmid, $conf, $arch, $device, $deviceid) = @_;
2630d2a9 4403
d559309f 4404 my $netdev = print_netdev_full($vmid, $conf, $arch, $device, $deviceid, 1);
73aa03b8 4405 my %options = split(/[=,]/, $netdev);
2630d2a9 4406
bf5aef9b
DC
4407 if (defined(my $vhost = $options{vhost})) {
4408 $options{vhost} = JSON::boolean(PVE::JSONSchema::parse_boolean($vhost));
4409 }
4410
4411 if (defined(my $queues = $options{queues})) {
4412 $options{queues} = $queues + 0;
4413 }
4414
0a13e08e 4415 mon_cmd($vmid, "netdev_add", %options);
73aa03b8 4416 return 1;
2630d2a9
DA
4417}
4418
4419sub qemu_netdevdel {
4420 my ($vmid, $deviceid) = @_;
4421
0a13e08e 4422 mon_cmd($vmid, "netdev_del", id => $deviceid);
2630d2a9
DA
4423}
4424
16521d63 4425sub qemu_usb_hotplug {
d559309f 4426 my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_;
16521d63
DC
4427
4428 return if !$device;
4429
4430 # remove the old one first
4431 vm_deviceunplug($vmid, $conf, $deviceid);
4432
4433 # check if xhci controller is necessary and available
4434 if ($device->{usb3}) {
4435
4436 my $devicelist = vm_devices_list($vmid);
4437
4438 if (!$devicelist->{xhci}) {
d559309f 4439 my $pciaddr = print_pci_addr("xhci", undef, $arch, $machine_type);
16521d63
DC
4440 qemu_deviceadd($vmid, "nec-usb-xhci,id=xhci$pciaddr");
4441 }
4442 }
4443 my $d = parse_usb_device($device->{host});
4444 $d->{usb3} = $device->{usb3};
4445
4446 # add the new one
d559309f 4447 vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $d, $arch, $machine_type);
16521d63
DC
4448}
4449
838776ab 4450sub qemu_cpu_hotplug {
8edc9c08 4451 my ($vmid, $conf, $vcpus) = @_;
838776ab 4452
3392d6ca 4453 my $machine_type = PVE::QemuServer::Machine::get_current_qemu_machine($vmid);
1e881b75 4454
8edc9c08
AD
4455 my $sockets = 1;
4456 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
4457 $sockets = $conf->{sockets} if $conf->{sockets};
4458 my $cores = $conf->{cores} || 1;
4459 my $maxcpus = $sockets * $cores;
838776ab 4460
8edc9c08 4461 $vcpus = $maxcpus if !$vcpus;
3a11fadb 4462
8edc9c08
AD
4463 die "you can't add more vcpus than maxcpus\n"
4464 if $vcpus > $maxcpus;
3a11fadb 4465
8edc9c08 4466 my $currentvcpus = $conf->{vcpus} || $maxcpus;
1e881b75 4467
eba3e64d 4468 if ($vcpus < $currentvcpus) {
1e881b75 4469
2ea5fb7e 4470 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
1e881b75
AD
4471
4472 for (my $i = $currentvcpus; $i > $vcpus; $i--) {
4473 qemu_devicedel($vmid, "cpu$i");
4474 my $retry = 0;
4475 my $currentrunningvcpus = undef;
4476 while (1) {
65af8c31 4477 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
1e881b75 4478 last if scalar(@{$currentrunningvcpus}) == $i-1;
961af8a3 4479 raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5;
1e881b75
AD
4480 $retry++;
4481 sleep 1;
4482 }
4483 #update conf after each succesfull cpu unplug
4484 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4485 PVE::QemuConfig->write_config($vmid, $conf);
4486 }
4487 } else {
961af8a3 4488 die "cpu hot-unplugging requires qemu version 2.7 or higher\n";
1e881b75
AD
4489 }
4490
4491 return;
4492 }
838776ab 4493
65af8c31 4494 my $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
961af8a3 4495 die "vcpus in running vm does not match its configuration\n"
8edc9c08 4496 if scalar(@{$currentrunningvcpus}) != $currentvcpus;
838776ab 4497
2ea5fb7e 4498 if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) {
eba3e64d
AD
4499
4500 for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) {
4501 my $cpustr = print_cpu_device($conf, $i);
4502 qemu_deviceadd($vmid, $cpustr);
4503
4504 my $retry = 0;
4505 my $currentrunningvcpus = undef;
4506 while (1) {
65af8c31 4507 $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast");
eba3e64d 4508 last if scalar(@{$currentrunningvcpus}) == $i;
961af8a3 4509 raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10;
eba3e64d
AD
4510 sleep 1;
4511 $retry++;
4512 }
4513 #update conf after each succesfull cpu hotplug
4514 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
4515 PVE::QemuConfig->write_config($vmid, $conf);
4516 }
4517 } else {
4518
4519 for (my $i = $currentvcpus; $i < $vcpus; $i++) {
0a13e08e 4520 mon_cmd($vmid, "cpu-add", id => int($i));
eba3e64d 4521 }
838776ab
AD
4522 }
4523}
4524
affd2f88 4525sub qemu_block_set_io_throttle {
277ca170
WB
4526 my ($vmid, $deviceid,
4527 $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr,
9196a8ec
WB
4528 $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max,
4529 $bps_max_length, $bps_rd_max_length, $bps_wr_max_length,
4530 $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_;
affd2f88 4531
f3f323a3
AD
4532 return if !check_running($vmid) ;
4533
0a13e08e 4534 mon_cmd($vmid, "block_set_io_throttle", device => $deviceid,
277ca170
WB
4535 bps => int($bps),
4536 bps_rd => int($bps_rd),
4537 bps_wr => int($bps_wr),
4538 iops => int($iops),
4539 iops_rd => int($iops_rd),
4540 iops_wr => int($iops_wr),
4541 bps_max => int($bps_max),
4542 bps_rd_max => int($bps_rd_max),
4543 bps_wr_max => int($bps_wr_max),
4544 iops_max => int($iops_max),
4545 iops_rd_max => int($iops_rd_max),
9196a8ec
WB
4546 iops_wr_max => int($iops_wr_max),
4547 bps_max_length => int($bps_max_length),
4548 bps_rd_max_length => int($bps_rd_max_length),
4549 bps_wr_max_length => int($bps_wr_max_length),
4550 iops_max_length => int($iops_max_length),
4551 iops_rd_max_length => int($iops_rd_max_length),
4552 iops_wr_max_length => int($iops_wr_max_length),
277ca170 4553 );
f3f323a3 4554
affd2f88
AD
4555}
4556
c1175c92
AD
4557sub qemu_block_resize {
4558 my ($vmid, $deviceid, $storecfg, $volid, $size) = @_;
4559
ed221350 4560 my $running = check_running($vmid);
c1175c92 4561
7246e8f9 4562 $size = 0 if !PVE::Storage::volume_resize($storecfg, $volid, $size, $running);
c1175c92
AD
4563
4564 return if !$running;
4565
375db731
FE
4566 my $padding = (1024 - $size % 1024) % 1024;
4567 $size = $size + $padding;
4568
190c8461
SR
4569 mon_cmd(
4570 $vmid,
4571 "block_resize",
4572 device => $deviceid,
4573 size => int($size),
4574 timeout => 60,
4575 );
c1175c92
AD
4576}
4577
1ab0057c
AD
4578sub qemu_volume_snapshot {
4579 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4580
ed221350 4581 my $running = check_running($vmid);
1ab0057c 4582
9d83932d 4583 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4584 mon_cmd($vmid, 'blockdev-snapshot-internal-sync', device => $deviceid, name => $snap);
e5eaa028
WL
4585 } else {
4586 PVE::Storage::volume_snapshot($storecfg, $volid, $snap);
4587 }
1ab0057c
AD
4588}
4589
fc46aff9
AD
4590sub qemu_volume_snapshot_delete {
4591 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4592
ed221350 4593 my $running = check_running($vmid);
fc46aff9 4594
a2f1554b
AD
4595 if($running) {
4596
4597 $running = undef;
4598 my $conf = PVE::QemuConfig->load_config($vmid);
912792e2 4599 PVE::QemuConfig->foreach_volume($conf, sub {
a2f1554b
AD
4600 my ($ds, $drive) = @_;
4601 $running = 1 if $drive->{file} eq $volid;
4602 });
4603 }
4604
9d83932d 4605 if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) {
0a13e08e 4606 mon_cmd($vmid, 'blockdev-snapshot-delete-internal-sync', device => $deviceid, name => $snap);
1ef7592f
AD
4607 } else {
4608 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running);
4609 }
fc46aff9
AD
4610}
4611
264e519f 4612sub set_migration_caps {
27a5be53 4613 my ($vmid, $savevm) = @_;
a89fded1 4614
acc10e51
SR
4615 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
4616
27a5be53
SR
4617 my $bitmap_prop = $savevm ? 'pbs-dirty-bitmap-savevm' : 'pbs-dirty-bitmap-migration';
4618 my $dirty_bitmaps = $qemu_support->{$bitmap_prop} ? 1 : 0;
4619
8b8345f3 4620 my $cap_ref = [];
a89fded1
AD
4621
4622 my $enabled_cap = {
8b8345f3 4623 "auto-converge" => 1,
0b0a47e8 4624 "xbzrle" => 1,
8b8345f3
DM
4625 "x-rdma-pin-all" => 0,
4626 "zero-blocks" => 0,
acc10e51 4627 "compress" => 0,
27a5be53 4628 "dirty-bitmaps" => $dirty_bitmaps,
a89fded1
AD
4629 };
4630
0a13e08e 4631 my $supported_capabilities = mon_cmd($vmid, "query-migrate-capabilities");
a89fded1 4632
8b8345f3 4633 for my $supported_capability (@$supported_capabilities) {
b463a3ce
SP
4634 push @$cap_ref, {
4635 capability => $supported_capability->{capability},
22430fa2
DM
4636 state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false,
4637 };
a89fded1
AD
4638 }
4639
0a13e08e 4640 mon_cmd($vmid, "migrate-set-capabilities", capabilities => $cap_ref);
8b8345f3 4641}
a89fded1 4642
912792e2
FE
4643sub foreach_volid {
4644 my ($conf, $func, @param) = @_;
4645
4646 my $volhash = {};
4647
4648 my $test_volid = sub {
ae180b8f 4649 my ($key, $drive, $snapname) = @_;
912792e2 4650
ae180b8f 4651 my $volid = $drive->{file};
912792e2
FE
4652 return if !$volid;
4653
4654 $volhash->{$volid}->{cdrom} //= 1;
ae180b8f 4655 $volhash->{$volid}->{cdrom} = 0 if !drive_is_cdrom($drive);
912792e2 4656
ae180b8f 4657 my $replicate = $drive->{replicate} // 1;
912792e2
FE
4658 $volhash->{$volid}->{replicate} //= 0;
4659 $volhash->{$volid}->{replicate} = 1 if $replicate;
4660
4661 $volhash->{$volid}->{shared} //= 0;
ae180b8f 4662 $volhash->{$volid}->{shared} = 1 if $drive->{shared};
912792e2
FE
4663
4664 $volhash->{$volid}->{referenced_in_config} //= 0;
4665 $volhash->{$volid}->{referenced_in_config} = 1 if !defined($snapname);
4666
4667 $volhash->{$volid}->{referenced_in_snapshot}->{$snapname} = 1
4668 if defined($snapname);
ae180b8f
FE
4669
4670 my $size = $drive->{size};
4671 $volhash->{$volid}->{size} //= $size if $size;
4672
4673 $volhash->{$volid}->{is_vmstate} //= 0;
4674 $volhash->{$volid}->{is_vmstate} = 1 if $key eq 'vmstate';
4675
f9dde219
SR
4676 $volhash->{$volid}->{is_tpmstate} //= 0;
4677 $volhash->{$volid}->{is_tpmstate} = 1 if $key eq 'tpmstate0';
4678
ae180b8f
FE
4679 $volhash->{$volid}->{is_unused} //= 0;
4680 $volhash->{$volid}->{is_unused} = 1 if $key =~ /^unused\d+$/;
a6be63ac
FE
4681
4682 $volhash->{$volid}->{drivename} = $key if is_valid_drivename($key);
912792e2
FE
4683 };
4684
ae180b8f
FE
4685 my $include_opts = {
4686 extra_keys => ['vmstate'],
4687 include_unused => 1,
4688 };
4689
0b953b8e 4690 PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $test_volid);
912792e2
FE
4691 foreach my $snapname (keys %{$conf->{snapshots}}) {
4692 my $snap = $conf->{snapshots}->{$snapname};
0b953b8e 4693 PVE::QemuConfig->foreach_volume_full($snap, $include_opts, $test_volid, $snapname);
912792e2
FE
4694 }
4695
4696 foreach my $volid (keys %$volhash) {
4697 &$func($volid, $volhash->{$volid}, @param);
4698 }
4699}
4700
81d95ae1 4701my $fast_plug_option = {
7498eb64 4702 'lock' => 1,
81d95ae1 4703 'name' => 1,
a1b7d579 4704 'onboot' => 1,
81d95ae1
DM
4705 'shares' => 1,
4706 'startup' => 1,
b0ec896e 4707 'description' => 1,
ec647db4 4708 'protection' => 1,
8cad5e9b 4709 'vmstatestorage' => 1,
9e784b11 4710 'hookscript' => 1,
b8e7068a 4711 'tags' => 1,
81d95ae1
DM
4712};
4713
3a11fadb
DM
4714# hotplug changes in [PENDING]
4715# $selection hash can be used to only apply specified options, for
4716# example: { cores => 1 } (only apply changed 'cores')
4717# $errors ref is used to return error messages
c427973b 4718sub vmconfig_hotplug_pending {
3a11fadb 4719 my ($vmid, $conf, $storecfg, $selection, $errors) = @_;
c427973b 4720
8e90138a 4721 my $defaults = load_defaults();
045749f2
TL
4722 my $arch = get_vm_arch($conf);
4723 my $machine_type = get_vm_machine($conf, undef, $arch);
c427973b
DM
4724
4725 # commit values which do not have any impact on running VM first
3a11fadb
DM
4726 # Note: those option cannot raise errors, we we do not care about
4727 # $selection and always apply them.
4728
4729 my $add_error = sub {
4730 my ($opt, $msg) = @_;
4731 $errors->{$opt} = "hotplug problem - $msg";
4732 };
c427973b
DM
4733
4734 my $changes = 0;
4735 foreach my $opt (keys %{$conf->{pending}}) { # add/change
81d95ae1 4736 if ($fast_plug_option->{$opt}) {
c427973b
DM
4737 $conf->{$opt} = $conf->{pending}->{$opt};
4738 delete $conf->{pending}->{$opt};
4739 $changes = 1;
4740 }
4741 }
4742
4743 if ($changes) {
ffda963f 4744 PVE::QemuConfig->write_config($vmid, $conf);
c427973b
DM
4745 }
4746
b3c2bdd1 4747 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
c427973b 4748
5b65b00d 4749 my $cgroup = PVE::QemuServer::CGroup->new($vmid);
98bc3aeb 4750 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
d321c4a9 4751 foreach my $opt (sort keys %$pending_delete_hash) {
3a11fadb 4752 next if $selection && !$selection->{$opt};
d321c4a9 4753 my $force = $pending_delete_hash->{$opt}->{force};
3a11fadb 4754 eval {
51a6f637
AD
4755 if ($opt eq 'hotplug') {
4756 die "skip\n" if ($conf->{hotplug} =~ /memory/);
4757 } elsif ($opt eq 'tablet') {
b3c2bdd1 4758 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 4759 if ($defaults->{tablet}) {
d559309f
WB
4760 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
4761 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
4762 if $arch eq 'aarch64';
3a11fadb 4763 } else {
d559309f
WB
4764 vm_deviceunplug($vmid, $conf, 'tablet');
4765 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 4766 }
4eb68604 4767 } elsif ($opt =~ m/^usb\d+/) {
f745762b 4768 die "skip\n";
50bbe377
TL
4769 # since we cannot reliably hot unplug usb devices we are disabling it
4770 #die "skip\n" if !$hotplug_features->{usb} || $conf->{$opt} =~ m/spice/i;
4771 #vm_deviceunplug($vmid, $conf, $opt);
8edc9c08 4772 } elsif ($opt eq 'vcpus') {
b3c2bdd1 4773 die "skip\n" if !$hotplug_features->{cpu};
8edc9c08 4774 qemu_cpu_hotplug($vmid, $conf, undef);
9c2f7069 4775 } elsif ($opt eq 'balloon') {
81d95ae1 4776 # enable balloon device is not hotpluggable
75b51053
DC
4777 die "skip\n" if defined($conf->{balloon}) && $conf->{balloon} == 0;
4778 # here we reset the ballooning value to memory
4779 my $balloon = $conf->{memory} || $defaults->{memory};
0a13e08e 4780 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
81d95ae1
DM
4781 } elsif ($fast_plug_option->{$opt}) {
4782 # do nothing
3eec5767 4783 } elsif ($opt =~ m/^net(\d+)$/) {
b3c2bdd1 4784 die "skip\n" if !$hotplug_features->{network};
3eec5767 4785 vm_deviceunplug($vmid, $conf, $opt);
74479ee9 4786 } elsif (is_valid_drivename($opt)) {
b3c2bdd1 4787 die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/;
19120f99 4788 vm_deviceunplug($vmid, $conf, $opt);
3dc38fbb 4789 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4d3f29ed
AD
4790 } elsif ($opt =~ m/^memory$/) {
4791 die "skip\n" if !$hotplug_features->{memory};
6779f1ac 4792 PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt);
c8effec3 4793 } elsif ($opt eq 'cpuunits') {
d3f9db4d 4794 $cgroup->change_cpu_shares(undef, 1024);
58be00f1 4795 } elsif ($opt eq 'cpulimit') {
25de70ae 4796 $cgroup->change_cpu_quota(undef, undef); # reset, cgroup module can better decide values
3d7389fe 4797 } else {
e56beeda 4798 die "skip\n";
3d7389fe 4799 }
3a11fadb
DM
4800 };
4801 if (my $err = $@) {
e56beeda
DM
4802 &$add_error($opt, $err) if $err ne "skip\n";
4803 } else {
3a11fadb 4804 delete $conf->{$opt};
98bc3aeb 4805 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
3d7389fe 4806 }
3d7389fe
DM
4807 }
4808
e5a66e48 4809 my ($apply_pending_cloudinit, $apply_pending_cloudinit_done);
9ed7a77c 4810 $apply_pending_cloudinit = sub {
e5a66e48
WB
4811 return if $apply_pending_cloudinit_done; # once is enough
4812 $apply_pending_cloudinit_done = 1; # once is enough
4813
9ed7a77c 4814 my ($key, $value) = @_;
9ed7a77c
WB
4815
4816 my @cloudinit_opts = keys %$confdesc_cloudinit;
4817 foreach my $opt (keys %{$conf->{pending}}) {
4818 next if !grep { $_ eq $opt } @cloudinit_opts;
4819 $conf->{$opt} = delete $conf->{pending}->{$opt};
4820 }
4821
e6ec384f
AD
4822 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
4823 foreach my $opt (sort keys %$pending_delete_hash) {
4824 next if !grep { $_ eq $opt } @cloudinit_opts;
4825 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
4826 delete $conf->{$opt};
4827 }
4828
9ed7a77c
WB
4829 my $new_conf = { %$conf };
4830 $new_conf->{$key} = $value;
4831 PVE::QemuServer::Cloudinit::generate_cloudinitconfig($new_conf, $vmid);
4832 };
4833
3d7389fe 4834 foreach my $opt (keys %{$conf->{pending}}) {
3a11fadb 4835 next if $selection && !$selection->{$opt};
3d7389fe 4836 my $value = $conf->{pending}->{$opt};
3a11fadb 4837 eval {
51a6f637
AD
4838 if ($opt eq 'hotplug') {
4839 die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/);
4840 } elsif ($opt eq 'tablet') {
b3c2bdd1 4841 die "skip\n" if !$hotplug_features->{usb};
3a11fadb 4842 if ($value == 1) {
d559309f
WB
4843 vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type);
4844 vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type)
4845 if $arch eq 'aarch64';
3a11fadb 4846 } elsif ($value == 0) {
d559309f
WB
4847 vm_deviceunplug($vmid, $conf, 'tablet');
4848 vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64';
3a11fadb 4849 }
4eb68604 4850 } elsif ($opt =~ m/^usb\d+$/) {
f745762b 4851 die "skip\n";
50bbe377
TL
4852 # since we cannot reliably hot unplug usb devices we disable it for now
4853 #die "skip\n" if !$hotplug_features->{usb} || $value =~ m/spice/i;
4854 #my $d = eval { parse_property_string($usbdesc->{format}, $value) };
4855 #die "skip\n" if !$d;
4856 #qemu_usb_hotplug($storecfg, $conf, $vmid, $opt, $d, $arch, $machine_type);
8edc9c08 4857 } elsif ($opt eq 'vcpus') {
b3c2bdd1 4858 die "skip\n" if !$hotplug_features->{cpu};
3a11fadb
DM
4859 qemu_cpu_hotplug($vmid, $conf, $value);
4860 } elsif ($opt eq 'balloon') {
81d95ae1 4861 # enable/disable balloning device is not hotpluggable
8fe689e7 4862 my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon});
a1b7d579 4863 my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon});
81d95ae1
DM
4864 die "skip\n" if $old_balloon_enabled != $new_balloon_enabled;
4865
3a11fadb 4866 # allow manual ballooning if shares is set to zero
4cc1efa6 4867 if ((defined($conf->{shares}) && ($conf->{shares} == 0))) {
9c2f7069 4868 my $balloon = $conf->{pending}->{balloon} || $conf->{memory} || $defaults->{memory};
0a13e08e 4869 mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
9c2f7069 4870 }
a1b7d579 4871 } elsif ($opt =~ m/^net(\d+)$/) {
3eec5767 4872 # some changes can be done without hotplug
a1b7d579 4873 vmconfig_update_net($storecfg, $conf, $hotplug_features->{network},
d559309f 4874 $vmid, $opt, $value, $arch, $machine_type);
74479ee9 4875 } elsif (is_valid_drivename($opt)) {
f9dde219 4876 die "skip\n" if $opt eq 'efidisk0' || $opt eq 'tpmstate0';
a05cff86 4877 # some changes can be done without hotplug
9ed7a77c
WB
4878 my $drive = parse_drive($opt, $value);
4879 if (drive_is_cloudinit($drive)) {
4880 &$apply_pending_cloudinit($opt, $value);
4881 }
b3c2bdd1 4882 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
9e7bce2c 4883 $vmid, $opt, $value, $arch, $machine_type);
4d3f29ed
AD
4884 } elsif ($opt =~ m/^memory$/) { #dimms
4885 die "skip\n" if !$hotplug_features->{memory};
6779f1ac 4886 $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt, $value);
c8effec3 4887 } elsif ($opt eq 'cpuunits') {
d3f9db4d 4888 $cgroup->change_cpu_shares($conf->{pending}->{$opt}, 1024);
58be00f1 4889 } elsif ($opt eq 'cpulimit') {
c6f773b8 4890 my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000);
5b65b00d 4891 $cgroup->change_cpu_quota($cpulimit, 100000);
74ea2c65
AD
4892 } elsif ($opt eq 'agent') {
4893 vmconfig_update_agent($conf, $opt, $value);
3a11fadb 4894 } else {
e56beeda 4895 die "skip\n"; # skip non-hot-pluggable options
3d7389fe 4896 }
3a11fadb
DM
4897 };
4898 if (my $err = $@) {
e56beeda
DM
4899 &$add_error($opt, $err) if $err ne "skip\n";
4900 } else {
3a11fadb
DM
4901 $conf->{$opt} = $value;
4902 delete $conf->{pending}->{$opt};
3d7389fe 4903 }
3d7389fe 4904 }
4df15a03
OB
4905
4906 PVE::QemuConfig->write_config($vmid, $conf);
c427973b 4907}
055d554d 4908
3dc38fbb
WB
4909sub try_deallocate_drive {
4910 my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_;
4911
4912 if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) {
4913 my $volid = $drive->{file};
4914 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
4915 my $sid = PVE::Storage::parse_volume_id($volid);
4916 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
cee01bcb
WB
4917
4918 # check if the disk is really unused
cee01bcb 4919 die "unable to delete '$volid' - volume is still in use (snapshot?)\n"
e0fd2b2f 4920 if PVE::QemuServer::Drive::is_volume_in_use($storecfg, $conf, $key, $volid);
cee01bcb 4921 PVE::Storage::vdisk_free($storecfg, $volid);
3dc38fbb 4922 return 1;
40b977f3
WL
4923 } else {
4924 # If vm is not owner of this disk remove from config
4925 return 1;
3dc38fbb
WB
4926 }
4927 }
4928
d1c1af4b 4929 return;
3dc38fbb
WB
4930}
4931
4932sub vmconfig_delete_or_detach_drive {
4933 my ($vmid, $storecfg, $conf, $opt, $force) = @_;
4934
4935 my $drive = parse_drive($opt, $conf->{$opt});
4936
4937 my $rpcenv = PVE::RPCEnvironment::get();
4938 my $authuser = $rpcenv->get_user();
4939
4940 if ($force) {
4941 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']);
4942 try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force);
4943 } else {
4944 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive);
4945 }
4946}
4947
98bc3aeb
OB
4948
4949
055d554d 4950sub vmconfig_apply_pending {
eb5e482d
OB
4951 my ($vmid, $conf, $storecfg, $errors) = @_;
4952
4953 my $add_apply_error = sub {
4954 my ($opt, $msg) = @_;
4955 my $err_msg = "unable to apply pending change $opt : $msg";
4956 $errors->{$opt} = $err_msg;
4957 warn $err_msg;
4958 };
c427973b
DM
4959
4960 # cold plug
055d554d 4961
98bc3aeb 4962 my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete});
d321c4a9 4963 foreach my $opt (sort keys %$pending_delete_hash) {
fb4d1ba2 4964 my $force = $pending_delete_hash->{$opt}->{force};
eb5e482d 4965 eval {
3d48b95a
OB
4966 if ($opt =~ m/^unused/) {
4967 die "internal error";
4968 } elsif (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 4969 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
eb5e482d
OB
4970 }
4971 };
4972 if (my $err = $@) {
4973 $add_apply_error->($opt, $err);
055d554d 4974 } else {
98bc3aeb 4975 PVE::QemuConfig->remove_from_pending_delete($conf, $opt);
055d554d 4976 delete $conf->{$opt};
055d554d
DM
4977 }
4978 }
4979
3d48b95a 4980 PVE::QemuConfig->cleanup_pending($conf);
055d554d
DM
4981
4982 foreach my $opt (keys %{$conf->{pending}}) { # add/change
3d48b95a 4983 next if $opt eq 'delete'; # just to be sure
eb5e482d 4984 eval {
3d48b95a 4985 if (defined($conf->{$opt}) && is_valid_drivename($opt)) {
eb5e482d 4986 vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt}))
eb5e482d
OB
4987 }
4988 };
4989 if (my $err = $@) {
4990 $add_apply_error->($opt, $err);
055d554d 4991 } else {
eb5e482d 4992 $conf->{$opt} = delete $conf->{pending}->{$opt};
055d554d 4993 }
055d554d 4994 }
3d48b95a
OB
4995
4996 # write all changes at once to avoid unnecessary i/o
4997 PVE::QemuConfig->write_config($vmid, $conf);
055d554d
DM
4998}
4999
3eec5767 5000sub vmconfig_update_net {
d559309f 5001 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
3eec5767
DM
5002
5003 my $newnet = parse_net($value);
5004
5005 if ($conf->{$opt}) {
5006 my $oldnet = parse_net($conf->{$opt});
5007
0f1af9e7
OB
5008 if (safe_string_ne($oldnet->{model}, $newnet->{model}) ||
5009 safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) ||
5010 safe_num_ne($oldnet->{queues}, $newnet->{queues}) ||
3eec5767
DM
5011 !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change
5012
5013 # for non online change, we try to hot-unplug
7196b757 5014 die "skip\n" if !$hotplug;
3eec5767
DM
5015 vm_deviceunplug($vmid, $conf, $opt);
5016 } else {
5017
5018 die "internal error" if $opt !~ m/net(\d+)/;
5019 my $iface = "tap${vmid}i$1";
a1b7d579 5020
0f1af9e7
OB
5021 if (safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
5022 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
5023 safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) ||
5024 safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
3eec5767 5025 PVE::Network::tap_unplug($iface);
28e129cc
AD
5026
5027 if ($have_sdn) {
5028 PVE::Network::SDN::Zones::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5029 } else {
5030 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
5031 }
0f1af9e7 5032 } elsif (safe_num_ne($oldnet->{rate}, $newnet->{rate})) {
4f4fbeb0
WB
5033 # Rate can be applied on its own but any change above needs to
5034 # include the rate in tap_plug since OVS resets everything.
5035 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
3eec5767 5036 }
38c590d9 5037
0f1af9e7 5038 if (safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) {
25088687
DM
5039 qemu_set_link_status($vmid, $opt, !$newnet->{link_down});
5040 }
5041
38c590d9 5042 return 1;
3eec5767
DM
5043 }
5044 }
a1b7d579 5045
7196b757 5046 if ($hotplug) {
d559309f 5047 vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet, $arch, $machine_type);
38c590d9
DM
5048 } else {
5049 die "skip\n";
5050 }
3eec5767
DM
5051}
5052
74ea2c65
AD
5053sub vmconfig_update_agent {
5054 my ($conf, $opt, $value) = @_;
5055
5056 die "skip\n" if !$conf->{$opt};
5057
5058 my $hotplug_options = { fstrim_cloned_disks => 1 };
5059
5060 my $old_agent = parse_guest_agent($conf);
5061 my $agent = parse_guest_agent({$opt => $value});
5062
33f8b887 5063 for my $option (keys %$agent) { # added/changed options
74ea2c65
AD
5064 next if defined($hotplug_options->{$option});
5065 die "skip\n" if safe_string_ne($agent->{$option}, $old_agent->{$option});
5066 }
5067
33f8b887 5068 for my $option (keys %$old_agent) { # removed options
74ea2c65
AD
5069 next if defined($hotplug_options->{$option});
5070 die "skip\n" if safe_string_ne($old_agent->{$option}, $agent->{$option});
5071 }
33f8b887
TL
5072
5073 return; # either no actual change (e.g., format string reordered) or just hotpluggable changes
74ea2c65
AD
5074}
5075
a05cff86 5076sub vmconfig_update_disk {
9e7bce2c 5077 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_;
a05cff86
DM
5078
5079 my $drive = parse_drive($opt, $value);
5080
4df98f2f
TL
5081 if ($conf->{$opt} && (my $old_drive = parse_drive($opt, $conf->{$opt}))) {
5082 my $media = $drive->{media} || 'disk';
5083 my $oldmedia = $old_drive->{media} || 'disk';
5084 die "unable to change media type\n" if $media ne $oldmedia;
a05cff86 5085
4df98f2f 5086 if (!drive_is_cdrom($old_drive)) {
a05cff86 5087
4df98f2f 5088 if ($drive->{file} ne $old_drive->{file}) {
a05cff86 5089
4df98f2f 5090 die "skip\n" if !$hotplug;
a05cff86 5091
4df98f2f
TL
5092 # unplug and register as unused
5093 vm_deviceunplug($vmid, $conf, $opt);
5094 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive)
a1b7d579 5095
4df98f2f
TL
5096 } else {
5097 # update existing disk
5098
5099 # skip non hotpluggable value
5100 if (safe_string_ne($drive->{discard}, $old_drive->{discard}) ||
5101 safe_string_ne($drive->{iothread}, $old_drive->{iothread}) ||
5102 safe_string_ne($drive->{queues}, $old_drive->{queues}) ||
5103 safe_string_ne($drive->{cache}, $old_drive->{cache}) ||
5104 safe_string_ne($drive->{ssd}, $old_drive->{ssd})) {
5105 die "skip\n";
5106 }
a05cff86 5107
4df98f2f
TL
5108 # apply throttle
5109 if (safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
5110 safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
5111 safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
5112 safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
5113 safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
5114 safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) ||
5115 safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) ||
5116 safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) ||
5117 safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) ||
5118 safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) ||
5119 safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) ||
5120 safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) ||
5121 safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) ||
5122 safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) ||
5123 safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) ||
5124 safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) ||
5125 safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) ||
5126 safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) {
5127
5128 qemu_block_set_io_throttle(
5129 $vmid,"drive-$opt",
5130 ($drive->{mbps} || 0)*1024*1024,
5131 ($drive->{mbps_rd} || 0)*1024*1024,
5132 ($drive->{mbps_wr} || 0)*1024*1024,
5133 $drive->{iops} || 0,
5134 $drive->{iops_rd} || 0,
5135 $drive->{iops_wr} || 0,
5136 ($drive->{mbps_max} || 0)*1024*1024,
5137 ($drive->{mbps_rd_max} || 0)*1024*1024,
5138 ($drive->{mbps_wr_max} || 0)*1024*1024,
5139 $drive->{iops_max} || 0,
5140 $drive->{iops_rd_max} || 0,
5141 $drive->{iops_wr_max} || 0,
5142 $drive->{bps_max_length} || 1,
5143 $drive->{bps_rd_max_length} || 1,
5144 $drive->{bps_wr_max_length} || 1,
5145 $drive->{iops_max_length} || 1,
5146 $drive->{iops_rd_max_length} || 1,
5147 $drive->{iops_wr_max_length} || 1,
5148 );
a05cff86 5149
4df98f2f 5150 }
a1b7d579 5151
4df98f2f
TL
5152 return 1;
5153 }
4de1bb25 5154
4df98f2f 5155 } else { # cdrom
a1b7d579 5156
4df98f2f
TL
5157 if ($drive->{file} eq 'none') {
5158 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
5159 if (drive_is_cloudinit($old_drive)) {
5160 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive);
5161 }
5162 } else {
5163 my $path = get_iso_path($storecfg, $vmid, $drive->{file});
ce9fce79 5164
4df98f2f
TL
5165 # force eject if locked
5166 mon_cmd($vmid, "eject", force => JSON::true, id => "$opt");
ce9fce79 5167
4df98f2f
TL
5168 if ($path) {
5169 mon_cmd($vmid, "blockdev-change-medium",
5170 id => "$opt", filename => "$path");
4de1bb25 5171 }
a05cff86 5172 }
4df98f2f
TL
5173
5174 return 1;
a05cff86
DM
5175 }
5176 }
5177
a1b7d579 5178 die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/;
4de1bb25 5179 # hotplug new disks
f7b4356f 5180 PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|;
d559309f 5181 vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive, $arch, $machine_type);
a05cff86
DM
5182}
5183
13cfe3b7 5184# called in locked context by incoming migration
ba5396b5
FG
5185sub vm_migrate_get_nbd_disks {
5186 my ($storecfg, $conf, $replicated_volumes) = @_;
13cfe3b7
FG
5187
5188 my $local_volumes = {};
912792e2 5189 PVE::QemuConfig->foreach_volume($conf, sub {
13cfe3b7
FG
5190 my ($ds, $drive) = @_;
5191
5192 return if drive_is_cdrom($drive);
5193
5194 my $volid = $drive->{file};
5195
5196 return if !$volid;
5197
5198 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
5199
5200 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
5201 return if $scfg->{shared};
ba5396b5
FG
5202
5203 # replicated disks re-use existing state via bitmap
5204 my $use_existing = $replicated_volumes->{$volid} ? 1 : 0;
5205 $local_volumes->{$ds} = [$volid, $storeid, $volname, $drive, $use_existing];
13cfe3b7 5206 });
ba5396b5
FG
5207 return $local_volumes;
5208}
5209
5210# called in locked context by incoming migration
5211sub vm_migrate_alloc_nbd_disks {
5212 my ($storecfg, $vmid, $source_volumes, $storagemap) = @_;
13cfe3b7
FG
5213
5214 my $format = undef;
5215
5216 my $nbd = {};
ba5396b5
FG
5217 foreach my $opt (sort keys %$source_volumes) {
5218 my ($volid, $storeid, $volname, $drive, $use_existing) = @{$source_volumes->{$opt}};
5219
5220 if ($use_existing) {
5221 $nbd->{$opt}->{drivestr} = print_drive($drive);
5222 $nbd->{$opt}->{volid} = $volid;
5223 $nbd->{$opt}->{replicated} = 1;
13cfe3b7
FG
5224 next;
5225 }
13cfe3b7
FG
5226
5227 # If a remote storage is specified and the format of the original
5228 # volume is not available there, fall back to the default format.
5229 # Otherwise use the same format as the original.
bf8fc5a3
FG
5230 if (!$storagemap->{identity}) {
5231 $storeid = map_storage($storagemap, $storeid);
13cfe3b7
FG
5232 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
5233 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
5234 my $fileFormat = qemu_img_format($scfg, $volname);
5235 $format = (grep {$fileFormat eq $_} @{$validFormats}) ? $fileFormat : $defFormat;
5236 } else {
5237 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
5238 $format = qemu_img_format($scfg, $volname);
5239 }
5240
4df98f2f
TL
5241 my $size = $drive->{size} / 1024;
5242 my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, $size);
13cfe3b7
FG
5243 my $newdrive = $drive;
5244 $newdrive->{format} = $format;
5245 $newdrive->{file} = $newvolid;
5246 my $drivestr = print_drive($newdrive);
ba5396b5
FG
5247 $nbd->{$opt}->{drivestr} = $drivestr;
5248 $nbd->{$opt}->{volid} = $newvolid;
13cfe3b7
FG
5249 }
5250
5251 return $nbd;
5252}
5253
5254# see vm_start_nolock for parameters, additionally:
5255# migrate_opts:
bf8fc5a3 5256# storagemap = parsed storage map for allocating NBD disks
3898a563
FG
5257sub vm_start {
5258 my ($storecfg, $vmid, $params, $migrate_opts) = @_;
5259
84da8217 5260 return PVE::QemuConfig->lock_config($vmid, sub {
3898a563
FG
5261 my $conf = PVE::QemuConfig->load_config($vmid, $migrate_opts->{migratedfrom});
5262
4ef13a7f
FG
5263 die "you can't start a vm if it's a template\n"
5264 if !$params->{skiptemplate} && PVE::QemuConfig->is_template($conf);
3898a563 5265
d544e0e0 5266 my $has_suspended_lock = PVE::QemuConfig->has_lock($conf, 'suspended');
8e0c97bb
SR
5267 my $has_backup_lock = PVE::QemuConfig->has_lock($conf, 'backup');
5268
5269 my $running = check_running($vmid, undef, $migrate_opts->{migratedfrom});
5270
5271 if ($has_backup_lock && $running) {
5272 # a backup is currently running, attempt to start the guest in the
5273 # existing QEMU instance
5274 return vm_resume($vmid);
5275 }
3898a563
FG
5276
5277 PVE::QemuConfig->check_lock($conf)
d544e0e0
FE
5278 if !($params->{skiplock} || $has_suspended_lock);
5279
5280 $params->{resume} = $has_suspended_lock || defined($conf->{vmstate});
3898a563 5281
8e0c97bb 5282 die "VM $vmid already running\n" if $running;
3898a563 5283
ba5396b5
FG
5284 if (my $storagemap = $migrate_opts->{storagemap}) {
5285 my $replicated = $migrate_opts->{replicated_volumes};
5286 my $disks = vm_migrate_get_nbd_disks($storecfg, $conf, $replicated);
5287 $migrate_opts->{nbd} = vm_migrate_alloc_nbd_disks($storecfg, $vmid, $disks, $storagemap);
5288
5289 foreach my $opt (keys %{$migrate_opts->{nbd}}) {
5290 $conf->{$opt} = $migrate_opts->{nbd}->{$opt}->{drivestr};
5291 }
5292 }
13cfe3b7 5293
84da8217 5294 return vm_start_nolock($storecfg, $vmid, $conf, $params, $migrate_opts);
3898a563
FG
5295 });
5296}
5297
5298
0c498cca
FG
5299# params:
5300# statefile => 'tcp', 'unix' for migration or path/volid for RAM state
5301# skiplock => 0/1, skip checking for config lock
4ef13a7f 5302# skiptemplate => 0/1, skip checking whether VM is template
0c498cca 5303# forcemachine => to force Qemu machine (rollback/migration)
58c64ad5 5304# forcecpu => a QEMU '-cpu' argument string to override get_cpu_options
0c498cca
FG
5305# timeout => in seconds
5306# paused => start VM in paused state (backup)
3898a563 5307# resume => resume from hibernation
5921764c
SR
5308# pbs-backing => {
5309# sata0 => {
5310# repository
5311# snapshot
5312# keyfile
5313# archive
5314# },
5315# virtio2 => ...
5316# }
0c498cca 5317# migrate_opts:
ba5396b5 5318# nbd => volumes for NBD exports (vm_migrate_alloc_nbd_disks)
0c498cca
FG
5319# migratedfrom => source node
5320# spice_ticket => used for spice migration, passed via tunnel/stdin
5321# network => CIDR of migration network
5322# type => secure/insecure - tunnel over encrypted connection or plain-text
0c498cca
FG
5323# nbd_proto_version => int, 0 for TCP, 1 for UNIX
5324# replicated_volumes = which volids should be re-used with bitmaps for nbd migration
3898a563
FG
5325sub vm_start_nolock {
5326 my ($storecfg, $vmid, $conf, $params, $migrate_opts) = @_;
1e3baf05 5327
3898a563
FG
5328 my $statefile = $params->{statefile};
5329 my $resume = $params->{resume};
3dcb98d5 5330
3898a563
FG
5331 my $migratedfrom = $migrate_opts->{migratedfrom};
5332 my $migration_type = $migrate_opts->{type};
7ceade4c 5333
84da8217
FG
5334 my $res = {};
5335
3898a563
FG
5336 # clean up leftover reboot request files
5337 eval { clear_reboot_request($vmid); };
5338 warn $@ if $@;
1e3baf05 5339
3898a563
FG
5340 if (!$statefile && scalar(keys %{$conf->{pending}})) {
5341 vmconfig_apply_pending($vmid, $conf, $storecfg);
5342 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
5343 }
64457ed4 5344
104f47a9
ML
5345 # don't regenerate the ISO if the VM is started as part of a live migration
5346 # this way we can reuse the old ISO with the correct config
5347 PVE::QemuServer::Cloudinit::generate_cloudinitconfig($conf, $vmid) if !$migratedfrom;
055d554d 5348
3898a563 5349 my $defaults = load_defaults();
0c9a7596 5350
3898a563
FG
5351 # set environment variable useful inside network script
5352 $ENV{PVE_MIGRATED_FROM} = $migratedfrom if $migratedfrom;
6c47d546 5353
3898a563 5354 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
9e784b11 5355
3898a563 5356 my $forcemachine = $params->{forcemachine};
ea1c2110 5357 my $forcecpu = $params->{forcecpu};
3898a563 5358 if ($resume) {
ea1c2110 5359 # enforce machine and CPU type on suspended vm to ensure HW compatibility
3898a563 5360 $forcemachine = $conf->{runningmachine};
ea1c2110 5361 $forcecpu = $conf->{runningcpu};
3898a563
FG
5362 print "Resuming suspended VM\n";
5363 }
7ceade4c 5364
5921764c
SR
5365 my ($cmd, $vollist, $spice_port) = config_to_command($storecfg, $vmid,
5366 $conf, $defaults, $forcemachine, $forcecpu, $params->{'pbs-backing'});
6c47d546 5367
3898a563
FG
5368 my $migration_ip;
5369 my $get_migration_ip = sub {
5370 my ($nodename) = @_;
b24e1ac2 5371
3898a563 5372 return $migration_ip if defined($migration_ip);
b24e1ac2 5373
3898a563 5374 my $cidr = $migrate_opts->{network};
0c498cca 5375
3898a563
FG
5376 if (!defined($cidr)) {
5377 my $dc_conf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5378 $cidr = $dc_conf->{migration}->{network};
5379 }
b24e1ac2 5380
3898a563
FG
5381 if (defined($cidr)) {
5382 my $ips = PVE::Network::get_local_ip_from_cidr($cidr);
b24e1ac2 5383
3898a563
FG
5384 die "could not get IP: no address configured on local " .
5385 "node for network '$cidr'\n" if scalar(@$ips) == 0;
b24e1ac2 5386
3898a563
FG
5387 die "could not get IP: multiple addresses configured on local " .
5388 "node for network '$cidr'\n" if scalar(@$ips) > 1;
b24e1ac2 5389
3898a563
FG
5390 $migration_ip = @$ips[0];
5391 }
b24e1ac2 5392
3898a563
FG
5393 $migration_ip = PVE::Cluster::remote_node_ip($nodename, 1)
5394 if !defined($migration_ip);
b24e1ac2 5395
3898a563
FG
5396 return $migration_ip;
5397 };
b24e1ac2 5398
3898a563
FG
5399 my $migrate_uri;
5400 if ($statefile) {
5401 if ($statefile eq 'tcp') {
5402 my $localip = "localhost";
5403 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
5404 my $nodename = nodename();
2de2d6f7 5405
3898a563
FG
5406 if (!defined($migration_type)) {
5407 if (defined($datacenterconf->{migration}->{type})) {
5408 $migration_type = $datacenterconf->{migration}->{type};
5409 } else {
5410 $migration_type = 'secure';
b7a5a225 5411 }
3898a563 5412 }
b7a5a225 5413
3898a563
FG
5414 if ($migration_type eq 'insecure') {
5415 $localip = $get_migration_ip->($nodename);
5416 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
5417 }
2de2d6f7 5418
3898a563
FG
5419 my $pfamily = PVE::Tools::get_host_address_family($nodename);
5420 my $migrate_port = PVE::Tools::next_migrate_port($pfamily);
5421 $migrate_uri = "tcp:${localip}:${migrate_port}";
5422 push @$cmd, '-incoming', $migrate_uri;
5423 push @$cmd, '-S';
1c9d54bf 5424
3898a563
FG
5425 } elsif ($statefile eq 'unix') {
5426 # should be default for secure migrations as a ssh TCP forward
5427 # tunnel is not deterministic reliable ready and fails regurarly
5428 # to set up in time, so use UNIX socket forwards
5429 my $socket_addr = "/run/qemu-server/$vmid.migrate";
5430 unlink $socket_addr;
54323eed 5431
3898a563 5432 $migrate_uri = "unix:$socket_addr";
1c9d54bf 5433
3898a563
FG
5434 push @$cmd, '-incoming', $migrate_uri;
5435 push @$cmd, '-S';
1c9d54bf 5436
3898a563
FG
5437 } elsif (-e $statefile) {
5438 push @$cmd, '-loadstate', $statefile;
5439 } else {
5440 my $statepath = PVE::Storage::path($storecfg, $statefile);
5441 push @$vollist, $statefile;
5442 push @$cmd, '-loadstate', $statepath;
5443 }
5444 } elsif ($params->{paused}) {
5445 push @$cmd, '-S';
5446 }
5447
1fb1822e
DC
5448 my $start_timeout = $params->{timeout} // config_aware_timeout($conf, $resume);
5449
5450 my $pci_devices = {}; # host pci devices
74c17b7a 5451 for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) {
1fb1822e
DC
5452 my $dev = $conf->{"hostpci$i"} or next;
5453 $pci_devices->{$i} = parse_hostpci($dev);
5454 }
5455
5456 my $pci_id_list = [ map { $_->{id} } map { $_->{pciid}->@* } values $pci_devices->%* ];
5457 # reserve all PCI IDs before actually doing anything with them
5458 PVE::QemuServer::PCI::reserve_pci_usage($pci_id_list, $vmid, $start_timeout);
5459
5460 eval {
5461 for my $id (sort keys %$pci_devices) {
5462 my $d = $pci_devices->{$id};
5463 for my $dev ($d->{pciid}->@*) {
5464 PVE::QemuServer::PCI::prepare_pci_device($vmid, $dev->{id}, $id, $d->{mdev});
5465 }
5466 }
5467 };
5468 if (my $err = $@) {
5469 eval { PVE::QemuServer::PCI::remove_pci_reservation($pci_id_list) };
5470 warn $@ if $@;
5471 die $err;
3898a563 5472 }
1e3baf05 5473
3898a563 5474 PVE::Storage::activate_volumes($storecfg, $vollist);
1e3baf05 5475
3898a563 5476 eval {
6bbcd71f 5477 run_command(['/bin/systemctl', 'stop', "$vmid.scope"], outfunc => sub{}, errfunc => sub{});
3898a563
FG
5478 };
5479 # Issues with the above 'stop' not being fully completed are extremely rare, a very low
5480 # timeout should be more than enough here...
5481 PVE::Systemd::wait_for_unit_removed("$vmid.scope", 5);
5482
d3f9db4d 5483 my $cpuunits = get_cpuunits($conf);
3898a563 5484
3898a563
FG
5485 my %run_params = (
5486 timeout => $statefile ? undef : $start_timeout,
5487 umask => 0077,
5488 noerr => 1,
5489 );
1e3baf05 5490
3898a563
FG
5491 # when migrating, prefix QEMU output so other side can pick up any
5492 # errors that might occur and show the user
5493 if ($migratedfrom) {
5494 $run_params{quiet} = 1;
5495 $run_params{logfunc} = sub { print "QEMU: $_[0]\n" };
5496 }
8bf30c2a 5497
212220a4 5498 my %systemd_properties = (
3898a563 5499 Slice => 'qemu.slice',
354e61aa
SR
5500 KillMode => 'process',
5501 SendSIGKILL => 0,
5502 TimeoutStopUSec => ULONG_MAX, # infinity
3898a563 5503 );
7023f3ea 5504
6cbd3eb8 5505 if (PVE::CGroup::cgroup_mode() == 2) {
6c71a52a 5506 $cpuunits = 10000 if $cpuunits >= 10000; # else we get an error
212220a4 5507 $systemd_properties{CPUWeight} = $cpuunits;
6cbd3eb8 5508 } else {
212220a4 5509 $systemd_properties{CPUShares} = $cpuunits;
6cbd3eb8
AD
5510 }
5511
3898a563 5512 if (my $cpulimit = $conf->{cpulimit}) {
212220a4 5513 $systemd_properties{CPUQuota} = int($cpulimit * 100);
3898a563 5514 }
212220a4 5515 $systemd_properties{timeout} = 10 if $statefile; # setting up the scope shoul be quick
7023f3ea 5516
3898a563
FG
5517 my $run_qemu = sub {
5518 PVE::Tools::run_fork sub {
212220a4 5519 PVE::Systemd::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %systemd_properties);
6e0216d8 5520
f9dde219
SR
5521 my $tpmpid;
5522 if (my $tpm = $conf->{tpmstate0}) {
5523 # start the TPM emulator so QEMU can connect on start
5524 $tpmpid = start_swtpm($storecfg, $vmid, $tpm, $migratedfrom);
5525 }
5526
3898a563 5527 my $exitcode = run_command($cmd, %run_params);
f9dde219 5528 if ($exitcode) {
23bee97d
FE
5529 if ($tpmpid) {
5530 warn "stopping swtpm instance (pid $tpmpid) due to QEMU startup error\n";
5531 kill 'TERM', $tpmpid;
5532 }
f9dde219
SR
5533 die "QEMU exited with code $exitcode\n";
5534 }
503308ed 5535 };
3898a563 5536 };
503308ed 5537
3898a563 5538 if ($conf->{hugepages}) {
7023f3ea 5539
3898a563
FG
5540 my $code = sub {
5541 my $hugepages_topology = PVE::QemuServer::Memory::hugepages_topology($conf);
5542 my $hugepages_host_topology = PVE::QemuServer::Memory::hugepages_host_topology();
7023f3ea 5543
3898a563
FG
5544 PVE::QemuServer::Memory::hugepages_mount();
5545 PVE::QemuServer::Memory::hugepages_allocate($hugepages_topology, $hugepages_host_topology);
7023f3ea 5546
503308ed 5547 eval { $run_qemu->() };
3898a563 5548 if (my $err = $@) {
f36e9894
SR
5549 PVE::QemuServer::Memory::hugepages_reset($hugepages_host_topology)
5550 if !$conf->{keephugepages};
3898a563
FG
5551 die $err;
5552 }
77cde36b 5553
f36e9894
SR
5554 PVE::QemuServer::Memory::hugepages_pre_deallocate($hugepages_topology)
5555 if !$conf->{keephugepages};
3898a563
FG
5556 };
5557 eval { PVE::QemuServer::Memory::hugepages_update_locked($code); };
1e3baf05 5558
3898a563
FG
5559 } else {
5560 eval { $run_qemu->() };
5561 }
afdb31d5 5562
3898a563
FG
5563 if (my $err = $@) {
5564 # deactivate volumes if start fails
5565 eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); };
1fb1822e
DC
5566 eval { PVE::QemuServer::PCI::remove_pci_reservation($pci_id_list) };
5567
3898a563
FG
5568 die "start failed: $err";
5569 }
62de2cbd 5570
1fb1822e
DC
5571 # re-reserve all PCI IDs now that we can know the actual VM PID
5572 my $pid = PVE::QemuServer::Helpers::vm_running_locally($vmid);
5573 eval { PVE::QemuServer::PCI::reserve_pci_usage($pci_id_list, $vmid, undef, $pid) };
5574 warn $@ if $@;
5575
3898a563 5576 print "migration listens on $migrate_uri\n" if $migrate_uri;
84da8217 5577 $res->{migrate_uri} = $migrate_uri;
eb8cddb5 5578
3898a563
FG
5579 if ($statefile && $statefile ne 'tcp' && $statefile ne 'unix') {
5580 eval { mon_cmd($vmid, "cont"); };
5581 warn $@ if $@;
5582 }
2189246c 5583
3898a563 5584 #start nbd server for storage migration
13cfe3b7 5585 if (my $nbd = $migrate_opts->{nbd}) {
3898a563 5586 my $nbd_protocol_version = $migrate_opts->{nbd_proto_version} // 0;
2189246c 5587
3898a563
FG
5588 my $migrate_storage_uri;
5589 # nbd_protocol_version > 0 for unix socket support
5590 if ($nbd_protocol_version > 0 && $migration_type eq 'secure') {
5591 my $socket_path = "/run/qemu-server/$vmid\_nbd.migrate";
5592 mon_cmd($vmid, "nbd-server-start", addr => { type => 'unix', data => { path => $socket_path } } );
5593 $migrate_storage_uri = "nbd:unix:$socket_path";
5594 } else {
5595 my $nodename = nodename();
5596 my $localip = $get_migration_ip->($nodename);
5597 my $pfamily = PVE::Tools::get_host_address_family($nodename);
5598 my $storage_migrate_port = PVE::Tools::next_migrate_port($pfamily);
5599
4df98f2f
TL
5600 mon_cmd($vmid, "nbd-server-start", addr => {
5601 type => 'inet',
5602 data => {
5603 host => "${localip}",
5604 port => "${storage_migrate_port}",
5605 },
5606 });
3898a563
FG
5607 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
5608 $migrate_storage_uri = "nbd:${localip}:${storage_migrate_port}";
2189246c
AD
5609 }
5610
84da8217
FG
5611 $res->{migrate_storage_uri} = $migrate_storage_uri;
5612
13cfe3b7 5613 foreach my $opt (sort keys %$nbd) {
ba5396b5
FG
5614 my $drivestr = $nbd->{$opt}->{drivestr};
5615 my $volid = $nbd->{$opt}->{volid};
3898a563 5616 mon_cmd($vmid, "nbd-server-add", device => "drive-$opt", writable => JSON::true );
84da8217
FG
5617 my $nbd_uri = "$migrate_storage_uri:exportname=drive-$opt";
5618 print "storage migration listens on $nbd_uri volume:$drivestr\n";
ba5396b5
FG
5619 print "re-using replicated volume: $opt - $volid\n"
5620 if $nbd->{$opt}->{replicated};
84da8217
FG
5621
5622 $res->{drives}->{$opt} = $nbd->{$opt};
5623 $res->{drives}->{$opt}->{nbd_uri} = $nbd_uri;
3898a563
FG
5624 }
5625 }
a89fded1 5626
3898a563
FG
5627 if ($migratedfrom) {
5628 eval {
5629 set_migration_caps($vmid);
5630 };
5631 warn $@ if $@;
5632
5633 if ($spice_port) {
5634 print "spice listens on port $spice_port\n";
84da8217 5635 $res->{spice_port} = $spice_port;
3898a563 5636 if ($migrate_opts->{spice_ticket}) {
4df98f2f
TL
5637 mon_cmd($vmid, "set_password", protocol => 'spice', password =>
5638 $migrate_opts->{spice_ticket});
3898a563 5639 mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30");
95a4b4a9 5640 }
3898a563 5641 }
95a4b4a9 5642
3898a563
FG
5643 } else {
5644 mon_cmd($vmid, "balloon", value => $conf->{balloon}*1024*1024)
5645 if !$statefile && $conf->{balloon};
25088687 5646
3898a563
FG
5647 foreach my $opt (keys %$conf) {
5648 next if $opt !~ m/^net\d+$/;
5649 my $nicconf = parse_net($conf->{$opt});
5650 qemu_set_link_status($vmid, $opt, 0) if $nicconf->{link_down};
e18b0b99 5651 }
3898a563 5652 }
a1b7d579 5653
3898a563
FG
5654 mon_cmd($vmid, 'qom-set',
5655 path => "machine/peripheral/balloon0",
5656 property => "guest-stats-polling-interval",
5657 value => 2) if (!defined($conf->{balloon}) || $conf->{balloon});
eb065317 5658
3898a563
FG
5659 if ($resume) {
5660 print "Resumed VM, removing state\n";
5661 if (my $vmstate = $conf->{vmstate}) {
5662 PVE::Storage::deactivate_volumes($storecfg, [$vmstate]);
5663 PVE::Storage::vdisk_free($storecfg, $vmstate);
7ceade4c 5664 }
ea1c2110 5665 delete $conf->@{qw(lock vmstate runningmachine runningcpu)};
3898a563
FG
5666 PVE::QemuConfig->write_config($vmid, $conf);
5667 }
7ceade4c 5668
3898a563 5669 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
84da8217
FG
5670
5671 return $res;
1e3baf05
DM
5672}
5673
1e3baf05 5674sub vm_commandline {
b14477e7 5675 my ($storecfg, $vmid, $snapname) = @_;
1e3baf05 5676
ffda963f 5677 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 5678
e8a26810 5679 my ($forcemachine, $forcecpu);
b14477e7
RV
5680 if ($snapname) {
5681 my $snapshot = $conf->{snapshots}->{$snapname};
87d92707
TL
5682 die "snapshot '$snapname' does not exist\n" if !defined($snapshot);
5683
ea1c2110
SR
5684 # check for machine or CPU overrides in snapshot
5685 $forcemachine = $snapshot->{runningmachine};
5686 $forcecpu = $snapshot->{runningcpu};
092868c4 5687
87d92707 5688 $snapshot->{digest} = $conf->{digest}; # keep file digest for API
b14477e7 5689
b14477e7
RV
5690 $conf = $snapshot;
5691 }
5692
1e3baf05
DM
5693 my $defaults = load_defaults();
5694
e8a26810 5695 my $cmd = config_to_command($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu);
1e3baf05 5696
5930c1ff 5697 return PVE::Tools::cmd2string($cmd);
1e3baf05
DM
5698}
5699
5700sub vm_reset {
5701 my ($vmid, $skiplock) = @_;
5702
ffda963f 5703 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 5704
ffda963f 5705 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 5706
ffda963f 5707 PVE::QemuConfig->check_lock($conf) if !$skiplock;
1e3baf05 5708
0a13e08e 5709 mon_cmd($vmid, "system_reset");
ff1a2432
DM
5710 });
5711}
5712
5713sub get_vm_volumes {
5714 my ($conf) = @_;
1e3baf05 5715
ff1a2432 5716 my $vollist = [];
d5769dc2 5717 foreach_volid($conf, sub {
392f8b5d 5718 my ($volid, $attr) = @_;
ff1a2432 5719
d5769dc2 5720 return if $volid =~ m|^/|;
ff1a2432 5721
d5769dc2
DM
5722 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
5723 return if !$sid;
ff1a2432
DM
5724
5725 push @$vollist, $volid;
1e3baf05 5726 });
ff1a2432
DM
5727
5728 return $vollist;
5729}
5730
5731sub vm_stop_cleanup {
70b04821 5732 my ($storecfg, $vmid, $conf, $keepActive, $apply_pending_changes) = @_;
ff1a2432 5733
745fed70 5734 eval {
ff1a2432 5735
254575e9
DM
5736 if (!$keepActive) {
5737 my $vollist = get_vm_volumes($conf);
5738 PVE::Storage::deactivate_volumes($storecfg, $vollist);
f9dde219
SR
5739
5740 if (my $tpmdrive = $conf->{tpmstate0}) {
5741 my $tpm = parse_drive("tpmstate0", $tpmdrive);
5742 my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1);
5743 if ($storeid) {
5744 PVE::Storage::unmap_volume($storecfg, $tpm->{file});
5745 }
5746 }
254575e9 5747 }
a1b7d579 5748
ab6a046f 5749 foreach my $ext (qw(mon qmp pid vnc qga)) {
961bfcb2
DM
5750 unlink "/var/run/qemu-server/${vmid}.$ext";
5751 }
a1b7d579 5752
6dbcb073 5753 if ($conf->{ivshmem}) {
4df98f2f 5754 my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem});
4c5a6a24
TL
5755 # just delete it for now, VMs which have this already open do not
5756 # are affected, but new VMs will get a separated one. If this
5757 # becomes an issue we either add some sort of ref-counting or just
5758 # add a "don't delete on stop" flag to the ivshmem format.
6dbcb073
DC
5759 unlink '/dev/shm/pve-shm-' . ($ivshmem->{name} // $vmid);
5760 }
5761
1fb1822e 5762 my $ids = [];
6ab45bd7
DC
5763 foreach my $key (keys %$conf) {
5764 next if $key !~ m/^hostpci(\d+)$/;
5765 my $hostpciindex = $1;
5766 my $d = parse_hostpci($conf->{$key});
5767 my $uuid = PVE::SysFSTools::generate_mdev_uuid($vmid, $hostpciindex);
5768
5769 foreach my $pci (@{$d->{pciid}}) {
2fd24788 5770 my $pciid = $pci->{id};
1fb1822e 5771 push @$ids, $pci->{id};
6ab45bd7
DC
5772 PVE::SysFSTools::pci_cleanup_mdev_device($pciid, $uuid);
5773 }
5774 }
1fb1822e 5775 PVE::QemuServer::PCI::remove_pci_reservation($ids);
6ab45bd7 5776
70b04821 5777 vmconfig_apply_pending($vmid, $conf, $storecfg) if $apply_pending_changes;
745fed70
DM
5778 };
5779 warn $@ if $@; # avoid errors - just warn
1e3baf05
DM
5780}
5781
575d19da
DC
5782# call only in locked context
5783sub _do_vm_stop {
5784 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive) = @_;
9269013a 5785
575d19da
DC
5786 my $pid = check_running($vmid, $nocheck);
5787 return if !$pid;
1e3baf05 5788
575d19da
DC
5789 my $conf;
5790 if (!$nocheck) {
5791 $conf = PVE::QemuConfig->load_config($vmid);
5792 PVE::QemuConfig->check_lock($conf) if !$skiplock;
5793 if (!defined($timeout) && $shutdown && $conf->{startup}) {
5794 my $opts = PVE::JSONSchema::pve_parse_startup_order($conf->{startup});
5795 $timeout = $opts->{down} if $opts->{down};
e6c3b671 5796 }
575d19da
DC
5797 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
5798 }
19672434 5799
575d19da
DC
5800 eval {
5801 if ($shutdown) {
a2af1bbe 5802 if (defined($conf) && get_qga_key($conf, 'enabled')) {
0a13e08e 5803 mon_cmd($vmid, "guest-shutdown", timeout => $timeout);
9269013a 5804 } else {
0a13e08e 5805 mon_cmd($vmid, "system_powerdown");
1e3baf05
DM
5806 }
5807 } else {
0a13e08e 5808 mon_cmd($vmid, "quit");
1e3baf05 5809 }
575d19da
DC
5810 };
5811 my $err = $@;
1e3baf05 5812
575d19da
DC
5813 if (!$err) {
5814 $timeout = 60 if !defined($timeout);
1e3baf05
DM
5815
5816 my $count = 0;
e6c3b671 5817 while (($count < $timeout) && check_running($vmid, $nocheck)) {
1e3baf05
DM
5818 $count++;
5819 sleep 1;
5820 }
5821
5822 if ($count >= $timeout) {
575d19da
DC
5823 if ($force) {
5824 warn "VM still running - terminating now with SIGTERM\n";
5825 kill 15, $pid;
5826 } else {
5827 die "VM quit/powerdown failed - got timeout\n";
5828 }
5829 } else {
5830 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
5831 return;
1e3baf05 5832 }
575d19da 5833 } else {
d60cbb97
TL
5834 if (!check_running($vmid, $nocheck)) {
5835 warn "Unexpected: VM shutdown command failed, but VM not running anymore..\n";
5836 return;
5837 }
5838 if ($force) {
575d19da
DC
5839 warn "VM quit/powerdown failed - terminating now with SIGTERM\n";
5840 kill 15, $pid;
5841 } else {
5842 die "VM quit/powerdown failed\n";
5843 }
5844 }
5845
5846 # wait again
5847 $timeout = 10;
5848
5849 my $count = 0;
5850 while (($count < $timeout) && check_running($vmid, $nocheck)) {
5851 $count++;
5852 sleep 1;
5853 }
5854
5855 if ($count >= $timeout) {
5856 warn "VM still running - terminating now with SIGKILL\n";
5857 kill 9, $pid;
5858 sleep 1;
5859 }
1e3baf05 5860
575d19da
DC
5861 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
5862}
5863
5864# Note: use $nocheck to skip tests if VM configuration file exists.
5865# We need that when migration VMs to other nodes (files already moved)
5866# Note: we set $keepActive in vzdump stop mode - volumes need to stay active
5867sub vm_stop {
5868 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive, $migratedfrom) = @_;
5869
5870 $force = 1 if !defined($force) && !$shutdown;
5871
5872 if ($migratedfrom){
5873 my $pid = check_running($vmid, $nocheck, $migratedfrom);
5874 kill 15, $pid if $pid;
5875 my $conf = PVE::QemuConfig->load_config($vmid, $migratedfrom);
5876 vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 0);
5877 return;
5878 }
5879
5880 PVE::QemuConfig->lock_config($vmid, sub {
5881 _do_vm_stop($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive);
ff1a2432 5882 });
1e3baf05
DM
5883}
5884
165411f0
DC
5885sub vm_reboot {
5886 my ($vmid, $timeout) = @_;
5887
5888 PVE::QemuConfig->lock_config($vmid, sub {
66026117 5889 eval {
165411f0 5890
66026117
OB
5891 # only reboot if running, as qmeventd starts it again on a stop event
5892 return if !check_running($vmid);
165411f0 5893
66026117 5894 create_reboot_request($vmid);
165411f0 5895
66026117
OB
5896 my $storecfg = PVE::Storage::config();
5897 _do_vm_stop($storecfg, $vmid, undef, undef, $timeout, 1);
165411f0 5898
66026117
OB
5899 };
5900 if (my $err = $@) {
3c1c3fe6 5901 # avoid that the next normal shutdown will be confused for a reboot
66026117
OB
5902 clear_reboot_request($vmid);
5903 die $err;
5904 }
165411f0
DC
5905 });
5906}
5907
75c24bba 5908# note: if using the statestorage parameter, the caller has to check privileges
1e3baf05 5909sub vm_suspend {
48b4cdc2 5910 my ($vmid, $skiplock, $includestate, $statestorage) = @_;
159719e5
DC
5911
5912 my $conf;
5913 my $path;
5914 my $storecfg;
5915 my $vmstate;
1e3baf05 5916
ffda963f 5917 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 5918
159719e5 5919 $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 5920
159719e5 5921 my $is_backing_up = PVE::QemuConfig->has_lock($conf, 'backup');
e79706d4 5922 PVE::QemuConfig->check_lock($conf)
159719e5
DC
5923 if !($skiplock || $is_backing_up);
5924
5925 die "cannot suspend to disk during backup\n"
5926 if $is_backing_up && $includestate;
bcb7c9cf 5927
159719e5
DC
5928 if ($includestate) {
5929 $conf->{lock} = 'suspending';
5930 my $date = strftime("%Y-%m-%d", localtime(time()));
5931 $storecfg = PVE::Storage::config();
75c24bba
DC
5932 if (!$statestorage) {
5933 $statestorage = find_vmstate_storage($conf, $storecfg);
5934 # check permissions for the storage
5935 my $rpcenv = PVE::RPCEnvironment::get();
5936 if ($rpcenv->{type} ne 'cli') {
5937 my $authuser = $rpcenv->get_user();
5938 $rpcenv->check($authuser, "/storage/$statestorage", ['Datastore.AllocateSpace']);
5939 }
5940 }
5941
5942
4df98f2f
TL
5943 $vmstate = PVE::QemuConfig->__snapshot_save_vmstate(
5944 $vmid, $conf, "suspend-$date", $storecfg, $statestorage, 1);
159719e5
DC
5945 $path = PVE::Storage::path($storecfg, $vmstate);
5946 PVE::QemuConfig->write_config($vmid, $conf);
5947 } else {
0a13e08e 5948 mon_cmd($vmid, "stop");
159719e5 5949 }
1e3baf05 5950 });
159719e5
DC
5951
5952 if ($includestate) {
5953 # save vm state
5954 PVE::Storage::activate_volumes($storecfg, [$vmstate]);
5955
5956 eval {
27a5be53 5957 set_migration_caps($vmid, 1);
0a13e08e 5958 mon_cmd($vmid, "savevm-start", statefile => $path);
159719e5 5959 for(;;) {
0a13e08e 5960 my $state = mon_cmd($vmid, "query-savevm");
159719e5
DC
5961 if (!$state->{status}) {
5962 die "savevm not active\n";
5963 } elsif ($state->{status} eq 'active') {
5964 sleep(1);
5965 next;
5966 } elsif ($state->{status} eq 'completed') {
b0a9a385 5967 print "State saved, quitting\n";
159719e5
DC
5968 last;
5969 } elsif ($state->{status} eq 'failed' && $state->{error}) {
5970 die "query-savevm failed with error '$state->{error}'\n"
5971 } else {
5972 die "query-savevm returned status '$state->{status}'\n";
5973 }
5974 }
5975 };
5976 my $err = $@;
5977
5978 PVE::QemuConfig->lock_config($vmid, sub {
5979 $conf = PVE::QemuConfig->load_config($vmid);
5980 if ($err) {
5981 # cleanup, but leave suspending lock, to indicate something went wrong
5982 eval {
0a13e08e 5983 mon_cmd($vmid, "savevm-end");
159719e5
DC
5984 PVE::Storage::deactivate_volumes($storecfg, [$vmstate]);
5985 PVE::Storage::vdisk_free($storecfg, $vmstate);
ea1c2110 5986 delete $conf->@{qw(vmstate runningmachine runningcpu)};
159719e5
DC
5987 PVE::QemuConfig->write_config($vmid, $conf);
5988 };
5989 warn $@ if $@;
5990 die $err;
5991 }
5992
5993 die "lock changed unexpectedly\n"
5994 if !PVE::QemuConfig->has_lock($conf, 'suspending');
5995
0a13e08e 5996 mon_cmd($vmid, "quit");
159719e5
DC
5997 $conf->{lock} = 'suspended';
5998 PVE::QemuConfig->write_config($vmid, $conf);
5999 });
6000 }
1e3baf05
DM
6001}
6002
6003sub vm_resume {
289e0b85 6004 my ($vmid, $skiplock, $nocheck) = @_;
1e3baf05 6005
ffda963f 6006 PVE::QemuConfig->lock_config($vmid, sub {
0a13e08e 6007 my $res = mon_cmd($vmid, 'query-status');
c2786bed 6008 my $resume_cmd = 'cont';
8e0c97bb 6009 my $reset = 0;
c2786bed 6010
8e0c97bb
SR
6011 if ($res->{status}) {
6012 return if $res->{status} eq 'running'; # job done, go home
6013 $resume_cmd = 'system_wakeup' if $res->{status} eq 'suspended';
6014 $reset = 1 if $res->{status} eq 'shutdown';
c2786bed
DC
6015 }
6016
289e0b85 6017 if (!$nocheck) {
1e3baf05 6018
ffda963f 6019 my $conf = PVE::QemuConfig->load_config($vmid);
1e3baf05 6020
e79706d4
FG
6021 PVE::QemuConfig->check_lock($conf)
6022 if !($skiplock || PVE::QemuConfig->has_lock($conf, 'backup'));
289e0b85 6023 }
3e24733b 6024
8e0c97bb
SR
6025 if ($reset) {
6026 # required if a VM shuts down during a backup and we get a resume
6027 # request before the backup finishes for example
6028 mon_cmd($vmid, "system_reset");
6029 }
0a13e08e 6030 mon_cmd($vmid, $resume_cmd);
1e3baf05
DM
6031 });
6032}
6033
5fdbe4f0
DM
6034sub vm_sendkey {
6035 my ($vmid, $skiplock, $key) = @_;
1e3baf05 6036
ffda963f 6037 PVE::QemuConfig->lock_config($vmid, sub {
1e3baf05 6038
ffda963f 6039 my $conf = PVE::QemuConfig->load_config($vmid);
f5eb281a 6040
7b7c6d1b 6041 # there is no qmp command, so we use the human monitor command
0a13e08e 6042 my $res = PVE::QemuServer::Monitor::hmp_cmd($vmid, "sendkey $key");
d30820d6 6043 die $res if $res ne '';
1e3baf05
DM
6044 });
6045}
6046
3e16d5fc
DM
6047# vzdump restore implementaion
6048
ed221350 6049sub tar_archive_read_firstfile {
3e16d5fc 6050 my $archive = shift;
afdb31d5 6051
3e16d5fc
DM
6052 die "ERROR: file '$archive' does not exist\n" if ! -f $archive;
6053
6054 # try to detect archive type first
387ba257 6055 my $pid = open (my $fh, '-|', 'tar', 'tf', $archive) ||
3e16d5fc 6056 die "unable to open file '$archive'\n";
387ba257 6057 my $firstfile = <$fh>;
3e16d5fc 6058 kill 15, $pid;
387ba257 6059 close $fh;
3e16d5fc
DM
6060
6061 die "ERROR: archive contaions no data\n" if !$firstfile;
6062 chomp $firstfile;
6063
6064 return $firstfile;
6065}
6066
ed221350
DM
6067sub tar_restore_cleanup {
6068 my ($storecfg, $statfile) = @_;
3e16d5fc
DM
6069
6070 print STDERR "starting cleanup\n";
6071
6072 if (my $fd = IO::File->new($statfile, "r")) {
6073 while (defined(my $line = <$fd>)) {
6074 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
6075 my $volid = $2;
6076 eval {
6077 if ($volid =~ m|^/|) {
6078 unlink $volid || die 'unlink failed\n';
6079 } else {
ed221350 6080 PVE::Storage::vdisk_free($storecfg, $volid);
3e16d5fc 6081 }
afdb31d5 6082 print STDERR "temporary volume '$volid' sucessfuly removed\n";
3e16d5fc
DM
6083 };
6084 print STDERR "unable to cleanup '$volid' - $@" if $@;
6085 } else {
6086 print STDERR "unable to parse line in statfile - $line";
afdb31d5 6087 }
3e16d5fc
DM
6088 }
6089 $fd->close();
6090 }
6091}
6092
d1e92cf6 6093sub restore_file_archive {
a0d1b1a2 6094 my ($archive, $vmid, $user, $opts) = @_;
3e16d5fc 6095
a2ec5a67
FG
6096 return restore_vma_archive($archive, $vmid, $user, $opts)
6097 if $archive eq '-';
6098
c6d51783
AA
6099 my $info = PVE::Storage::archive_info($archive);
6100 my $format = $opts->{format} // $info->{format};
6101 my $comp = $info->{compression};
91bd6c90
DM
6102
6103 # try to detect archive format
6104 if ($format eq 'tar') {
6105 return restore_tar_archive($archive, $vmid, $user, $opts);
6106 } else {
6107 return restore_vma_archive($archive, $vmid, $user, $opts, $comp);
6108 }
6109}
6110
d1e92cf6
DM
6111# hepler to remove disks that will not be used after restore
6112my $restore_cleanup_oldconf = sub {
6113 my ($storecfg, $vmid, $oldconf, $virtdev_hash) = @_;
6114
912792e2 6115 PVE::QemuConfig->foreach_volume($oldconf, sub {
d1e92cf6
DM
6116 my ($ds, $drive) = @_;
6117
6118 return if drive_is_cdrom($drive, 1);
6119
6120 my $volid = $drive->{file};
6121 return if !$volid || $volid =~ m|^/|;
6122
6123 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
6124 return if !$path || !$owner || ($owner != $vmid);
6125
6126 # Note: only delete disk we want to restore
6127 # other volumes will become unused
6128 if ($virtdev_hash->{$ds}) {
6129 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
6130 if (my $err = $@) {
6131 warn $err;
6132 }
6133 }
6134 });
6135
6136 # delete vmstate files, after the restore we have no snapshots anymore
6137 foreach my $snapname (keys %{$oldconf->{snapshots}}) {
6138 my $snap = $oldconf->{snapshots}->{$snapname};
6139 if ($snap->{vmstate}) {
6140 eval { PVE::Storage::vdisk_free($storecfg, $snap->{vmstate}); };
6141 if (my $err = $@) {
6142 warn $err;
6143 }
6144 }
6145 }
6146};
6147
9f3d73bc
DM
6148# Helper to parse vzdump backup device hints
6149#
6150# $rpcenv: Environment, used to ckeck storage permissions
6151# $user: User ID, to check storage permissions
6152# $storecfg: Storage configuration
6153# $fh: the file handle for reading the configuration
6154# $devinfo: should contain device sizes for all backu-up'ed devices
6155# $options: backup options (pool, default storage)
6156#
6157# Return: $virtdev_hash, updates $devinfo (add devname, virtdev, format, storeid)
6158my $parse_backup_hints = sub {
6159 my ($rpcenv, $user, $storecfg, $fh, $devinfo, $options) = @_;
d1e92cf6 6160
9f3d73bc 6161 my $virtdev_hash = {};
d1e92cf6 6162
9f3d73bc
DM
6163 while (defined(my $line = <$fh>)) {
6164 if ($line =~ m/^\#qmdump\#map:(\S+):(\S+):(\S*):(\S*):$/) {
6165 my ($virtdev, $devname, $storeid, $format) = ($1, $2, $3, $4);
6166 die "archive does not contain data for drive '$virtdev'\n"
6167 if !$devinfo->{$devname};
6168
6169 if (defined($options->{storage})) {
6170 $storeid = $options->{storage} || 'local';
6171 } elsif (!$storeid) {
6172 $storeid = 'local';
d1e92cf6 6173 }
9f3d73bc
DM
6174 $format = 'raw' if !$format;
6175 $devinfo->{$devname}->{devname} = $devname;
6176 $devinfo->{$devname}->{virtdev} = $virtdev;
6177 $devinfo->{$devname}->{format} = $format;
6178 $devinfo->{$devname}->{storeid} = $storeid;
6179
6180 # check permission on storage
6181 my $pool = $options->{pool}; # todo: do we need that?
6182 if ($user ne 'root@pam') {
6183 $rpcenv->check($user, "/storage/$storeid", ['Datastore.AllocateSpace']);
d1e92cf6 6184 }
d1e92cf6 6185
9f3d73bc
DM
6186 $virtdev_hash->{$virtdev} = $devinfo->{$devname};
6187 } elsif ($line =~ m/^((?:ide|sata|scsi)\d+):\s*(.*)\s*$/) {
6188 my $virtdev = $1;
6189 my $drive = parse_drive($virtdev, $2);
6190 if (drive_is_cloudinit($drive)) {
6191 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
5364990d
TL
6192 $storeid = $options->{storage} if defined ($options->{storage});
6193 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
9f3d73bc 6194 my $format = qemu_img_format($scfg, $volname); # has 'raw' fallback
d1e92cf6 6195
9f3d73bc
DM
6196 $virtdev_hash->{$virtdev} = {
6197 format => $format,
5364990d 6198 storeid => $storeid,
9f3d73bc
DM
6199 size => PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE,
6200 is_cloudinit => 1,
6201 };
d1e92cf6 6202 }
9f3d73bc
DM
6203 }
6204 }
d1e92cf6 6205
9f3d73bc
DM
6206 return $virtdev_hash;
6207};
d1e92cf6 6208
9f3d73bc
DM
6209# Helper to allocate and activate all volumes required for a restore
6210#
6211# $storecfg: Storage configuration
6212# $virtdev_hash: as returned by parse_backup_hints()
6213#
6214# Returns: { $virtdev => $volid }
6215my $restore_allocate_devices = sub {
6216 my ($storecfg, $virtdev_hash, $vmid) = @_;
d1e92cf6 6217
9f3d73bc
DM
6218 my $map = {};
6219 foreach my $virtdev (sort keys %$virtdev_hash) {
6220 my $d = $virtdev_hash->{$virtdev};
6221 my $alloc_size = int(($d->{size} + 1024 - 1)/1024);
6222 my $storeid = $d->{storeid};
6223 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
d1e92cf6 6224
9f3d73bc
DM
6225 # test if requested format is supported
6226 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
6227 my $supported = grep { $_ eq $d->{format} } @$validFormats;
6228 $d->{format} = $defFormat if !$supported;
d1e92cf6 6229
9f3d73bc
DM
6230 my $name;
6231 if ($d->{is_cloudinit}) {
6232 $name = "vm-$vmid-cloudinit";
c997e24a
ML
6233 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
6234 if ($scfg->{path}) {
6235 $name .= ".$d->{format}";
6236 }
d1e92cf6
DM
6237 }
6238
4df98f2f
TL
6239 my $volid = PVE::Storage::vdisk_alloc(
6240 $storecfg, $storeid, $vmid, $d->{format}, $name, $alloc_size);
d1e92cf6 6241
9f3d73bc
DM
6242 print STDERR "new volume ID is '$volid'\n";
6243 $d->{volid} = $volid;
d1e92cf6 6244
9f3d73bc 6245 PVE::Storage::activate_volumes($storecfg, [$volid]);
d1e92cf6 6246
9f3d73bc 6247 $map->{$virtdev} = $volid;
d1e92cf6
DM
6248 }
6249
9f3d73bc
DM
6250 return $map;
6251};
d1e92cf6 6252
c62d7cf5 6253sub restore_update_config_line {
eabac302 6254 my ($cookie, $map, $line, $unique) = @_;
91bd6c90 6255
98a4b3fb
FE
6256 return '' if $line =~ m/^\#qmdump\#/;
6257 return '' if $line =~ m/^\#vzdump\#/;
6258 return '' if $line =~ m/^lock:/;
6259 return '' if $line =~ m/^unused\d+:/;
6260 return '' if $line =~ m/^parent:/;
6261
6262 my $res = '';
91bd6c90 6263
b5b99790 6264 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
91bd6c90
DM
6265 if (($line =~ m/^(vlan(\d+)):\s*(\S+)\s*$/)) {
6266 # try to convert old 1.X settings
6267 my ($id, $ind, $ethcfg) = ($1, $2, $3);
6268 foreach my $devconfig (PVE::Tools::split_list($ethcfg)) {
6269 my ($model, $macaddr) = split(/\=/, $devconfig);
b5b99790 6270 $macaddr = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if !$macaddr || $unique;
91bd6c90
DM
6271 my $net = {
6272 model => $model,
6273 bridge => "vmbr$ind",
6274 macaddr => $macaddr,
6275 };
6276 my $netstr = print_net($net);
6277
98a4b3fb 6278 $res .= "net$cookie->{netcount}: $netstr\n";
91bd6c90
DM
6279 $cookie->{netcount}++;
6280 }
6281 } elsif (($line =~ m/^(net\d+):\s*(\S+)\s*$/) && $unique) {
6282 my ($id, $netstr) = ($1, $2);
6283 my $net = parse_net($netstr);
b5b99790 6284 $net->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if $net->{macaddr};
91bd6c90 6285 $netstr = print_net($net);
98a4b3fb 6286 $res .= "$id: $netstr\n";
f9dde219 6287 } elsif ($line =~ m/^((ide|scsi|virtio|sata|efidisk|tpmstate)\d+):\s*(\S+)\s*$/) {
91bd6c90 6288 my $virtdev = $1;
907ea891 6289 my $value = $3;
d9faf790
WB
6290 my $di = parse_drive($virtdev, $value);
6291 if (defined($di->{backup}) && !$di->{backup}) {
98a4b3fb 6292 $res .= "#$line";
c0f7406e 6293 } elsif ($map->{$virtdev}) {
8fd57431 6294 delete $di->{format}; # format can change on restore
91bd6c90 6295 $di->{file} = $map->{$virtdev};
71c58bb7 6296 $value = print_drive($di);
98a4b3fb 6297 $res .= "$virtdev: $value\n";
91bd6c90 6298 } else {
98a4b3fb 6299 $res .= $line;
91bd6c90 6300 }
1a0c2f03 6301 } elsif (($line =~ m/^vmgenid: (.*)/)) {
babecffe 6302 my $vmgenid = $1;
6ee499ff 6303 if ($vmgenid ne '0') {
1a0c2f03 6304 # always generate a new vmgenid if there was a valid one setup
6ee499ff
DC
6305 $vmgenid = generate_uuid();
6306 }
98a4b3fb 6307 $res .= "vmgenid: $vmgenid\n";
19a5dd55
WL
6308 } elsif (($line =~ m/^(smbios1: )(.*)/) && $unique) {
6309 my ($uuid, $uuid_str);
6310 UUID::generate($uuid);
6311 UUID::unparse($uuid, $uuid_str);
6312 my $smbios1 = parse_smbios1($2);
6313 $smbios1->{uuid} = $uuid_str;
98a4b3fb 6314 $res .= $1.print_smbios1($smbios1)."\n";
91bd6c90 6315 } else {
98a4b3fb 6316 $res .= $line;
91bd6c90 6317 }
98a4b3fb
FE
6318
6319 return $res;
c62d7cf5 6320}
9f3d73bc
DM
6321
6322my $restore_deactivate_volumes = sub {
6323 my ($storecfg, $devinfo) = @_;
6324
6325 my $vollist = [];
6326 foreach my $devname (keys %$devinfo) {
6327 my $volid = $devinfo->{$devname}->{volid};
6328 push @$vollist, $volid if $volid;
6329 }
6330
6331 PVE::Storage::deactivate_volumes($storecfg, $vollist);
6332};
6333
6334my $restore_destroy_volumes = sub {
6335 my ($storecfg, $devinfo) = @_;
6336
6337 foreach my $devname (keys %$devinfo) {
6338 my $volid = $devinfo->{$devname}->{volid};
6339 next if !$volid;
6340 eval {
6341 if ($volid =~ m|^/|) {
6342 unlink $volid || die 'unlink failed\n';
6343 } else {
6344 PVE::Storage::vdisk_free($storecfg, $volid);
6345 }
6346 print STDERR "temporary volume '$volid' sucessfuly removed\n";
6347 };
6348 print STDERR "unable to cleanup '$volid' - $@" if $@;
6349 }
6350};
91bd6c90
DM
6351
6352sub scan_volids {
9a8ba127 6353 my ($cfg, $vmid) = @_;
91bd6c90 6354
9a8ba127 6355 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'images');
91bd6c90
DM
6356
6357 my $volid_hash = {};
6358 foreach my $storeid (keys %$info) {
6359 foreach my $item (@{$info->{$storeid}}) {
6360 next if !($item->{volid} && $item->{size});
5996a936 6361 $item->{path} = PVE::Storage::path($cfg, $item->{volid});
91bd6c90
DM
6362 $volid_hash->{$item->{volid}} = $item;
6363 }
6364 }
6365
6366 return $volid_hash;
6367}
6368
68b108ee 6369sub update_disk_config {
91bd6c90 6370 my ($vmid, $conf, $volid_hash) = @_;
be190583 6371
91bd6c90 6372 my $changes;
9b29cbd0 6373 my $prefix = "VM $vmid";
91bd6c90 6374
c449137a
DC
6375 # used and unused disks
6376 my $referenced = {};
91bd6c90 6377
5996a936
DM
6378 # Note: it is allowed to define multiple storages with same path (alias), so
6379 # we need to check both 'volid' and real 'path' (two different volid can point
6380 # to the same path).
6381
c449137a 6382 my $referencedpath = {};
be190583 6383
91bd6c90 6384 # update size info
0c4fef3f 6385 PVE::QemuConfig->foreach_volume($conf, sub {
ca04977c 6386 my ($opt, $drive) = @_;
91bd6c90 6387
ca04977c
FE
6388 my $volid = $drive->{file};
6389 return if !$volid;
4df98f2f 6390 my $volume = $volid_hash->{$volid};
91bd6c90 6391
ca04977c
FE
6392 # mark volid as "in-use" for next step
6393 $referenced->{$volid} = 1;
4df98f2f 6394 if ($volume && (my $path = $volume->{path})) {
ca04977c 6395 $referencedpath->{$path} = 1;
91bd6c90 6396 }
ca04977c
FE
6397
6398 return if drive_is_cdrom($drive);
4df98f2f 6399 return if !$volume;
ca04977c 6400
4df98f2f 6401 my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $volume->{size});
ca04977c
FE
6402 if (defined($updated)) {
6403 $changes = 1;
6404 $conf->{$opt} = print_drive($updated);
9b29cbd0 6405 print "$prefix ($opt): $msg\n";
ca04977c
FE
6406 }
6407 });
91bd6c90 6408
5996a936 6409 # remove 'unusedX' entry if volume is used
ca04977c
FE
6410 PVE::QemuConfig->foreach_unused_volume($conf, sub {
6411 my ($opt, $drive) = @_;
6412
6413 my $volid = $drive->{file};
6414 return if !$volid;
6415
f7d1505b
TL
6416 my $path;
6417 $path = $volid_hash->{$volid}->{path} if $volid_hash->{$volid};
c449137a 6418 if ($referenced->{$volid} || ($path && $referencedpath->{$path})) {
68b108ee 6419 print "$prefix remove entry '$opt', its volume '$volid' is in use\n";
5996a936
DM
6420 $changes = 1;
6421 delete $conf->{$opt};
6422 }
c449137a
DC
6423
6424 $referenced->{$volid} = 1;
6425 $referencedpath->{$path} = 1 if $path;
ca04977c 6426 });
5996a936 6427
91bd6c90
DM
6428 foreach my $volid (sort keys %$volid_hash) {
6429 next if $volid =~ m/vm-$vmid-state-/;
c449137a 6430 next if $referenced->{$volid};
5996a936
DM
6431 my $path = $volid_hash->{$volid}->{path};
6432 next if !$path; # just to be sure
c449137a 6433 next if $referencedpath->{$path};
91bd6c90 6434 $changes = 1;
53b81297 6435 my $key = PVE::QemuConfig->add_unused_volume($conf, $volid);
68b108ee 6436 print "$prefix add unreferenced volume '$volid' as '$key' to config\n";
c449137a 6437 $referencedpath->{$path} = 1; # avoid to add more than once (aliases)
91bd6c90
DM
6438 }
6439
6440 return $changes;
6441}
6442
6443sub rescan {
9224dcee 6444 my ($vmid, $nolock, $dryrun) = @_;
91bd6c90 6445
20519efc 6446 my $cfg = PVE::Storage::config();
91bd6c90 6447
53b81297 6448 print "rescan volumes...\n";
9a8ba127 6449 my $volid_hash = scan_volids($cfg, $vmid);
91bd6c90
DM
6450
6451 my $updatefn = sub {
6452 my ($vmid) = @_;
6453
ffda963f 6454 my $conf = PVE::QemuConfig->load_config($vmid);
be190583 6455
ffda963f 6456 PVE::QemuConfig->check_lock($conf);
91bd6c90 6457
03da3f0d
DM
6458 my $vm_volids = {};
6459 foreach my $volid (keys %$volid_hash) {
6460 my $info = $volid_hash->{$volid};
6461 $vm_volids->{$volid} = $info if $info->{vmid} && $info->{vmid} == $vmid;
6462 }
6463
68b108ee 6464 my $changes = update_disk_config($vmid, $conf, $vm_volids);
91bd6c90 6465
9224dcee 6466 PVE::QemuConfig->write_config($vmid, $conf) if $changes && !$dryrun;
91bd6c90
DM
6467 };
6468
6469 if (defined($vmid)) {
6470 if ($nolock) {
6471 &$updatefn($vmid);
6472 } else {
ffda963f 6473 PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid);
91bd6c90
DM
6474 }
6475 } else {
6476 my $vmlist = config_list();
6477 foreach my $vmid (keys %$vmlist) {
6478 if ($nolock) {
6479 &$updatefn($vmid);
6480 } else {
ffda963f 6481 PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid);
be190583 6482 }
91bd6c90
DM
6483 }
6484 }
6485}
6486
9f3d73bc
DM
6487sub restore_proxmox_backup_archive {
6488 my ($archive, $vmid, $user, $options) = @_;
6489
6490 my $storecfg = PVE::Storage::config();
6491
6492 my ($storeid, $volname) = PVE::Storage::parse_volume_id($archive);
6493 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
6494
9f3d73bc 6495 my $fingerprint = $scfg->{fingerprint};
503e96f8 6496 my $keyfile = PVE::Storage::PBSPlugin::pbs_encryption_key_file_name($storecfg, $storeid);
9f3d73bc 6497
fbec3f89 6498 my $repo = PVE::PBSClient::get_repository($scfg);
dea4b04c 6499
26731a3c 6500 # This is only used for `pbs-restore` and the QEMU PBS driver (live-restore)
9f3d73bc
DM
6501 my $password = PVE::Storage::PBSPlugin::pbs_get_password($scfg, $storeid);
6502 local $ENV{PBS_PASSWORD} = $password;
6503 local $ENV{PBS_FINGERPRINT} = $fingerprint if defined($fingerprint);
6504
6505 my ($vtype, $pbs_backup_name, undef, undef, undef, undef, $format) =
6506 PVE::Storage::parse_volname($storecfg, $archive);
6507
6508 die "got unexpected vtype '$vtype'\n" if $vtype ne 'backup';
6509
6510 die "got unexpected backup format '$format'\n" if $format ne 'pbs-vm';
6511
6512 my $tmpdir = "/var/tmp/vzdumptmp$$";
6513 rmtree $tmpdir;
6514 mkpath $tmpdir;
6515
6516 my $conffile = PVE::QemuConfig->config_file($vmid);
9f3d73bc
DM
6517 # disable interrupts (always do cleanups)
6518 local $SIG{INT} =
6519 local $SIG{TERM} =
6520 local $SIG{QUIT} =
6521 local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; };
6522
6523 # Note: $oldconf is undef if VM does not exists
6524 my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid);
6525 my $oldconf = PVE::Cluster::cfs_read_file($cfs_path);
98a4b3fb 6526 my $new_conf_raw = '';
9f3d73bc
DM
6527
6528 my $rpcenv = PVE::RPCEnvironment::get();
6529 my $devinfo = {};
6530
6531 eval {
6532 # enable interrupts
6533 local $SIG{INT} =
6534 local $SIG{TERM} =
6535 local $SIG{QUIT} =
6536 local $SIG{HUP} =
6537 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
6538
6539 my $cfgfn = "$tmpdir/qemu-server.conf";
6540 my $firewall_config_fn = "$tmpdir/fw.conf";
6541 my $index_fn = "$tmpdir/index.json";
6542
6543 my $cmd = "restore";
6544
6545 my $param = [$pbs_backup_name, "index.json", $index_fn];
6546 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
6547 my $index = PVE::Tools::file_get_contents($index_fn);
6548 $index = decode_json($index);
6549
6550 # print Dumper($index);
6551 foreach my $info (@{$index->{files}}) {
6552 if ($info->{filename} =~ m/^(drive-\S+).img.fidx$/) {
6553 my $devname = $1;
6554 if ($info->{size} =~ m/^(\d+)$/) { # untaint size
6555 $devinfo->{$devname}->{size} = $1;
6556 } else {
6557 die "unable to parse file size in 'index.json' - got '$info->{size}'\n";
6558 }
6559 }
6560 }
6561
4df98f2f
TL
6562 my $is_qemu_server_backup = scalar(
6563 grep { $_->{filename} eq 'qemu-server.conf.blob' } @{$index->{files}}
6564 );
9f3d73bc
DM
6565 if (!$is_qemu_server_backup) {
6566 die "backup does not look like a qemu-server backup (missing 'qemu-server.conf' file)\n";
6567 }
6568 my $has_firewall_config = scalar(grep { $_->{filename} eq 'fw.conf.blob' } @{$index->{files}});
6569
6570 $param = [$pbs_backup_name, "qemu-server.conf", $cfgfn];
6571 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
6572
6573 if ($has_firewall_config) {
6574 $param = [$pbs_backup_name, "fw.conf", $firewall_config_fn];
6575 PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param);
6576
6577 my $pve_firewall_dir = '/etc/pve/firewall';
6578 mkdir $pve_firewall_dir; # make sure the dir exists
6579 PVE::Tools::file_copy($firewall_config_fn, "${pve_firewall_dir}/$vmid.fw");
6580 }
6581
6582 my $fh = IO::File->new($cfgfn, "r") ||
a1cbe55c 6583 die "unable to read qemu-server.conf - $!\n";
9f3d73bc
DM
6584
6585 my $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $storecfg, $fh, $devinfo, $options);
6586
6587 # fixme: rate limit?
6588
6589 # create empty/temp config
6590 PVE::Tools::file_set_contents($conffile, "memory: 128\nlock: create");
6591
6592 $restore_cleanup_oldconf->($storecfg, $vmid, $oldconf, $virtdev_hash) if $oldconf;
6593
6594 # allocate volumes
6595 my $map = $restore_allocate_devices->($storecfg, $virtdev_hash, $vmid);
6596
6f94e162
SR
6597 foreach my $virtdev (sort keys %$virtdev_hash) {
6598 my $d = $virtdev_hash->{$virtdev};
6599 next if $d->{is_cloudinit}; # no need to restore cloudinit
9f3d73bc 6600
55c7f9cf 6601 # this fails if storage is unavailable
6f94e162 6602 my $volid = $d->{volid};
6f94e162 6603 my $path = PVE::Storage::path($storecfg, $volid);
9f3d73bc 6604
f9dde219
SR
6605 # for live-restore we only want to preload the efidisk and TPM state
6606 next if $options->{live} && $virtdev ne 'efidisk0' && $virtdev ne 'tpmstate0';
55c7f9cf 6607
6f94e162
SR
6608 my $pbs_restore_cmd = [
6609 '/usr/bin/pbs-restore',
6610 '--repository', $repo,
6611 $pbs_backup_name,
6612 "$d->{devname}.img.fidx",
6613 $path,
6614 '--verbose',
6615 ];
55fb78aa 6616
6f94e162
SR
6617 push @$pbs_restore_cmd, '--format', $d->{format} if $d->{format};
6618 push @$pbs_restore_cmd, '--keyfile', $keyfile if -e $keyfile;
9f3d73bc 6619
6f94e162
SR
6620 if (PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $volid)) {
6621 push @$pbs_restore_cmd, '--skip-zero';
26731a3c 6622 }
6f94e162
SR
6623
6624 my $dbg_cmdstring = PVE::Tools::cmd2string($pbs_restore_cmd);
6625 print "restore proxmox backup image: $dbg_cmdstring\n";
6626 run_command($pbs_restore_cmd);
9f3d73bc
DM
6627 }
6628
6629 $fh->seek(0, 0) || die "seek failed - $!\n";
6630
9f3d73bc
DM
6631 my $cookie = { netcount => 0 };
6632 while (defined(my $line = <$fh>)) {
c62d7cf5 6633 $new_conf_raw .= restore_update_config_line(
98a4b3fb 6634 $cookie,
98a4b3fb
FE
6635 $map,
6636 $line,
6637 $options->{unique},
6638 );
9f3d73bc
DM
6639 }
6640
6641 $fh->close();
9f3d73bc
DM
6642 };
6643 my $err = $@;
6644
26731a3c
SR
6645 if ($err || !$options->{live}) {
6646 $restore_deactivate_volumes->($storecfg, $devinfo);
6647 }
9f3d73bc
DM
6648
6649 rmtree $tmpdir;
6650
6651 if ($err) {
9f3d73bc
DM
6652 $restore_destroy_volumes->($storecfg, $devinfo);
6653 die $err;
6654 }
6655
f7551170
SR
6656 if ($options->{live}) {
6657 # keep lock during live-restore
6658 $new_conf_raw .= "\nlock: create";
6659 }
6660
98a4b3fb 6661 PVE::Tools::file_set_contents($conffile, $new_conf_raw);
9f3d73bc
DM
6662
6663 PVE::Cluster::cfs_update(); # make sure we read new file
6664
6665 eval { rescan($vmid, 1); };
6666 warn $@ if $@;
26731a3c
SR
6667
6668 PVE::AccessControl::add_vm_to_pool($vmid, $options->{pool}) if $options->{pool};
6669
6670 if ($options->{live}) {
fefd65a1
SR
6671 # enable interrupts
6672 local $SIG{INT} =
6673 local $SIG{TERM} =
6674 local $SIG{QUIT} =
6675 local $SIG{HUP} =
6676 local $SIG{PIPE} = sub { die "got signal ($!) - abort\n"; };
26731a3c 6677
fefd65a1
SR
6678 my $conf = PVE::QemuConfig->load_config($vmid);
6679 die "cannot do live-restore for template\n" if PVE::QemuConfig->is_template($conf);
26731a3c 6680
f9dde219
SR
6681 # these special drives are already restored before start
6682 delete $devinfo->{'drive-efidisk0'};
6683 delete $devinfo->{'drive-tpmstate0-backup'};
fefd65a1 6684 pbs_live_restore($vmid, $conf, $storecfg, $devinfo, $repo, $keyfile, $pbs_backup_name);
f7551170
SR
6685
6686 PVE::QemuConfig->remove_lock($vmid, "create");
26731a3c
SR
6687 }
6688}
6689
6690sub pbs_live_restore {
6691 my ($vmid, $conf, $storecfg, $restored_disks, $repo, $keyfile, $snap) = @_;
6692
88cabb62 6693 print "starting VM for live-restore\n";
daf829ec 6694 print "repository: '$repo', snapshot: '$snap'\n";
26731a3c
SR
6695
6696 my $pbs_backing = {};
8986e36e 6697 for my $ds (keys %$restored_disks) {
26731a3c 6698 $ds =~ m/^drive-(.*)$/;
88cabb62
SR
6699 my $confname = $1;
6700 $pbs_backing->{$confname} = {
26731a3c
SR
6701 repository => $repo,
6702 snapshot => $snap,
6703 archive => "$ds.img.fidx",
6704 };
88cabb62
SR
6705 $pbs_backing->{$confname}->{keyfile} = $keyfile if -e $keyfile;
6706
6707 my $drive = parse_drive($confname, $conf->{$confname});
6708 print "restoring '$ds' to '$drive->{file}'\n";
26731a3c
SR
6709 }
6710
fd70c843 6711 my $drives_streamed = 0;
26731a3c
SR
6712 eval {
6713 # make sure HA doesn't interrupt our restore by stopping the VM
6714 if (PVE::HA::Config::vm_is_ha_managed($vmid)) {
fd70c843 6715 run_command(['ha-manager', 'set', "vm:$vmid", '--state', 'started']);
26731a3c
SR
6716 }
6717
fd70c843
TL
6718 # start VM with backing chain pointing to PBS backup, environment vars for PBS driver
6719 # in QEMU (PBS_PASSWORD and PBS_FINGERPRINT) are already set by our caller
bfb12678 6720 vm_start_nolock($storecfg, $vmid, $conf, {paused => 1, 'pbs-backing' => $pbs_backing}, {});
26731a3c 6721
26697640
SR
6722 my $qmeventd_fd = register_qmeventd_handle($vmid);
6723
26731a3c
SR
6724 # begin streaming, i.e. data copy from PBS to target disk for every vol,
6725 # this will effectively collapse the backing image chain consisting of
6726 # [target <- alloc-track -> PBS snapshot] to just [target] (alloc-track
6727 # removes itself once all backing images vanish with 'auto-remove=on')
6728 my $jobs = {};
8986e36e 6729 for my $ds (sort keys %$restored_disks) {
26731a3c
SR
6730 my $job_id = "restore-$ds";
6731 mon_cmd($vmid, 'block-stream',
6732 'job-id' => $job_id,
6733 device => "$ds",
6734 );
6735 $jobs->{$job_id} = {};
6736 }
6737
6738 mon_cmd($vmid, 'cont');
6739 qemu_drive_mirror_monitor($vmid, undef, $jobs, 'auto', 0, 'stream');
6740
a09b39f1
TL
6741 print "restore-drive jobs finished successfully, removing all tracking block devices"
6742 ." to disconnect from Proxmox Backup Server\n";
6743
8986e36e 6744 for my $ds (sort keys %$restored_disks) {
26731a3c
SR
6745 mon_cmd($vmid, 'blockdev-del', 'node-name' => "$ds-pbs");
6746 }
26697640
SR
6747
6748 close($qmeventd_fd);
26731a3c
SR
6749 };
6750
6751 my $err = $@;
6752
6753 if ($err) {
6754 warn "An error occured during live-restore: $err\n";
6755 _do_vm_stop($storecfg, $vmid, 1, 1, 10, 0, 1);
6756 die "live-restore failed\n";
6757 }
9f3d73bc
DM
6758}
6759
91bd6c90
DM
6760sub restore_vma_archive {
6761 my ($archive, $vmid, $user, $opts, $comp) = @_;
6762
91bd6c90
DM
6763 my $readfrom = $archive;
6764
7c536e11
WB
6765 my $cfg = PVE::Storage::config();
6766 my $commands = [];
6767 my $bwlimit = $opts->{bwlimit};
6768
6769 my $dbg_cmdstring = '';
6770 my $add_pipe = sub {
6771 my ($cmd) = @_;
6772 push @$commands, $cmd;
6773 $dbg_cmdstring .= ' | ' if length($dbg_cmdstring);
6774 $dbg_cmdstring .= PVE::Tools::cmd2string($cmd);
91bd6c90 6775 $readfrom = '-';
7c536e11
WB
6776 };
6777
6778 my $input = undef;
6779 if ($archive eq '-') {
6780 $input = '<&STDIN';
6781 } else {
6782 # If we use a backup from a PVE defined storage we also consider that
6783 # storage's rate limit:
6784 my (undef, $volid) = PVE::Storage::path_to_volume_id($cfg, $archive);
6785 if (defined($volid)) {
6786 my ($sid, undef) = PVE::Storage::parse_volume_id($volid);
6787 my $readlimit = PVE::Storage::get_bandwidth_limit('restore', [$sid], $bwlimit);
6788 if ($readlimit) {
6789 print STDERR "applying read rate limit: $readlimit\n";
9444c6e4 6790 my $cstream = ['cstream', '-t', $readlimit*1024, '--', $readfrom];
7c536e11
WB
6791 $add_pipe->($cstream);
6792 }
6793 }
6794 }
6795
6796 if ($comp) {
c6d51783
AA
6797 my $info = PVE::Storage::decompressor_info('vma', $comp);
6798 my $cmd = $info->{decompressor};
6799 push @$cmd, $readfrom;
7c536e11 6800 $add_pipe->($cmd);
91bd6c90
DM
6801 }
6802
6803 my $tmpdir = "/var/tmp/vzdumptmp$$";
6804 rmtree $tmpdir;
6805
6806 # disable interrupts (always do cleanups)
5b97ef24
TL
6807 local $SIG{INT} =
6808 local $SIG{TERM} =
6809 local $SIG{QUIT} =
6810 local $SIG{HUP} = sub { warn "got interrupt - ignored\n"; };
91bd6c90
DM
6811
6812 my $mapfifo = "/var/tmp/vzdumptmp$$.fifo";
6813 POSIX::mkfifo($mapfifo, 0600);
6814 my $fifofh;
808a65b5 6815 my $openfifo = sub { open($fifofh, '>', $mapfifo) or die $! };
91bd6c90 6816
7c536e11 6817 $add_pipe->(['vma', 'extract', '-v', '-r', $mapfifo, $readfrom, $tmpdir]);
91bd6c90
DM
6818
6819 my $oldtimeout;
6820 my $timeout = 5;
6821
6822 my $devinfo = {};
6823
6824 my $rpcenv = PVE::RPCEnvironment::get();
6825
ffda963f 6826 my $conffile = PVE::QemuConfig->config_file($vmid);
91bd6c90 6827
ae200950 6828 # Note: $oldconf is undef if VM does not exist
ffda963f
FG
6829 my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid);
6830 my $oldconf = PVE::Cluster::cfs_read_file($cfs_path);
98a4b3fb 6831 my $new_conf_raw = '';
ed221350 6832
7c536e11
WB
6833 my %storage_limits;
6834
91bd6c90 6835 my $print_devmap = sub {
91bd6c90
DM
6836 my $cfgfn = "$tmpdir/qemu-server.conf";
6837
6838 # we can read the config - that is already extracted
6839 my $fh = IO::File->new($cfgfn, "r") ||
a1cbe55c 6840 die "unable to read qemu-server.conf - $!\n";
91bd6c90 6841
6738ab9c 6842 my $fwcfgfn = "$tmpdir/qemu-server.fw";
3457d090
WL
6843 if (-f $fwcfgfn) {
6844 my $pve_firewall_dir = '/etc/pve/firewall';
6845 mkdir $pve_firewall_dir; # make sure the dir exists
6846 PVE::Tools::file_copy($fwcfgfn, "${pve_firewall_dir}/$vmid.fw");
6847 }
6738ab9c 6848
9f3d73bc 6849 my $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $cfg, $fh, $devinfo, $opts);
91bd6c90 6850
c8964278
FE
6851 foreach my $info (values %{$virtdev_hash}) {
6852 my $storeid = $info->{storeid};
6853 next if defined($storage_limits{$storeid});
6854
6855 my $limit = PVE::Storage::get_bandwidth_limit('restore', [$storeid], $bwlimit) // 0;
6856 print STDERR "rate limit for storage $storeid: $limit KiB/s\n" if $limit;
6857 $storage_limits{$storeid} = $limit * 1024;
7c536e11
WB
6858 }
6859
91bd6c90 6860 foreach my $devname (keys %$devinfo) {
be190583
DM
6861 die "found no device mapping information for device '$devname'\n"
6862 if !$devinfo->{$devname}->{virtdev};
91bd6c90
DM
6863 }
6864
ed221350 6865 # create empty/temp config
be190583 6866 if ($oldconf) {
ed221350 6867 PVE::Tools::file_set_contents($conffile, "memory: 128\n");
d1e92cf6 6868 $restore_cleanup_oldconf->($cfg, $vmid, $oldconf, $virtdev_hash);
ed221350
DM
6869 }
6870
9f3d73bc
DM
6871 # allocate volumes
6872 my $map = $restore_allocate_devices->($cfg, $virtdev_hash, $vmid);
6873
6874 # print restore information to $fifofh
91bd6c90
DM
6875 foreach my $virtdev (sort keys %$virtdev_hash) {
6876 my $d = $virtdev_hash->{$virtdev};
9f3d73bc
DM
6877 next if $d->{is_cloudinit}; # no need to restore cloudinit
6878
7c536e11 6879 my $storeid = $d->{storeid};
9f3d73bc 6880 my $volid = $d->{volid};
7c536e11
WB
6881
6882 my $map_opts = '';
6883 if (my $limit = $storage_limits{$storeid}) {
6884 $map_opts .= "throttling.bps=$limit:throttling.group=$storeid:";
6885 }
8fd57431 6886
91bd6c90 6887 my $write_zeros = 1;
88240a83 6888 if (PVE::Storage::volume_has_feature($cfg, 'sparseinit', $volid)) {
91bd6c90
DM
6889 $write_zeros = 0;
6890 }
6891
9f3d73bc 6892 my $path = PVE::Storage::path($cfg, $volid);
87056e18 6893
9f3d73bc 6894 print $fifofh "${map_opts}format=$d->{format}:${write_zeros}:$d->{devname}=$path\n";
91bd6c90 6895
9f3d73bc 6896 print "map '$d->{devname}' to '$path' (write zeros = ${write_zeros})\n";
91bd6c90
DM
6897 }
6898
6899 $fh->seek(0, 0) || die "seek failed - $!\n";
6900
91bd6c90
DM
6901 my $cookie = { netcount => 0 };
6902 while (defined(my $line = <$fh>)) {
c62d7cf5 6903 $new_conf_raw .= restore_update_config_line(
98a4b3fb 6904 $cookie,
98a4b3fb
FE
6905 $map,
6906 $line,
6907 $opts->{unique},
6908 );
91bd6c90
DM
6909 }
6910
6911 $fh->close();
91bd6c90
DM
6912 };
6913
6914 eval {
6915 # enable interrupts
6cb0144a
EK
6916 local $SIG{INT} =
6917 local $SIG{TERM} =
6918 local $SIG{QUIT} =
6919 local $SIG{HUP} =
6920 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
91bd6c90
DM
6921 local $SIG{ALRM} = sub { die "got timeout\n"; };
6922
6923 $oldtimeout = alarm($timeout);
6924
6925 my $parser = sub {
6926 my $line = shift;
6927
6928 print "$line\n";
6929
6930 if ($line =~ m/^DEV:\sdev_id=(\d+)\ssize:\s(\d+)\sdevname:\s(\S+)$/) {
6931 my ($dev_id, $size, $devname) = ($1, $2, $3);
6932 $devinfo->{$devname} = { size => $size, dev_id => $dev_id };
6933 } elsif ($line =~ m/^CTIME: /) {
46f58b5f 6934 # we correctly received the vma config, so we can disable
3cf90d7a
DM
6935 # the timeout now for disk allocation (set to 10 minutes, so
6936 # that we always timeout if something goes wrong)
6937 alarm(600);
91bd6c90
DM
6938 &$print_devmap();
6939 print $fifofh "done\n";
6940 my $tmp = $oldtimeout || 0;
6941 $oldtimeout = undef;
6942 alarm($tmp);
6943 close($fifofh);
808a65b5 6944 $fifofh = undef;
91bd6c90
DM
6945 }
6946 };
be190583 6947
7c536e11
WB
6948 print "restore vma archive: $dbg_cmdstring\n";
6949 run_command($commands, input => $input, outfunc => $parser, afterfork => $openfifo);
91bd6c90
DM
6950 };
6951 my $err = $@;
6952
6953 alarm($oldtimeout) if $oldtimeout;
6954
9f3d73bc 6955 $restore_deactivate_volumes->($cfg, $devinfo);
5f96f4df 6956
808a65b5 6957 close($fifofh) if $fifofh;
91bd6c90 6958 unlink $mapfifo;
9f3d73bc 6959 rmtree $tmpdir;
91bd6c90
DM
6960
6961 if ($err) {
9f3d73bc 6962 $restore_destroy_volumes->($cfg, $devinfo);
91bd6c90
DM
6963 die $err;
6964 }
6965
98a4b3fb 6966 PVE::Tools::file_set_contents($conffile, $new_conf_raw);
91bd6c90 6967
ed221350
DM
6968 PVE::Cluster::cfs_update(); # make sure we read new file
6969
91bd6c90
DM
6970 eval { rescan($vmid, 1); };
6971 warn $@ if $@;
26731a3c
SR
6972
6973 PVE::AccessControl::add_vm_to_pool($vmid, $opts->{pool}) if $opts->{pool};
91bd6c90
DM
6974}
6975
6976sub restore_tar_archive {
6977 my ($archive, $vmid, $user, $opts) = @_;
6978
9c502e26 6979 if ($archive ne '-') {
ed221350 6980 my $firstfile = tar_archive_read_firstfile($archive);
32e54050 6981 die "ERROR: file '$archive' does not look like a QemuServer vzdump backup\n"
9c502e26
DM
6982 if $firstfile ne 'qemu-server.conf';
6983 }
3e16d5fc 6984
20519efc 6985 my $storecfg = PVE::Storage::config();
ebb55558 6986
4b026937
TL
6987 # avoid zombie disks when restoring over an existing VM -> cleanup first
6988 # pass keep_empty_config=1 to keep the config (thus VMID) reserved for us
6989 # skiplock=1 because qmrestore has set the 'create' lock itself already
ffda963f 6990 my $vmcfgfn = PVE::QemuConfig->config_file($vmid);
b04ea584 6991 destroy_vm($storecfg, $vmid, 1, { lock => 'restore' }) if -f $vmcfgfn;
ed221350 6992
3e16d5fc
DM
6993 my $tocmd = "/usr/lib/qemu-server/qmextract";
6994
2415a446 6995 $tocmd .= " --storage " . PVE::Tools::shellquote($opts->{storage}) if $opts->{storage};
a0d1b1a2 6996 $tocmd .= " --pool " . PVE::Tools::shellquote($opts->{pool}) if $opts->{pool};
3e16d5fc
DM
6997 $tocmd .= ' --prealloc' if $opts->{prealloc};
6998 $tocmd .= ' --info' if $opts->{info};
6999
a0d1b1a2 7000 # tar option "xf" does not autodetect compression when read from STDIN,
9c502e26 7001 # so we pipe to zcat
2415a446
DM
7002 my $cmd = "zcat -f|tar xf " . PVE::Tools::shellquote($archive) . " " .
7003 PVE::Tools::shellquote("--to-command=$tocmd");
3e16d5fc
DM
7004
7005 my $tmpdir = "/var/tmp/vzdumptmp$$";
7006 mkpath $tmpdir;
7007
7008 local $ENV{VZDUMP_TMPDIR} = $tmpdir;
7009 local $ENV{VZDUMP_VMID} = $vmid;
a0d1b1a2 7010 local $ENV{VZDUMP_USER} = $user;
3e16d5fc 7011
ffda963f 7012 my $conffile = PVE::QemuConfig->config_file($vmid);
98a4b3fb 7013 my $new_conf_raw = '';
3e16d5fc
DM
7014
7015 # disable interrupts (always do cleanups)
6cb0144a
EK
7016 local $SIG{INT} =
7017 local $SIG{TERM} =
7018 local $SIG{QUIT} =
7019 local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; };
3e16d5fc 7020
afdb31d5 7021 eval {
3e16d5fc 7022 # enable interrupts
6cb0144a
EK
7023 local $SIG{INT} =
7024 local $SIG{TERM} =
7025 local $SIG{QUIT} =
7026 local $SIG{HUP} =
7027 local $SIG{PIPE} = sub { die "interrupted by signal\n"; };
3e16d5fc 7028
9c502e26
DM
7029 if ($archive eq '-') {
7030 print "extracting archive from STDIN\n";
7031 run_command($cmd, input => "<&STDIN");
7032 } else {
7033 print "extracting archive '$archive'\n";
7034 run_command($cmd);
7035 }
3e16d5fc
DM
7036
7037 return if $opts->{info};
7038
7039 # read new mapping
7040 my $map = {};
7041 my $statfile = "$tmpdir/qmrestore.stat";
7042 if (my $fd = IO::File->new($statfile, "r")) {
7043 while (defined (my $line = <$fd>)) {
7044 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
7045 $map->{$1} = $2 if $1;
7046 } else {
7047 print STDERR "unable to parse line in statfile - $line\n";
7048 }
7049 }
7050 $fd->close();
7051 }
7052
7053 my $confsrc = "$tmpdir/qemu-server.conf";
7054
f7d1505b 7055 my $srcfd = IO::File->new($confsrc, "r") || die "unable to open file '$confsrc'\n";
3e16d5fc 7056
91bd6c90 7057 my $cookie = { netcount => 0 };
3e16d5fc 7058 while (defined (my $line = <$srcfd>)) {
c62d7cf5 7059 $new_conf_raw .= restore_update_config_line(
98a4b3fb 7060 $cookie,
98a4b3fb
FE
7061 $map,
7062 $line,
7063 $opts->{unique},
7064 );
3e16d5fc
DM
7065 }
7066
7067 $srcfd->close();
3e16d5fc 7068 };
7dc7f315 7069 if (my $err = $@) {
ed221350 7070 tar_restore_cleanup($storecfg, "$tmpdir/qmrestore.stat") if !$opts->{info};
3e16d5fc 7071 die $err;
afdb31d5 7072 }
3e16d5fc
DM
7073
7074 rmtree $tmpdir;
7075
98a4b3fb 7076 PVE::Tools::file_set_contents($conffile, $new_conf_raw);
91bd6c90 7077
ed221350
DM
7078 PVE::Cluster::cfs_update(); # make sure we read new file
7079
91bd6c90
DM
7080 eval { rescan($vmid, 1); };
7081 warn $@ if $@;
3e16d5fc
DM
7082};
7083
65a5ce88 7084sub foreach_storage_used_by_vm {
18bfb361
DM
7085 my ($conf, $func) = @_;
7086
7087 my $sidhash = {};
7088
912792e2 7089 PVE::QemuConfig->foreach_volume($conf, sub {
8ddbcf8b
FG
7090 my ($ds, $drive) = @_;
7091 return if drive_is_cdrom($drive);
18bfb361
DM
7092
7093 my $volid = $drive->{file};
7094
7095 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
be190583 7096 $sidhash->{$sid} = $sid if $sid;
8ddbcf8b 7097 });
18bfb361
DM
7098
7099 foreach my $sid (sort keys %$sidhash) {
7100 &$func($sid);
7101 }
7102}
7103
6c9f59c1
TL
7104my $qemu_snap_storage = {
7105 rbd => 1,
7106};
e5eaa028 7107sub do_snapshots_with_qemu {
9d83932d
SR
7108 my ($storecfg, $volid, $deviceid) = @_;
7109
7110 return if $deviceid =~ m/tpmstate0/;
e5eaa028
WL
7111
7112 my $storage_name = PVE::Storage::parse_volume_id($volid);
8aa2ed7c 7113 my $scfg = $storecfg->{ids}->{$storage_name};
f7d1505b 7114 die "could not find storage '$storage_name'\n" if !defined($scfg);
e5eaa028 7115
8aa2ed7c 7116 if ($qemu_snap_storage->{$scfg->{type}} && !$scfg->{krbd}){
e5eaa028
WL
7117 return 1;
7118 }
7119
7120 if ($volid =~ m/\.(qcow2|qed)$/){
7121 return 1;
7122 }
7123
d1c1af4b 7124 return;
e5eaa028
WL
7125}
7126
4dcc780c 7127sub qga_check_running {
a4938c72 7128 my ($vmid, $nowarn) = @_;
4dcc780c 7129
0a13e08e 7130 eval { mon_cmd($vmid, "guest-ping", timeout => 3); };
4dcc780c 7131 if ($@) {
a4938c72 7132 warn "Qemu Guest Agent is not running - $@" if !$nowarn;
4dcc780c
WL
7133 return 0;
7134 }
7135 return 1;
7136}
7137
04a69bb4
AD
7138sub template_create {
7139 my ($vmid, $conf, $disk) = @_;
7140
04a69bb4 7141 my $storecfg = PVE::Storage::config();
04a69bb4 7142
912792e2 7143 PVE::QemuConfig->foreach_volume($conf, sub {
9cd07842
DM
7144 my ($ds, $drive) = @_;
7145
7146 return if drive_is_cdrom($drive);
7147 return if $disk && $ds ne $disk;
7148
7149 my $volid = $drive->{file};
bbd56097 7150 return if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
9cd07842 7151
04a69bb4
AD
7152 my $voliddst = PVE::Storage::vdisk_create_base($storecfg, $volid);
7153 $drive->{file} = $voliddst;
71c58bb7 7154 $conf->{$ds} = print_drive($drive);
ffda963f 7155 PVE::QemuConfig->write_config($vmid, $conf);
04a69bb4 7156 });
04a69bb4
AD
7157}
7158
92bdc3f0
DC
7159sub convert_iscsi_path {
7160 my ($path) = @_;
7161
7162 if ($path =~ m|^iscsi://([^/]+)/([^/]+)/(.+)$|) {
7163 my $portal = $1;
7164 my $target = $2;
7165 my $lun = $3;
7166
7167 my $initiator_name = get_initiator_name();
7168
7169 return "file.driver=iscsi,file.transport=tcp,file.initiator-name=$initiator_name,".
7170 "file.portal=$portal,file.target=$target,file.lun=$lun,driver=raw";
7171 }
7172
7173 die "cannot convert iscsi path '$path', unkown format\n";
7174}
7175
5133de42 7176sub qemu_img_convert {
988e2714 7177 my ($src_volid, $dst_volid, $size, $snapname, $is_zero_initialized) = @_;
5133de42
AD
7178
7179 my $storecfg = PVE::Storage::config();
7180 my ($src_storeid, $src_volname) = PVE::Storage::parse_volume_id($src_volid, 1);
7181 my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid, 1);
7182
af1f1ec0 7183 die "destination '$dst_volid' is not a valid volid form qemu-img convert\n" if !$dst_storeid;
6bb91c17 7184
af1f1ec0
DC
7185 my $cachemode;
7186 my $src_path;
7187 my $src_is_iscsi = 0;
bdd1feef 7188 my $src_format;
6bb91c17 7189
af1f1ec0
DC
7190 if ($src_storeid) {
7191 PVE::Storage::activate_volumes($storecfg, [$src_volid], $snapname);
5133de42 7192 my $src_scfg = PVE::Storage::storage_config($storecfg, $src_storeid);
af1f1ec0
DC
7193 $src_format = qemu_img_format($src_scfg, $src_volname);
7194 $src_path = PVE::Storage::path($storecfg, $src_volid, $snapname);
7195 $src_is_iscsi = ($src_path =~ m|^iscsi://|);
7196 $cachemode = 'none' if $src_scfg->{type} eq 'zfspool';
7197 } elsif (-f $src_volid) {
7198 $src_path = $src_volid;
e0fd2b2f 7199 if ($src_path =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) {
af1f1ec0
DC
7200 $src_format = $1;
7201 }
7202 }
5133de42 7203
af1f1ec0 7204 die "source '$src_volid' is not a valid volid nor path for qemu-img convert\n" if !$src_path;
5133de42 7205
af1f1ec0
DC
7206 my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid);
7207 my $dst_format = qemu_img_format($dst_scfg, $dst_volname);
7208 my $dst_path = PVE::Storage::path($storecfg, $dst_volid);
7209 my $dst_is_iscsi = ($dst_path =~ m|^iscsi://|);
5133de42 7210
af1f1ec0
DC
7211 my $cmd = [];
7212 push @$cmd, '/usr/bin/qemu-img', 'convert', '-p', '-n';
bdd1feef
TL
7213 push @$cmd, '-l', "snapshot.name=$snapname"
7214 if $snapname && $src_format && $src_format eq "qcow2";
af1f1ec0
DC
7215 push @$cmd, '-t', 'none' if $dst_scfg->{type} eq 'zfspool';
7216 push @$cmd, '-T', $cachemode if defined($cachemode);
7217
7218 if ($src_is_iscsi) {
7219 push @$cmd, '--image-opts';
7220 $src_path = convert_iscsi_path($src_path);
bdd1feef 7221 } elsif ($src_format) {
af1f1ec0
DC
7222 push @$cmd, '-f', $src_format;
7223 }
92bdc3f0 7224
af1f1ec0
DC
7225 if ($dst_is_iscsi) {
7226 push @$cmd, '--target-image-opts';
7227 $dst_path = convert_iscsi_path($dst_path);
7228 } else {
7229 push @$cmd, '-O', $dst_format;
7230 }
92bdc3f0 7231
af1f1ec0 7232 push @$cmd, $src_path;
92bdc3f0 7233
af1f1ec0
DC
7234 if (!$dst_is_iscsi && $is_zero_initialized) {
7235 push @$cmd, "zeroinit:$dst_path";
7236 } else {
7237 push @$cmd, $dst_path;
7238 }
92bdc3f0 7239
af1f1ec0
DC
7240 my $parser = sub {
7241 my $line = shift;
7242 if($line =~ m/\((\S+)\/100\%\)/){
7243 my $percent = $1;
7244 my $transferred = int($size * $percent / 100);
b5e9d97b
TL
7245 my $total_h = render_bytes($size, 1);
7246 my $transferred_h = render_bytes($transferred, 1);
92bdc3f0 7247
6629f976 7248 print "transferred $transferred_h of $total_h ($percent%)\n";
988e2714 7249 }
5133de42 7250
af1f1ec0 7251 };
5133de42 7252
af1f1ec0
DC
7253 eval { run_command($cmd, timeout => undef, outfunc => $parser); };
7254 my $err = $@;
7255 die "copy failed: $err" if $err;
5133de42
AD
7256}
7257
7258sub qemu_img_format {
7259 my ($scfg, $volname) = @_;
7260
e0fd2b2f 7261 if ($scfg->{path} && $volname =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) {
5133de42 7262 return $1;
be190583 7263 } else {
5133de42 7264 return "raw";
5133de42
AD
7265 }
7266}
7267
cfad42af 7268sub qemu_drive_mirror {
bc6c8231 7269 my ($vmid, $drive, $dst_volid, $vmiddst, $is_zero_initialized, $jobs, $completion, $qga, $bwlimit, $src_bitmap) = @_;
cfad42af 7270
5a345967
AD
7271 $jobs = {} if !$jobs;
7272
7273 my $qemu_target;
7274 my $format;
35e4ab04 7275 $jobs->{"drive-$drive"} = {};
152fe752 7276
1e5143de 7277 if ($dst_volid =~ /^nbd:/) {
87955688 7278 $qemu_target = $dst_volid;
5a345967 7279 $format = "nbd";
5a345967 7280 } else {
5a345967
AD
7281 my $storecfg = PVE::Storage::config();
7282 my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid);
7283
7284 my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid);
cfad42af 7285
5a345967 7286 $format = qemu_img_format($dst_scfg, $dst_volname);
21ccdb50 7287
5a345967 7288 my $dst_path = PVE::Storage::path($storecfg, $dst_volid);
21ccdb50 7289
5a345967
AD
7290 $qemu_target = $is_zero_initialized ? "zeroinit:$dst_path" : $dst_path;
7291 }
988e2714
WB
7292
7293 my $opts = { timeout => 10, device => "drive-$drive", mode => "existing", sync => "full", target => $qemu_target };
88383920
DM
7294 $opts->{format} = $format if $format;
7295
bc6c8231
FG
7296 if (defined($src_bitmap)) {
7297 $opts->{sync} = 'incremental';
7298 $opts->{bitmap} = $src_bitmap;
7299 print "drive mirror re-using dirty bitmap '$src_bitmap'\n";
7300 }
7301
9fa05d31 7302 if (defined($bwlimit)) {
f6409f61
TL
7303 $opts->{speed} = $bwlimit * 1024;
7304 print "drive mirror is starting for drive-$drive with bandwidth limit: ${bwlimit} KB/s\n";
9fa05d31
SI
7305 } else {
7306 print "drive mirror is starting for drive-$drive\n";
7307 }
21ccdb50 7308
6dde5ea2 7309 # if a job already runs for this device we get an error, catch it for cleanup
0a13e08e 7310 eval { mon_cmd($vmid, "drive-mirror", %$opts); };
5a345967
AD
7311 if (my $err = $@) {
7312 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
6dde5ea2
TL
7313 warn "$@\n" if $@;
7314 die "mirroring error: $err\n";
5a345967
AD
7315 }
7316
e02fb126 7317 qemu_drive_mirror_monitor ($vmid, $vmiddst, $jobs, $completion, $qga);
5a345967
AD
7318}
7319
db1f8b39
FG
7320# $completion can be either
7321# 'complete': wait until all jobs are ready, block-job-complete them (default)
7322# 'cancel': wait until all jobs are ready, block-job-cancel them
7323# 'skip': wait until all jobs are ready, return with block jobs in ready state
9e671722 7324# 'auto': wait until all jobs disappear, only use for jobs which complete automatically
5a345967 7325sub qemu_drive_mirror_monitor {
9e671722 7326 my ($vmid, $vmiddst, $jobs, $completion, $qga, $op) = @_;
e02fb126 7327
db1f8b39 7328 $completion //= 'complete';
9e671722 7329 $op //= "mirror";
2e953867 7330
08ac653f 7331 eval {
5a345967
AD
7332 my $err_complete = 0;
7333
3b56383b 7334 my $starttime = time ();
08ac653f 7335 while (1) {
9e671722 7336 die "block job ('$op') timed out\n" if $err_complete > 300;
5a345967 7337
0a13e08e 7338 my $stats = mon_cmd($vmid, "query-block-jobs");
3b56383b 7339 my $ctime = time();
08ac653f 7340
9e671722 7341 my $running_jobs = {};
0ea24bf0 7342 for my $stat (@$stats) {
9e671722
SR
7343 next if $stat->{type} ne $op;
7344 $running_jobs->{$stat->{device}} = $stat;
5a345967 7345 }
08ac653f 7346
5a345967 7347 my $readycounter = 0;
67fb9de6 7348
0ea24bf0 7349 for my $job_id (sort keys %$jobs) {
1057fc74 7350 my $job = $running_jobs->{$job_id};
5a345967 7351
1057fc74 7352 my $vanished = !defined($job);
0ea24bf0 7353 my $complete = defined($jobs->{$job_id}->{complete}) && $vanished;
9e671722 7354 if($complete || ($vanished && $completion eq 'auto')) {
3b56383b 7355 print "$job_id: $op-job finished\n";
0ea24bf0 7356 delete $jobs->{$job_id};
5a345967
AD
7357 next;
7358 }
7359
1057fc74 7360 die "$job_id: '$op' has been cancelled\n" if !defined($job);
f34ebd52 7361
1057fc74
TL
7362 my $busy = $job->{busy};
7363 my $ready = $job->{ready};
7364 if (my $total = $job->{len}) {
7365 my $transferred = $job->{offset} || 0;
5a345967
AD
7366 my $remaining = $total - $transferred;
7367 my $percent = sprintf "%.2f", ($transferred * 100 / $total);
08ac653f 7368
3b56383b
TL
7369 my $duration = $ctime - $starttime;
7370 my $total_h = render_bytes($total, 1);
7371 my $transferred_h = render_bytes($transferred, 1);
7372
7373 my $status = sprintf(
7374 "transferred $transferred_h of $total_h ($percent%%) in %s",
7375 render_duration($duration),
7376 );
7377
7378 if ($ready) {
7379 if ($busy) {
7380 $status .= ", still busy"; # shouldn't even happen? but mirror is weird
7381 } else {
7382 $status .= ", ready";
7383 }
7384 }
67daf692
TL
7385 print "$job_id: $status\n" if !$jobs->{$job_id}->{ready};
7386 $jobs->{$job_id}->{ready} = $ready;
5a345967 7387 }
f34ebd52 7388
1057fc74 7389 $readycounter++ if $job->{ready};
5a345967 7390 }
b467f79a 7391
5a345967
AD
7392 last if scalar(keys %$jobs) == 0;
7393
7394 if ($readycounter == scalar(keys %$jobs)) {
9e671722
SR
7395 print "all '$op' jobs are ready\n";
7396
7397 # do the complete later (or has already been done)
7398 last if $completion eq 'skip' || $completion eq 'auto';
5a345967
AD
7399
7400 if ($vmiddst && $vmiddst != $vmid) {
1a988fd2
DC
7401 my $agent_running = $qga && qga_check_running($vmid);
7402 if ($agent_running) {
5619e74a 7403 print "freeze filesystem\n";
0a13e08e 7404 eval { mon_cmd($vmid, "guest-fsfreeze-freeze"); };
5619e74a
AD
7405 } else {
7406 print "suspend vm\n";
7407 eval { PVE::QemuServer::vm_suspend($vmid, 1); };
7408 }
7409
5a345967
AD
7410 # if we clone a disk for a new target vm, we don't switch the disk
7411 PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs);
5619e74a 7412
1a988fd2 7413 if ($agent_running) {
5619e74a 7414 print "unfreeze filesystem\n";
0a13e08e 7415 eval { mon_cmd($vmid, "guest-fsfreeze-thaw"); };
5619e74a
AD
7416 } else {
7417 print "resume vm\n";
7418 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
7419 }
7420
2e953867 7421 last;
5a345967
AD
7422 } else {
7423
0ea24bf0 7424 for my $job_id (sort keys %$jobs) {
5a345967 7425 # try to switch the disk if source and destination are on the same guest
0ea24bf0 7426 print "$job_id: Completing block job_id...\n";
5a345967 7427
e02fb126 7428 my $op;
db1f8b39 7429 if ($completion eq 'complete') {
e02fb126 7430 $op = 'block-job-complete';
db1f8b39 7431 } elsif ($completion eq 'cancel') {
e02fb126
ML
7432 $op = 'block-job-cancel';
7433 } else {
7434 die "invalid completion value: $completion\n";
7435 }
0ea24bf0 7436 eval { mon_cmd($vmid, $op, device => $job_id) };
5a345967 7437 if ($@ =~ m/cannot be completed/) {
3b56383b 7438 print "$job_id: block job cannot be completed, trying again.\n";
5a345967
AD
7439 $err_complete++;
7440 }else {
0ea24bf0
TL
7441 print "$job_id: Completed successfully.\n";
7442 $jobs->{$job_id}->{complete} = 1;
5a345967
AD
7443 }
7444 }
2e953867 7445 }
08ac653f 7446 }
08ac653f 7447 sleep 1;
cfad42af 7448 }
08ac653f 7449 };
88383920 7450 my $err = $@;
08ac653f 7451
88383920 7452 if ($err) {
5a345967 7453 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) };
3b56383b 7454 die "block job ($op) error: $err";
88383920 7455 }
5a345967
AD
7456}
7457
7458sub qemu_blockjobs_cancel {
7459 my ($vmid, $jobs) = @_;
7460
7461 foreach my $job (keys %$jobs) {
bd2d5fe6 7462 print "$job: Cancelling block job\n";
0a13e08e 7463 eval { mon_cmd($vmid, "block-job-cancel", device => $job); };
5a345967
AD
7464 $jobs->{$job}->{cancel} = 1;
7465 }
7466
7467 while (1) {
0a13e08e 7468 my $stats = mon_cmd($vmid, "query-block-jobs");
5a345967
AD
7469
7470 my $running_jobs = {};
7471 foreach my $stat (@$stats) {
7472 $running_jobs->{$stat->{device}} = $stat;
7473 }
7474
7475 foreach my $job (keys %$jobs) {
7476
bd2d5fe6
WB
7477 if (defined($jobs->{$job}->{cancel}) && !defined($running_jobs->{$job})) {
7478 print "$job: Done.\n";
5a345967
AD
7479 delete $jobs->{$job};
7480 }
7481 }
7482
7483 last if scalar(keys %$jobs) == 0;
7484
7485 sleep 1;
cfad42af
AD
7486 }
7487}
7488
152fe752 7489sub clone_disk {
be190583 7490 my ($storecfg, $vmid, $running, $drivename, $drive, $snapname,
818ce80e 7491 $newvmid, $storage, $format, $full, $newvollist, $jobs, $completion, $qga, $bwlimit, $conf) = @_;
152fe752
DM
7492
7493 my $newvolid;
7494
7495 if (!$full) {
7496 print "create linked clone of drive $drivename ($drive->{file})\n";
258e646c 7497 $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname);
152fe752
DM
7498 push @$newvollist, $newvolid;
7499 } else {
5a345967 7500
152fe752
DM
7501 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
7502 $storeid = $storage if $storage;
7503
44549149 7504 my $dst_format = resolve_dst_disk_format($storecfg, $storeid, $volname, $format);
152fe752
DM
7505
7506 print "create full clone of drive $drivename ($drive->{file})\n";
931432bd 7507 my $name = undef;
d0abc774 7508 my $size = undef;
7fe8b44c
TL
7509 if (drive_is_cloudinit($drive)) {
7510 $name = "vm-$newvmid-cloudinit";
c997e24a
ML
7511 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
7512 if ($scfg->{path}) {
7513 $name .= ".$dst_format";
7514 }
7fe8b44c
TL
7515 $snapname = undef;
7516 $size = PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE;
818ce80e
DC
7517 } elsif ($drivename eq 'efidisk0') {
7518 $size = get_efivars_size($conf);
f9dde219
SR
7519 } elsif ($drivename eq 'tpmstate0') {
7520 $size = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE;
d0abc774 7521 } else {
3bae384f 7522 ($size) = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 10);
7fe8b44c 7523 }
b5688f69
FE
7524 $newvolid = PVE::Storage::vdisk_alloc(
7525 $storecfg, $storeid, $newvmid, $dst_format, $name, ($size/1024)
7526 );
152fe752
DM
7527 push @$newvollist, $newvolid;
7528
3999f370 7529 PVE::Storage::activate_volumes($storecfg, [$newvolid]);
1dbd6d30 7530
7fe8b44c 7531 if (drive_is_cloudinit($drive)) {
1b485263
ML
7532 # when cloning multiple disks (e.g. during clone_vm) it might be the last disk
7533 # if this is the case, we have to complete any block-jobs still there from
7534 # previous drive-mirrors
7535 if (($completion eq 'complete') && (scalar(keys %$jobs) > 0)) {
7536 qemu_drive_mirror_monitor($vmid, $newvmid, $jobs, $completion, $qga);
7537 }
7fe8b44c
TL
7538 goto no_data_clone;
7539 }
7540
988e2714 7541 my $sparseinit = PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $newvolid);
152fe752 7542 if (!$running || $snapname) {
d189e590 7543 # TODO: handle bwlimits
818ce80e
DC
7544 if ($drivename eq 'efidisk0') {
7545 # the relevant data on the efidisk may be smaller than the source
7546 # e.g. on RBD/ZFS, so we use dd to copy only the amount
7547 # that is given by the OVMF_VARS.fd
7548 my $src_path = PVE::Storage::path($storecfg, $drive->{file});
7549 my $dst_path = PVE::Storage::path($storecfg, $newvolid);
fdfdc80e
FE
7550
7551 # better for Ceph if block size is not too small, see bug #3324
7552 my $bs = 1024*1024;
7553
7554 run_command(['qemu-img', 'dd', '-n', '-O', $dst_format, "bs=$bs", "osize=$size",
4df98f2f 7555 "if=$src_path", "of=$dst_path"]);
818ce80e
DC
7556 } else {
7557 qemu_img_convert($drive->{file}, $newvolid, $size, $snapname, $sparseinit);
7558 }
152fe752 7559 } else {
2e541679 7560
f9dde219
SR
7561 die "cannot move TPM state while VM is running\n" if $drivename eq 'tpmstate0';
7562
2e541679 7563 my $kvmver = get_running_qemu_version ($vmid);
2ea5fb7e 7564 if (!min_version($kvmver, 2, 7)) {
961af8a3
WB
7565 die "drive-mirror with iothread requires qemu version 2.7 or higher\n"
7566 if $drive->{iothread};
2e541679 7567 }
2af848a2 7568
4df98f2f
TL
7569 qemu_drive_mirror($vmid, $drivename, $newvolid, $newvmid, $sparseinit, $jobs,
7570 $completion, $qga, $bwlimit);
be190583 7571 }
152fe752
DM
7572 }
7573
7fe8b44c 7574no_data_clone:
3bae384f 7575 my ($size) = eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) };
152fe752
DM
7576
7577 my $disk = $drive;
7578 $disk->{format} = undef;
7579 $disk->{file} = $newvolid;
3bae384f 7580 $disk->{size} = $size if defined($size);
152fe752
DM
7581
7582 return $disk;
7583}
7584
98cfd8b6
AD
7585sub get_running_qemu_version {
7586 my ($vmid) = @_;
0a13e08e 7587 my $res = mon_cmd($vmid, "query-version");
98cfd8b6
AD
7588 return "$res->{qemu}->{major}.$res->{qemu}->{minor}";
7589}
7590
249c4a6c
AD
7591sub qemu_use_old_bios_files {
7592 my ($machine_type) = @_;
7593
7594 return if !$machine_type;
7595
7596 my $use_old_bios_files = undef;
7597
7598 if ($machine_type =~ m/^(\S+)\.pxe$/) {
7599 $machine_type = $1;
7600 $use_old_bios_files = 1;
7601 } else {
4df98f2f 7602 my $version = extract_version($machine_type, kvm_user_version());
249c4a6c
AD
7603 # Note: kvm version < 2.4 use non-efi pxe files, and have problems when we
7604 # load new efi bios files on migration. So this hack is required to allow
7605 # live migration from qemu-2.2 to qemu-2.4, which is sometimes used when
7606 # updrading from proxmox-ve-3.X to proxmox-ve 4.0
2ea5fb7e 7607 $use_old_bios_files = !min_version($version, 2, 4);
249c4a6c
AD
7608 }
7609
7610 return ($use_old_bios_files, $machine_type);
7611}
7612
818ce80e
DC
7613sub get_efivars_size {
7614 my ($conf) = @_;
7615 my $arch = get_vm_arch($conf);
b5099b4f 7616 my $efidisk = $conf->{efidisk0} ? parse_drive('efidisk0', $conf->{efidisk0}) : undef;
90b20b15
DC
7617 my $smm = PVE::QemuServer::Machine::machine_type_is_q35($conf);
7618 my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm);
818ce80e
DC
7619 die "uefi vars image '$ovmf_vars' not found\n" if ! -f $ovmf_vars;
7620 return -s $ovmf_vars;
7621}
7622
7623sub update_efidisk_size {
7624 my ($conf) = @_;
7625
7626 return if !defined($conf->{efidisk0});
7627
7628 my $disk = PVE::QemuServer::parse_drive('efidisk0', $conf->{efidisk0});
7629 $disk->{size} = get_efivars_size($conf);
7630 $conf->{efidisk0} = print_drive($disk);
7631
7632 return;
7633}
7634
f9dde219
SR
7635sub update_tpmstate_size {
7636 my ($conf) = @_;
7637
7638 my $disk = PVE::QemuServer::parse_drive('tpmstate0', $conf->{tpmstate0});
7639 $disk->{size} = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE;
7640 $conf->{tpmstate0} = print_drive($disk);
7641}
7642
90b20b15
DC
7643sub create_efidisk($$$$$$$) {
7644 my ($storecfg, $storeid, $vmid, $fmt, $arch, $efidisk, $smm) = @_;
3e1f1122 7645
90b20b15 7646 my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm);
96ed3574 7647 die "EFI vars default image not found\n" if ! -f $ovmf_vars;
3e1f1122 7648
af1f1ec0
DC
7649 my $vars_size_b = -s $ovmf_vars;
7650 my $vars_size = PVE::Tools::convert_size($vars_size_b, 'b' => 'kb');
3e1f1122
TL
7651 my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, undef, $vars_size);
7652 PVE::Storage::activate_volumes($storecfg, [$volid]);
7653
af1f1ec0 7654 qemu_img_convert($ovmf_vars, $volid, $vars_size_b, undef, 0);
340dbcf7 7655 my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 3);
3e1f1122 7656
340dbcf7 7657 return ($volid, $size/1024);
3e1f1122
TL
7658}
7659
22de899a
AD
7660sub vm_iothreads_list {
7661 my ($vmid) = @_;
7662
0a13e08e 7663 my $res = mon_cmd($vmid, 'query-iothreads');
22de899a
AD
7664
7665 my $iothreads = {};
7666 foreach my $iothread (@$res) {
7667 $iothreads->{ $iothread->{id} } = $iothread->{"thread-id"};
7668 }
7669
7670 return $iothreads;
7671}
7672
ee034f5c
AD
7673sub scsihw_infos {
7674 my ($conf, $drive) = @_;
7675
7676 my $maxdev = 0;
7677
7fe1b688 7678 if (!$conf->{scsihw} || ($conf->{scsihw} =~ m/^lsi/)) {
ee034f5c 7679 $maxdev = 7;
a1511b3c 7680 } elsif ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
ee034f5c
AD
7681 $maxdev = 1;
7682 } else {
7683 $maxdev = 256;
7684 }
7685
7686 my $controller = int($drive->{index} / $maxdev);
4df98f2f
TL
7687 my $controller_prefix = ($conf->{scsihw} && $conf->{scsihw} eq 'virtio-scsi-single')
7688 ? "virtioscsi"
7689 : "scsihw";
ee034f5c
AD
7690
7691 return ($maxdev, $controller, $controller_prefix);
7692}
a1511b3c 7693
4317f69f
AD
7694sub windows_version {
7695 my ($ostype) = @_;
7696
7697 return 0 if !$ostype;
7698
7699 my $winversion = 0;
7700
7701 if($ostype eq 'wxp' || $ostype eq 'w2k3' || $ostype eq 'w2k') {
7702 $winversion = 5;
7703 } elsif($ostype eq 'w2k8' || $ostype eq 'wvista') {
7704 $winversion = 6;
7705 } elsif ($ostype =~ m/^win(\d+)$/) {
7706 $winversion = $1;
7707 }
7708
7709 return $winversion;
7710}
7711
44549149
EK
7712sub resolve_dst_disk_format {
7713 my ($storecfg, $storeid, $src_volname, $format) = @_;
7714 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
7715
7716 if (!$format) {
7717 # if no target format is specified, use the source disk format as hint
7718 if ($src_volname) {
7719 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
7720 $format = qemu_img_format($scfg, $src_volname);
7721 } else {
7722 return $defFormat;
7723 }
7724 }
7725
7726 # test if requested format is supported - else use default
7727 my $supported = grep { $_ eq $format } @$validFormats;
7728 $format = $defFormat if !$supported;
7729 return $format;
7730}
7731
66cebc46
DC
7732# NOTE: if this logic changes, please update docs & possibly gui logic
7733sub find_vmstate_storage {
7734 my ($conf, $storecfg) = @_;
7735
7736 # first, return storage from conf if set
7737 return $conf->{vmstatestorage} if $conf->{vmstatestorage};
7738
7739 my ($target, $shared, $local);
7740
7741 foreach_storage_used_by_vm($conf, sub {
7742 my ($sid) = @_;
7743 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
7744 my $dst = $scfg->{shared} ? \$shared : \$local;
7745 $$dst = $sid if !$$dst || $scfg->{path}; # prefer file based storage
7746 });
7747
7748 # second, use shared storage where VM has at least one disk
7749 # third, use local storage where VM has at least one disk
7750 # fall back to local storage
7751 $target = $shared // $local // 'local';
7752
7753 return $target;
7754}
7755
6ee499ff 7756sub generate_uuid {
ae2fcb3b
EK
7757 my ($uuid, $uuid_str);
7758 UUID::generate($uuid);
7759 UUID::unparse($uuid, $uuid_str);
6ee499ff
DC
7760 return $uuid_str;
7761}
7762
7763sub generate_smbios1_uuid {
7764 return "uuid=".generate_uuid();
ae2fcb3b
EK
7765}
7766
9c152e87
TL
7767sub nbd_stop {
7768 my ($vmid) = @_;
7769
0a13e08e 7770 mon_cmd($vmid, 'nbd-server-stop');
9c152e87
TL
7771}
7772
dae98db9
DC
7773sub create_reboot_request {
7774 my ($vmid) = @_;
7775 open(my $fh, '>', "/run/qemu-server/$vmid.reboot")
7776 or die "failed to create reboot trigger file: $!\n";
7777 close($fh);
7778}
7779
7780sub clear_reboot_request {
7781 my ($vmid) = @_;
7782 my $path = "/run/qemu-server/$vmid.reboot";
7783 my $res = 0;
7784
7785 $res = unlink($path);
7786 die "could not remove reboot request for $vmid: $!"
7787 if !$res && $! != POSIX::ENOENT;
7788
7789 return $res;
7790}
7791
5cfa9f5f
SR
7792sub bootorder_from_legacy {
7793 my ($conf, $bootcfg) = @_;
7794
7795 my $boot = $bootcfg->{legacy} || $boot_fmt->{legacy}->{default};
7796 my $bootindex_hash = {};
7797 my $i = 1;
7798 foreach my $o (split(//, $boot)) {
7799 $bootindex_hash->{$o} = $i*100;
7800 $i++;
7801 }
7802
7803 my $bootorder = {};
7804
7805 PVE::QemuConfig->foreach_volume($conf, sub {
7806 my ($ds, $drive) = @_;
7807
7808 if (drive_is_cdrom ($drive, 1)) {
7809 if ($bootindex_hash->{d}) {
7810 $bootorder->{$ds} = $bootindex_hash->{d};
7811 $bootindex_hash->{d} += 1;
7812 }
7813 } elsif ($bootindex_hash->{c}) {
7814 $bootorder->{$ds} = $bootindex_hash->{c}
7815 if $conf->{bootdisk} && $conf->{bootdisk} eq $ds;
7816 $bootindex_hash->{c} += 1;
7817 }
7818 });
7819
7820 if ($bootindex_hash->{n}) {
7821 for (my $i = 0; $i < $MAX_NETS; $i++) {
7822 my $netname = "net$i";
7823 next if !$conf->{$netname};
7824 $bootorder->{$netname} = $bootindex_hash->{n};
7825 $bootindex_hash->{n} += 1;
7826 }
7827 }
7828
7829 return $bootorder;
7830}
7831
7832# Generate default device list for 'boot: order=' property. Matches legacy
7833# default boot order, but with explicit device names. This is important, since
7834# the fallback for when neither 'order' nor the old format is specified relies
7835# on 'bootorder_from_legacy' above, and it would be confusing if this diverges.
7836sub get_default_bootdevices {
7837 my ($conf) = @_;
7838
7839 my @ret = ();
7840
7841 # harddisk
7842 my $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 0);
7843 push @ret, $first if $first;
7844
7845 # cdrom
7846 $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 1);
7847 push @ret, $first if $first;
7848
7849 # network
7850 for (my $i = 0; $i < $MAX_NETS; $i++) {
7851 my $netname = "net$i";
7852 next if !$conf->{$netname};
7853 push @ret, $netname;
7854 last;
7855 }
7856
7857 return \@ret;
7858}
7859
e5d611c3
TL
7860sub device_bootorder {
7861 my ($conf) = @_;
7862
7863 return bootorder_from_legacy($conf) if !defined($conf->{boot});
7864
7865 my $boot = parse_property_string($boot_fmt, $conf->{boot});
7866
7867 my $bootorder = {};
7868 if (!defined($boot) || $boot->{legacy}) {
7869 $bootorder = bootorder_from_legacy($conf, $boot);
7870 } elsif ($boot->{order}) {
7871 my $i = 100; # start at 100 to allow user to insert devices before us with -args
7872 for my $dev (PVE::Tools::split_list($boot->{order})) {
7873 $bootorder->{$dev} = $i++;
7874 }
7875 }
7876
7877 return $bootorder;
7878}
7879
65911545
SR
7880sub register_qmeventd_handle {
7881 my ($vmid) = @_;
7882
7883 my $fh;
7884 my $peer = "/var/run/qmeventd.sock";
7885 my $count = 0;
7886
7887 for (;;) {
7888 $count++;
7889 $fh = IO::Socket::UNIX->new(Peer => $peer, Blocking => 0, Timeout => 1);
7890 last if $fh;
7891 if ($! != EINTR && $! != EAGAIN) {
7892 die "unable to connect to qmeventd socket (vmid: $vmid) - $!\n";
7893 }
7894 if ($count > 4) {
7895 die "unable to connect to qmeventd socket (vmid: $vmid) - timeout "
7896 . "after $count retries\n";
7897 }
7898 usleep(25000);
7899 }
7900
7901 # send handshake to mark VM as backing up
7902 print $fh to_json({vzdump => {vmid => "$vmid"}});
7903
7904 # return handle to be closed later when inhibit is no longer required
7905 return $fh;
7906}
7907
65e866e5
DM
7908# bash completion helper
7909
7910sub complete_backup_archives {
7911 my ($cmdname, $pname, $cvalue) = @_;
7912
7913 my $cfg = PVE::Storage::config();
7914
7915 my $storeid;
7916
7917 if ($cvalue =~ m/^([^:]+):/) {
7918 $storeid = $1;
7919 }
7920
7921 my $data = PVE::Storage::template_list($cfg, $storeid, 'backup');
7922
7923 my $res = [];
7924 foreach my $id (keys %$data) {
7925 foreach my $item (@{$data->{$id}}) {
f43a4f12 7926 next if $item->{format} !~ m/^vma\.(${\PVE::Storage::Plugin::COMPRESSOR_RE})$/;
65e866e5
DM
7927 push @$res, $item->{volid} if defined($item->{volid});
7928 }
7929 }
7930
7931 return $res;
7932}
7933
7934my $complete_vmid_full = sub {
7935 my ($running) = @_;
7936
7937 my $idlist = vmstatus();
7938
7939 my $res = [];
7940
7941 foreach my $id (keys %$idlist) {
7942 my $d = $idlist->{$id};
7943 if (defined($running)) {
7944 next if $d->{template};
7945 next if $running && $d->{status} ne 'running';
7946 next if !$running && $d->{status} eq 'running';
7947 }
7948 push @$res, $id;
7949
7950 }
7951 return $res;
7952};
7953
7954sub complete_vmid {
7955 return &$complete_vmid_full();
7956}
7957
7958sub complete_vmid_stopped {
7959 return &$complete_vmid_full(0);
7960}
7961
7962sub complete_vmid_running {
7963 return &$complete_vmid_full(1);
7964}
7965
335af808
DM
7966sub complete_storage {
7967
7968 my $cfg = PVE::Storage::config();
7969 my $ids = $cfg->{ids};
7970
7971 my $res = [];
7972 foreach my $sid (keys %$ids) {
7973 next if !PVE::Storage::storage_check_enabled($cfg, $sid, undef, 1);
c4c844ef 7974 next if !$ids->{$sid}->{content}->{images};
335af808
DM
7975 push @$res, $sid;
7976 }
7977
7978 return $res;
7979}
7980
255e9c54
AL
7981sub complete_migration_storage {
7982 my ($cmd, $param, $current_value, $all_args) = @_;
7983
7984 my $targetnode = @$all_args[1];
7985
7986 my $cfg = PVE::Storage::config();
7987 my $ids = $cfg->{ids};
7988
7989 my $res = [];
7990 foreach my $sid (keys %$ids) {
7991 next if !PVE::Storage::storage_check_enabled($cfg, $sid, $targetnode, 1);
7992 next if !$ids->{$sid}->{content}->{images};
7993 push @$res, $sid;
7994 }
7995
7996 return $res;
7997}
7998
b08c37c3
DC
7999sub vm_is_paused {
8000 my ($vmid) = @_;
8001 my $qmpstatus = eval {
8002 PVE::QemuConfig::assert_config_exists_on_node($vmid);
8003 mon_cmd($vmid, "query-status");
8004 };
8005 warn "$@\n" if $@;
8006 return $qmpstatus && $qmpstatus->{status} eq "paused";
8007}
8008
3f11f0d7
LS
8009sub check_volume_storage_type {
8010 my ($storecfg, $vol) = @_;
8011
8012 my ($storeid, $volname) = PVE::Storage::parse_volume_id($vol);
8013 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
8014 my ($vtype) = PVE::Storage::parse_volname($storecfg, $vol);
8015
8016 die "storage '$storeid' does not support content-type '$vtype'\n"
8017 if !$scfg->{content}->{$vtype};
8018
8019 return 1;
8020}
8021
1e3baf05 80221;