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