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