]>
Commit | Line | Data |
---|---|---|
1 | package PVE::QemuServer; | |
2 | ||
3 | use strict; | |
4 | use warnings; | |
5 | ||
6 | use Cwd 'abs_path'; | |
7 | use Digest::SHA; | |
8 | use Fcntl ':flock'; | |
9 | use Fcntl; | |
10 | use File::Basename; | |
11 | use File::Copy qw(copy); | |
12 | use File::Path; | |
13 | use File::stat; | |
14 | use Getopt::Long; | |
15 | use IO::Dir; | |
16 | use IO::File; | |
17 | use IO::Handle; | |
18 | use IO::Select; | |
19 | use IO::Socket::UNIX; | |
20 | use IPC::Open3; | |
21 | use JSON; | |
22 | use MIME::Base64; | |
23 | use POSIX; | |
24 | use Storable qw(dclone); | |
25 | use Time::HiRes qw(gettimeofday usleep); | |
26 | use URI::Escape; | |
27 | use UUID; | |
28 | ||
29 | use PVE::Cluster qw(cfs_register_file cfs_read_file cfs_write_file); | |
30 | use PVE::CGroup; | |
31 | use PVE::DataCenterConfig; | |
32 | use PVE::Exception qw(raise raise_param_exc); | |
33 | use PVE::Format qw(render_duration render_bytes); | |
34 | use PVE::GuestHelpers qw(safe_string_ne safe_num_ne safe_boolean_ne); | |
35 | use PVE::INotify; | |
36 | use PVE::JSONSchema qw(get_standard_option parse_property_string); | |
37 | use PVE::ProcFSTools; | |
38 | use PVE::PBSClient; | |
39 | use PVE::RPCEnvironment; | |
40 | use PVE::Storage; | |
41 | use PVE::SysFSTools; | |
42 | use PVE::Systemd; | |
43 | use PVE::Tools qw(run_command file_read_firstline file_get_contents dir_glob_foreach get_host_arch $IPV6RE); | |
44 | ||
45 | use PVE::QMPClient; | |
46 | use PVE::QemuConfig; | |
47 | use PVE::QemuServer::Helpers qw(min_version config_aware_timeout); | |
48 | use PVE::QemuServer::Cloudinit; | |
49 | use PVE::QemuServer::CGroup; | |
50 | use PVE::QemuServer::CPUConfig qw(print_cpu_device get_cpu_options); | |
51 | use PVE::QemuServer::Drive qw(is_valid_drivename drive_is_cloudinit drive_is_cdrom drive_is_read_only parse_drive print_drive); | |
52 | use PVE::QemuServer::Machine; | |
53 | use PVE::QemuServer::Memory; | |
54 | use PVE::QemuServer::Monitor qw(mon_cmd); | |
55 | use PVE::QemuServer::PCI qw(print_pci_addr print_pcie_addr print_pcie_root_port parse_hostpci); | |
56 | use PVE::QemuServer::USB qw(parse_usb_device); | |
57 | ||
58 | my $have_sdn; | |
59 | eval { | |
60 | require PVE::Network::SDN::Zones; | |
61 | $have_sdn = 1; | |
62 | }; | |
63 | ||
64 | my $EDK2_FW_BASE = '/usr/share/pve-edk2-firmware/'; | |
65 | my $OVMF = { | |
66 | x86_64 => { | |
67 | '4m-no-smm' => [ | |
68 | "$EDK2_FW_BASE/OVMF_CODE_4M.fd", | |
69 | "$EDK2_FW_BASE/OVMF_VARS_4M.fd", | |
70 | ], | |
71 | '4m-no-smm-ms' => [ | |
72 | "$EDK2_FW_BASE/OVMF_CODE_4M.fd", | |
73 | "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd", | |
74 | ], | |
75 | '4m' => [ | |
76 | "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd", | |
77 | "$EDK2_FW_BASE/OVMF_VARS_4M.fd", | |
78 | ], | |
79 | '4m-ms' => [ | |
80 | "$EDK2_FW_BASE/OVMF_CODE_4M.secboot.fd", | |
81 | "$EDK2_FW_BASE/OVMF_VARS_4M.ms.fd", | |
82 | ], | |
83 | default => [ | |
84 | "$EDK2_FW_BASE/OVMF_CODE.fd", | |
85 | "$EDK2_FW_BASE/OVMF_VARS.fd", | |
86 | ], | |
87 | }, | |
88 | aarch64 => { | |
89 | default => [ | |
90 | "$EDK2_FW_BASE/AAVMF_CODE.fd", | |
91 | "$EDK2_FW_BASE/AAVMF_VARS.fd", | |
92 | ], | |
93 | }, | |
94 | }; | |
95 | ||
96 | my $cpuinfo = PVE::ProcFSTools::read_cpuinfo(); | |
97 | ||
98 | # Note about locking: we use flock on the config file protect against concurent actions. | |
99 | # Aditionaly, we have a 'lock' setting in the config file. This can be set to 'migrate', | |
100 | # 'backup', 'snapshot' or 'rollback'. Most actions are not allowed when such lock is set. | |
101 | # But you can ignore this kind of lock with the --skiplock flag. | |
102 | ||
103 | cfs_register_file('/qemu-server/', | |
104 | \&parse_vm_config, | |
105 | \&write_vm_config); | |
106 | ||
107 | PVE::JSONSchema::register_standard_option('pve-qm-stateuri', { | |
108 | description => "Some command save/restore state from this location.", | |
109 | type => 'string', | |
110 | maxLength => 128, | |
111 | optional => 1, | |
112 | }); | |
113 | ||
114 | PVE::JSONSchema::register_standard_option('pve-qemu-machine', { | |
115 | description => "Specifies the Qemu machine type.", | |
116 | type => 'string', | |
117 | pattern => '(pc|pc(-i440fx)?-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|q35|pc-q35-\d+(\.\d+)+(\+pve\d+)?(\.pxe)?|virt(?:-\d+(\.\d+)+)?(\+pve\d+)?)', | |
118 | maxLength => 40, | |
119 | optional => 1, | |
120 | }); | |
121 | ||
122 | ||
123 | sub map_storage { | |
124 | my ($map, $source) = @_; | |
125 | ||
126 | return $source if !defined($map); | |
127 | ||
128 | return $map->{entries}->{$source} | |
129 | if $map->{entries} && defined($map->{entries}->{$source}); | |
130 | ||
131 | return $map->{default} if $map->{default}; | |
132 | ||
133 | # identity (fallback) | |
134 | return $source; | |
135 | } | |
136 | ||
137 | PVE::JSONSchema::register_standard_option('pve-targetstorage', { | |
138 | description => "Mapping from source to target storages. Providing only a single storage ID maps all source storages to that storage. Providing the special value '1' will map each source storage to itself.", | |
139 | type => 'string', | |
140 | format => 'storagepair-list', | |
141 | optional => 1, | |
142 | }); | |
143 | ||
144 | #no warnings 'redefine'; | |
145 | ||
146 | my $nodename_cache; | |
147 | sub nodename { | |
148 | $nodename_cache //= PVE::INotify::nodename(); | |
149 | return $nodename_cache; | |
150 | } | |
151 | ||
152 | my $watchdog_fmt = { | |
153 | model => { | |
154 | default_key => 1, | |
155 | type => 'string', | |
156 | enum => [qw(i6300esb ib700)], | |
157 | description => "Watchdog type to emulate.", | |
158 | default => 'i6300esb', | |
159 | optional => 1, | |
160 | }, | |
161 | action => { | |
162 | type => 'string', | |
163 | enum => [qw(reset shutdown poweroff pause debug none)], | |
164 | description => "The action to perform if after activation the guest fails to poll the watchdog in time.", | |
165 | optional => 1, | |
166 | }, | |
167 | }; | |
168 | PVE::JSONSchema::register_format('pve-qm-watchdog', $watchdog_fmt); | |
169 | ||
170 | my $agent_fmt = { | |
171 | enabled => { | |
172 | description => "Enable/disable communication with a Qemu Guest Agent (QGA) running in the VM.", | |
173 | type => 'boolean', | |
174 | default => 0, | |
175 | default_key => 1, | |
176 | }, | |
177 | fstrim_cloned_disks => { | |
178 | description => "Run fstrim after moving a disk or migrating the VM.", | |
179 | type => 'boolean', | |
180 | optional => 1, | |
181 | default => 0 | |
182 | }, | |
183 | type => { | |
184 | description => "Select the agent type", | |
185 | type => 'string', | |
186 | default => 'virtio', | |
187 | optional => 1, | |
188 | enum => [qw(virtio isa)], | |
189 | }, | |
190 | }; | |
191 | ||
192 | my $vga_fmt = { | |
193 | type => { | |
194 | description => "Select the VGA type.", | |
195 | type => 'string', | |
196 | default => 'std', | |
197 | optional => 1, | |
198 | default_key => 1, | |
199 | enum => [qw(cirrus qxl qxl2 qxl3 qxl4 none serial0 serial1 serial2 serial3 std virtio vmware)], | |
200 | }, | |
201 | memory => { | |
202 | description => "Sets the VGA memory (in MiB). Has no effect with serial display.", | |
203 | type => 'integer', | |
204 | optional => 1, | |
205 | minimum => 4, | |
206 | maximum => 512, | |
207 | }, | |
208 | }; | |
209 | ||
210 | my $ivshmem_fmt = { | |
211 | size => { | |
212 | type => 'integer', | |
213 | minimum => 1, | |
214 | description => "The size of the file in MB.", | |
215 | }, | |
216 | name => { | |
217 | type => 'string', | |
218 | pattern => '[a-zA-Z0-9\-]+', | |
219 | optional => 1, | |
220 | format_description => 'string', | |
221 | description => "The name of the file. Will be prefixed with 'pve-shm-'. Default is the VMID. Will be deleted when the VM is stopped.", | |
222 | }, | |
223 | }; | |
224 | ||
225 | my $audio_fmt = { | |
226 | device => { | |
227 | type => 'string', | |
228 | enum => [qw(ich9-intel-hda intel-hda AC97)], | |
229 | description => "Configure an audio device." | |
230 | }, | |
231 | driver => { | |
232 | type => 'string', | |
233 | enum => ['spice', 'none'], | |
234 | default => 'spice', | |
235 | optional => 1, | |
236 | description => "Driver backend for the audio device." | |
237 | }, | |
238 | }; | |
239 | ||
240 | my $spice_enhancements_fmt = { | |
241 | foldersharing => { | |
242 | type => 'boolean', | |
243 | optional => 1, | |
244 | default => '0', | |
245 | description => "Enable folder sharing via SPICE. Needs Spice-WebDAV daemon installed in the VM." | |
246 | }, | |
247 | videostreaming => { | |
248 | type => 'string', | |
249 | enum => ['off', 'all', 'filter'], | |
250 | default => 'off', | |
251 | optional => 1, | |
252 | description => "Enable video streaming. Uses compression for detected video streams." | |
253 | }, | |
254 | }; | |
255 | ||
256 | my $rng_fmt = { | |
257 | source => { | |
258 | type => 'string', | |
259 | enum => ['/dev/urandom', '/dev/random', '/dev/hwrng'], | |
260 | default_key => 1, | |
261 | description => "The file on the host to gather entropy from. In most cases '/dev/urandom'" | |
262 | ." should be preferred over '/dev/random' to avoid entropy-starvation issues on the" | |
263 | ." host. Using urandom does *not* decrease security in any meaningful way, as it's" | |
264 | ." still seeded from real entropy, and the bytes provided will most likely be mixed" | |
265 | ." with real entropy on the guest as well. '/dev/hwrng' can be used to pass through" | |
266 | ." a hardware RNG from the host.", | |
267 | }, | |
268 | max_bytes => { | |
269 | type => 'integer', | |
270 | description => "Maximum bytes of entropy allowed to get injected into the guest every" | |
271 | ." 'period' milliseconds. Prefer a lower value when using '/dev/random' as source. Use" | |
272 | ." `0` to disable limiting (potentially dangerous!).", | |
273 | optional => 1, | |
274 | ||
275 | # default is 1 KiB/s, provides enough entropy to the guest to avoid boot-starvation issues | |
276 | # (e.g. systemd etc...) while allowing no chance of overwhelming the host, provided we're | |
277 | # reading from /dev/urandom | |
278 | default => 1024, | |
279 | }, | |
280 | period => { | |
281 | type => 'integer', | |
282 | description => "Every 'period' milliseconds the entropy-injection quota is reset, allowing" | |
283 | ." the guest to retrieve another 'max_bytes' of entropy.", | |
284 | optional => 1, | |
285 | default => 1000, | |
286 | }, | |
287 | }; | |
288 | ||
289 | my $meta_info_fmt = { | |
290 | 'ctime' => { | |
291 | type => 'integer', | |
292 | description => "The guest creation timestamp as UNIX epoch time", | |
293 | minimum => 0, | |
294 | optional => 1, | |
295 | }, | |
296 | }; | |
297 | ||
298 | my $confdesc = { | |
299 | onboot => { | |
300 | optional => 1, | |
301 | type => 'boolean', | |
302 | description => "Specifies whether a VM will be started during system bootup.", | |
303 | default => 0, | |
304 | }, | |
305 | autostart => { | |
306 | optional => 1, | |
307 | type => 'boolean', | |
308 | description => "Automatic restart after crash (currently ignored).", | |
309 | default => 0, | |
310 | }, | |
311 | hotplug => { | |
312 | optional => 1, | |
313 | type => 'string', format => 'pve-hotplug-features', | |
314 | description => "Selectively enable hotplug features. This is a comma separated list of" | |
315 | ." hotplug features: 'network', 'disk', 'cpu', 'memory' and 'usb'. Use '0' to disable" | |
316 | ." hotplug completely. Using '1' as value is an alias for the default `network,disk,usb`.", | |
317 | default => 'network,disk,usb', | |
318 | }, | |
319 | reboot => { | |
320 | optional => 1, | |
321 | type => 'boolean', | |
322 | description => "Allow reboot. If set to '0' the VM exit on reboot.", | |
323 | default => 1, | |
324 | }, | |
325 | lock => { | |
326 | optional => 1, | |
327 | type => 'string', | |
328 | description => "Lock/unlock the VM.", | |
329 | enum => [qw(backup clone create migrate rollback snapshot snapshot-delete suspending suspended)], | |
330 | }, | |
331 | cpulimit => { | |
332 | optional => 1, | |
333 | type => 'number', | |
334 | description => "Limit of CPU usage.", | |
335 | verbose_description => "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has" | |
336 | ." total of '2' CPU time. Value '0' indicates no CPU limit.", | |
337 | minimum => 0, | |
338 | maximum => 128, | |
339 | default => 0, | |
340 | }, | |
341 | cpuunits => { | |
342 | optional => 1, | |
343 | type => 'integer', | |
344 | description => "CPU weight for a VM, will be clamped to [1, 10000] in cgroup v2.", | |
345 | verbose_description => "CPU weight for a VM. Argument is used in the kernel fair scheduler." | |
346 | ." The larger the number is, the more CPU time this VM gets. Number is relative to" | |
347 | ." weights of all the other running VMs.", | |
348 | minimum => 2, | |
349 | maximum => 262144, | |
350 | default => 'cgroup v1: 1024, cgroup v2: 100', | |
351 | }, | |
352 | memory => { | |
353 | optional => 1, | |
354 | type => 'integer', | |
355 | description => "Amount of RAM for the VM in MB. This is the maximum available memory when" | |
356 | ." you use the balloon device.", | |
357 | minimum => 16, | |
358 | default => 512, | |
359 | }, | |
360 | balloon => { | |
361 | optional => 1, | |
362 | type => 'integer', | |
363 | description => "Amount of target RAM for the VM in MB. Using zero disables the ballon driver.", | |
364 | minimum => 0, | |
365 | }, | |
366 | shares => { | |
367 | optional => 1, | |
368 | type => 'integer', | |
369 | description => "Amount of memory shares for auto-ballooning. The larger the number is, the" | |
370 | ." more memory this VM gets. Number is relative to weights of all other running VMs." | |
371 | ." Using zero disables auto-ballooning. Auto-ballooning is done by pvestatd.", | |
372 | minimum => 0, | |
373 | maximum => 50000, | |
374 | default => 1000, | |
375 | }, | |
376 | keyboard => { | |
377 | optional => 1, | |
378 | type => 'string', | |
379 | description => "Keyboard layout for VNC server. The default is read from the" | |
380 | ."'/etc/pve/datacenter.cfg' configuration file. It should not be necessary to set it.", | |
381 | enum => PVE::Tools::kvmkeymaplist(), | |
382 | default => undef, | |
383 | }, | |
384 | name => { | |
385 | optional => 1, | |
386 | type => 'string', format => 'dns-name', | |
387 | description => "Set a name for the VM. Only used on the configuration web interface.", | |
388 | }, | |
389 | scsihw => { | |
390 | optional => 1, | |
391 | type => 'string', | |
392 | description => "SCSI controller model", | |
393 | enum => [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)], | |
394 | default => 'lsi', | |
395 | }, | |
396 | description => { | |
397 | optional => 1, | |
398 | type => 'string', | |
399 | description => "Description for the VM. Shown in the web-interface VM's summary." | |
400 | ." This is saved as comment inside the configuration file.", | |
401 | maxLength => 1024 * 8, | |
402 | }, | |
403 | ostype => { | |
404 | optional => 1, | |
405 | type => 'string', | |
406 | enum => [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 win11 l24 l26 solaris)], | |
407 | description => "Specify guest operating system.", | |
408 | verbose_description => <<EODESC, | |
409 | Specify guest operating system. This is used to enable special | |
410 | optimization/features for specific operating systems: | |
411 | ||
412 | [horizontal] | |
413 | other;; unspecified OS | |
414 | wxp;; Microsoft Windows XP | |
415 | w2k;; Microsoft Windows 2000 | |
416 | w2k3;; Microsoft Windows 2003 | |
417 | w2k8;; Microsoft Windows 2008 | |
418 | wvista;; Microsoft Windows Vista | |
419 | win7;; Microsoft Windows 7 | |
420 | win8;; Microsoft Windows 8/2012/2012r2 | |
421 | win10;; Microsoft Windows 10/2016/2019 | |
422 | win11;; Microsoft Windows 11/2022 | |
423 | l24;; Linux 2.4 Kernel | |
424 | l26;; Linux 2.6 - 5.X Kernel | |
425 | solaris;; Solaris/OpenSolaris/OpenIndiania kernel | |
426 | EODESC | |
427 | }, | |
428 | boot => { | |
429 | optional => 1, | |
430 | type => 'string', format => 'pve-qm-boot', | |
431 | description => "Specify guest boot order. Use the 'order=' sub-property as usage with no" | |
432 | ." key or 'legacy=' is deprecated.", | |
433 | }, | |
434 | bootdisk => { | |
435 | optional => 1, | |
436 | type => 'string', format => 'pve-qm-bootdisk', | |
437 | description => "Enable booting from specified disk. Deprecated: Use 'boot: order=foo;bar' instead.", | |
438 | pattern => '(ide|sata|scsi|virtio)\d+', | |
439 | }, | |
440 | smp => { | |
441 | optional => 1, | |
442 | type => 'integer', | |
443 | description => "The number of CPUs. Please use option -sockets instead.", | |
444 | minimum => 1, | |
445 | default => 1, | |
446 | }, | |
447 | sockets => { | |
448 | optional => 1, | |
449 | type => 'integer', | |
450 | description => "The number of CPU sockets.", | |
451 | minimum => 1, | |
452 | default => 1, | |
453 | }, | |
454 | cores => { | |
455 | optional => 1, | |
456 | type => 'integer', | |
457 | description => "The number of cores per socket.", | |
458 | minimum => 1, | |
459 | default => 1, | |
460 | }, | |
461 | numa => { | |
462 | optional => 1, | |
463 | type => 'boolean', | |
464 | description => "Enable/disable NUMA.", | |
465 | default => 0, | |
466 | }, | |
467 | hugepages => { | |
468 | optional => 1, | |
469 | type => 'string', | |
470 | description => "Enable/disable hugepages memory.", | |
471 | enum => [qw(any 2 1024)], | |
472 | }, | |
473 | keephugepages => { | |
474 | optional => 1, | |
475 | type => 'boolean', | |
476 | default => 0, | |
477 | description => "Use together with hugepages. If enabled, hugepages will not not be deleted" | |
478 | ." after VM shutdown and can be used for subsequent starts.", | |
479 | }, | |
480 | vcpus => { | |
481 | optional => 1, | |
482 | type => 'integer', | |
483 | description => "Number of hotplugged vcpus.", | |
484 | minimum => 1, | |
485 | default => 0, | |
486 | }, | |
487 | acpi => { | |
488 | optional => 1, | |
489 | type => 'boolean', | |
490 | description => "Enable/disable ACPI.", | |
491 | default => 1, | |
492 | }, | |
493 | agent => { | |
494 | optional => 1, | |
495 | description => "Enable/disable communication with the Qemu Guest Agent and its properties.", | |
496 | type => 'string', | |
497 | format => $agent_fmt, | |
498 | }, | |
499 | kvm => { | |
500 | optional => 1, | |
501 | type => 'boolean', | |
502 | description => "Enable/disable KVM hardware virtualization.", | |
503 | default => 1, | |
504 | }, | |
505 | tdf => { | |
506 | optional => 1, | |
507 | type => 'boolean', | |
508 | description => "Enable/disable time drift fix.", | |
509 | default => 0, | |
510 | }, | |
511 | localtime => { | |
512 | optional => 1, | |
513 | type => 'boolean', | |
514 | description => "Set the real time clock (RTC) to local time. This is enabled by default if" | |
515 | ." the `ostype` indicates a Microsoft Windows OS.", | |
516 | }, | |
517 | freeze => { | |
518 | optional => 1, | |
519 | type => 'boolean', | |
520 | description => "Freeze CPU at startup (use 'c' monitor command to start execution).", | |
521 | }, | |
522 | vga => { | |
523 | optional => 1, | |
524 | type => 'string', format => $vga_fmt, | |
525 | description => "Configure the VGA hardware.", | |
526 | verbose_description => "Configure the VGA Hardware. If you want to use high resolution" | |
527 | ." modes (>= 1280x1024x16) you may need to increase the vga memory option. Since QEMU" | |
528 | ." 2.9 the default VGA display type is 'std' for all OS types besides some Windows" | |
529 | ." versions (XP and older) which use 'cirrus'. The 'qxl' option enables the SPICE" | |
530 | ." display server. For win* OS you can select how many independent displays you want," | |
531 | ." Linux guests can add displays them self.\nYou can also run without any graphic card," | |
532 | ." using a serial device as terminal.", | |
533 | }, | |
534 | watchdog => { | |
535 | optional => 1, | |
536 | type => 'string', format => 'pve-qm-watchdog', | |
537 | description => "Create a virtual hardware watchdog device.", | |
538 | verbose_description => "Create a virtual hardware watchdog device. Once enabled (by a guest" | |
539 | ." action), the watchdog must be periodically polled by an agent inside the guest or" | |
540 | ." else the watchdog will reset the guest (or execute the respective action specified)", | |
541 | }, | |
542 | startdate => { | |
543 | optional => 1, | |
544 | type => 'string', | |
545 | typetext => "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)", | |
546 | description => "Set the initial date of the real time clock. Valid format for date are:" | |
547 | ."'now' or '2006-06-17T16:01:21' or '2006-06-17'.", | |
548 | pattern => '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)', | |
549 | default => 'now', | |
550 | }, | |
551 | startup => get_standard_option('pve-startup-order'), | |
552 | template => { | |
553 | optional => 1, | |
554 | type => 'boolean', | |
555 | description => "Enable/disable Template.", | |
556 | default => 0, | |
557 | }, | |
558 | args => { | |
559 | optional => 1, | |
560 | type => 'string', | |
561 | description => "Arbitrary arguments passed to kvm.", | |
562 | verbose_description => <<EODESCR, | |
563 | Arbitrary arguments passed to kvm, for example: | |
564 | ||
565 | args: -no-reboot -no-hpet | |
566 | ||
567 | NOTE: this option is for experts only. | |
568 | EODESCR | |
569 | }, | |
570 | tablet => { | |
571 | optional => 1, | |
572 | type => 'boolean', | |
573 | default => 1, | |
574 | description => "Enable/disable the USB tablet device.", | |
575 | verbose_description => "Enable/disable the USB tablet device. This device is usually needed" | |
576 | ." to allow absolute mouse positioning with VNC. Else the mouse runs out of sync with" | |
577 | ." normal VNC clients. If you're running lots of console-only guests on one host, you" | |
578 | ." may consider disabling this to save some context switches. This is turned off by" | |
579 | ." default if you use spice (`qm set <vmid> --vga qxl`).", | |
580 | }, | |
581 | migrate_speed => { | |
582 | optional => 1, | |
583 | type => 'integer', | |
584 | description => "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.", | |
585 | minimum => 0, | |
586 | default => 0, | |
587 | }, | |
588 | migrate_downtime => { | |
589 | optional => 1, | |
590 | type => 'number', | |
591 | description => "Set maximum tolerated downtime (in seconds) for migrations.", | |
592 | minimum => 0, | |
593 | default => 0.1, | |
594 | }, | |
595 | cdrom => { | |
596 | optional => 1, | |
597 | type => 'string', format => 'pve-qm-ide', | |
598 | typetext => '<volume>', | |
599 | description => "This is an alias for option -ide2", | |
600 | }, | |
601 | cpu => { | |
602 | optional => 1, | |
603 | description => "Emulated CPU type.", | |
604 | type => 'string', | |
605 | format => 'pve-vm-cpu-conf', | |
606 | }, | |
607 | parent => get_standard_option('pve-snapshot-name', { | |
608 | optional => 1, | |
609 | description => "Parent snapshot name. This is used internally, and should not be modified.", | |
610 | }), | |
611 | snaptime => { | |
612 | optional => 1, | |
613 | description => "Timestamp for snapshots.", | |
614 | type => 'integer', | |
615 | minimum => 0, | |
616 | }, | |
617 | vmstate => { | |
618 | optional => 1, | |
619 | type => 'string', format => 'pve-volume-id', | |
620 | description => "Reference to a volume which stores the VM state. This is used internally" | |
621 | ." for snapshots.", | |
622 | }, | |
623 | vmstatestorage => get_standard_option('pve-storage-id', { | |
624 | description => "Default storage for VM state volumes/files.", | |
625 | optional => 1, | |
626 | }), | |
627 | runningmachine => get_standard_option('pve-qemu-machine', { | |
628 | description => "Specifies the QEMU machine type of the running vm. This is used internally" | |
629 | ." for snapshots.", | |
630 | }), | |
631 | runningcpu => { | |
632 | description => "Specifies the QEMU '-cpu' parameter of the running vm. This is used" | |
633 | ." internally for snapshots.", | |
634 | optional => 1, | |
635 | type => 'string', | |
636 | pattern => $PVE::QemuServer::CPUConfig::qemu_cmdline_cpu_re, | |
637 | format_description => 'QEMU -cpu parameter' | |
638 | }, | |
639 | machine => get_standard_option('pve-qemu-machine'), | |
640 | arch => { | |
641 | description => "Virtual processor architecture. Defaults to the host.", | |
642 | optional => 1, | |
643 | type => 'string', | |
644 | enum => [qw(x86_64 aarch64)], | |
645 | }, | |
646 | smbios1 => { | |
647 | description => "Specify SMBIOS type 1 fields.", | |
648 | type => 'string', format => 'pve-qm-smbios1', | |
649 | maxLength => 512, | |
650 | optional => 1, | |
651 | }, | |
652 | protection => { | |
653 | optional => 1, | |
654 | type => 'boolean', | |
655 | description => "Sets the protection flag of the VM. This will disable the remove VM and" | |
656 | ." remove disk operations.", | |
657 | default => 0, | |
658 | }, | |
659 | bios => { | |
660 | optional => 1, | |
661 | type => 'string', | |
662 | enum => [ qw(seabios ovmf) ], | |
663 | description => "Select BIOS implementation.", | |
664 | default => 'seabios', | |
665 | }, | |
666 | vmgenid => { | |
667 | type => 'string', | |
668 | pattern => '(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}|[01])', | |
669 | format_description => 'UUID', | |
670 | description => "Set VM Generation ID. Use '1' to autogenerate on create or update, pass '0'" | |
671 | ." to disable explicitly.", | |
672 | verbose_description => "The VM generation ID (vmgenid) device exposes a 128-bit integer" | |
673 | ." value identifier to the guest OS. This allows to notify the guest operating system" | |
674 | ." when the virtual machine is executed with a different configuration (e.g. snapshot" | |
675 | ." execution or creation from a template). The guest operating system notices the" | |
676 | ." change, and is then able to react as appropriate by marking its copies of" | |
677 | ." distributed databases as dirty, re-initializing its random number generator, etc.\n" | |
678 | ."Note that auto-creation only works when done through API/CLI create or update methods" | |
679 | .", but not when manually editing the config file.", | |
680 | default => "1 (autogenerated)", | |
681 | optional => 1, | |
682 | }, | |
683 | hookscript => { | |
684 | type => 'string', | |
685 | format => 'pve-volume-id', | |
686 | optional => 1, | |
687 | description => "Script that will be executed during various steps in the vms lifetime.", | |
688 | }, | |
689 | ivshmem => { | |
690 | type => 'string', | |
691 | format => $ivshmem_fmt, | |
692 | description => "Inter-VM shared memory. Useful for direct communication between VMs, or to" | |
693 | ." the host.", | |
694 | optional => 1, | |
695 | }, | |
696 | audio0 => { | |
697 | type => 'string', | |
698 | format => $audio_fmt, | |
699 | description => "Configure a audio device, useful in combination with QXL/Spice.", | |
700 | optional => 1 | |
701 | }, | |
702 | spice_enhancements => { | |
703 | type => 'string', | |
704 | format => $spice_enhancements_fmt, | |
705 | description => "Configure additional enhancements for SPICE.", | |
706 | optional => 1 | |
707 | }, | |
708 | tags => { | |
709 | type => 'string', format => 'pve-tag-list', | |
710 | description => 'Tags of the VM. This is only meta information.', | |
711 | optional => 1, | |
712 | }, | |
713 | rng0 => { | |
714 | type => 'string', | |
715 | format => $rng_fmt, | |
716 | description => "Configure a VirtIO-based Random Number Generator.", | |
717 | optional => 1, | |
718 | }, | |
719 | meta => { | |
720 | type => 'string', | |
721 | format => $meta_info_fmt, | |
722 | description => "Some (read-only) meta-information about this guest.", | |
723 | optional => 1, | |
724 | }, | |
725 | }; | |
726 | ||
727 | my $cicustom_fmt = { | |
728 | meta => { | |
729 | type => 'string', | |
730 | optional => 1, | |
731 | description => 'Specify a custom file containing all meta data passed to the VM via" | |
732 | ." cloud-init. This is provider specific meaning configdrive2 and nocloud differ.', | |
733 | format => 'pve-volume-id', | |
734 | format_description => 'volume', | |
735 | }, | |
736 | network => { | |
737 | type => 'string', | |
738 | optional => 1, | |
739 | description => 'Specify a custom file containing all network data passed to the VM via' | |
740 | .' cloud-init.', | |
741 | format => 'pve-volume-id', | |
742 | format_description => 'volume', | |
743 | }, | |
744 | user => { | |
745 | type => 'string', | |
746 | optional => 1, | |
747 | description => 'Specify a custom file containing all user data passed to the VM via' | |
748 | .' cloud-init.', | |
749 | format => 'pve-volume-id', | |
750 | format_description => 'volume', | |
751 | }, | |
752 | vendor => { | |
753 | type => 'string', | |
754 | optional => 1, | |
755 | description => 'Specify a custom file containing all vendor data passed to the VM via' | |
756 | .' cloud-init.', | |
757 | format => 'pve-volume-id', | |
758 | format_description => 'volume', | |
759 | }, | |
760 | }; | |
761 | PVE::JSONSchema::register_format('pve-qm-cicustom', $cicustom_fmt); | |
762 | ||
763 | my $confdesc_cloudinit = { | |
764 | citype => { | |
765 | optional => 1, | |
766 | type => 'string', | |
767 | description => 'Specifies the cloud-init configuration format. The default depends on the' | |
768 | .' configured operating system type (`ostype`. We use the `nocloud` format for Linux,' | |
769 | .' and `configdrive2` for windows.', | |
770 | enum => ['configdrive2', 'nocloud', 'opennebula'], | |
771 | }, | |
772 | ciuser => { | |
773 | optional => 1, | |
774 | type => 'string', | |
775 | description => "cloud-init: User name to change ssh keys and password for instead of the" | |
776 | ." image's configured default user.", | |
777 | }, | |
778 | cipassword => { | |
779 | optional => 1, | |
780 | type => 'string', | |
781 | description => 'cloud-init: Password to assign the user. Using this is generally not' | |
782 | .' recommended. Use ssh keys instead. Also note that older cloud-init versions do not' | |
783 | .' support hashed passwords.', | |
784 | }, | |
785 | cicustom => { | |
786 | optional => 1, | |
787 | type => 'string', | |
788 | description => 'cloud-init: Specify custom files to replace the automatically generated' | |
789 | .' ones at start.', | |
790 | format => 'pve-qm-cicustom', | |
791 | }, | |
792 | searchdomain => { | |
793 | optional => 1, | |
794 | type => 'string', | |
795 | description => "cloud-init: Sets DNS search domains for a container. Create will' | |
796 | .' automatically use the setting from the host if neither searchdomain nor nameserver' | |
797 | .' are set.", | |
798 | }, | |
799 | nameserver => { | |
800 | optional => 1, | |
801 | type => 'string', format => 'address-list', | |
802 | description => "cloud-init: Sets DNS server IP address for a container. Create will' | |
803 | .' automatically use the setting from the host if neither searchdomain nor nameserver' | |
804 | .' are set.", | |
805 | }, | |
806 | sshkeys => { | |
807 | optional => 1, | |
808 | type => 'string', | |
809 | format => 'urlencoded', | |
810 | description => "cloud-init: Setup public SSH keys (one key per line, OpenSSH format).", | |
811 | }, | |
812 | }; | |
813 | ||
814 | # what about other qemu settings ? | |
815 | #cpu => 'string', | |
816 | #machine => 'string', | |
817 | #fda => 'file', | |
818 | #fdb => 'file', | |
819 | #mtdblock => 'file', | |
820 | #sd => 'file', | |
821 | #pflash => 'file', | |
822 | #snapshot => 'bool', | |
823 | #bootp => 'file', | |
824 | ##tftp => 'dir', | |
825 | ##smb => 'dir', | |
826 | #kernel => 'file', | |
827 | #append => 'string', | |
828 | #initrd => 'file', | |
829 | ##soundhw => 'string', | |
830 | ||
831 | while (my ($k, $v) = each %$confdesc) { | |
832 | PVE::JSONSchema::register_standard_option("pve-qm-$k", $v); | |
833 | } | |
834 | ||
835 | my $MAX_USB_DEVICES = 5; | |
836 | my $MAX_NETS = 32; | |
837 | my $MAX_SERIAL_PORTS = 4; | |
838 | my $MAX_PARALLEL_PORTS = 3; | |
839 | my $MAX_NUMA = 8; | |
840 | ||
841 | my $numa_fmt = { | |
842 | cpus => { | |
843 | type => "string", | |
844 | pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/, | |
845 | description => "CPUs accessing this NUMA node.", | |
846 | format_description => "id[-id];...", | |
847 | }, | |
848 | memory => { | |
849 | type => "number", | |
850 | description => "Amount of memory this NUMA node provides.", | |
851 | optional => 1, | |
852 | }, | |
853 | hostnodes => { | |
854 | type => "string", | |
855 | pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/, | |
856 | description => "Host NUMA nodes to use.", | |
857 | format_description => "id[-id];...", | |
858 | optional => 1, | |
859 | }, | |
860 | policy => { | |
861 | type => 'string', | |
862 | enum => [qw(preferred bind interleave)], | |
863 | description => "NUMA allocation policy.", | |
864 | optional => 1, | |
865 | }, | |
866 | }; | |
867 | PVE::JSONSchema::register_format('pve-qm-numanode', $numa_fmt); | |
868 | my $numadesc = { | |
869 | optional => 1, | |
870 | type => 'string', format => $numa_fmt, | |
871 | description => "NUMA topology.", | |
872 | }; | |
873 | PVE::JSONSchema::register_standard_option("pve-qm-numanode", $numadesc); | |
874 | ||
875 | for (my $i = 0; $i < $MAX_NUMA; $i++) { | |
876 | $confdesc->{"numa$i"} = $numadesc; | |
877 | } | |
878 | ||
879 | my $nic_model_list = [ | |
880 | 'e1000', | |
881 | 'e1000-82540em', | |
882 | 'e1000-82544gc', | |
883 | 'e1000-82545em', | |
884 | 'e1000e', | |
885 | 'i82551', | |
886 | 'i82557b', | |
887 | 'i82559er', | |
888 | 'ne2k_isa', | |
889 | 'ne2k_pci', | |
890 | 'pcnet', | |
891 | 'rtl8139', | |
892 | 'virtio', | |
893 | 'vmxnet3', | |
894 | ]; | |
895 | my $nic_model_list_txt = join(' ', sort @$nic_model_list); | |
896 | ||
897 | my $net_fmt_bridge_descr = <<__EOD__; | |
898 | Bridge to attach the network device to. The Proxmox VE standard bridge | |
899 | is called 'vmbr0'. | |
900 | ||
901 | If you do not specify a bridge, we create a kvm user (NATed) network | |
902 | device, which provides DHCP and DNS services. The following addresses | |
903 | are used: | |
904 | ||
905 | 10.0.2.2 Gateway | |
906 | 10.0.2.3 DNS Server | |
907 | 10.0.2.4 SMB Server | |
908 | ||
909 | The DHCP server assign addresses to the guest starting from 10.0.2.15. | |
910 | __EOD__ | |
911 | ||
912 | my $net_fmt = { | |
913 | macaddr => get_standard_option('mac-addr', { | |
914 | description => "MAC address. That address must be unique withing your network. This is" | |
915 | ." automatically generated if not specified.", | |
916 | }), | |
917 | model => { | |
918 | type => 'string', | |
919 | description => "Network Card Model. The 'virtio' model provides the best performance with" | |
920 | ." very low CPU overhead. If your guest does not support this driver, it is usually" | |
921 | ." best to use 'e1000'.", | |
922 | enum => $nic_model_list, | |
923 | default_key => 1, | |
924 | }, | |
925 | (map { $_ => { keyAlias => 'model', alias => 'macaddr' }} @$nic_model_list), | |
926 | bridge => { | |
927 | type => 'string', | |
928 | description => $net_fmt_bridge_descr, | |
929 | format_description => 'bridge', | |
930 | pattern => '[-_.\w\d]+', | |
931 | optional => 1, | |
932 | }, | |
933 | queues => { | |
934 | type => 'integer', | |
935 | minimum => 0, maximum => 16, | |
936 | description => 'Number of packet queues to be used on the device.', | |
937 | optional => 1, | |
938 | }, | |
939 | rate => { | |
940 | type => 'number', | |
941 | minimum => 0, | |
942 | description => "Rate limit in mbps (megabytes per second) as floating point number.", | |
943 | optional => 1, | |
944 | }, | |
945 | tag => { | |
946 | type => 'integer', | |
947 | minimum => 1, maximum => 4094, | |
948 | description => 'VLAN tag to apply to packets on this interface.', | |
949 | optional => 1, | |
950 | }, | |
951 | trunks => { | |
952 | type => 'string', | |
953 | pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/, | |
954 | description => 'VLAN trunks to pass through this interface.', | |
955 | format_description => 'vlanid[;vlanid...]', | |
956 | optional => 1, | |
957 | }, | |
958 | firewall => { | |
959 | type => 'boolean', | |
960 | description => 'Whether this interface should be protected by the firewall.', | |
961 | optional => 1, | |
962 | }, | |
963 | link_down => { | |
964 | type => 'boolean', | |
965 | description => 'Whether this interface should be disconnected (like pulling the plug).', | |
966 | optional => 1, | |
967 | }, | |
968 | mtu => { | |
969 | type => 'integer', | |
970 | minimum => 1, maximum => 65520, | |
971 | description => "Force MTU, for VirtIO only. Set to '1' to use the bridge MTU", | |
972 | optional => 1, | |
973 | }, | |
974 | }; | |
975 | ||
976 | my $netdesc = { | |
977 | optional => 1, | |
978 | type => 'string', format => $net_fmt, | |
979 | description => "Specify network devices.", | |
980 | }; | |
981 | ||
982 | PVE::JSONSchema::register_standard_option("pve-qm-net", $netdesc); | |
983 | ||
984 | my $ipconfig_fmt = { | |
985 | ip => { | |
986 | type => 'string', | |
987 | format => 'pve-ipv4-config', | |
988 | format_description => 'IPv4Format/CIDR', | |
989 | description => 'IPv4 address in CIDR format.', | |
990 | optional => 1, | |
991 | default => 'dhcp', | |
992 | }, | |
993 | gw => { | |
994 | type => 'string', | |
995 | format => 'ipv4', | |
996 | format_description => 'GatewayIPv4', | |
997 | description => 'Default gateway for IPv4 traffic.', | |
998 | optional => 1, | |
999 | requires => 'ip', | |
1000 | }, | |
1001 | ip6 => { | |
1002 | type => 'string', | |
1003 | format => 'pve-ipv6-config', | |
1004 | format_description => 'IPv6Format/CIDR', | |
1005 | description => 'IPv6 address in CIDR format.', | |
1006 | optional => 1, | |
1007 | default => 'dhcp', | |
1008 | }, | |
1009 | gw6 => { | |
1010 | type => 'string', | |
1011 | format => 'ipv6', | |
1012 | format_description => 'GatewayIPv6', | |
1013 | description => 'Default gateway for IPv6 traffic.', | |
1014 | optional => 1, | |
1015 | requires => 'ip6', | |
1016 | }, | |
1017 | }; | |
1018 | PVE::JSONSchema::register_format('pve-qm-ipconfig', $ipconfig_fmt); | |
1019 | my $ipconfigdesc = { | |
1020 | optional => 1, | |
1021 | type => 'string', format => 'pve-qm-ipconfig', | |
1022 | description => <<'EODESCR', | |
1023 | cloud-init: Specify IP addresses and gateways for the corresponding interface. | |
1024 | ||
1025 | IP addresses use CIDR notation, gateways are optional but need an IP of the same type specified. | |
1026 | ||
1027 | The special string 'dhcp' can be used for IP addresses to use DHCP, in which case no explicit | |
1028 | gateway should be provided. | |
1029 | For IPv6 the special string 'auto' can be used to use stateless autoconfiguration. This requires | |
1030 | cloud-init 19.4 or newer. | |
1031 | ||
1032 | If cloud-init is enabled and neither an IPv4 nor an IPv6 address is specified, it defaults to using | |
1033 | dhcp on IPv4. | |
1034 | EODESCR | |
1035 | }; | |
1036 | PVE::JSONSchema::register_standard_option("pve-qm-ipconfig", $netdesc); | |
1037 | ||
1038 | for (my $i = 0; $i < $MAX_NETS; $i++) { | |
1039 | $confdesc->{"net$i"} = $netdesc; | |
1040 | $confdesc_cloudinit->{"ipconfig$i"} = $ipconfigdesc; | |
1041 | } | |
1042 | ||
1043 | foreach my $key (keys %$confdesc_cloudinit) { | |
1044 | $confdesc->{$key} = $confdesc_cloudinit->{$key}; | |
1045 | } | |
1046 | ||
1047 | PVE::JSONSchema::register_format('pve-volume-id-or-qm-path', \&verify_volume_id_or_qm_path); | |
1048 | sub verify_volume_id_or_qm_path { | |
1049 | my ($volid, $noerr) = @_; | |
1050 | ||
1051 | if ($volid eq 'none' || $volid eq 'cdrom' || $volid =~ m|^/|) { | |
1052 | return $volid; | |
1053 | } | |
1054 | ||
1055 | # if its neither 'none' nor 'cdrom' nor a path, check if its a volume-id | |
1056 | $volid = eval { PVE::JSONSchema::check_format('pve-volume-id', $volid, '') }; | |
1057 | if ($@) { | |
1058 | return if $noerr; | |
1059 | die $@; | |
1060 | } | |
1061 | return $volid; | |
1062 | } | |
1063 | ||
1064 | my $usb_fmt = { | |
1065 | host => { | |
1066 | default_key => 1, | |
1067 | type => 'string', format => 'pve-qm-usb-device', | |
1068 | format_description => 'HOSTUSBDEVICE|spice', | |
1069 | description => <<EODESCR, | |
1070 | The Host USB device or port or the value 'spice'. HOSTUSBDEVICE syntax is: | |
1071 | ||
1072 | 'bus-port(.port)*' (decimal numbers) or | |
1073 | 'vendor_id:product_id' (hexadeciaml numbers) or | |
1074 | 'spice' | |
1075 | ||
1076 | You can use the 'lsusb -t' command to list existing usb devices. | |
1077 | ||
1078 | NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such | |
1079 | machines - use with special care. | |
1080 | ||
1081 | The value 'spice' can be used to add a usb redirection devices for spice. | |
1082 | EODESCR | |
1083 | }, | |
1084 | usb3 => { | |
1085 | optional => 1, | |
1086 | type => 'boolean', | |
1087 | description => "Specifies whether if given host option is a USB3 device or port.", | |
1088 | default => 0, | |
1089 | }, | |
1090 | }; | |
1091 | ||
1092 | my $usbdesc = { | |
1093 | optional => 1, | |
1094 | type => 'string', format => $usb_fmt, | |
1095 | description => "Configure an USB device (n is 0 to 4).", | |
1096 | }; | |
1097 | PVE::JSONSchema::register_standard_option("pve-qm-usb", $usbdesc); | |
1098 | ||
1099 | my $serialdesc = { | |
1100 | optional => 1, | |
1101 | type => 'string', | |
1102 | pattern => '(/dev/.+|socket)', | |
1103 | description => "Create a serial device inside the VM (n is 0 to 3)", | |
1104 | verbose_description => <<EODESCR, | |
1105 | Create a serial device inside the VM (n is 0 to 3), and pass through a | |
1106 | host serial device (i.e. /dev/ttyS0), or create a unix socket on the | |
1107 | host side (use 'qm terminal' to open a terminal connection). | |
1108 | ||
1109 | NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines - | |
1110 | use with special care. | |
1111 | ||
1112 | CAUTION: Experimental! User reported problems with this option. | |
1113 | EODESCR | |
1114 | }; | |
1115 | ||
1116 | my $paralleldesc= { | |
1117 | optional => 1, | |
1118 | type => 'string', | |
1119 | pattern => '/dev/parport\d+|/dev/usb/lp\d+', | |
1120 | description => "Map host parallel devices (n is 0 to 2).", | |
1121 | verbose_description => <<EODESCR, | |
1122 | Map host parallel devices (n is 0 to 2). | |
1123 | ||
1124 | NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such | |
1125 | machines - use with special care. | |
1126 | ||
1127 | CAUTION: Experimental! User reported problems with this option. | |
1128 | EODESCR | |
1129 | }; | |
1130 | ||
1131 | for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) { | |
1132 | $confdesc->{"parallel$i"} = $paralleldesc; | |
1133 | } | |
1134 | ||
1135 | for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) { | |
1136 | $confdesc->{"serial$i"} = $serialdesc; | |
1137 | } | |
1138 | ||
1139 | for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) { | |
1140 | $confdesc->{"hostpci$i"} = $PVE::QemuServer::PCI::hostpcidesc; | |
1141 | } | |
1142 | ||
1143 | for my $key (keys %{$PVE::QemuServer::Drive::drivedesc_hash}) { | |
1144 | $confdesc->{$key} = $PVE::QemuServer::Drive::drivedesc_hash->{$key}; | |
1145 | } | |
1146 | ||
1147 | for (my $i = 0; $i < $MAX_USB_DEVICES; $i++) { | |
1148 | $confdesc->{"usb$i"} = $usbdesc; | |
1149 | } | |
1150 | ||
1151 | my $boot_fmt = { | |
1152 | legacy => { | |
1153 | optional => 1, | |
1154 | default_key => 1, | |
1155 | type => 'string', | |
1156 | description => "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)." | |
1157 | . " Deprecated, use 'order=' instead.", | |
1158 | pattern => '[acdn]{1,4}', | |
1159 | format_description => "[acdn]{1,4}", | |
1160 | ||
1161 | # note: this is also the fallback if boot: is not given at all | |
1162 | default => 'cdn', | |
1163 | }, | |
1164 | order => { | |
1165 | optional => 1, | |
1166 | type => 'string', | |
1167 | format => 'pve-qm-bootdev-list', | |
1168 | format_description => "device[;device...]", | |
1169 | description => <<EODESC, | |
1170 | The guest will attempt to boot from devices in the order they appear here. | |
1171 | ||
1172 | Disks, optical drives and passed-through storage USB devices will be directly | |
1173 | booted from, NICs will load PXE, and PCIe devices will either behave like disks | |
1174 | (e.g. NVMe) or load an option ROM (e.g. RAID controller, hardware NIC). | |
1175 | ||
1176 | Note that only devices in this list will be marked as bootable and thus loaded | |
1177 | by the guest firmware (BIOS/UEFI). If you require multiple disks for booting | |
1178 | (e.g. software-raid), you need to specify all of them here. | |
1179 | ||
1180 | Overrides the deprecated 'legacy=[acdn]*' value when given. | |
1181 | EODESC | |
1182 | }, | |
1183 | }; | |
1184 | PVE::JSONSchema::register_format('pve-qm-boot', $boot_fmt); | |
1185 | ||
1186 | PVE::JSONSchema::register_format('pve-qm-bootdev', \&verify_bootdev); | |
1187 | sub verify_bootdev { | |
1188 | my ($dev, $noerr) = @_; | |
1189 | ||
1190 | my $special = $dev =~ m/^efidisk/ || $dev =~ m/^tpmstate/; | |
1191 | return $dev if PVE::QemuServer::Drive::is_valid_drivename($dev) && !$special; | |
1192 | ||
1193 | my $check = sub { | |
1194 | my ($base) = @_; | |
1195 | return 0 if $dev !~ m/^$base\d+$/; | |
1196 | return 0 if !$confdesc->{$dev}; | |
1197 | return 1; | |
1198 | }; | |
1199 | ||
1200 | return $dev if $check->("net"); | |
1201 | return $dev if $check->("usb"); | |
1202 | return $dev if $check->("hostpci"); | |
1203 | ||
1204 | return if $noerr; | |
1205 | die "invalid boot device '$dev'\n"; | |
1206 | } | |
1207 | ||
1208 | sub print_bootorder { | |
1209 | my ($devs) = @_; | |
1210 | return "" if !@$devs; | |
1211 | my $data = { order => join(';', @$devs) }; | |
1212 | return PVE::JSONSchema::print_property_string($data, $boot_fmt); | |
1213 | } | |
1214 | ||
1215 | my $kvm_api_version = 0; | |
1216 | ||
1217 | sub kvm_version { | |
1218 | return $kvm_api_version if $kvm_api_version; | |
1219 | ||
1220 | open my $fh, '<', '/dev/kvm' or return; | |
1221 | ||
1222 | # 0xae00 => KVM_GET_API_VERSION | |
1223 | $kvm_api_version = ioctl($fh, 0xae00, 0); | |
1224 | close($fh); | |
1225 | ||
1226 | return $kvm_api_version; | |
1227 | } | |
1228 | ||
1229 | my $kvm_user_version = {}; | |
1230 | my $kvm_mtime = {}; | |
1231 | ||
1232 | sub kvm_user_version { | |
1233 | my ($binary) = @_; | |
1234 | ||
1235 | $binary //= get_command_for_arch(get_host_arch()); # get the native arch by default | |
1236 | my $st = stat($binary); | |
1237 | ||
1238 | my $cachedmtime = $kvm_mtime->{$binary} // -1; | |
1239 | return $kvm_user_version->{$binary} if $kvm_user_version->{$binary} && | |
1240 | $cachedmtime == $st->mtime; | |
1241 | ||
1242 | $kvm_user_version->{$binary} = 'unknown'; | |
1243 | $kvm_mtime->{$binary} = $st->mtime; | |
1244 | ||
1245 | my $code = sub { | |
1246 | my $line = shift; | |
1247 | if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) { | |
1248 | $kvm_user_version->{$binary} = $2; | |
1249 | } | |
1250 | }; | |
1251 | ||
1252 | eval { run_command([$binary, '--version'], outfunc => $code); }; | |
1253 | warn $@ if $@; | |
1254 | ||
1255 | return $kvm_user_version->{$binary}; | |
1256 | ||
1257 | } | |
1258 | my sub extract_version { | |
1259 | my ($machine_type, $version) = @_; | |
1260 | $version = kvm_user_version() if !defined($version); | |
1261 | return PVE::QemuServer::Machine::extract_version($machine_type, $version) | |
1262 | } | |
1263 | ||
1264 | sub kernel_has_vhost_net { | |
1265 | return -c '/dev/vhost-net'; | |
1266 | } | |
1267 | ||
1268 | sub option_exists { | |
1269 | my $key = shift; | |
1270 | return defined($confdesc->{$key}); | |
1271 | } | |
1272 | ||
1273 | my $cdrom_path; | |
1274 | sub get_cdrom_path { | |
1275 | ||
1276 | return $cdrom_path if $cdrom_path; | |
1277 | ||
1278 | return $cdrom_path = "/dev/cdrom" if -l "/dev/cdrom"; | |
1279 | return $cdrom_path = "/dev/cdrom1" if -l "/dev/cdrom1"; | |
1280 | return $cdrom_path = "/dev/cdrom2" if -l "/dev/cdrom2"; | |
1281 | } | |
1282 | ||
1283 | sub get_iso_path { | |
1284 | my ($storecfg, $vmid, $cdrom) = @_; | |
1285 | ||
1286 | if ($cdrom eq 'cdrom') { | |
1287 | return get_cdrom_path(); | |
1288 | } elsif ($cdrom eq 'none') { | |
1289 | return ''; | |
1290 | } elsif ($cdrom =~ m|^/|) { | |
1291 | return $cdrom; | |
1292 | } else { | |
1293 | return PVE::Storage::path($storecfg, $cdrom); | |
1294 | } | |
1295 | } | |
1296 | ||
1297 | # try to convert old style file names to volume IDs | |
1298 | sub filename_to_volume_id { | |
1299 | my ($vmid, $file, $media) = @_; | |
1300 | ||
1301 | if (!($file eq 'none' || $file eq 'cdrom' || | |
1302 | $file =~ m|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) { | |
1303 | ||
1304 | return if $file =~ m|/|; | |
1305 | ||
1306 | if ($media && $media eq 'cdrom') { | |
1307 | $file = "local:iso/$file"; | |
1308 | } else { | |
1309 | $file = "local:$vmid/$file"; | |
1310 | } | |
1311 | } | |
1312 | ||
1313 | return $file; | |
1314 | } | |
1315 | ||
1316 | sub verify_media_type { | |
1317 | my ($opt, $vtype, $media) = @_; | |
1318 | ||
1319 | return if !$media; | |
1320 | ||
1321 | my $etype; | |
1322 | if ($media eq 'disk') { | |
1323 | $etype = 'images'; | |
1324 | } elsif ($media eq 'cdrom') { | |
1325 | $etype = 'iso'; | |
1326 | } else { | |
1327 | die "internal error"; | |
1328 | } | |
1329 | ||
1330 | return if ($vtype eq $etype); | |
1331 | ||
1332 | raise_param_exc({ $opt => "unexpected media type ($vtype != $etype)" }); | |
1333 | } | |
1334 | ||
1335 | sub cleanup_drive_path { | |
1336 | my ($opt, $storecfg, $drive) = @_; | |
1337 | ||
1338 | # try to convert filesystem paths to volume IDs | |
1339 | ||
1340 | if (($drive->{file} !~ m/^(cdrom|none)$/) && | |
1341 | ($drive->{file} !~ m|^/dev/.+|) && | |
1342 | ($drive->{file} !~ m/^([^:]+):(.+)$/) && | |
1343 | ($drive->{file} !~ m/^\d+$/)) { | |
1344 | my ($vtype, $volid) = PVE::Storage::path_to_volume_id($storecfg, $drive->{file}); | |
1345 | raise_param_exc({ $opt => "unable to associate path '$drive->{file}' to any storage"}) | |
1346 | if !$vtype; | |
1347 | $drive->{media} = 'cdrom' if !$drive->{media} && $vtype eq 'iso'; | |
1348 | verify_media_type($opt, $vtype, $drive->{media}); | |
1349 | $drive->{file} = $volid; | |
1350 | } | |
1351 | ||
1352 | $drive->{media} = 'cdrom' if !$drive->{media} && $drive->{file} =~ m/^(cdrom|none)$/; | |
1353 | } | |
1354 | ||
1355 | sub parse_hotplug_features { | |
1356 | my ($data) = @_; | |
1357 | ||
1358 | my $res = {}; | |
1359 | ||
1360 | return $res if $data eq '0'; | |
1361 | ||
1362 | $data = $confdesc->{hotplug}->{default} if $data eq '1'; | |
1363 | ||
1364 | foreach my $feature (PVE::Tools::split_list($data)) { | |
1365 | if ($feature =~ m/^(network|disk|cpu|memory|usb)$/) { | |
1366 | $res->{$1} = 1; | |
1367 | } else { | |
1368 | die "invalid hotplug feature '$feature'\n"; | |
1369 | } | |
1370 | } | |
1371 | return $res; | |
1372 | } | |
1373 | ||
1374 | PVE::JSONSchema::register_format('pve-hotplug-features', \&pve_verify_hotplug_features); | |
1375 | sub pve_verify_hotplug_features { | |
1376 | my ($value, $noerr) = @_; | |
1377 | ||
1378 | return $value if parse_hotplug_features($value); | |
1379 | ||
1380 | return if $noerr; | |
1381 | ||
1382 | die "unable to parse hotplug option\n"; | |
1383 | } | |
1384 | ||
1385 | sub scsi_inquiry { | |
1386 | my($fh, $noerr) = @_; | |
1387 | ||
1388 | my $SG_IO = 0x2285; | |
1389 | my $SG_GET_VERSION_NUM = 0x2282; | |
1390 | ||
1391 | my $versionbuf = "\x00" x 8; | |
1392 | my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf); | |
1393 | if (!$ret) { | |
1394 | die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr; | |
1395 | return; | |
1396 | } | |
1397 | my $version = unpack("I", $versionbuf); | |
1398 | if ($version < 30000) { | |
1399 | die "scsi generic interface too old\n" if !$noerr; | |
1400 | return; | |
1401 | } | |
1402 | ||
1403 | my $buf = "\x00" x 36; | |
1404 | my $sensebuf = "\x00" x 8; | |
1405 | my $cmd = pack("C x3 C x1", 0x12, 36); | |
1406 | ||
1407 | # see /usr/include/scsi/sg.h | |
1408 | my $sg_io_hdr_t = "i i C C s I P P P I I i P C C C C S S i I I"; | |
1409 | ||
1410 | my $packet = pack( | |
1411 | $sg_io_hdr_t, ord('S'), -3, length($cmd), length($sensebuf), 0, length($buf), $buf, $cmd, $sensebuf, 6000 | |
1412 | ); | |
1413 | ||
1414 | $ret = ioctl($fh, $SG_IO, $packet); | |
1415 | if (!$ret) { | |
1416 | die "scsi ioctl SG_IO failed - $!\n" if !$noerr; | |
1417 | return; | |
1418 | } | |
1419 | ||
1420 | my @res = unpack($sg_io_hdr_t, $packet); | |
1421 | if ($res[17] || $res[18]) { | |
1422 | die "scsi ioctl SG_IO status error - $!\n" if !$noerr; | |
1423 | return; | |
1424 | } | |
1425 | ||
1426 | my $res = {}; | |
1427 | $res->@{qw(type removable vendor product revision)} = unpack("C C x6 A8 A16 A4", $buf); | |
1428 | ||
1429 | $res->{removable} = $res->{removable} & 128 ? 1 : 0; | |
1430 | $res->{type} &= 0x1F; | |
1431 | ||
1432 | return $res; | |
1433 | } | |
1434 | ||
1435 | sub path_is_scsi { | |
1436 | my ($path) = @_; | |
1437 | ||
1438 | my $fh = IO::File->new("+<$path") || return; | |
1439 | my $res = scsi_inquiry($fh, 1); | |
1440 | close($fh); | |
1441 | ||
1442 | return $res; | |
1443 | } | |
1444 | ||
1445 | sub print_tabletdevice_full { | |
1446 | my ($conf, $arch) = @_; | |
1447 | ||
1448 | my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf); | |
1449 | ||
1450 | # we use uhci for old VMs because tablet driver was buggy in older qemu | |
1451 | my $usbbus; | |
1452 | if (PVE::QemuServer::Machine::machine_type_is_q35($conf) || $arch eq 'aarch64') { | |
1453 | $usbbus = 'ehci'; | |
1454 | } else { | |
1455 | $usbbus = 'uhci'; | |
1456 | } | |
1457 | ||
1458 | return "usb-tablet,id=tablet,bus=$usbbus.0,port=1"; | |
1459 | } | |
1460 | ||
1461 | sub print_keyboarddevice_full { | |
1462 | my ($conf, $arch) = @_; | |
1463 | ||
1464 | return if $arch ne 'aarch64'; | |
1465 | ||
1466 | return "usb-kbd,id=keyboard,bus=ehci.0,port=2"; | |
1467 | } | |
1468 | ||
1469 | my sub get_drive_id { | |
1470 | my ($drive) = @_; | |
1471 | return "$drive->{interface}$drive->{index}"; | |
1472 | } | |
1473 | ||
1474 | sub print_drivedevice_full { | |
1475 | my ($storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type) = @_; | |
1476 | ||
1477 | my $device = ''; | |
1478 | my $maxdev = 0; | |
1479 | ||
1480 | my $drive_id = get_drive_id($drive); | |
1481 | if ($drive->{interface} eq 'virtio') { | |
1482 | my $pciaddr = print_pci_addr("$drive_id", $bridges, $arch, $machine_type); | |
1483 | $device = "virtio-blk-pci,drive=drive-$drive_id,id=${drive_id}${pciaddr}"; | |
1484 | $device .= ",iothread=iothread-$drive_id" if $drive->{iothread}; | |
1485 | } elsif ($drive->{interface} eq 'scsi') { | |
1486 | ||
1487 | my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive); | |
1488 | my $unit = $drive->{index} % $maxdev; | |
1489 | my $devicetype = 'hd'; | |
1490 | my $path = ''; | |
1491 | if (drive_is_cdrom($drive)) { | |
1492 | $devicetype = 'cd'; | |
1493 | } else { | |
1494 | if ($drive->{file} =~ m|^/|) { | |
1495 | $path = $drive->{file}; | |
1496 | if (my $info = path_is_scsi($path)) { | |
1497 | if ($info->{type} == 0 && $drive->{scsiblock}) { | |
1498 | $devicetype = 'block'; | |
1499 | } elsif ($info->{type} == 1) { # tape | |
1500 | $devicetype = 'generic'; | |
1501 | } | |
1502 | } | |
1503 | } else { | |
1504 | $path = PVE::Storage::path($storecfg, $drive->{file}); | |
1505 | } | |
1506 | ||
1507 | # for compatibility only, we prefer scsi-hd (#2408, #2355, #2380) | |
1508 | my $version = extract_version($machine_type, kvm_user_version()); | |
1509 | if ($path =~ m/^iscsi\:\/\// && | |
1510 | !min_version($version, 4, 1)) { | |
1511 | $devicetype = 'generic'; | |
1512 | } | |
1513 | } | |
1514 | ||
1515 | if (!$conf->{scsihw} || $conf->{scsihw} =~ m/^lsi/ || $conf->{scsihw} eq 'pvscsi') { | |
1516 | $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit"; | |
1517 | } else { | |
1518 | $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,channel=0,scsi-id=0" | |
1519 | .",lun=$drive->{index}"; | |
1520 | } | |
1521 | $device .= ",drive=drive-$drive_id,id=$drive_id"; | |
1522 | ||
1523 | if ($drive->{ssd} && ($devicetype eq 'block' || $devicetype eq 'hd')) { | |
1524 | $device .= ",rotation_rate=1"; | |
1525 | } | |
1526 | $device .= ",wwn=$drive->{wwn}" if $drive->{wwn}; | |
1527 | ||
1528 | } elsif ($drive->{interface} eq 'ide' || $drive->{interface} eq 'sata') { | |
1529 | my $maxdev = ($drive->{interface} eq 'sata') ? $PVE::QemuServer::Drive::MAX_SATA_DISKS : 2; | |
1530 | my $controller = int($drive->{index} / $maxdev); | |
1531 | my $unit = $drive->{index} % $maxdev; | |
1532 | my $devicetype = ($drive->{media} && $drive->{media} eq 'cdrom') ? "cd" : "hd"; | |
1533 | ||
1534 | $device = "ide-$devicetype"; | |
1535 | if ($drive->{interface} eq 'ide') { | |
1536 | $device .= ",bus=ide.$controller,unit=$unit"; | |
1537 | } else { | |
1538 | $device .= ",bus=ahci$controller.$unit"; | |
1539 | } | |
1540 | $device .= ",drive=drive-$drive_id,id=$drive_id"; | |
1541 | ||
1542 | if ($devicetype eq 'hd') { | |
1543 | if (my $model = $drive->{model}) { | |
1544 | $model = URI::Escape::uri_unescape($model); | |
1545 | $device .= ",model=$model"; | |
1546 | } | |
1547 | if ($drive->{ssd}) { | |
1548 | $device .= ",rotation_rate=1"; | |
1549 | } | |
1550 | } | |
1551 | $device .= ",wwn=$drive->{wwn}" if $drive->{wwn}; | |
1552 | } elsif ($drive->{interface} eq 'usb') { | |
1553 | die "implement me"; | |
1554 | # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0 | |
1555 | } else { | |
1556 | die "unsupported interface type"; | |
1557 | } | |
1558 | ||
1559 | $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex}; | |
1560 | ||
1561 | if (my $serial = $drive->{serial}) { | |
1562 | $serial = URI::Escape::uri_unescape($serial); | |
1563 | $device .= ",serial=$serial"; | |
1564 | } | |
1565 | ||
1566 | ||
1567 | return $device; | |
1568 | } | |
1569 | ||
1570 | sub get_initiator_name { | |
1571 | my $initiator; | |
1572 | ||
1573 | my $fh = IO::File->new('/etc/iscsi/initiatorname.iscsi') || return; | |
1574 | while (defined(my $line = <$fh>)) { | |
1575 | next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/; | |
1576 | $initiator = $1; | |
1577 | last; | |
1578 | } | |
1579 | $fh->close(); | |
1580 | ||
1581 | return $initiator; | |
1582 | } | |
1583 | ||
1584 | sub print_drive_commandline_full { | |
1585 | my ($storecfg, $vmid, $drive, $pbs_name, $io_uring) = @_; | |
1586 | ||
1587 | my $path; | |
1588 | my $volid = $drive->{file}; | |
1589 | my $format = $drive->{format}; | |
1590 | my $drive_id = get_drive_id($drive); | |
1591 | ||
1592 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
1593 | my $scfg = $storeid ? PVE::Storage::storage_config($storecfg, $storeid) : undef; | |
1594 | ||
1595 | if (drive_is_cdrom($drive)) { | |
1596 | $path = get_iso_path($storecfg, $vmid, $volid); | |
1597 | die "$drive_id: cannot back cdrom drive with PBS snapshot\n" if $pbs_name; | |
1598 | } else { | |
1599 | if ($storeid) { | |
1600 | $path = PVE::Storage::path($storecfg, $volid); | |
1601 | $format //= qemu_img_format($scfg, $volname); | |
1602 | } else { | |
1603 | $path = $volid; | |
1604 | $format //= "raw"; | |
1605 | } | |
1606 | } | |
1607 | ||
1608 | my $is_rbd = $path =~ m/^rbd:/; | |
1609 | ||
1610 | my $opts = ''; | |
1611 | my @qemu_drive_options = qw(heads secs cyls trans media cache rerror werror aio discard); | |
1612 | foreach my $o (@qemu_drive_options) { | |
1613 | $opts .= ",$o=$drive->{$o}" if defined($drive->{$o}); | |
1614 | } | |
1615 | ||
1616 | # snapshot only accepts on|off | |
1617 | if (defined($drive->{snapshot})) { | |
1618 | my $v = $drive->{snapshot} ? 'on' : 'off'; | |
1619 | $opts .= ",snapshot=$v"; | |
1620 | } | |
1621 | ||
1622 | if (defined($drive->{ro})) { # ro maps to QEMUs `readonly`, which accepts `on` or `off` only | |
1623 | $opts .= ",readonly=" . ($drive->{ro} ? 'on' : 'off'); | |
1624 | } | |
1625 | ||
1626 | foreach my $type (['', '-total'], [_rd => '-read'], [_wr => '-write']) { | |
1627 | my ($dir, $qmpname) = @$type; | |
1628 | if (my $v = $drive->{"mbps$dir"}) { | |
1629 | $opts .= ",throttling.bps$qmpname=".int($v*1024*1024); | |
1630 | } | |
1631 | if (my $v = $drive->{"mbps${dir}_max"}) { | |
1632 | $opts .= ",throttling.bps$qmpname-max=".int($v*1024*1024); | |
1633 | } | |
1634 | if (my $v = $drive->{"bps${dir}_max_length"}) { | |
1635 | $opts .= ",throttling.bps$qmpname-max-length=$v"; | |
1636 | } | |
1637 | if (my $v = $drive->{"iops${dir}"}) { | |
1638 | $opts .= ",throttling.iops$qmpname=$v"; | |
1639 | } | |
1640 | if (my $v = $drive->{"iops${dir}_max"}) { | |
1641 | $opts .= ",throttling.iops$qmpname-max=$v"; | |
1642 | } | |
1643 | if (my $v = $drive->{"iops${dir}_max_length"}) { | |
1644 | $opts .= ",throttling.iops$qmpname-max-length=$v"; | |
1645 | } | |
1646 | } | |
1647 | ||
1648 | if ($pbs_name) { | |
1649 | $format = "rbd" if $is_rbd; | |
1650 | die "$drive_id: Proxmox Backup Server backed drive cannot auto-detect the format\n" | |
1651 | if !$format; | |
1652 | $opts .= ",format=alloc-track,file.driver=$format"; | |
1653 | } elsif ($format) { | |
1654 | $opts .= ",format=$format"; | |
1655 | } | |
1656 | ||
1657 | my $cache_direct = 0; | |
1658 | ||
1659 | if (my $cache = $drive->{cache}) { | |
1660 | $cache_direct = $cache =~ /^(?:off|none|directsync)$/; | |
1661 | } elsif (!drive_is_cdrom($drive) && !($scfg && $scfg->{type} eq 'btrfs' && !$scfg->{nocow})) { | |
1662 | $opts .= ",cache=none"; | |
1663 | $cache_direct = 1; | |
1664 | } | |
1665 | ||
1666 | # io_uring with cache mode writeback or writethrough on krbd will hang... | |
1667 | my $rbd_no_io_uring = $scfg && $scfg->{type} eq 'rbd' && $scfg->{krbd} && !$cache_direct; | |
1668 | ||
1669 | # io_uring with cache mode writeback or writethrough on LVM will hang, without cache only | |
1670 | # sometimes, just plain disable... | |
1671 | my $lvm_no_io_uring = $scfg && $scfg->{type} eq 'lvm'; | |
1672 | ||
1673 | if (!$drive->{aio}) { | |
1674 | if ($io_uring && !$rbd_no_io_uring && !$lvm_no_io_uring) { | |
1675 | # io_uring supports all cache modes | |
1676 | $opts .= ",aio=io_uring"; | |
1677 | } else { | |
1678 | # aio native works only with O_DIRECT | |
1679 | if($cache_direct) { | |
1680 | $opts .= ",aio=native"; | |
1681 | } else { | |
1682 | $opts .= ",aio=threads"; | |
1683 | } | |
1684 | } | |
1685 | } | |
1686 | ||
1687 | if (!drive_is_cdrom($drive)) { | |
1688 | my $detectzeroes; | |
1689 | if (defined($drive->{detect_zeroes}) && !$drive->{detect_zeroes}) { | |
1690 | $detectzeroes = 'off'; | |
1691 | } elsif ($drive->{discard}) { | |
1692 | $detectzeroes = $drive->{discard} eq 'on' ? 'unmap' : 'on'; | |
1693 | } else { | |
1694 | # This used to be our default with discard not being specified: | |
1695 | $detectzeroes = 'on'; | |
1696 | } | |
1697 | ||
1698 | # note: 'detect-zeroes' works per blockdev and we want it to persist | |
1699 | # after the alloc-track is removed, so put it on 'file' directly | |
1700 | my $dz_param = $pbs_name ? "file.detect-zeroes" : "detect-zeroes"; | |
1701 | $opts .= ",$dz_param=$detectzeroes" if $detectzeroes; | |
1702 | } | |
1703 | ||
1704 | if ($pbs_name) { | |
1705 | $opts .= ",backing=$pbs_name"; | |
1706 | $opts .= ",auto-remove=on"; | |
1707 | } | |
1708 | ||
1709 | # my $file_param = $pbs_name ? "file.file.filename" : "file"; | |
1710 | my $file_param = "file"; | |
1711 | if ($pbs_name) { | |
1712 | # non-rbd drivers require the underlying file to be a seperate block | |
1713 | # node, so add a second .file indirection | |
1714 | $file_param .= ".file" if !$is_rbd; | |
1715 | $file_param .= ".filename"; | |
1716 | } | |
1717 | my $pathinfo = $path ? "$file_param=$path," : ''; | |
1718 | ||
1719 | return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts"; | |
1720 | } | |
1721 | ||
1722 | sub print_pbs_blockdev { | |
1723 | my ($pbs_conf, $pbs_name) = @_; | |
1724 | my $blockdev = "driver=pbs,node-name=$pbs_name,read-only=on"; | |
1725 | $blockdev .= ",repository=$pbs_conf->{repository}"; | |
1726 | $blockdev .= ",snapshot=$pbs_conf->{snapshot}"; | |
1727 | $blockdev .= ",archive=$pbs_conf->{archive}"; | |
1728 | $blockdev .= ",keyfile=$pbs_conf->{keyfile}" if $pbs_conf->{keyfile}; | |
1729 | return $blockdev; | |
1730 | } | |
1731 | ||
1732 | sub print_netdevice_full { | |
1733 | my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files, $arch, $machine_type) = @_; | |
1734 | ||
1735 | my $device = $net->{model}; | |
1736 | if ($net->{model} eq 'virtio') { | |
1737 | $device = 'virtio-net-pci'; | |
1738 | }; | |
1739 | ||
1740 | my $pciaddr = print_pci_addr("$netid", $bridges, $arch, $machine_type); | |
1741 | my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid"; | |
1742 | if ($net->{queues} && $net->{queues} > 1 && $net->{model} eq 'virtio'){ | |
1743 | # Consider we have N queues, the number of vectors needed is 2 * N + 2, i.e., one per in | |
1744 | # and out of each queue plus one config interrupt and control vector queue | |
1745 | my $vectors = $net->{queues} * 2 + 2; | |
1746 | $tmpstr .= ",vectors=$vectors,mq=on"; | |
1747 | } | |
1748 | $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex} ; | |
1749 | ||
1750 | if (my $mtu = $net->{mtu}) { | |
1751 | if ($net->{model} eq 'virtio' && $net->{bridge}) { | |
1752 | my $bridge_mtu = PVE::Network::read_bridge_mtu($net->{bridge}); | |
1753 | if ($mtu == 1) { | |
1754 | $mtu = $bridge_mtu; | |
1755 | } elsif ($mtu < 576) { | |
1756 | die "netdev $netid: MTU '$mtu' is smaller than the IP minimum MTU '576'\n"; | |
1757 | } elsif ($mtu > $bridge_mtu) { | |
1758 | die "netdev $netid: MTU '$mtu' is bigger than the bridge MTU '$bridge_mtu'\n"; | |
1759 | } | |
1760 | $tmpstr .= ",host_mtu=$mtu"; | |
1761 | } else { | |
1762 | warn "WARN: netdev $netid: ignoring MTU '$mtu', not using VirtIO or no bridge configured.\n"; | |
1763 | } | |
1764 | } | |
1765 | ||
1766 | if ($use_old_bios_files) { | |
1767 | my $romfile; | |
1768 | if ($device eq 'virtio-net-pci') { | |
1769 | $romfile = 'pxe-virtio.rom'; | |
1770 | } elsif ($device eq 'e1000') { | |
1771 | $romfile = 'pxe-e1000.rom'; | |
1772 | } elsif ($device eq 'e1000e') { | |
1773 | $romfile = 'pxe-e1000e.rom'; | |
1774 | } elsif ($device eq 'ne2k') { | |
1775 | $romfile = 'pxe-ne2k_pci.rom'; | |
1776 | } elsif ($device eq 'pcnet') { | |
1777 | $romfile = 'pxe-pcnet.rom'; | |
1778 | } elsif ($device eq 'rtl8139') { | |
1779 | $romfile = 'pxe-rtl8139.rom'; | |
1780 | } | |
1781 | $tmpstr .= ",romfile=$romfile" if $romfile; | |
1782 | } | |
1783 | ||
1784 | return $tmpstr; | |
1785 | } | |
1786 | ||
1787 | sub print_netdev_full { | |
1788 | my ($vmid, $conf, $arch, $net, $netid, $hotplug) = @_; | |
1789 | ||
1790 | my $i = ''; | |
1791 | if ($netid =~ m/^net(\d+)$/) { | |
1792 | $i = int($1); | |
1793 | } | |
1794 | ||
1795 | die "got strange net id '$i'\n" if $i >= ${MAX_NETS}; | |
1796 | ||
1797 | my $ifname = "tap${vmid}i$i"; | |
1798 | ||
1799 | # kvm uses TUNSETIFF ioctl, and that limits ifname length | |
1800 | die "interface name '$ifname' is too long (max 15 character)\n" | |
1801 | if length($ifname) >= 16; | |
1802 | ||
1803 | my $vhostparam = ''; | |
1804 | if (is_native($arch)) { | |
1805 | $vhostparam = ',vhost=on' if kernel_has_vhost_net() && $net->{model} eq 'virtio'; | |
1806 | } | |
1807 | ||
1808 | my $vmname = $conf->{name} || "vm$vmid"; | |
1809 | ||
1810 | my $netdev = ""; | |
1811 | my $script = $hotplug ? "pve-bridge-hotplug" : "pve-bridge"; | |
1812 | ||
1813 | if ($net->{bridge}) { | |
1814 | $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script" | |
1815 | .",downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam"; | |
1816 | } else { | |
1817 | $netdev = "type=user,id=$netid,hostname=$vmname"; | |
1818 | } | |
1819 | ||
1820 | $netdev .= ",queues=$net->{queues}" if ($net->{queues} && $net->{model} eq 'virtio'); | |
1821 | ||
1822 | return $netdev; | |
1823 | } | |
1824 | ||
1825 | my $vga_map = { | |
1826 | 'cirrus' => 'cirrus-vga', | |
1827 | 'std' => 'VGA', | |
1828 | 'vmware' => 'vmware-svga', | |
1829 | 'virtio' => 'virtio-vga', | |
1830 | }; | |
1831 | ||
1832 | sub print_vga_device { | |
1833 | my ($conf, $vga, $arch, $machine_version, $machine, $id, $qxlnum, $bridges) = @_; | |
1834 | ||
1835 | my $type = $vga_map->{$vga->{type}}; | |
1836 | if ($arch eq 'aarch64' && defined($type) && $type eq 'virtio-vga') { | |
1837 | $type = 'virtio-gpu'; | |
1838 | } | |
1839 | my $vgamem_mb = $vga->{memory}; | |
1840 | ||
1841 | my $max_outputs = ''; | |
1842 | if ($qxlnum) { | |
1843 | $type = $id ? 'qxl' : 'qxl-vga'; | |
1844 | ||
1845 | if (!$conf->{ostype} || $conf->{ostype} =~ m/^(?:l\d\d)|(?:other)$/) { | |
1846 | # set max outputs so linux can have up to 4 qxl displays with one device | |
1847 | if (min_version($machine_version, 4, 1)) { | |
1848 | $max_outputs = ",max_outputs=4"; | |
1849 | } | |
1850 | } | |
1851 | } | |
1852 | ||
1853 | die "no devicetype for $vga->{type}\n" if !$type; | |
1854 | ||
1855 | my $memory = ""; | |
1856 | if ($vgamem_mb) { | |
1857 | if ($vga->{type} eq 'virtio') { | |
1858 | my $bytes = PVE::Tools::convert_size($vgamem_mb, "mb" => "b"); | |
1859 | $memory = ",max_hostmem=$bytes"; | |
1860 | } elsif ($qxlnum) { | |
1861 | # from https://www.spice-space.org/multiple-monitors.html | |
1862 | $memory = ",vgamem_mb=$vga->{memory}"; | |
1863 | my $ram = $vgamem_mb * 4; | |
1864 | my $vram = $vgamem_mb * 2; | |
1865 | $memory .= ",ram_size_mb=$ram,vram_size_mb=$vram"; | |
1866 | } else { | |
1867 | $memory = ",vgamem_mb=$vga->{memory}"; | |
1868 | } | |
1869 | } elsif ($qxlnum && $id) { | |
1870 | $memory = ",ram_size=67108864,vram_size=33554432"; | |
1871 | } | |
1872 | ||
1873 | my $edidoff = ""; | |
1874 | if ($type eq 'VGA' && windows_version($conf->{ostype})) { | |
1875 | $edidoff=",edid=off" if (!defined($conf->{bios}) || $conf->{bios} ne 'ovmf'); | |
1876 | } | |
1877 | ||
1878 | my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf); | |
1879 | my $vgaid = "vga" . ($id // ''); | |
1880 | my $pciaddr; | |
1881 | if ($q35 && $vgaid eq 'vga') { | |
1882 | # the first display uses pcie.0 bus on q35 machines | |
1883 | $pciaddr = print_pcie_addr($vgaid, $bridges, $arch, $machine); | |
1884 | } else { | |
1885 | $pciaddr = print_pci_addr($vgaid, $bridges, $arch, $machine); | |
1886 | } | |
1887 | ||
1888 | return "$type,id=${vgaid}${memory}${max_outputs}${pciaddr}${edidoff}"; | |
1889 | } | |
1890 | ||
1891 | sub parse_number_sets { | |
1892 | my ($set) = @_; | |
1893 | my $res = []; | |
1894 | foreach my $part (split(/;/, $set)) { | |
1895 | if ($part =~ /^\s*(\d+)(?:-(\d+))?\s*$/) { | |
1896 | die "invalid range: $part ($2 < $1)\n" if defined($2) && $2 < $1; | |
1897 | push @$res, [ $1, $2 ]; | |
1898 | } else { | |
1899 | die "invalid range: $part\n"; | |
1900 | } | |
1901 | } | |
1902 | return $res; | |
1903 | } | |
1904 | ||
1905 | sub parse_numa { | |
1906 | my ($data) = @_; | |
1907 | ||
1908 | my $res = parse_property_string($numa_fmt, $data); | |
1909 | $res->{cpus} = parse_number_sets($res->{cpus}) if defined($res->{cpus}); | |
1910 | $res->{hostnodes} = parse_number_sets($res->{hostnodes}) if defined($res->{hostnodes}); | |
1911 | return $res; | |
1912 | } | |
1913 | ||
1914 | # netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps> | |
1915 | sub parse_net { | |
1916 | my ($data) = @_; | |
1917 | ||
1918 | my $res = eval { parse_property_string($net_fmt, $data) }; | |
1919 | if ($@) { | |
1920 | warn $@; | |
1921 | return; | |
1922 | } | |
1923 | if (!defined($res->{macaddr})) { | |
1924 | my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg'); | |
1925 | $res->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix}); | |
1926 | } | |
1927 | return $res; | |
1928 | } | |
1929 | ||
1930 | # ipconfigX ip=cidr,gw=ip,ip6=cidr,gw6=ip | |
1931 | sub parse_ipconfig { | |
1932 | my ($data) = @_; | |
1933 | ||
1934 | my $res = eval { parse_property_string($ipconfig_fmt, $data) }; | |
1935 | if ($@) { | |
1936 | warn $@; | |
1937 | return; | |
1938 | } | |
1939 | ||
1940 | if ($res->{gw} && !$res->{ip}) { | |
1941 | warn 'gateway specified without specifying an IP address'; | |
1942 | return; | |
1943 | } | |
1944 | if ($res->{gw6} && !$res->{ip6}) { | |
1945 | warn 'IPv6 gateway specified without specifying an IPv6 address'; | |
1946 | return; | |
1947 | } | |
1948 | if ($res->{gw} && $res->{ip} eq 'dhcp') { | |
1949 | warn 'gateway specified together with DHCP'; | |
1950 | return; | |
1951 | } | |
1952 | if ($res->{gw6} && $res->{ip6} !~ /^$IPV6RE/) { | |
1953 | # gw6 + auto/dhcp | |
1954 | warn "IPv6 gateway specified together with $res->{ip6} address"; | |
1955 | return; | |
1956 | } | |
1957 | ||
1958 | if (!$res->{ip} && !$res->{ip6}) { | |
1959 | return { ip => 'dhcp', ip6 => 'dhcp' }; | |
1960 | } | |
1961 | ||
1962 | return $res; | |
1963 | } | |
1964 | ||
1965 | sub print_net { | |
1966 | my $net = shift; | |
1967 | ||
1968 | return PVE::JSONSchema::print_property_string($net, $net_fmt); | |
1969 | } | |
1970 | ||
1971 | sub add_random_macs { | |
1972 | my ($settings) = @_; | |
1973 | ||
1974 | foreach my $opt (keys %$settings) { | |
1975 | next if $opt !~ m/^net(\d+)$/; | |
1976 | my $net = parse_net($settings->{$opt}); | |
1977 | next if !$net; | |
1978 | $settings->{$opt} = print_net($net); | |
1979 | } | |
1980 | } | |
1981 | ||
1982 | sub vm_is_volid_owner { | |
1983 | my ($storecfg, $vmid, $volid) = @_; | |
1984 | ||
1985 | if ($volid !~ m|^/|) { | |
1986 | my ($path, $owner); | |
1987 | eval { ($path, $owner) = PVE::Storage::path($storecfg, $volid); }; | |
1988 | if ($owner && ($owner == $vmid)) { | |
1989 | return 1; | |
1990 | } | |
1991 | } | |
1992 | ||
1993 | return; | |
1994 | } | |
1995 | ||
1996 | sub vmconfig_register_unused_drive { | |
1997 | my ($storecfg, $vmid, $conf, $drive) = @_; | |
1998 | ||
1999 | if (drive_is_cloudinit($drive)) { | |
2000 | eval { PVE::Storage::vdisk_free($storecfg, $drive->{file}) }; | |
2001 | warn $@ if $@; | |
2002 | } elsif (!drive_is_cdrom($drive)) { | |
2003 | my $volid = $drive->{file}; | |
2004 | if (vm_is_volid_owner($storecfg, $vmid, $volid)) { | |
2005 | PVE::QemuConfig->add_unused_volume($conf, $volid, $vmid); | |
2006 | } | |
2007 | } | |
2008 | } | |
2009 | ||
2010 | # smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str][,base64=bool] | |
2011 | my $smbios1_fmt = { | |
2012 | uuid => { | |
2013 | type => 'string', | |
2014 | pattern => '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}', | |
2015 | format_description => 'UUID', | |
2016 | description => "Set SMBIOS1 UUID.", | |
2017 | optional => 1, | |
2018 | }, | |
2019 | version => { | |
2020 | type => 'string', | |
2021 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2022 | format_description => 'Base64 encoded string', | |
2023 | description => "Set SMBIOS1 version.", | |
2024 | optional => 1, | |
2025 | }, | |
2026 | serial => { | |
2027 | type => 'string', | |
2028 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2029 | format_description => 'Base64 encoded string', | |
2030 | description => "Set SMBIOS1 serial number.", | |
2031 | optional => 1, | |
2032 | }, | |
2033 | manufacturer => { | |
2034 | type => 'string', | |
2035 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2036 | format_description => 'Base64 encoded string', | |
2037 | description => "Set SMBIOS1 manufacturer.", | |
2038 | optional => 1, | |
2039 | }, | |
2040 | product => { | |
2041 | type => 'string', | |
2042 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2043 | format_description => 'Base64 encoded string', | |
2044 | description => "Set SMBIOS1 product ID.", | |
2045 | optional => 1, | |
2046 | }, | |
2047 | sku => { | |
2048 | type => 'string', | |
2049 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2050 | format_description => 'Base64 encoded string', | |
2051 | description => "Set SMBIOS1 SKU string.", | |
2052 | optional => 1, | |
2053 | }, | |
2054 | family => { | |
2055 | type => 'string', | |
2056 | pattern => '[A-Za-z0-9+\/]+={0,2}', | |
2057 | format_description => 'Base64 encoded string', | |
2058 | description => "Set SMBIOS1 family string.", | |
2059 | optional => 1, | |
2060 | }, | |
2061 | base64 => { | |
2062 | type => 'boolean', | |
2063 | description => 'Flag to indicate that the SMBIOS values are base64 encoded', | |
2064 | optional => 1, | |
2065 | }, | |
2066 | }; | |
2067 | ||
2068 | sub parse_smbios1 { | |
2069 | my ($data) = @_; | |
2070 | ||
2071 | my $res = eval { parse_property_string($smbios1_fmt, $data) }; | |
2072 | warn $@ if $@; | |
2073 | return $res; | |
2074 | } | |
2075 | ||
2076 | sub print_smbios1 { | |
2077 | my ($smbios1) = @_; | |
2078 | return PVE::JSONSchema::print_property_string($smbios1, $smbios1_fmt); | |
2079 | } | |
2080 | ||
2081 | PVE::JSONSchema::register_format('pve-qm-smbios1', $smbios1_fmt); | |
2082 | ||
2083 | sub parse_watchdog { | |
2084 | my ($value) = @_; | |
2085 | ||
2086 | return if !$value; | |
2087 | ||
2088 | my $res = eval { parse_property_string($watchdog_fmt, $value) }; | |
2089 | warn $@ if $@; | |
2090 | return $res; | |
2091 | } | |
2092 | ||
2093 | sub parse_guest_agent { | |
2094 | my ($conf) = @_; | |
2095 | ||
2096 | return {} if !defined($conf->{agent}); | |
2097 | ||
2098 | my $res = eval { parse_property_string($agent_fmt, $conf->{agent}) }; | |
2099 | warn $@ if $@; | |
2100 | ||
2101 | # if the agent is disabled ignore the other potentially set properties | |
2102 | return {} if !$res->{enabled}; | |
2103 | return $res; | |
2104 | } | |
2105 | ||
2106 | sub get_qga_key { | |
2107 | my ($conf, $key) = @_; | |
2108 | return undef if !defined($conf->{agent}); | |
2109 | ||
2110 | my $agent = parse_guest_agent($conf); | |
2111 | return $agent->{$key}; | |
2112 | } | |
2113 | ||
2114 | sub parse_vga { | |
2115 | my ($value) = @_; | |
2116 | ||
2117 | return {} if !$value; | |
2118 | my $res = eval { parse_property_string($vga_fmt, $value) }; | |
2119 | warn $@ if $@; | |
2120 | return $res; | |
2121 | } | |
2122 | ||
2123 | sub parse_rng { | |
2124 | my ($value) = @_; | |
2125 | ||
2126 | return if !$value; | |
2127 | ||
2128 | my $res = eval { parse_property_string($rng_fmt, $value) }; | |
2129 | warn $@ if $@; | |
2130 | return $res; | |
2131 | } | |
2132 | ||
2133 | sub parse_meta_info { | |
2134 | my ($value) = @_; | |
2135 | ||
2136 | return if !$value; | |
2137 | ||
2138 | my $res = eval { parse_property_string($meta_info_fmt, $value) }; | |
2139 | warn $@ if $@; | |
2140 | return $res; | |
2141 | } | |
2142 | ||
2143 | sub new_meta_info_string { | |
2144 | my () = @_; # for now do not allow to override any value | |
2145 | ||
2146 | return PVE::JSONSchema::print_property_string( | |
2147 | { | |
2148 | ctime => "". int(time()), | |
2149 | }, | |
2150 | $meta_info_fmt | |
2151 | ); | |
2152 | } | |
2153 | ||
2154 | PVE::JSONSchema::register_format('pve-qm-usb-device', \&verify_usb_device); | |
2155 | sub verify_usb_device { | |
2156 | my ($value, $noerr) = @_; | |
2157 | ||
2158 | return $value if parse_usb_device($value); | |
2159 | ||
2160 | return if $noerr; | |
2161 | ||
2162 | die "unable to parse usb device\n"; | |
2163 | } | |
2164 | ||
2165 | # add JSON properties for create and set function | |
2166 | sub json_config_properties { | |
2167 | my $prop = shift; | |
2168 | ||
2169 | my $skip_json_config_opts = { | |
2170 | parent => 1, | |
2171 | snaptime => 1, | |
2172 | vmstate => 1, | |
2173 | runningmachine => 1, | |
2174 | runningcpu => 1, | |
2175 | meta => 1, | |
2176 | }; | |
2177 | ||
2178 | foreach my $opt (keys %$confdesc) { | |
2179 | next if $skip_json_config_opts->{$opt}; | |
2180 | $prop->{$opt} = $confdesc->{$opt}; | |
2181 | } | |
2182 | ||
2183 | return $prop; | |
2184 | } | |
2185 | ||
2186 | # return copy of $confdesc_cloudinit to generate documentation | |
2187 | sub cloudinit_config_properties { | |
2188 | ||
2189 | return dclone($confdesc_cloudinit); | |
2190 | } | |
2191 | ||
2192 | sub check_type { | |
2193 | my ($key, $value) = @_; | |
2194 | ||
2195 | die "unknown setting '$key'\n" if !$confdesc->{$key}; | |
2196 | ||
2197 | my $type = $confdesc->{$key}->{type}; | |
2198 | ||
2199 | if (!defined($value)) { | |
2200 | die "got undefined value\n"; | |
2201 | } | |
2202 | ||
2203 | if ($value =~ m/[\n\r]/) { | |
2204 | die "property contains a line feed\n"; | |
2205 | } | |
2206 | ||
2207 | if ($type eq 'boolean') { | |
2208 | return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i); | |
2209 | return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i); | |
2210 | die "type check ('boolean') failed - got '$value'\n"; | |
2211 | } elsif ($type eq 'integer') { | |
2212 | return int($1) if $value =~ m/^(\d+)$/; | |
2213 | die "type check ('integer') failed - got '$value'\n"; | |
2214 | } elsif ($type eq 'number') { | |
2215 | return $value if $value =~ m/^(\d+)(\.\d+)?$/; | |
2216 | die "type check ('number') failed - got '$value'\n"; | |
2217 | } elsif ($type eq 'string') { | |
2218 | if (my $fmt = $confdesc->{$key}->{format}) { | |
2219 | PVE::JSONSchema::check_format($fmt, $value); | |
2220 | return $value; | |
2221 | } | |
2222 | $value =~ s/^\"(.*)\"$/$1/; | |
2223 | return $value; | |
2224 | } else { | |
2225 | die "internal error" | |
2226 | } | |
2227 | } | |
2228 | ||
2229 | sub destroy_vm { | |
2230 | my ($storecfg, $vmid, $skiplock, $replacement_conf, $purge_unreferenced) = @_; | |
2231 | ||
2232 | my $conf = PVE::QemuConfig->load_config($vmid); | |
2233 | ||
2234 | PVE::QemuConfig->check_lock($conf) if !$skiplock; | |
2235 | ||
2236 | if ($conf->{template}) { | |
2237 | # check if any base image is still used by a linked clone | |
2238 | PVE::QemuConfig->foreach_volume_full($conf, { include_unused => 1 }, sub { | |
2239 | my ($ds, $drive) = @_; | |
2240 | return if drive_is_cdrom($drive); | |
2241 | ||
2242 | my $volid = $drive->{file}; | |
2243 | return if !$volid || $volid =~ m|^/|; | |
2244 | ||
2245 | die "base volume '$volid' is still in use by linked cloned\n" | |
2246 | if PVE::Storage::volume_is_base_and_used($storecfg, $volid); | |
2247 | ||
2248 | }); | |
2249 | } | |
2250 | ||
2251 | my $volids = {}; | |
2252 | my $remove_owned_drive = sub { | |
2253 | my ($ds, $drive) = @_; | |
2254 | return if drive_is_cdrom($drive, 1); | |
2255 | ||
2256 | my $volid = $drive->{file}; | |
2257 | return if !$volid || $volid =~ m|^/|; | |
2258 | return if $volids->{$volid}; | |
2259 | ||
2260 | my ($path, $owner) = PVE::Storage::path($storecfg, $volid); | |
2261 | return if !$path || !$owner || ($owner != $vmid); | |
2262 | ||
2263 | $volids->{$volid} = 1; | |
2264 | eval { PVE::Storage::vdisk_free($storecfg, $volid) }; | |
2265 | warn "Could not remove disk '$volid', check manually: $@" if $@; | |
2266 | }; | |
2267 | ||
2268 | # only remove disks owned by this VM (referenced in the config) | |
2269 | my $include_opts = { | |
2270 | include_unused => 1, | |
2271 | extra_keys => ['vmstate'], | |
2272 | }; | |
2273 | PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $remove_owned_drive); | |
2274 | ||
2275 | for my $snap (values %{$conf->{snapshots}}) { | |
2276 | next if !defined($snap->{vmstate}); | |
2277 | my $drive = PVE::QemuConfig->parse_volume('vmstate', $snap->{vmstate}, 1); | |
2278 | next if !defined($drive); | |
2279 | $remove_owned_drive->('vmstate', $drive); | |
2280 | } | |
2281 | ||
2282 | PVE::QemuConfig->foreach_volume_full($conf->{pending}, $include_opts, $remove_owned_drive); | |
2283 | ||
2284 | if ($purge_unreferenced) { # also remove unreferenced disk | |
2285 | my $vmdisks = PVE::Storage::vdisk_list($storecfg, undef, $vmid, undef, 'images'); | |
2286 | PVE::Storage::foreach_volid($vmdisks, sub { | |
2287 | my ($volid, $sid, $volname, $d) = @_; | |
2288 | eval { PVE::Storage::vdisk_free($storecfg, $volid) }; | |
2289 | warn $@ if $@; | |
2290 | }); | |
2291 | } | |
2292 | ||
2293 | if (defined $replacement_conf) { | |
2294 | PVE::QemuConfig->write_config($vmid, $replacement_conf); | |
2295 | } else { | |
2296 | PVE::QemuConfig->destroy_config($vmid); | |
2297 | } | |
2298 | } | |
2299 | ||
2300 | sub parse_vm_config { | |
2301 | my ($filename, $raw) = @_; | |
2302 | ||
2303 | return if !defined($raw); | |
2304 | ||
2305 | my $res = { | |
2306 | digest => Digest::SHA::sha1_hex($raw), | |
2307 | snapshots => {}, | |
2308 | pending => {}, | |
2309 | }; | |
2310 | ||
2311 | $filename =~ m|/qemu-server/(\d+)\.conf$| | |
2312 | || die "got strange filename '$filename'"; | |
2313 | ||
2314 | my $vmid = $1; | |
2315 | ||
2316 | my $conf = $res; | |
2317 | my $descr; | |
2318 | my $section = ''; | |
2319 | ||
2320 | my @lines = split(/\n/, $raw); | |
2321 | foreach my $line (@lines) { | |
2322 | next if $line =~ m/^\s*$/; | |
2323 | ||
2324 | if ($line =~ m/^\[PENDING\]\s*$/i) { | |
2325 | $section = 'pending'; | |
2326 | if (defined($descr)) { | |
2327 | $descr =~ s/\s+$//; | |
2328 | $conf->{description} = $descr; | |
2329 | } | |
2330 | $descr = undef; | |
2331 | $conf = $res->{$section} = {}; | |
2332 | next; | |
2333 | ||
2334 | } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) { | |
2335 | $section = $1; | |
2336 | if (defined($descr)) { | |
2337 | $descr =~ s/\s+$//; | |
2338 | $conf->{description} = $descr; | |
2339 | } | |
2340 | $descr = undef; | |
2341 | $conf = $res->{snapshots}->{$section} = {}; | |
2342 | next; | |
2343 | } | |
2344 | ||
2345 | if ($line =~ m/^\#(.*)\s*$/) { | |
2346 | $descr = '' if !defined($descr); | |
2347 | $descr .= PVE::Tools::decode_text($1) . "\n"; | |
2348 | next; | |
2349 | } | |
2350 | ||
2351 | if ($line =~ m/^(description):\s*(.*\S)\s*$/) { | |
2352 | $descr = '' if !defined($descr); | |
2353 | $descr .= PVE::Tools::decode_text($2); | |
2354 | } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) { | |
2355 | $conf->{snapstate} = $1; | |
2356 | } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) { | |
2357 | my $key = $1; | |
2358 | my $value = $2; | |
2359 | $conf->{$key} = $value; | |
2360 | } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) { | |
2361 | my $value = $1; | |
2362 | if ($section eq 'pending') { | |
2363 | $conf->{delete} = $value; # we parse this later | |
2364 | } else { | |
2365 | warn "vm $vmid - propertry 'delete' is only allowed in [PENDING]\n"; | |
2366 | } | |
2367 | } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(.+?)\s*$/) { | |
2368 | my $key = $1; | |
2369 | my $value = $2; | |
2370 | eval { $value = check_type($key, $value); }; | |
2371 | if ($@) { | |
2372 | warn "vm $vmid - unable to parse value of '$key' - $@"; | |
2373 | } else { | |
2374 | $key = 'ide2' if $key eq 'cdrom'; | |
2375 | my $fmt = $confdesc->{$key}->{format}; | |
2376 | if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) { | |
2377 | my $v = parse_drive($key, $value); | |
2378 | if (my $volid = filename_to_volume_id($vmid, $v->{file}, $v->{media})) { | |
2379 | $v->{file} = $volid; | |
2380 | $value = print_drive($v); | |
2381 | } else { | |
2382 | warn "vm $vmid - unable to parse value of '$key'\n"; | |
2383 | next; | |
2384 | } | |
2385 | } | |
2386 | ||
2387 | $conf->{$key} = $value; | |
2388 | } | |
2389 | } else { | |
2390 | warn "vm $vmid - unable to parse config: $line\n"; | |
2391 | } | |
2392 | } | |
2393 | ||
2394 | if (defined($descr)) { | |
2395 | $descr =~ s/\s+$//; | |
2396 | $conf->{description} = $descr; | |
2397 | } | |
2398 | delete $res->{snapstate}; # just to be sure | |
2399 | ||
2400 | return $res; | |
2401 | } | |
2402 | ||
2403 | sub write_vm_config { | |
2404 | my ($filename, $conf) = @_; | |
2405 | ||
2406 | delete $conf->{snapstate}; # just to be sure | |
2407 | ||
2408 | if ($conf->{cdrom}) { | |
2409 | die "option ide2 conflicts with cdrom\n" if $conf->{ide2}; | |
2410 | $conf->{ide2} = $conf->{cdrom}; | |
2411 | delete $conf->{cdrom}; | |
2412 | } | |
2413 | ||
2414 | # we do not use 'smp' any longer | |
2415 | if ($conf->{sockets}) { | |
2416 | delete $conf->{smp}; | |
2417 | } elsif ($conf->{smp}) { | |
2418 | $conf->{sockets} = $conf->{smp}; | |
2419 | delete $conf->{cores}; | |
2420 | delete $conf->{smp}; | |
2421 | } | |
2422 | ||
2423 | my $used_volids = {}; | |
2424 | ||
2425 | my $cleanup_config = sub { | |
2426 | my ($cref, $pending, $snapname) = @_; | |
2427 | ||
2428 | foreach my $key (keys %$cref) { | |
2429 | next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' || | |
2430 | $key eq 'snapstate' || $key eq 'pending'; | |
2431 | my $value = $cref->{$key}; | |
2432 | if ($key eq 'delete') { | |
2433 | die "propertry 'delete' is only allowed in [PENDING]\n" | |
2434 | if !$pending; | |
2435 | # fixme: check syntax? | |
2436 | next; | |
2437 | } | |
2438 | eval { $value = check_type($key, $value); }; | |
2439 | die "unable to parse value of '$key' - $@" if $@; | |
2440 | ||
2441 | $cref->{$key} = $value; | |
2442 | ||
2443 | if (!$snapname && is_valid_drivename($key)) { | |
2444 | my $drive = parse_drive($key, $value); | |
2445 | $used_volids->{$drive->{file}} = 1 if $drive && $drive->{file}; | |
2446 | } | |
2447 | } | |
2448 | }; | |
2449 | ||
2450 | &$cleanup_config($conf); | |
2451 | ||
2452 | &$cleanup_config($conf->{pending}, 1); | |
2453 | ||
2454 | foreach my $snapname (keys %{$conf->{snapshots}}) { | |
2455 | die "internal error: snapshot name '$snapname' is forbidden" if lc($snapname) eq 'pending'; | |
2456 | &$cleanup_config($conf->{snapshots}->{$snapname}, undef, $snapname); | |
2457 | } | |
2458 | ||
2459 | # remove 'unusedX' settings if we re-add a volume | |
2460 | foreach my $key (keys %$conf) { | |
2461 | my $value = $conf->{$key}; | |
2462 | if ($key =~ m/^unused/ && $used_volids->{$value}) { | |
2463 | delete $conf->{$key}; | |
2464 | } | |
2465 | } | |
2466 | ||
2467 | my $generate_raw_config = sub { | |
2468 | my ($conf, $pending) = @_; | |
2469 | ||
2470 | my $raw = ''; | |
2471 | ||
2472 | # add description as comment to top of file | |
2473 | if (defined(my $descr = $conf->{description})) { | |
2474 | if ($descr) { | |
2475 | foreach my $cl (split(/\n/, $descr)) { | |
2476 | $raw .= '#' . PVE::Tools::encode_text($cl) . "\n"; | |
2477 | } | |
2478 | } else { | |
2479 | $raw .= "#\n" if $pending; | |
2480 | } | |
2481 | } | |
2482 | ||
2483 | foreach my $key (sort keys %$conf) { | |
2484 | next if $key =~ /^(digest|description|pending|snapshots)$/; | |
2485 | $raw .= "$key: $conf->{$key}\n"; | |
2486 | } | |
2487 | return $raw; | |
2488 | }; | |
2489 | ||
2490 | my $raw = &$generate_raw_config($conf); | |
2491 | ||
2492 | if (scalar(keys %{$conf->{pending}})){ | |
2493 | $raw .= "\n[PENDING]\n"; | |
2494 | $raw .= &$generate_raw_config($conf->{pending}, 1); | |
2495 | } | |
2496 | ||
2497 | foreach my $snapname (sort keys %{$conf->{snapshots}}) { | |
2498 | $raw .= "\n[$snapname]\n"; | |
2499 | $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname}); | |
2500 | } | |
2501 | ||
2502 | return $raw; | |
2503 | } | |
2504 | ||
2505 | sub load_defaults { | |
2506 | ||
2507 | my $res = {}; | |
2508 | ||
2509 | # we use static defaults from our JSON schema configuration | |
2510 | foreach my $key (keys %$confdesc) { | |
2511 | if (defined(my $default = $confdesc->{$key}->{default})) { | |
2512 | $res->{$key} = $default; | |
2513 | } | |
2514 | } | |
2515 | ||
2516 | return $res; | |
2517 | } | |
2518 | ||
2519 | sub config_list { | |
2520 | my $vmlist = PVE::Cluster::get_vmlist(); | |
2521 | my $res = {}; | |
2522 | return $res if !$vmlist || !$vmlist->{ids}; | |
2523 | my $ids = $vmlist->{ids}; | |
2524 | my $nodename = nodename(); | |
2525 | ||
2526 | foreach my $vmid (keys %$ids) { | |
2527 | my $d = $ids->{$vmid}; | |
2528 | next if !$d->{node} || $d->{node} ne $nodename; | |
2529 | next if !$d->{type} || $d->{type} ne 'qemu'; | |
2530 | $res->{$vmid}->{exists} = 1; | |
2531 | } | |
2532 | return $res; | |
2533 | } | |
2534 | ||
2535 | # test if VM uses local resources (to prevent migration) | |
2536 | sub check_local_resources { | |
2537 | my ($conf, $noerr) = @_; | |
2538 | ||
2539 | my @loc_res = (); | |
2540 | ||
2541 | push @loc_res, "hostusb" if $conf->{hostusb}; # old syntax | |
2542 | push @loc_res, "hostpci" if $conf->{hostpci}; # old syntax | |
2543 | ||
2544 | push @loc_res, "ivshmem" if $conf->{ivshmem}; | |
2545 | ||
2546 | foreach my $k (keys %$conf) { | |
2547 | next if $k =~ m/^usb/ && ($conf->{$k} =~ m/^spice(?![^,])/); | |
2548 | # sockets are safe: they will recreated be on the target side post-migrate | |
2549 | next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket'); | |
2550 | push @loc_res, $k if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/; | |
2551 | } | |
2552 | ||
2553 | die "VM uses local resources\n" if scalar @loc_res && !$noerr; | |
2554 | ||
2555 | return \@loc_res; | |
2556 | } | |
2557 | ||
2558 | # check if used storages are available on all nodes (use by migrate) | |
2559 | sub check_storage_availability { | |
2560 | my ($storecfg, $conf, $node) = @_; | |
2561 | ||
2562 | PVE::QemuConfig->foreach_volume($conf, sub { | |
2563 | my ($ds, $drive) = @_; | |
2564 | ||
2565 | my $volid = $drive->{file}; | |
2566 | return if !$volid; | |
2567 | ||
2568 | my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
2569 | return if !$sid; | |
2570 | ||
2571 | # check if storage is available on both nodes | |
2572 | my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid); | |
2573 | PVE::Storage::storage_check_enabled($storecfg, $sid, $node); | |
2574 | ||
2575 | my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid); | |
2576 | ||
2577 | die "$volid: content type '$vtype' is not available on storage '$sid'\n" | |
2578 | if !$scfg->{content}->{$vtype}; | |
2579 | }); | |
2580 | } | |
2581 | ||
2582 | # list nodes where all VM images are available (used by has_feature API) | |
2583 | sub shared_nodes { | |
2584 | my ($conf, $storecfg) = @_; | |
2585 | ||
2586 | my $nodelist = PVE::Cluster::get_nodelist(); | |
2587 | my $nodehash = { map { $_ => 1 } @$nodelist }; | |
2588 | my $nodename = nodename(); | |
2589 | ||
2590 | PVE::QemuConfig->foreach_volume($conf, sub { | |
2591 | my ($ds, $drive) = @_; | |
2592 | ||
2593 | my $volid = $drive->{file}; | |
2594 | return if !$volid; | |
2595 | ||
2596 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
2597 | if ($storeid) { | |
2598 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
2599 | if ($scfg->{disable}) { | |
2600 | $nodehash = {}; | |
2601 | } elsif (my $avail = $scfg->{nodes}) { | |
2602 | foreach my $node (keys %$nodehash) { | |
2603 | delete $nodehash->{$node} if !$avail->{$node}; | |
2604 | } | |
2605 | } elsif (!$scfg->{shared}) { | |
2606 | foreach my $node (keys %$nodehash) { | |
2607 | delete $nodehash->{$node} if $node ne $nodename | |
2608 | } | |
2609 | } | |
2610 | } | |
2611 | }); | |
2612 | ||
2613 | return $nodehash | |
2614 | } | |
2615 | ||
2616 | sub check_local_storage_availability { | |
2617 | my ($conf, $storecfg) = @_; | |
2618 | ||
2619 | my $nodelist = PVE::Cluster::get_nodelist(); | |
2620 | my $nodehash = { map { $_ => {} } @$nodelist }; | |
2621 | ||
2622 | PVE::QemuConfig->foreach_volume($conf, sub { | |
2623 | my ($ds, $drive) = @_; | |
2624 | ||
2625 | my $volid = $drive->{file}; | |
2626 | return if !$volid; | |
2627 | ||
2628 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
2629 | if ($storeid) { | |
2630 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
2631 | ||
2632 | if ($scfg->{disable}) { | |
2633 | foreach my $node (keys %$nodehash) { | |
2634 | $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1; | |
2635 | } | |
2636 | } elsif (my $avail = $scfg->{nodes}) { | |
2637 | foreach my $node (keys %$nodehash) { | |
2638 | if (!$avail->{$node}) { | |
2639 | $nodehash->{$node}->{unavailable_storages}->{$storeid} = 1; | |
2640 | } | |
2641 | } | |
2642 | } | |
2643 | } | |
2644 | }); | |
2645 | ||
2646 | foreach my $node (values %$nodehash) { | |
2647 | if (my $unavail = $node->{unavailable_storages}) { | |
2648 | $node->{unavailable_storages} = [ sort keys %$unavail ]; | |
2649 | } | |
2650 | } | |
2651 | ||
2652 | return $nodehash | |
2653 | } | |
2654 | ||
2655 | # Compat only, use assert_config_exists_on_node and vm_running_locally where possible | |
2656 | sub check_running { | |
2657 | my ($vmid, $nocheck, $node) = @_; | |
2658 | ||
2659 | PVE::QemuConfig::assert_config_exists_on_node($vmid, $node) if !$nocheck; | |
2660 | return PVE::QemuServer::Helpers::vm_running_locally($vmid); | |
2661 | } | |
2662 | ||
2663 | sub vzlist { | |
2664 | ||
2665 | my $vzlist = config_list(); | |
2666 | ||
2667 | my $fd = IO::Dir->new($PVE::QemuServer::Helpers::var_run_tmpdir) || return $vzlist; | |
2668 | ||
2669 | while (defined(my $de = $fd->read)) { | |
2670 | next if $de !~ m/^(\d+)\.pid$/; | |
2671 | my $vmid = $1; | |
2672 | next if !defined($vzlist->{$vmid}); | |
2673 | if (my $pid = check_running($vmid)) { | |
2674 | $vzlist->{$vmid}->{pid} = $pid; | |
2675 | } | |
2676 | } | |
2677 | ||
2678 | return $vzlist; | |
2679 | } | |
2680 | ||
2681 | our $vmstatus_return_properties = { | |
2682 | vmid => get_standard_option('pve-vmid'), | |
2683 | status => { | |
2684 | description => "Qemu process status.", | |
2685 | type => 'string', | |
2686 | enum => ['stopped', 'running'], | |
2687 | }, | |
2688 | maxmem => { | |
2689 | description => "Maximum memory in bytes.", | |
2690 | type => 'integer', | |
2691 | optional => 1, | |
2692 | renderer => 'bytes', | |
2693 | }, | |
2694 | maxdisk => { | |
2695 | description => "Root disk size in bytes.", | |
2696 | type => 'integer', | |
2697 | optional => 1, | |
2698 | renderer => 'bytes', | |
2699 | }, | |
2700 | name => { | |
2701 | description => "VM name.", | |
2702 | type => 'string', | |
2703 | optional => 1, | |
2704 | }, | |
2705 | qmpstatus => { | |
2706 | description => "Qemu QMP agent status.", | |
2707 | type => 'string', | |
2708 | optional => 1, | |
2709 | }, | |
2710 | pid => { | |
2711 | description => "PID of running qemu process.", | |
2712 | type => 'integer', | |
2713 | optional => 1, | |
2714 | }, | |
2715 | uptime => { | |
2716 | description => "Uptime.", | |
2717 | type => 'integer', | |
2718 | optional => 1, | |
2719 | renderer => 'duration', | |
2720 | }, | |
2721 | cpus => { | |
2722 | description => "Maximum usable CPUs.", | |
2723 | type => 'number', | |
2724 | optional => 1, | |
2725 | }, | |
2726 | lock => { | |
2727 | description => "The current config lock, if any.", | |
2728 | type => 'string', | |
2729 | optional => 1, | |
2730 | }, | |
2731 | tags => { | |
2732 | description => "The current configured tags, if any", | |
2733 | type => 'string', | |
2734 | optional => 1, | |
2735 | }, | |
2736 | 'running-machine' => { | |
2737 | description => "The currently running machine type (if running).", | |
2738 | type => 'string', | |
2739 | optional => 1, | |
2740 | }, | |
2741 | 'running-qemu' => { | |
2742 | description => "The currently running QEMU version (if running).", | |
2743 | type => 'string', | |
2744 | optional => 1, | |
2745 | }, | |
2746 | }; | |
2747 | ||
2748 | my $last_proc_pid_stat; | |
2749 | ||
2750 | # get VM status information | |
2751 | # This must be fast and should not block ($full == false) | |
2752 | # We only query KVM using QMP if $full == true (this can be slow) | |
2753 | sub vmstatus { | |
2754 | my ($opt_vmid, $full) = @_; | |
2755 | ||
2756 | my $res = {}; | |
2757 | ||
2758 | my $storecfg = PVE::Storage::config(); | |
2759 | ||
2760 | my $list = vzlist(); | |
2761 | my $defaults = load_defaults(); | |
2762 | ||
2763 | my ($uptime) = PVE::ProcFSTools::read_proc_uptime(1); | |
2764 | ||
2765 | my $cpucount = $cpuinfo->{cpus} || 1; | |
2766 | ||
2767 | foreach my $vmid (keys %$list) { | |
2768 | next if $opt_vmid && ($vmid ne $opt_vmid); | |
2769 | ||
2770 | my $conf = PVE::QemuConfig->load_config($vmid); | |
2771 | ||
2772 | my $d = { vmid => int($vmid) }; | |
2773 | $d->{pid} = int($list->{$vmid}->{pid}) if $list->{$vmid}->{pid}; | |
2774 | ||
2775 | # fixme: better status? | |
2776 | $d->{status} = $list->{$vmid}->{pid} ? 'running' : 'stopped'; | |
2777 | ||
2778 | my $size = PVE::QemuServer::Drive::bootdisk_size($storecfg, $conf); | |
2779 | if (defined($size)) { | |
2780 | $d->{disk} = 0; # no info available | |
2781 | $d->{maxdisk} = $size; | |
2782 | } else { | |
2783 | $d->{disk} = 0; | |
2784 | $d->{maxdisk} = 0; | |
2785 | } | |
2786 | ||
2787 | $d->{cpus} = ($conf->{sockets} || $defaults->{sockets}) | |
2788 | * ($conf->{cores} || $defaults->{cores}); | |
2789 | $d->{cpus} = $cpucount if $d->{cpus} > $cpucount; | |
2790 | $d->{cpus} = $conf->{vcpus} if $conf->{vcpus}; | |
2791 | ||
2792 | $d->{name} = $conf->{name} || "VM $vmid"; | |
2793 | $d->{maxmem} = $conf->{memory} ? $conf->{memory}*(1024*1024) | |
2794 | : $defaults->{memory}*(1024*1024); | |
2795 | ||
2796 | if ($conf->{balloon}) { | |
2797 | $d->{balloon_min} = $conf->{balloon}*(1024*1024); | |
2798 | $d->{shares} = defined($conf->{shares}) ? $conf->{shares} | |
2799 | : $defaults->{shares}; | |
2800 | } | |
2801 | ||
2802 | $d->{uptime} = 0; | |
2803 | $d->{cpu} = 0; | |
2804 | $d->{mem} = 0; | |
2805 | ||
2806 | $d->{netout} = 0; | |
2807 | $d->{netin} = 0; | |
2808 | ||
2809 | $d->{diskread} = 0; | |
2810 | $d->{diskwrite} = 0; | |
2811 | ||
2812 | $d->{template} = 1 if PVE::QemuConfig->is_template($conf); | |
2813 | ||
2814 | $d->{serial} = 1 if conf_has_serial($conf); | |
2815 | $d->{lock} = $conf->{lock} if $conf->{lock}; | |
2816 | $d->{tags} = $conf->{tags} if defined($conf->{tags}); | |
2817 | ||
2818 | $res->{$vmid} = $d; | |
2819 | } | |
2820 | ||
2821 | my $netdev = PVE::ProcFSTools::read_proc_net_dev(); | |
2822 | foreach my $dev (keys %$netdev) { | |
2823 | next if $dev !~ m/^tap([1-9]\d*)i/; | |
2824 | my $vmid = $1; | |
2825 | my $d = $res->{$vmid}; | |
2826 | next if !$d; | |
2827 | ||
2828 | $d->{netout} += $netdev->{$dev}->{receive}; | |
2829 | $d->{netin} += $netdev->{$dev}->{transmit}; | |
2830 | ||
2831 | if ($full) { | |
2832 | $d->{nics}->{$dev}->{netout} = int($netdev->{$dev}->{receive}); | |
2833 | $d->{nics}->{$dev}->{netin} = int($netdev->{$dev}->{transmit}); | |
2834 | } | |
2835 | ||
2836 | } | |
2837 | ||
2838 | my $ctime = gettimeofday; | |
2839 | ||
2840 | foreach my $vmid (keys %$list) { | |
2841 | ||
2842 | my $d = $res->{$vmid}; | |
2843 | my $pid = $d->{pid}; | |
2844 | next if !$pid; | |
2845 | ||
2846 | my $pstat = PVE::ProcFSTools::read_proc_pid_stat($pid); | |
2847 | next if !$pstat; # not running | |
2848 | ||
2849 | my $used = $pstat->{utime} + $pstat->{stime}; | |
2850 | ||
2851 | $d->{uptime} = int(($uptime - $pstat->{starttime})/$cpuinfo->{user_hz}); | |
2852 | ||
2853 | if ($pstat->{vsize}) { | |
2854 | $d->{mem} = int(($pstat->{rss}/$pstat->{vsize})*$d->{maxmem}); | |
2855 | } | |
2856 | ||
2857 | my $old = $last_proc_pid_stat->{$pid}; | |
2858 | if (!$old) { | |
2859 | $last_proc_pid_stat->{$pid} = { | |
2860 | time => $ctime, | |
2861 | used => $used, | |
2862 | cpu => 0, | |
2863 | }; | |
2864 | next; | |
2865 | } | |
2866 | ||
2867 | my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz}; | |
2868 | ||
2869 | if ($dtime > 1000) { | |
2870 | my $dutime = $used - $old->{used}; | |
2871 | ||
2872 | $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus}; | |
2873 | $last_proc_pid_stat->{$pid} = { | |
2874 | time => $ctime, | |
2875 | used => $used, | |
2876 | cpu => $d->{cpu}, | |
2877 | }; | |
2878 | } else { | |
2879 | $d->{cpu} = $old->{cpu}; | |
2880 | } | |
2881 | } | |
2882 | ||
2883 | return $res if !$full; | |
2884 | ||
2885 | my $qmpclient = PVE::QMPClient->new(); | |
2886 | ||
2887 | my $ballooncb = sub { | |
2888 | my ($vmid, $resp) = @_; | |
2889 | ||
2890 | my $info = $resp->{'return'}; | |
2891 | return if !$info->{max_mem}; | |
2892 | ||
2893 | my $d = $res->{$vmid}; | |
2894 | ||
2895 | # use memory assigned to VM | |
2896 | $d->{maxmem} = $info->{max_mem}; | |
2897 | $d->{balloon} = $info->{actual}; | |
2898 | ||
2899 | if (defined($info->{total_mem}) && defined($info->{free_mem})) { | |
2900 | $d->{mem} = $info->{total_mem} - $info->{free_mem}; | |
2901 | $d->{freemem} = $info->{free_mem}; | |
2902 | } | |
2903 | ||
2904 | $d->{ballooninfo} = $info; | |
2905 | }; | |
2906 | ||
2907 | my $blockstatscb = sub { | |
2908 | my ($vmid, $resp) = @_; | |
2909 | my $data = $resp->{'return'} || []; | |
2910 | my $totalrdbytes = 0; | |
2911 | my $totalwrbytes = 0; | |
2912 | ||
2913 | for my $blockstat (@$data) { | |
2914 | $totalrdbytes = $totalrdbytes + $blockstat->{stats}->{rd_bytes}; | |
2915 | $totalwrbytes = $totalwrbytes + $blockstat->{stats}->{wr_bytes}; | |
2916 | ||
2917 | $blockstat->{device} =~ s/drive-//; | |
2918 | $res->{$vmid}->{blockstat}->{$blockstat->{device}} = $blockstat->{stats}; | |
2919 | } | |
2920 | $res->{$vmid}->{diskread} = $totalrdbytes; | |
2921 | $res->{$vmid}->{diskwrite} = $totalwrbytes; | |
2922 | }; | |
2923 | ||
2924 | my $machinecb = sub { | |
2925 | my ($vmid, $resp) = @_; | |
2926 | my $data = $resp->{'return'} || []; | |
2927 | ||
2928 | $res->{$vmid}->{'running-machine'} = | |
2929 | PVE::QemuServer::Machine::current_from_query_machines($data); | |
2930 | }; | |
2931 | ||
2932 | my $versioncb = sub { | |
2933 | my ($vmid, $resp) = @_; | |
2934 | my $data = $resp->{'return'} // {}; | |
2935 | my $version = 'unknown'; | |
2936 | ||
2937 | if (my $v = $data->{qemu}) { | |
2938 | $version = $v->{major} . "." . $v->{minor} . "." . $v->{micro}; | |
2939 | } | |
2940 | ||
2941 | $res->{$vmid}->{'running-qemu'} = $version; | |
2942 | }; | |
2943 | ||
2944 | my $statuscb = sub { | |
2945 | my ($vmid, $resp) = @_; | |
2946 | ||
2947 | $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats'); | |
2948 | $qmpclient->queue_cmd($vmid, $machinecb, 'query-machines'); | |
2949 | $qmpclient->queue_cmd($vmid, $versioncb, 'query-version'); | |
2950 | # this fails if ballon driver is not loaded, so this must be | |
2951 | # the last commnand (following command are aborted if this fails). | |
2952 | $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon'); | |
2953 | ||
2954 | my $status = 'unknown'; | |
2955 | if (!defined($status = $resp->{'return'}->{status})) { | |
2956 | warn "unable to get VM status\n"; | |
2957 | return; | |
2958 | } | |
2959 | ||
2960 | $res->{$vmid}->{qmpstatus} = $resp->{'return'}->{status}; | |
2961 | }; | |
2962 | ||
2963 | foreach my $vmid (keys %$list) { | |
2964 | next if $opt_vmid && ($vmid ne $opt_vmid); | |
2965 | next if !$res->{$vmid}->{pid}; # not running | |
2966 | $qmpclient->queue_cmd($vmid, $statuscb, 'query-status'); | |
2967 | } | |
2968 | ||
2969 | $qmpclient->queue_execute(undef, 2); | |
2970 | ||
2971 | foreach my $vmid (keys %$list) { | |
2972 | next if $opt_vmid && ($vmid ne $opt_vmid); | |
2973 | next if !$res->{$vmid}->{pid}; #not running | |
2974 | ||
2975 | # we can't use the $qmpclient since it might have already aborted on | |
2976 | # 'query-balloon', but this might also fail for older versions... | |
2977 | my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") }; | |
2978 | $res->{$vmid}->{'proxmox-support'} = $qemu_support // {}; | |
2979 | } | |
2980 | ||
2981 | foreach my $vmid (keys %$list) { | |
2982 | next if $opt_vmid && ($vmid ne $opt_vmid); | |
2983 | $res->{$vmid}->{qmpstatus} = $res->{$vmid}->{status} if !$res->{$vmid}->{qmpstatus}; | |
2984 | } | |
2985 | ||
2986 | return $res; | |
2987 | } | |
2988 | ||
2989 | sub conf_has_serial { | |
2990 | my ($conf) = @_; | |
2991 | ||
2992 | for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) { | |
2993 | if ($conf->{"serial$i"}) { | |
2994 | return 1; | |
2995 | } | |
2996 | } | |
2997 | ||
2998 | return 0; | |
2999 | } | |
3000 | ||
3001 | sub conf_has_audio { | |
3002 | my ($conf, $id) = @_; | |
3003 | ||
3004 | $id //= 0; | |
3005 | my $audio = $conf->{"audio$id"}; | |
3006 | return if !defined($audio); | |
3007 | ||
3008 | my $audioproperties = parse_property_string($audio_fmt, $audio); | |
3009 | my $audiodriver = $audioproperties->{driver} // 'spice'; | |
3010 | ||
3011 | return { | |
3012 | dev => $audioproperties->{device}, | |
3013 | dev_id => "audiodev$id", | |
3014 | backend => $audiodriver, | |
3015 | backend_id => "$audiodriver-backend${id}", | |
3016 | }; | |
3017 | } | |
3018 | ||
3019 | sub audio_devs { | |
3020 | my ($audio, $audiopciaddr, $machine_version) = @_; | |
3021 | ||
3022 | my $devs = []; | |
3023 | ||
3024 | my $id = $audio->{dev_id}; | |
3025 | my $audiodev = ""; | |
3026 | if (min_version($machine_version, 4, 2)) { | |
3027 | $audiodev = ",audiodev=$audio->{backend_id}"; | |
3028 | } | |
3029 | ||
3030 | if ($audio->{dev} eq 'AC97') { | |
3031 | push @$devs, '-device', "AC97,id=${id}${audiopciaddr}$audiodev"; | |
3032 | } elsif ($audio->{dev} =~ /intel\-hda$/) { | |
3033 | push @$devs, '-device', "$audio->{dev},id=${id}${audiopciaddr}"; | |
3034 | push @$devs, '-device', "hda-micro,id=${id}-codec0,bus=${id}.0,cad=0$audiodev"; | |
3035 | push @$devs, '-device', "hda-duplex,id=${id}-codec1,bus=${id}.0,cad=1$audiodev"; | |
3036 | } else { | |
3037 | die "unkown audio device '$audio->{dev}', implement me!"; | |
3038 | } | |
3039 | ||
3040 | push @$devs, '-audiodev', "$audio->{backend},id=$audio->{backend_id}"; | |
3041 | ||
3042 | return $devs; | |
3043 | } | |
3044 | ||
3045 | sub get_tpm_paths { | |
3046 | my ($vmid) = @_; | |
3047 | return { | |
3048 | socket => "/var/run/qemu-server/$vmid.swtpm", | |
3049 | pid => "/var/run/qemu-server/$vmid.swtpm.pid", | |
3050 | }; | |
3051 | } | |
3052 | ||
3053 | sub add_tpm_device { | |
3054 | my ($vmid, $devices, $conf) = @_; | |
3055 | ||
3056 | return if !$conf->{tpmstate0}; | |
3057 | ||
3058 | my $paths = get_tpm_paths($vmid); | |
3059 | ||
3060 | push @$devices, "-chardev", "socket,id=tpmchar,path=$paths->{socket}"; | |
3061 | push @$devices, "-tpmdev", "emulator,id=tpmdev,chardev=tpmchar"; | |
3062 | push @$devices, "-device", "tpm-tis,tpmdev=tpmdev"; | |
3063 | } | |
3064 | ||
3065 | sub start_swtpm { | |
3066 | my ($storecfg, $vmid, $tpmdrive, $migration) = @_; | |
3067 | ||
3068 | return if !$tpmdrive; | |
3069 | ||
3070 | my $state; | |
3071 | my $tpm = parse_drive("tpmstate0", $tpmdrive); | |
3072 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1); | |
3073 | if ($storeid) { | |
3074 | $state = PVE::Storage::map_volume($storecfg, $tpm->{file}); | |
3075 | } else { | |
3076 | $state = $tpm->{file}; | |
3077 | } | |
3078 | ||
3079 | my $paths = get_tpm_paths($vmid); | |
3080 | ||
3081 | # during migration, we will get state from remote | |
3082 | # | |
3083 | if (!$migration) { | |
3084 | # run swtpm_setup to create a new TPM state if it doesn't exist yet | |
3085 | my $setup_cmd = [ | |
3086 | "swtpm_setup", | |
3087 | "--tpmstate", | |
3088 | "file://$state", | |
3089 | "--createek", | |
3090 | "--create-ek-cert", | |
3091 | "--create-platform-cert", | |
3092 | "--lock-nvram", | |
3093 | "--config", | |
3094 | "/etc/swtpm_setup.conf", # do not use XDG configs | |
3095 | "--runas", | |
3096 | "0", # force creation as root, error if not possible | |
3097 | "--not-overwrite", # ignore existing state, do not modify | |
3098 | ]; | |
3099 | ||
3100 | push @$setup_cmd, "--tpm2" if $tpm->{version} eq 'v2.0'; | |
3101 | # TPM 2.0 supports ECC crypto, use if possible | |
3102 | push @$setup_cmd, "--ecc" if $tpm->{version} eq 'v2.0'; | |
3103 | ||
3104 | run_command($setup_cmd, outfunc => sub { | |
3105 | print "swtpm_setup: $1\n"; | |
3106 | }); | |
3107 | } | |
3108 | ||
3109 | my $emulator_cmd = [ | |
3110 | "swtpm", | |
3111 | "socket", | |
3112 | "--tpmstate", | |
3113 | "backend-uri=file://$state,mode=0600", | |
3114 | "--ctrl", | |
3115 | "type=unixio,path=$paths->{socket},mode=0600", | |
3116 | "--pid", | |
3117 | "file=$paths->{pid}", | |
3118 | "--terminate", # terminate on QEMU disconnect | |
3119 | "--daemon", | |
3120 | ]; | |
3121 | push @$emulator_cmd, "--tpm2" if $tpm->{version} eq 'v2.0'; | |
3122 | run_command($emulator_cmd, outfunc => sub { print $1; }); | |
3123 | ||
3124 | my $tries = 100; # swtpm may take a bit to start before daemonizing, wait up to 5s for pid | |
3125 | while (! -e $paths->{pid}) { | |
3126 | die "failed to start swtpm: pid file '$paths->{pid}' wasn't created.\n" if --$tries == 0; | |
3127 | usleep(50_000); | |
3128 | } | |
3129 | ||
3130 | # return untainted PID of swtpm daemon so it can be killed on error | |
3131 | file_read_firstline($paths->{pid}) =~ m/(\d+)/; | |
3132 | return $1; | |
3133 | } | |
3134 | ||
3135 | sub vga_conf_has_spice { | |
3136 | my ($vga) = @_; | |
3137 | ||
3138 | my $vgaconf = parse_vga($vga); | |
3139 | my $vgatype = $vgaconf->{type}; | |
3140 | return 0 if !$vgatype || $vgatype !~ m/^qxl([234])?$/; | |
3141 | ||
3142 | return $1 || 1; | |
3143 | } | |
3144 | ||
3145 | sub is_native($) { | |
3146 | my ($arch) = @_; | |
3147 | return get_host_arch() eq $arch; | |
3148 | } | |
3149 | ||
3150 | sub get_vm_arch { | |
3151 | my ($conf) = @_; | |
3152 | return $conf->{arch} // get_host_arch(); | |
3153 | } | |
3154 | ||
3155 | my $default_machines = { | |
3156 | x86_64 => 'pc', | |
3157 | aarch64 => 'virt', | |
3158 | }; | |
3159 | ||
3160 | sub get_installed_machine_version { | |
3161 | my ($kvmversion) = @_; | |
3162 | $kvmversion = kvm_user_version() if !defined($kvmversion); | |
3163 | $kvmversion =~ m/^(\d+\.\d+)/; | |
3164 | return $1; | |
3165 | } | |
3166 | ||
3167 | sub windows_get_pinned_machine_version { | |
3168 | my ($machine, $base_version, $kvmversion) = @_; | |
3169 | ||
3170 | my $pin_version = $base_version; | |
3171 | if (!defined($base_version) || | |
3172 | !PVE::QemuServer::Machine::can_run_pve_machine_version($base_version, $kvmversion) | |
3173 | ) { | |
3174 | $pin_version = get_installed_machine_version($kvmversion); | |
3175 | } | |
3176 | if (!$machine || $machine eq 'pc') { | |
3177 | $machine = "pc-i440fx-$pin_version"; | |
3178 | } elsif ($machine eq 'q35') { | |
3179 | $machine = "pc-q35-$pin_version"; | |
3180 | } elsif ($machine eq 'virt') { | |
3181 | $machine = "virt-$pin_version"; | |
3182 | } else { | |
3183 | warn "unknown machine type '$machine', not touching that!\n"; | |
3184 | } | |
3185 | ||
3186 | return $machine; | |
3187 | } | |
3188 | ||
3189 | sub get_vm_machine { | |
3190 | my ($conf, $forcemachine, $arch, $add_pve_version, $kvmversion) = @_; | |
3191 | ||
3192 | my $machine = $forcemachine || $conf->{machine}; | |
3193 | ||
3194 | if (!$machine || $machine =~ m/^(?:pc|q35|virt)$/) { | |
3195 | $kvmversion //= kvm_user_version(); | |
3196 | # we must pin Windows VMs without a specific version to 5.1, as 5.2 fixed a bug in ACPI | |
3197 | # layout which confuses windows quite a bit and may result in various regressions.. | |
3198 | # see: https://lists.gnu.org/archive/html/qemu-devel/2021-02/msg08484.html | |
3199 | if (windows_version($conf->{ostype})) { | |
3200 | $machine = windows_get_pinned_machine_version($machine, '5.1', $kvmversion); | |
3201 | } | |
3202 | $arch //= 'x86_64'; | |
3203 | $machine ||= $default_machines->{$arch}; | |
3204 | if ($add_pve_version) { | |
3205 | my $pvever = PVE::QemuServer::Machine::get_pve_version($kvmversion); | |
3206 | $machine .= "+pve$pvever"; | |
3207 | } | |
3208 | } | |
3209 | ||
3210 | if ($add_pve_version && $machine !~ m/\+pve\d+?(?:\.pxe)?$/) { | |
3211 | my $is_pxe = $machine =~ m/^(.*?)\.pxe$/; | |
3212 | $machine = $1 if $is_pxe; | |
3213 | ||
3214 | # for version-pinned machines that do not include a pve-version (e.g. | |
3215 | # pc-q35-4.1), we assume 0 to keep them stable in case we bump | |
3216 | $machine .= '+pve0'; | |
3217 | ||
3218 | $machine .= '.pxe' if $is_pxe; | |
3219 | } | |
3220 | ||
3221 | return $machine; | |
3222 | } | |
3223 | ||
3224 | sub get_ovmf_files($$$) { | |
3225 | my ($arch, $efidisk, $smm) = @_; | |
3226 | ||
3227 | my $types = $OVMF->{$arch} | |
3228 | or die "no OVMF images known for architecture '$arch'\n"; | |
3229 | ||
3230 | my $type = 'default'; | |
3231 | if (defined($efidisk->{efitype}) && $efidisk->{efitype} eq '4m') { | |
3232 | $type = $smm ? "4m" : "4m-no-smm"; | |
3233 | $type .= '-ms' if $efidisk->{'pre-enrolled-keys'}; | |
3234 | } | |
3235 | ||
3236 | return $types->{$type}->@*; | |
3237 | } | |
3238 | ||
3239 | my $Arch2Qemu = { | |
3240 | aarch64 => '/usr/bin/qemu-system-aarch64', | |
3241 | x86_64 => '/usr/bin/qemu-system-x86_64', | |
3242 | }; | |
3243 | sub get_command_for_arch($) { | |
3244 | my ($arch) = @_; | |
3245 | return '/usr/bin/kvm' if is_native($arch); | |
3246 | ||
3247 | my $cmd = $Arch2Qemu->{$arch} | |
3248 | or die "don't know how to emulate architecture '$arch'\n"; | |
3249 | return $cmd; | |
3250 | } | |
3251 | ||
3252 | # To use query_supported_cpu_flags and query_understood_cpu_flags to get flags | |
3253 | # to use in a QEMU command line (-cpu element), first array_intersect the result | |
3254 | # of query_supported_ with query_understood_. This is necessary because: | |
3255 | # | |
3256 | # a) query_understood_ returns flags the host cannot use and | |
3257 | # b) query_supported_ (rather the QMP call) doesn't actually return CPU | |
3258 | # flags, but CPU settings - with most of them being flags. Those settings | |
3259 | # (and some flags, curiously) cannot be specified as a "-cpu" argument. | |
3260 | # | |
3261 | # query_supported_ needs to start up to 2 temporary VMs and is therefore rather | |
3262 | # expensive. If you need the value returned from this, you can get it much | |
3263 | # cheaper from pmxcfs using PVE::Cluster::get_node_kv('cpuflags-$accel') with | |
3264 | # $accel being 'kvm' or 'tcg'. | |
3265 | # | |
3266 | # pvestatd calls this function on startup and whenever the QEMU/KVM version | |
3267 | # changes, automatically populating pmxcfs. | |
3268 | # | |
3269 | # Returns: { kvm => [ flagX, flagY, ... ], tcg => [ flag1, flag2, ... ] } | |
3270 | # since kvm and tcg machines support different flags | |
3271 | # | |
3272 | sub query_supported_cpu_flags { | |
3273 | my ($arch) = @_; | |
3274 | ||
3275 | $arch //= get_host_arch(); | |
3276 | my $default_machine = $default_machines->{$arch}; | |
3277 | ||
3278 | my $flags = {}; | |
3279 | ||
3280 | # FIXME: Once this is merged, the code below should work for ARM as well: | |
3281 | # https://lists.nongnu.org/archive/html/qemu-devel/2019-06/msg04947.html | |
3282 | die "QEMU/KVM cannot detect CPU flags on ARM (aarch64)\n" if | |
3283 | $arch eq "aarch64"; | |
3284 | ||
3285 | my $kvm_supported = defined(kvm_version()); | |
3286 | my $qemu_cmd = get_command_for_arch($arch); | |
3287 | my $fakevmid = -1; | |
3288 | my $pidfile = PVE::QemuServer::Helpers::pidfile_name($fakevmid); | |
3289 | ||
3290 | # Start a temporary (frozen) VM with vmid -1 to allow sending a QMP command | |
3291 | my $query_supported_run_qemu = sub { | |
3292 | my ($kvm) = @_; | |
3293 | ||
3294 | my $flags = {}; | |
3295 | my $cmd = [ | |
3296 | $qemu_cmd, | |
3297 | '-machine', $default_machine, | |
3298 | '-display', 'none', | |
3299 | '-chardev', "socket,id=qmp,path=/var/run/qemu-server/$fakevmid.qmp,server=on,wait=off", | |
3300 | '-mon', 'chardev=qmp,mode=control', | |
3301 | '-pidfile', $pidfile, | |
3302 | '-S', '-daemonize' | |
3303 | ]; | |
3304 | ||
3305 | if (!$kvm) { | |
3306 | push @$cmd, '-accel', 'tcg'; | |
3307 | } | |
3308 | ||
3309 | my $rc = run_command($cmd, noerr => 1, quiet => 0); | |
3310 | die "QEMU flag querying VM exited with code " . $rc if $rc; | |
3311 | ||
3312 | eval { | |
3313 | my $cmd_result = mon_cmd( | |
3314 | $fakevmid, | |
3315 | 'query-cpu-model-expansion', | |
3316 | type => 'full', | |
3317 | model => { name => 'host' } | |
3318 | ); | |
3319 | ||
3320 | my $props = $cmd_result->{model}->{props}; | |
3321 | foreach my $prop (keys %$props) { | |
3322 | next if $props->{$prop} ne '1'; | |
3323 | # QEMU returns some flags multiple times, with '_', '.' or '-' | |
3324 | # (e.g. lahf_lm and lahf-lm; sse4.2, sse4-2 and sse4_2; ...). | |
3325 | # We only keep those with underscores, to match /proc/cpuinfo | |
3326 | $prop =~ s/\.|-/_/g; | |
3327 | $flags->{$prop} = 1; | |
3328 | } | |
3329 | }; | |
3330 | my $err = $@; | |
3331 | ||
3332 | # force stop with 10 sec timeout and 'nocheck', always stop, even if QMP failed | |
3333 | vm_stop(undef, $fakevmid, 1, 1, 10, 0, 1); | |
3334 | ||
3335 | die $err if $err; | |
3336 | ||
3337 | return [ sort keys %$flags ]; | |
3338 | }; | |
3339 | ||
3340 | # We need to query QEMU twice, since KVM and TCG have different supported flags | |
3341 | PVE::QemuConfig->lock_config($fakevmid, sub { | |
3342 | $flags->{tcg} = eval { $query_supported_run_qemu->(0) }; | |
3343 | warn "warning: failed querying supported tcg flags: $@\n" if $@; | |
3344 | ||
3345 | if ($kvm_supported) { | |
3346 | $flags->{kvm} = eval { $query_supported_run_qemu->(1) }; | |
3347 | warn "warning: failed querying supported kvm flags: $@\n" if $@; | |
3348 | } | |
3349 | }); | |
3350 | ||
3351 | return $flags; | |
3352 | } | |
3353 | ||
3354 | # Understood CPU flags are written to a file at 'pve-qemu' compile time | |
3355 | my $understood_cpu_flag_dir = "/usr/share/kvm"; | |
3356 | sub query_understood_cpu_flags { | |
3357 | my $arch = get_host_arch(); | |
3358 | my $filepath = "$understood_cpu_flag_dir/recognized-CPUID-flags-$arch"; | |
3359 | ||
3360 | die "Cannot query understood QEMU CPU flags for architecture: $arch (file not found)\n" | |
3361 | if ! -e $filepath; | |
3362 | ||
3363 | my $raw = file_get_contents($filepath); | |
3364 | $raw =~ s/^\s+|\s+$//g; | |
3365 | my @flags = split(/\s+/, $raw); | |
3366 | ||
3367 | return \@flags; | |
3368 | } | |
3369 | ||
3370 | my sub get_cpuunits { | |
3371 | my ($conf) = @_; | |
3372 | return $conf->{cpuunits} // (PVE::CGroup::cgroup_mode() == 2 ? 100 : 1024); | |
3373 | } | |
3374 | sub config_to_command { | |
3375 | my ($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu, | |
3376 | $pbs_backing) = @_; | |
3377 | ||
3378 | my $cmd = []; | |
3379 | my ($globalFlags, $machineFlags, $rtcFlags) = ([], [], []); | |
3380 | my $devices = []; | |
3381 | my $bridges = {}; | |
3382 | my $ostype = $conf->{ostype}; | |
3383 | my $winversion = windows_version($ostype); | |
3384 | my $kvm = $conf->{kvm}; | |
3385 | my $nodename = nodename(); | |
3386 | ||
3387 | my $arch = get_vm_arch($conf); | |
3388 | my $kvm_binary = get_command_for_arch($arch); | |
3389 | my $kvmver = kvm_user_version($kvm_binary); | |
3390 | ||
3391 | if (!$kvmver || $kvmver !~ m/^(\d+)\.(\d+)/ || $1 < 3) { | |
3392 | $kvmver //= "undefined"; | |
3393 | die "Detected old QEMU binary ('$kvmver', at least 3.0 is required)\n"; | |
3394 | } | |
3395 | ||
3396 | my $add_pve_version = min_version($kvmver, 4, 1); | |
3397 | ||
3398 | my $machine_type = get_vm_machine($conf, $forcemachine, $arch, $add_pve_version); | |
3399 | my $machine_version = extract_version($machine_type, $kvmver); | |
3400 | $kvm //= 1 if is_native($arch); | |
3401 | ||
3402 | $machine_version =~ m/(\d+)\.(\d+)/; | |
3403 | my ($machine_major, $machine_minor) = ($1, $2); | |
3404 | ||
3405 | if ($kvmver =~ m/^\d+\.\d+\.(\d+)/ && $1 >= 90) { | |
3406 | warn "warning: Installed QEMU version ($kvmver) is a release candidate, ignoring version checks\n"; | |
3407 | } elsif (!min_version($kvmver, $machine_major, $machine_minor)) { | |
3408 | die "Installed QEMU version '$kvmver' is too old to run machine type '$machine_type'," | |
3409 | ." please upgrade node '$nodename'\n" | |
3410 | } elsif (!PVE::QemuServer::Machine::can_run_pve_machine_version($machine_version, $kvmver)) { | |
3411 | my $max_pve_version = PVE::QemuServer::Machine::get_pve_version($machine_version); | |
3412 | die "Installed qemu-server (max feature level for $machine_major.$machine_minor is" | |
3413 | ." pve$max_pve_version) is too old to run machine type '$machine_type', please upgrade" | |
3414 | ." node '$nodename'\n"; | |
3415 | } | |
3416 | ||
3417 | # if a specific +pve version is required for a feature, use $version_guard | |
3418 | # instead of min_version to allow machines to be run with the minimum | |
3419 | # required version | |
3420 | my $required_pve_version = 0; | |
3421 | my $version_guard = sub { | |
3422 | my ($major, $minor, $pve) = @_; | |
3423 | return 0 if !min_version($machine_version, $major, $minor, $pve); | |
3424 | my $max_pve = PVE::QemuServer::Machine::get_pve_version("$major.$minor"); | |
3425 | return 1 if min_version($machine_version, $major, $minor, $max_pve+1); | |
3426 | $required_pve_version = $pve if $pve && $pve > $required_pve_version; | |
3427 | return 1; | |
3428 | }; | |
3429 | ||
3430 | if ($kvm && !defined kvm_version()) { | |
3431 | die "KVM virtualisation configured, but not available. Either disable in VM configuration" | |
3432 | ." or enable in BIOS.\n"; | |
3433 | } | |
3434 | ||
3435 | my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf); | |
3436 | my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1'); | |
3437 | my $use_old_bios_files = undef; | |
3438 | ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type); | |
3439 | ||
3440 | my $cpuunits = get_cpuunits($conf); | |
3441 | ||
3442 | push @$cmd, $kvm_binary; | |
3443 | ||
3444 | push @$cmd, '-id', $vmid; | |
3445 | ||
3446 | my $vmname = $conf->{name} || "vm$vmid"; | |
3447 | ||
3448 | push @$cmd, '-name', $vmname; | |
3449 | ||
3450 | push @$cmd, '-no-shutdown'; | |
3451 | ||
3452 | my $use_virtio = 0; | |
3453 | ||
3454 | my $qmpsocket = PVE::QemuServer::Helpers::qmp_socket($vmid); | |
3455 | push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server=on,wait=off"; | |
3456 | push @$cmd, '-mon', "chardev=qmp,mode=control"; | |
3457 | ||
3458 | if (min_version($machine_version, 2, 12)) { | |
3459 | push @$cmd, '-chardev', "socket,id=qmp-event,path=/var/run/qmeventd.sock,reconnect=5"; | |
3460 | push @$cmd, '-mon', "chardev=qmp-event,mode=control"; | |
3461 | } | |
3462 | ||
3463 | push @$cmd, '-pidfile' , PVE::QemuServer::Helpers::pidfile_name($vmid); | |
3464 | ||
3465 | push @$cmd, '-daemonize'; | |
3466 | ||
3467 | if ($conf->{smbios1}) { | |
3468 | my $smbios_conf = parse_smbios1($conf->{smbios1}); | |
3469 | if ($smbios_conf->{base64}) { | |
3470 | # Do not pass base64 flag to qemu | |
3471 | delete $smbios_conf->{base64}; | |
3472 | my $smbios_string = ""; | |
3473 | foreach my $key (keys %$smbios_conf) { | |
3474 | my $value; | |
3475 | if ($key eq "uuid") { | |
3476 | $value = $smbios_conf->{uuid} | |
3477 | } else { | |
3478 | $value = decode_base64($smbios_conf->{$key}); | |
3479 | } | |
3480 | # qemu accepts any binary data, only commas need escaping by double comma | |
3481 | $value =~ s/,/,,/g; | |
3482 | $smbios_string .= "," . $key . "=" . $value if $value; | |
3483 | } | |
3484 | push @$cmd, '-smbios', "type=1" . $smbios_string; | |
3485 | } else { | |
3486 | push @$cmd, '-smbios', "type=1,$conf->{smbios1}"; | |
3487 | } | |
3488 | } | |
3489 | ||
3490 | if ($conf->{bios} && $conf->{bios} eq 'ovmf') { | |
3491 | my $d; | |
3492 | if (my $efidisk = $conf->{efidisk0}) { | |
3493 | $d = parse_drive('efidisk0', $efidisk); | |
3494 | } | |
3495 | ||
3496 | my ($ovmf_code, $ovmf_vars) = get_ovmf_files($arch, $d, $q35); | |
3497 | die "uefi base image '$ovmf_code' not found\n" if ! -f $ovmf_code; | |
3498 | ||
3499 | my ($path, $format); | |
3500 | my $read_only_str = ''; | |
3501 | if ($d) { | |
3502 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($d->{file}, 1); | |
3503 | $format = $d->{format}; | |
3504 | if ($storeid) { | |
3505 | $path = PVE::Storage::path($storecfg, $d->{file}); | |
3506 | if (!defined($format)) { | |
3507 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
3508 | $format = qemu_img_format($scfg, $volname); | |
3509 | } | |
3510 | } else { | |
3511 | $path = $d->{file}; | |
3512 | die "efidisk format must be specified\n" | |
3513 | if !defined($format); | |
3514 | } | |
3515 | ||
3516 | $read_only_str = ',readonly=on' if drive_is_read_only($conf, $d); | |
3517 | } else { | |
3518 | warn "no efidisk configured! Using temporary efivars disk.\n"; | |
3519 | $path = "/tmp/$vmid-ovmf.fd"; | |
3520 | PVE::Tools::file_copy($ovmf_vars, $path, -s $ovmf_vars); | |
3521 | $format = 'raw'; | |
3522 | } | |
3523 | ||
3524 | my $size_str = ""; | |
3525 | ||
3526 | if ($format eq 'raw' && $version_guard->(4, 1, 2)) { | |
3527 | $size_str = ",size=" . (-s $ovmf_vars); | |
3528 | } | |
3529 | ||
3530 | # SPI flash does lots of read-modify-write OPs, without writeback this gets really slow #3329 | |
3531 | my $cache = ""; | |
3532 | if ($path =~ m/^rbd:/) { | |
3533 | $cache = ',cache=writeback'; | |
3534 | $path .= ':rbd_cache_policy=writeback'; # avoid write-around, we *need* to cache writes too | |
3535 | } | |
3536 | ||
3537 | push @$cmd, '-drive', "if=pflash,unit=0,format=raw,readonly=on,file=$ovmf_code"; | |
3538 | push @$cmd, '-drive', "if=pflash,unit=1$cache,format=$format,id=drive-efidisk0$size_str,file=${path}${read_only_str}"; | |
3539 | } | |
3540 | ||
3541 | if ($q35) { # tell QEMU to load q35 config early | |
3542 | # we use different pcie-port hardware for qemu >= 4.0 for passthrough | |
3543 | if (min_version($machine_version, 4, 0)) { | |
3544 | push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35-4.0.cfg'; | |
3545 | } else { | |
3546 | push @$devices, '-readconfig', '/usr/share/qemu-server/pve-q35.cfg'; | |
3547 | } | |
3548 | } | |
3549 | ||
3550 | if ($conf->{vmgenid}) { | |
3551 | push @$devices, '-device', 'vmgenid,guid='.$conf->{vmgenid}; | |
3552 | } | |
3553 | ||
3554 | # add usb controllers | |
3555 | my @usbcontrollers = PVE::QemuServer::USB::get_usb_controllers( | |
3556 | $conf, $bridges, $arch, $machine_type, $usbdesc->{format}, $MAX_USB_DEVICES); | |
3557 | push @$devices, @usbcontrollers if @usbcontrollers; | |
3558 | my $vga = parse_vga($conf->{vga}); | |
3559 | ||
3560 | my $qxlnum = vga_conf_has_spice($conf->{vga}); | |
3561 | $vga->{type} = 'qxl' if $qxlnum; | |
3562 | ||
3563 | if (!$vga->{type}) { | |
3564 | if ($arch eq 'aarch64') { | |
3565 | $vga->{type} = 'virtio'; | |
3566 | } elsif (min_version($machine_version, 2, 9)) { | |
3567 | $vga->{type} = (!$winversion || $winversion >= 6) ? 'std' : 'cirrus'; | |
3568 | } else { | |
3569 | $vga->{type} = ($winversion >= 6) ? 'std' : 'cirrus'; | |
3570 | } | |
3571 | } | |
3572 | ||
3573 | # enable absolute mouse coordinates (needed by vnc) | |
3574 | my $tablet = $conf->{tablet}; | |
3575 | if (!defined($tablet)) { | |
3576 | $tablet = $defaults->{tablet}; | |
3577 | $tablet = 0 if $qxlnum; # disable for spice because it is not needed | |
3578 | $tablet = 0 if $vga->{type} =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card) | |
3579 | } | |
3580 | ||
3581 | if ($tablet) { | |
3582 | push @$devices, '-device', print_tabletdevice_full($conf, $arch) if $tablet; | |
3583 | my $kbd = print_keyboarddevice_full($conf, $arch); | |
3584 | push @$devices, '-device', $kbd if defined($kbd); | |
3585 | } | |
3586 | ||
3587 | my $bootorder = device_bootorder($conf); | |
3588 | ||
3589 | # host pci device passthrough | |
3590 | my ($kvm_off, $gpu_passthrough, $legacy_igd) = PVE::QemuServer::PCI::print_hostpci_devices( | |
3591 | $vmid, $conf, $devices, $vga, $winversion, $q35, $bridges, $arch, $machine_type, $bootorder); | |
3592 | ||
3593 | # usb devices | |
3594 | my $usb_dev_features = {}; | |
3595 | $usb_dev_features->{spice_usb3} = 1 if min_version($machine_version, 4, 0); | |
3596 | ||
3597 | my @usbdevices = PVE::QemuServer::USB::get_usb_devices( | |
3598 | $conf, $usbdesc->{format}, $MAX_USB_DEVICES, $usb_dev_features, $bootorder); | |
3599 | push @$devices, @usbdevices if @usbdevices; | |
3600 | ||
3601 | # serial devices | |
3602 | for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) { | |
3603 | my $path = $conf->{"serial$i"} or next; | |
3604 | if ($path eq 'socket') { | |
3605 | my $socket = "/var/run/qemu-server/${vmid}.serial$i"; | |
3606 | push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server=on,wait=off"; | |
3607 | # On aarch64, serial0 is the UART device. Qemu only allows | |
3608 | # connecting UART devices via the '-serial' command line, as | |
3609 | # the device has a fixed slot on the hardware... | |
3610 | if ($arch eq 'aarch64' && $i == 0) { | |
3611 | push @$devices, '-serial', "chardev:serial$i"; | |
3612 | } else { | |
3613 | push @$devices, '-device', "isa-serial,chardev=serial$i"; | |
3614 | } | |
3615 | } else { | |
3616 | die "no such serial device\n" if ! -c $path; | |
3617 | push @$devices, '-chardev', "tty,id=serial$i,path=$path"; | |
3618 | push @$devices, '-device', "isa-serial,chardev=serial$i"; | |
3619 | } | |
3620 | } | |
3621 | ||
3622 | # parallel devices | |
3623 | for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) { | |
3624 | if (my $path = $conf->{"parallel$i"}) { | |
3625 | die "no such parallel device\n" if ! -c $path; | |
3626 | my $devtype = $path =~ m!^/dev/usb/lp! ? 'tty' : 'parport'; | |
3627 | push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path"; | |
3628 | push @$devices, '-device', "isa-parallel,chardev=parallel$i"; | |
3629 | } | |
3630 | } | |
3631 | ||
3632 | if (min_version($machine_version, 4, 0) && (my $audio = conf_has_audio($conf))) { | |
3633 | my $audiopciaddr = print_pci_addr("audio0", $bridges, $arch, $machine_type); | |
3634 | my $audio_devs = audio_devs($audio, $audiopciaddr, $machine_version); | |
3635 | push @$devices, @$audio_devs; | |
3636 | } | |
3637 | ||
3638 | add_tpm_device($vmid, $devices, $conf); | |
3639 | ||
3640 | my $sockets = 1; | |
3641 | $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused | |
3642 | $sockets = $conf->{sockets} if $conf->{sockets}; | |
3643 | ||
3644 | my $cores = $conf->{cores} || 1; | |
3645 | ||
3646 | my $maxcpus = $sockets * $cores; | |
3647 | ||
3648 | my $vcpus = $conf->{vcpus} ? $conf->{vcpus} : $maxcpus; | |
3649 | ||
3650 | my $allowed_vcpus = $cpuinfo->{cpus}; | |
3651 | ||
3652 | die "MAX $allowed_vcpus vcpus allowed per VM on this node\n" if ($allowed_vcpus < $maxcpus); | |
3653 | ||
3654 | if ($hotplug_features->{cpu} && min_version($machine_version, 2, 7)) { | |
3655 | push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus"; | |
3656 | for (my $i = 2; $i <= $vcpus; $i++) { | |
3657 | my $cpustr = print_cpu_device($conf,$i); | |
3658 | push @$cmd, '-device', $cpustr; | |
3659 | } | |
3660 | ||
3661 | } else { | |
3662 | ||
3663 | push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus"; | |
3664 | } | |
3665 | push @$cmd, '-nodefaults'; | |
3666 | ||
3667 | push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg"; | |
3668 | ||
3669 | push @$cmd, '-no-acpi' if defined($conf->{acpi}) && $conf->{acpi} == 0; | |
3670 | ||
3671 | push @$cmd, '-no-reboot' if defined($conf->{reboot}) && $conf->{reboot} == 0; | |
3672 | ||
3673 | if ($vga->{type} && $vga->{type} !~ m/^serial\d+$/ && $vga->{type} ne 'none'){ | |
3674 | push @$devices, '-device', print_vga_device( | |
3675 | $conf, $vga, $arch, $machine_version, $machine_type, undef, $qxlnum, $bridges); | |
3676 | my $socket = PVE::QemuServer::Helpers::vnc_socket($vmid); | |
3677 | push @$cmd, '-vnc', "unix:$socket,password=on"; | |
3678 | } else { | |
3679 | push @$cmd, '-vga', 'none' if $vga->{type} eq 'none'; | |
3680 | push @$cmd, '-nographic'; | |
3681 | } | |
3682 | ||
3683 | # time drift fix | |
3684 | my $tdf = defined($conf->{tdf}) ? $conf->{tdf} : $defaults->{tdf}; | |
3685 | my $useLocaltime = $conf->{localtime}; | |
3686 | ||
3687 | if ($winversion >= 5) { # windows | |
3688 | $useLocaltime = 1 if !defined($conf->{localtime}); | |
3689 | ||
3690 | # use time drift fix when acpi is enabled | |
3691 | if (!(defined($conf->{acpi}) && $conf->{acpi} == 0)) { | |
3692 | $tdf = 1 if !defined($conf->{tdf}); | |
3693 | } | |
3694 | } | |
3695 | ||
3696 | if ($winversion >= 6) { | |
3697 | push @$globalFlags, 'kvm-pit.lost_tick_policy=discard'; | |
3698 | push @$cmd, '-no-hpet'; | |
3699 | } | |
3700 | ||
3701 | push @$rtcFlags, 'driftfix=slew' if $tdf; | |
3702 | ||
3703 | if ($conf->{startdate} && $conf->{startdate} ne 'now') { | |
3704 | push @$rtcFlags, "base=$conf->{startdate}"; | |
3705 | } elsif ($useLocaltime) { | |
3706 | push @$rtcFlags, 'base=localtime'; | |
3707 | } | |
3708 | ||
3709 | if ($forcecpu) { | |
3710 | push @$cmd, '-cpu', $forcecpu; | |
3711 | } else { | |
3712 | push @$cmd, get_cpu_options($conf, $arch, $kvm, $kvm_off, $machine_version, $winversion, $gpu_passthrough); | |
3713 | } | |
3714 | ||
3715 | PVE::QemuServer::Memory::config($conf, $vmid, $sockets, $cores, $defaults, $hotplug_features, $cmd); | |
3716 | ||
3717 | push @$cmd, '-S' if $conf->{freeze}; | |
3718 | ||
3719 | push @$cmd, '-k', $conf->{keyboard} if defined($conf->{keyboard}); | |
3720 | ||
3721 | my $guest_agent = parse_guest_agent($conf); | |
3722 | ||
3723 | if ($guest_agent->{enabled}) { | |
3724 | my $qgasocket = PVE::QemuServer::Helpers::qmp_socket($vmid, 1); | |
3725 | push @$devices, '-chardev', "socket,path=$qgasocket,server=on,wait=off,id=qga0"; | |
3726 | ||
3727 | if (!$guest_agent->{type} || $guest_agent->{type} eq 'virtio') { | |
3728 | my $pciaddr = print_pci_addr("qga0", $bridges, $arch, $machine_type); | |
3729 | push @$devices, '-device', "virtio-serial,id=qga0$pciaddr"; | |
3730 | push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0'; | |
3731 | } elsif ($guest_agent->{type} eq 'isa') { | |
3732 | push @$devices, '-device', "isa-serial,chardev=qga0"; | |
3733 | } | |
3734 | } | |
3735 | ||
3736 | my $rng = $conf->{rng0} ? parse_rng($conf->{rng0}) : undef; | |
3737 | if ($rng && $version_guard->(4, 1, 2)) { | |
3738 | check_rng_source($rng->{source}); | |
3739 | ||
3740 | my $max_bytes = $rng->{max_bytes} // $rng_fmt->{max_bytes}->{default}; | |
3741 | my $period = $rng->{period} // $rng_fmt->{period}->{default}; | |
3742 | my $limiter_str = ""; | |
3743 | if ($max_bytes) { | |
3744 | $limiter_str = ",max-bytes=$max_bytes,period=$period"; | |
3745 | } | |
3746 | ||
3747 | my $rng_addr = print_pci_addr("rng0", $bridges, $arch, $machine_type); | |
3748 | push @$devices, '-object', "rng-random,filename=$rng->{source},id=rng0"; | |
3749 | push @$devices, '-device', "virtio-rng-pci,rng=rng0$limiter_str$rng_addr"; | |
3750 | } | |
3751 | ||
3752 | my $spice_port; | |
3753 | ||
3754 | if ($qxlnum) { | |
3755 | if ($qxlnum > 1) { | |
3756 | if ($winversion){ | |
3757 | for (my $i = 1; $i < $qxlnum; $i++){ | |
3758 | push @$devices, '-device', print_vga_device( | |
3759 | $conf, $vga, $arch, $machine_version, $machine_type, $i, $qxlnum, $bridges); | |
3760 | } | |
3761 | } else { | |
3762 | # assume other OS works like Linux | |
3763 | my ($ram, $vram) = ("134217728", "67108864"); | |
3764 | if ($vga->{memory}) { | |
3765 | $ram = PVE::Tools::convert_size($qxlnum*4*$vga->{memory}, 'mb' => 'b'); | |
3766 | $vram = PVE::Tools::convert_size($qxlnum*2*$vga->{memory}, 'mb' => 'b'); | |
3767 | } | |
3768 | push @$cmd, '-global', "qxl-vga.ram_size=$ram"; | |
3769 | push @$cmd, '-global', "qxl-vga.vram_size=$vram"; | |
3770 | } | |
3771 | } | |
3772 | ||
3773 | my $pciaddr = print_pci_addr("spice", $bridges, $arch, $machine_type); | |
3774 | ||
3775 | my $pfamily = PVE::Tools::get_host_address_family($nodename); | |
3776 | my @nodeaddrs = PVE::Tools::getaddrinfo_all('localhost', family => $pfamily); | |
3777 | die "failed to get an ip address of type $pfamily for 'localhost'\n" if !@nodeaddrs; | |
3778 | ||
3779 | push @$devices, '-device', "virtio-serial,id=spice$pciaddr"; | |
3780 | push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent"; | |
3781 | push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0"; | |
3782 | ||
3783 | my $localhost = PVE::Network::addr_to_ip($nodeaddrs[0]->{addr}); | |
3784 | $spice_port = PVE::Tools::next_spice_port($pfamily, $localhost); | |
3785 | ||
3786 | my $spice_enhancement_str = $conf->{spice_enhancements} // ''; | |
3787 | my $spice_enhancement = parse_property_string($spice_enhancements_fmt, $spice_enhancement_str); | |
3788 | if ($spice_enhancement->{foldersharing}) { | |
3789 | push @$devices, '-chardev', "spiceport,id=foldershare,name=org.spice-space.webdav.0"; | |
3790 | push @$devices, '-device', "virtserialport,chardev=foldershare,name=org.spice-space.webdav.0"; | |
3791 | } | |
3792 | ||
3793 | my $spice_opts = "tls-port=${spice_port},addr=$localhost,tls-ciphers=HIGH,seamless-migration=on"; | |
3794 | $spice_opts .= ",streaming-video=$spice_enhancement->{videostreaming}" | |
3795 | if $spice_enhancement->{videostreaming}; | |
3796 | ||
3797 | push @$devices, '-spice', "$spice_opts"; | |
3798 | } | |
3799 | ||
3800 | # enable balloon by default, unless explicitly disabled | |
3801 | if (!defined($conf->{balloon}) || $conf->{balloon}) { | |
3802 | my $pciaddr = print_pci_addr("balloon0", $bridges, $arch, $machine_type); | |
3803 | push @$devices, '-device', "virtio-balloon-pci,id=balloon0$pciaddr"; | |
3804 | } | |
3805 | ||
3806 | if ($conf->{watchdog}) { | |
3807 | my $wdopts = parse_watchdog($conf->{watchdog}); | |
3808 | my $pciaddr = print_pci_addr("watchdog", $bridges, $arch, $machine_type); | |
3809 | my $watchdog = $wdopts->{model} || 'i6300esb'; | |
3810 | push @$devices, '-device', "$watchdog$pciaddr"; | |
3811 | push @$devices, '-watchdog-action', $wdopts->{action} if $wdopts->{action}; | |
3812 | } | |
3813 | ||
3814 | my $vollist = []; | |
3815 | my $scsicontroller = {}; | |
3816 | my $ahcicontroller = {}; | |
3817 | my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : $defaults->{scsihw}; | |
3818 | ||
3819 | # Add iscsi initiator name if available | |
3820 | if (my $initiator = get_initiator_name()) { | |
3821 | push @$devices, '-iscsi', "initiator-name=$initiator"; | |
3822 | } | |
3823 | ||
3824 | PVE::QemuConfig->foreach_volume($conf, sub { | |
3825 | my ($ds, $drive) = @_; | |
3826 | ||
3827 | if (PVE::Storage::parse_volume_id($drive->{file}, 1)) { | |
3828 | check_volume_storage_type($storecfg, $drive->{file}); | |
3829 | push @$vollist, $drive->{file}; | |
3830 | } | |
3831 | ||
3832 | # ignore efidisk here, already added in bios/fw handling code above | |
3833 | return if $drive->{interface} eq 'efidisk'; | |
3834 | # similar for TPM | |
3835 | return if $drive->{interface} eq 'tpmstate'; | |
3836 | ||
3837 | $use_virtio = 1 if $ds =~ m/^virtio/; | |
3838 | ||
3839 | $drive->{bootindex} = $bootorder->{$ds} if $bootorder->{$ds}; | |
3840 | ||
3841 | if ($drive->{interface} eq 'virtio'){ | |
3842 | push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread}; | |
3843 | } | |
3844 | ||
3845 | if ($drive->{interface} eq 'scsi') { | |
3846 | ||
3847 | my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $drive); | |
3848 | ||
3849 | die "scsi$drive->{index}: machine version 4.1~pve2 or higher is required to use more than 14 SCSI disks\n" | |
3850 | if $drive->{index} > 13 && !&$version_guard(4, 1, 2); | |
3851 | ||
3852 | my $pciaddr = print_pci_addr("$controller_prefix$controller", $bridges, $arch, $machine_type); | |
3853 | my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ? "virtio-scsi-pci" : $scsihw; | |
3854 | ||
3855 | my $iothread = ''; | |
3856 | if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{iothread}){ | |
3857 | $iothread .= ",iothread=iothread-$controller_prefix$controller"; | |
3858 | push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller"; | |
3859 | } elsif ($drive->{iothread}) { | |
3860 | warn "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n"; | |
3861 | } | |
3862 | ||
3863 | my $queues = ''; | |
3864 | if($conf->{scsihw} && $conf->{scsihw} eq "virtio-scsi-single" && $drive->{queues}){ | |
3865 | $queues = ",num_queues=$drive->{queues}"; | |
3866 | } | |
3867 | ||
3868 | push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues" | |
3869 | if !$scsicontroller->{$controller}; | |
3870 | $scsicontroller->{$controller}=1; | |
3871 | } | |
3872 | ||
3873 | if ($drive->{interface} eq 'sata') { | |
3874 | my $controller = int($drive->{index} / $PVE::QemuServer::Drive::MAX_SATA_DISKS); | |
3875 | my $pciaddr = print_pci_addr("ahci$controller", $bridges, $arch, $machine_type); | |
3876 | push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr" | |
3877 | if !$ahcicontroller->{$controller}; | |
3878 | $ahcicontroller->{$controller}=1; | |
3879 | } | |
3880 | ||
3881 | my $pbs_conf = $pbs_backing->{$ds}; | |
3882 | my $pbs_name = undef; | |
3883 | if ($pbs_conf) { | |
3884 | $pbs_name = "drive-$ds-pbs"; | |
3885 | push @$devices, '-blockdev', print_pbs_blockdev($pbs_conf, $pbs_name); | |
3886 | } | |
3887 | ||
3888 | my $drive_cmd = print_drive_commandline_full( | |
3889 | $storecfg, $vmid, $drive, $pbs_name, min_version($kvmver, 6, 0)); | |
3890 | ||
3891 | # extra protection for templates, but SATA and IDE don't support it.. | |
3892 | $drive_cmd .= ',readonly=on' if drive_is_read_only($conf, $drive); | |
3893 | ||
3894 | push @$devices, '-drive',$drive_cmd; | |
3895 | push @$devices, '-device', print_drivedevice_full( | |
3896 | $storecfg, $conf, $vmid, $drive, $bridges, $arch, $machine_type); | |
3897 | }); | |
3898 | ||
3899 | for (my $i = 0; $i < $MAX_NETS; $i++) { | |
3900 | my $netname = "net$i"; | |
3901 | ||
3902 | next if !$conf->{$netname}; | |
3903 | my $d = parse_net($conf->{$netname}); | |
3904 | next if !$d; | |
3905 | ||
3906 | $use_virtio = 1 if $d->{model} eq 'virtio'; | |
3907 | ||
3908 | $d->{bootindex} = $bootorder->{$netname} if $bootorder->{$netname}; | |
3909 | ||
3910 | my $netdevfull = print_netdev_full($vmid, $conf, $arch, $d, $netname); | |
3911 | push @$devices, '-netdev', $netdevfull; | |
3912 | ||
3913 | my $netdevicefull = print_netdevice_full( | |
3914 | $vmid, $conf, $d, $netname, $bridges, $use_old_bios_files, $arch, $machine_type); | |
3915 | ||
3916 | push @$devices, '-device', $netdevicefull; | |
3917 | } | |
3918 | ||
3919 | if ($conf->{ivshmem}) { | |
3920 | my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem}); | |
3921 | ||
3922 | my $bus; | |
3923 | if ($q35) { | |
3924 | $bus = print_pcie_addr("ivshmem"); | |
3925 | } else { | |
3926 | $bus = print_pci_addr("ivshmem", $bridges, $arch, $machine_type); | |
3927 | } | |
3928 | ||
3929 | my $ivshmem_name = $ivshmem->{name} // $vmid; | |
3930 | my $path = '/dev/shm/pve-shm-' . $ivshmem_name; | |
3931 | ||
3932 | push @$devices, '-device', "ivshmem-plain,memdev=ivshmem$bus,"; | |
3933 | push @$devices, '-object', "memory-backend-file,id=ivshmem,share=on,mem-path=$path" | |
3934 | .",size=$ivshmem->{size}M"; | |
3935 | } | |
3936 | ||
3937 | # pci.4 is nested in pci.1 | |
3938 | $bridges->{1} = 1 if $bridges->{4}; | |
3939 | ||
3940 | if (!$q35) { # add pci bridges | |
3941 | if (min_version($machine_version, 2, 3)) { | |
3942 | $bridges->{1} = 1; | |
3943 | $bridges->{2} = 1; | |
3944 | } | |
3945 | $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/; | |
3946 | } | |
3947 | ||
3948 | for my $k (sort {$b cmp $a} keys %$bridges) { | |
3949 | next if $q35 && $k < 4; # q35.cfg already includes bridges up to 3 | |
3950 | ||
3951 | my $k_name = $k; | |
3952 | if ($k == 2 && $legacy_igd) { | |
3953 | $k_name = "$k-igd"; | |
3954 | } | |
3955 | my $pciaddr = print_pci_addr("pci.$k_name", undef, $arch, $machine_type); | |
3956 | my $devstr = "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr"; | |
3957 | ||
3958 | if ($q35) { # add after -readconfig pve-q35.cfg | |
3959 | splice @$devices, 2, 0, '-device', $devstr; | |
3960 | } else { | |
3961 | unshift @$devices, '-device', $devstr if $k > 0; | |
3962 | } | |
3963 | } | |
3964 | ||
3965 | if (!$kvm) { | |
3966 | push @$machineFlags, 'accel=tcg'; | |
3967 | } | |
3968 | ||
3969 | my $machine_type_min = $machine_type; | |
3970 | if ($add_pve_version) { | |
3971 | $machine_type_min =~ s/\+pve\d+$//; | |
3972 | $machine_type_min .= "+pve$required_pve_version"; | |
3973 | } | |
3974 | push @$machineFlags, "type=${machine_type_min}"; | |
3975 | ||
3976 | push @$cmd, @$devices; | |
3977 | push @$cmd, '-rtc', join(',', @$rtcFlags) if scalar(@$rtcFlags); | |
3978 | push @$cmd, '-machine', join(',', @$machineFlags) if scalar(@$machineFlags); | |
3979 | push @$cmd, '-global', join(',', @$globalFlags) if scalar(@$globalFlags); | |
3980 | ||
3981 | if (my $vmstate = $conf->{vmstate}) { | |
3982 | my $statepath = PVE::Storage::path($storecfg, $vmstate); | |
3983 | push @$vollist, $vmstate; | |
3984 | push @$cmd, '-loadstate', $statepath; | |
3985 | print "activating and using '$vmstate' as vmstate\n"; | |
3986 | } | |
3987 | ||
3988 | if (PVE::QemuConfig->is_template($conf)) { | |
3989 | # needed to workaround base volumes being read-only | |
3990 | push @$cmd, '-snapshot'; | |
3991 | } | |
3992 | ||
3993 | # add custom args | |
3994 | if ($conf->{args}) { | |
3995 | my $aa = PVE::Tools::split_args($conf->{args}); | |
3996 | push @$cmd, @$aa; | |
3997 | } | |
3998 | ||
3999 | return wantarray ? ($cmd, $vollist, $spice_port) : $cmd; | |
4000 | } | |
4001 | ||
4002 | sub check_rng_source { | |
4003 | my ($source) = @_; | |
4004 | ||
4005 | # mostly relevant for /dev/hwrng, but doesn't hurt to check others too | |
4006 | die "cannot create VirtIO RNG device: source file '$source' doesn't exist\n" | |
4007 | if ! -e $source; | |
4008 | ||
4009 | my $rng_current = '/sys/devices/virtual/misc/hw_random/rng_current'; | |
4010 | if ($source eq '/dev/hwrng' && file_read_firstline($rng_current) eq 'none') { | |
4011 | # Needs to abort, otherwise QEMU crashes on first rng access. Note that rng_current cannot | |
4012 | # be changed to 'none' manually, so once the VM is past this point, it's no longer an issue. | |
4013 | die "Cannot start VM with passed-through RNG device: '/dev/hwrng' exists, but" | |
4014 | ." '$rng_current' is set to 'none'. Ensure that a compatible hardware-RNG is attached" | |
4015 | ." to the host.\n"; | |
4016 | } | |
4017 | } | |
4018 | ||
4019 | sub spice_port { | |
4020 | my ($vmid) = @_; | |
4021 | ||
4022 | my $res = mon_cmd($vmid, 'query-spice'); | |
4023 | ||
4024 | return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n"; | |
4025 | } | |
4026 | ||
4027 | sub vm_devices_list { | |
4028 | my ($vmid) = @_; | |
4029 | ||
4030 | my $res = mon_cmd($vmid, 'query-pci'); | |
4031 | my $devices_to_check = []; | |
4032 | my $devices = {}; | |
4033 | foreach my $pcibus (@$res) { | |
4034 | push @$devices_to_check, @{$pcibus->{devices}}, | |
4035 | } | |
4036 | ||
4037 | while (@$devices_to_check) { | |
4038 | my $to_check = []; | |
4039 | for my $d (@$devices_to_check) { | |
4040 | $devices->{$d->{'qdev_id'}} = 1 if $d->{'qdev_id'}; | |
4041 | next if !$d->{'pci_bridge'}; | |
4042 | ||
4043 | $devices->{$d->{'qdev_id'}} += scalar(@{$d->{'pci_bridge'}->{devices}}); | |
4044 | push @$to_check, @{$d->{'pci_bridge'}->{devices}}; | |
4045 | } | |
4046 | $devices_to_check = $to_check; | |
4047 | } | |
4048 | ||
4049 | my $resblock = mon_cmd($vmid, 'query-block'); | |
4050 | foreach my $block (@$resblock) { | |
4051 | if($block->{device} =~ m/^drive-(\S+)/){ | |
4052 | $devices->{$1} = 1; | |
4053 | } | |
4054 | } | |
4055 | ||
4056 | my $resmice = mon_cmd($vmid, 'query-mice'); | |
4057 | foreach my $mice (@$resmice) { | |
4058 | if ($mice->{name} eq 'QEMU HID Tablet') { | |
4059 | $devices->{tablet} = 1; | |
4060 | last; | |
4061 | } | |
4062 | } | |
4063 | ||
4064 | # for usb devices there is no query-usb | |
4065 | # but we can iterate over the entries in | |
4066 | # qom-list path=/machine/peripheral | |
4067 | my $resperipheral = mon_cmd($vmid, 'qom-list', path => '/machine/peripheral'); | |
4068 | foreach my $per (@$resperipheral) { | |
4069 | if ($per->{name} =~ m/^usb\d+$/) { | |
4070 | $devices->{$per->{name}} = 1; | |
4071 | } | |
4072 | } | |
4073 | ||
4074 | return $devices; | |
4075 | } | |
4076 | ||
4077 | sub vm_deviceplug { | |
4078 | my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_; | |
4079 | ||
4080 | my $q35 = PVE::QemuServer::Machine::machine_type_is_q35($conf); | |
4081 | ||
4082 | my $devices_list = vm_devices_list($vmid); | |
4083 | return 1 if defined($devices_list->{$deviceid}); | |
4084 | ||
4085 | # add PCI bridge if we need it for the device | |
4086 | qemu_add_pci_bridge($storecfg, $conf, $vmid, $deviceid, $arch, $machine_type); | |
4087 | ||
4088 | if ($deviceid eq 'tablet') { | |
4089 | qemu_deviceadd($vmid, print_tabletdevice_full($conf, $arch)); | |
4090 | } elsif ($deviceid eq 'keyboard') { | |
4091 | qemu_deviceadd($vmid, print_keyboarddevice_full($conf, $arch)); | |
4092 | } elsif ($deviceid =~ m/^usb(\d+)$/) { | |
4093 | die "usb hotplug currently not reliable\n"; | |
4094 | # since we can't reliably hot unplug all added usb devices and usb | |
4095 | # passthrough breaks live migration we disable usb hotplugging for now | |
4096 | #qemu_deviceadd($vmid, PVE::QemuServer::USB::print_usbdevice_full($conf, $deviceid, $device)); | |
4097 | } elsif ($deviceid =~ m/^(virtio)(\d+)$/) { | |
4098 | qemu_iothread_add($vmid, $deviceid, $device); | |
4099 | ||
4100 | qemu_driveadd($storecfg, $vmid, $device); | |
4101 | my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type); | |
4102 | ||
4103 | qemu_deviceadd($vmid, $devicefull); | |
4104 | eval { qemu_deviceaddverify($vmid, $deviceid); }; | |
4105 | if (my $err = $@) { | |
4106 | eval { qemu_drivedel($vmid, $deviceid); }; | |
4107 | warn $@ if $@; | |
4108 | die $err; | |
4109 | } | |
4110 | } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) { | |
4111 | my $scsihw = defined($conf->{scsihw}) ? $conf->{scsihw} : "lsi"; | |
4112 | my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type); | |
4113 | my $scsihw_type = $scsihw eq 'virtio-scsi-single' ? "virtio-scsi-pci" : $scsihw; | |
4114 | ||
4115 | my $devicefull = "$scsihw_type,id=$deviceid$pciaddr"; | |
4116 | ||
4117 | if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread}) { | |
4118 | qemu_iothread_add($vmid, $deviceid, $device); | |
4119 | $devicefull .= ",iothread=iothread-$deviceid"; | |
4120 | } | |
4121 | ||
4122 | if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues}) { | |
4123 | $devicefull .= ",num_queues=$device->{queues}"; | |
4124 | } | |
4125 | ||
4126 | qemu_deviceadd($vmid, $devicefull); | |
4127 | qemu_deviceaddverify($vmid, $deviceid); | |
4128 | } elsif ($deviceid =~ m/^(scsi)(\d+)$/) { | |
4129 | qemu_findorcreatescsihw($storecfg,$conf, $vmid, $device, $arch, $machine_type); | |
4130 | qemu_driveadd($storecfg, $vmid, $device); | |
4131 | ||
4132 | my $devicefull = print_drivedevice_full($storecfg, $conf, $vmid, $device, undef, $arch, $machine_type); | |
4133 | eval { qemu_deviceadd($vmid, $devicefull); }; | |
4134 | if (my $err = $@) { | |
4135 | eval { qemu_drivedel($vmid, $deviceid); }; | |
4136 | warn $@ if $@; | |
4137 | die $err; | |
4138 | } | |
4139 | } elsif ($deviceid =~ m/^(net)(\d+)$/) { | |
4140 | return if !qemu_netdevadd($vmid, $conf, $arch, $device, $deviceid); | |
4141 | ||
4142 | my $machine_type = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf); | |
4143 | my $use_old_bios_files = undef; | |
4144 | ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type); | |
4145 | ||
4146 | my $netdevicefull = print_netdevice_full( | |
4147 | $vmid, $conf, $device, $deviceid, undef, $use_old_bios_files, $arch, $machine_type); | |
4148 | qemu_deviceadd($vmid, $netdevicefull); | |
4149 | eval { | |
4150 | qemu_deviceaddverify($vmid, $deviceid); | |
4151 | qemu_set_link_status($vmid, $deviceid, !$device->{link_down}); | |
4152 | }; | |
4153 | if (my $err = $@) { | |
4154 | eval { qemu_netdevdel($vmid, $deviceid); }; | |
4155 | warn $@ if $@; | |
4156 | die $err; | |
4157 | } | |
4158 | } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) { | |
4159 | my $bridgeid = $2; | |
4160 | my $pciaddr = print_pci_addr($deviceid, undef, $arch, $machine_type); | |
4161 | my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr"; | |
4162 | ||
4163 | qemu_deviceadd($vmid, $devicefull); | |
4164 | qemu_deviceaddverify($vmid, $deviceid); | |
4165 | } else { | |
4166 | die "can't hotplug device '$deviceid'\n"; | |
4167 | } | |
4168 | ||
4169 | return 1; | |
4170 | } | |
4171 | ||
4172 | # fixme: this should raise exceptions on error! | |
4173 | sub vm_deviceunplug { | |
4174 | my ($vmid, $conf, $deviceid) = @_; | |
4175 | ||
4176 | my $devices_list = vm_devices_list($vmid); | |
4177 | return 1 if !defined($devices_list->{$deviceid}); | |
4178 | ||
4179 | my $bootdisks = PVE::QemuServer::Drive::get_bootdisks($conf); | |
4180 | die "can't unplug bootdisk '$deviceid'\n" if grep {$_ eq $deviceid} @$bootdisks; | |
4181 | ||
4182 | if ($deviceid eq 'tablet' || $deviceid eq 'keyboard') { | |
4183 | qemu_devicedel($vmid, $deviceid); | |
4184 | } elsif ($deviceid =~ m/^usb\d+$/) { | |
4185 | die "usb hotplug currently not reliable\n"; | |
4186 | # when unplugging usb devices this way, there may be remaining usb | |
4187 | # controllers/hubs so we disable it for now | |
4188 | #qemu_devicedel($vmid, $deviceid); | |
4189 | #qemu_devicedelverify($vmid, $deviceid); | |
4190 | } elsif ($deviceid =~ m/^(virtio)(\d+)$/) { | |
4191 | my $device = parse_drive($deviceid, $conf->{$deviceid}); | |
4192 | ||
4193 | qemu_devicedel($vmid, $deviceid); | |
4194 | qemu_devicedelverify($vmid, $deviceid); | |
4195 | qemu_drivedel($vmid, $deviceid); | |
4196 | qemu_iothread_del($vmid, $deviceid, $device); | |
4197 | } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) { | |
4198 | qemu_devicedel($vmid, $deviceid); | |
4199 | qemu_devicedelverify($vmid, $deviceid); | |
4200 | } elsif ($deviceid =~ m/^(scsi)(\d+)$/) { | |
4201 | my $device = parse_drive($deviceid, $conf->{$deviceid}); | |
4202 | ||
4203 | qemu_devicedel($vmid, $deviceid); | |
4204 | qemu_drivedel($vmid, $deviceid); | |
4205 | qemu_deletescsihw($conf, $vmid, $deviceid); | |
4206 | ||
4207 | qemu_iothread_del($vmid, "virtioscsi$device->{index}", $device) | |
4208 | if $conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single'); | |
4209 | } elsif ($deviceid =~ m/^(net)(\d+)$/) { | |
4210 | qemu_devicedel($vmid, $deviceid); | |
4211 | qemu_devicedelverify($vmid, $deviceid); | |
4212 | qemu_netdevdel($vmid, $deviceid); | |
4213 | } else { | |
4214 | die "can't unplug device '$deviceid'\n"; | |
4215 | } | |
4216 | ||
4217 | return 1; | |
4218 | } | |
4219 | ||
4220 | sub qemu_deviceadd { | |
4221 | my ($vmid, $devicefull) = @_; | |
4222 | ||
4223 | $devicefull = "driver=".$devicefull; | |
4224 | my %options = split(/[=,]/, $devicefull); | |
4225 | ||
4226 | mon_cmd($vmid, "device_add" , %options); | |
4227 | } | |
4228 | ||
4229 | sub qemu_devicedel { | |
4230 | my ($vmid, $deviceid) = @_; | |
4231 | ||
4232 | my $ret = mon_cmd($vmid, "device_del", id => $deviceid); | |
4233 | } | |
4234 | ||
4235 | sub qemu_iothread_add { | |
4236 | my ($vmid, $deviceid, $device) = @_; | |
4237 | ||
4238 | if ($device->{iothread}) { | |
4239 | my $iothreads = vm_iothreads_list($vmid); | |
4240 | qemu_objectadd($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"}; | |
4241 | } | |
4242 | } | |
4243 | ||
4244 | sub qemu_iothread_del { | |
4245 | my ($vmid, $deviceid, $device) = @_; | |
4246 | ||
4247 | if ($device->{iothread}) { | |
4248 | my $iothreads = vm_iothreads_list($vmid); | |
4249 | qemu_objectdel($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"}; | |
4250 | } | |
4251 | } | |
4252 | ||
4253 | sub qemu_objectadd { | |
4254 | my ($vmid, $objectid, $qomtype) = @_; | |
4255 | ||
4256 | mon_cmd($vmid, "object-add", id => $objectid, "qom-type" => $qomtype); | |
4257 | ||
4258 | return 1; | |
4259 | } | |
4260 | ||
4261 | sub qemu_objectdel { | |
4262 | my ($vmid, $objectid) = @_; | |
4263 | ||
4264 | mon_cmd($vmid, "object-del", id => $objectid); | |
4265 | ||
4266 | return 1; | |
4267 | } | |
4268 | ||
4269 | sub qemu_driveadd { | |
4270 | my ($storecfg, $vmid, $device) = @_; | |
4271 | ||
4272 | my $kvmver = get_running_qemu_version($vmid); | |
4273 | my $io_uring = min_version($kvmver, 6, 0); | |
4274 | my $drive = print_drive_commandline_full($storecfg, $vmid, $device, undef, $io_uring); | |
4275 | $drive =~ s/\\/\\\\/g; | |
4276 | my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_add auto \"$drive\""); | |
4277 | ||
4278 | # If the command succeeds qemu prints: "OK" | |
4279 | return 1 if $ret =~ m/OK/s; | |
4280 | ||
4281 | die "adding drive failed: $ret\n"; | |
4282 | } | |
4283 | ||
4284 | sub qemu_drivedel { | |
4285 | my ($vmid, $deviceid) = @_; | |
4286 | ||
4287 | my $ret = PVE::QemuServer::Monitor::hmp_cmd($vmid, "drive_del drive-$deviceid"); | |
4288 | $ret =~ s/^\s+//; | |
4289 | ||
4290 | return 1 if $ret eq ""; | |
4291 | ||
4292 | # NB: device not found errors mean the drive was auto-deleted and we ignore the error | |
4293 | return 1 if $ret =~ m/Device \'.*?\' not found/s; | |
4294 | ||
4295 | die "deleting drive $deviceid failed : $ret\n"; | |
4296 | } | |
4297 | ||
4298 | sub qemu_deviceaddverify { | |
4299 | my ($vmid, $deviceid) = @_; | |
4300 | ||
4301 | for (my $i = 0; $i <= 5; $i++) { | |
4302 | my $devices_list = vm_devices_list($vmid); | |
4303 | return 1 if defined($devices_list->{$deviceid}); | |
4304 | sleep 1; | |
4305 | } | |
4306 | ||
4307 | die "error on hotplug device '$deviceid'\n"; | |
4308 | } | |
4309 | ||
4310 | ||
4311 | sub qemu_devicedelverify { | |
4312 | my ($vmid, $deviceid) = @_; | |
4313 | ||
4314 | # need to verify that the device is correctly removed as device_del | |
4315 | # is async and empty return is not reliable | |
4316 | ||
4317 | for (my $i = 0; $i <= 5; $i++) { | |
4318 | my $devices_list = vm_devices_list($vmid); | |
4319 | return 1 if !defined($devices_list->{$deviceid}); | |
4320 | sleep 1; | |
4321 | } | |
4322 | ||
4323 | die "error on hot-unplugging device '$deviceid'\n"; | |
4324 | } | |
4325 | ||
4326 | sub qemu_findorcreatescsihw { | |
4327 | my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_; | |
4328 | ||
4329 | my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device); | |
4330 | ||
4331 | my $scsihwid="$controller_prefix$controller"; | |
4332 | my $devices_list = vm_devices_list($vmid); | |
4333 | ||
4334 | if (!defined($devices_list->{$scsihwid})) { | |
4335 | vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device, $arch, $machine_type); | |
4336 | } | |
4337 | ||
4338 | return 1; | |
4339 | } | |
4340 | ||
4341 | sub qemu_deletescsihw { | |
4342 | my ($conf, $vmid, $opt) = @_; | |
4343 | ||
4344 | my $device = parse_drive($opt, $conf->{$opt}); | |
4345 | ||
4346 | if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) { | |
4347 | vm_deviceunplug($vmid, $conf, "virtioscsi$device->{index}"); | |
4348 | return 1; | |
4349 | } | |
4350 | ||
4351 | my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device); | |
4352 | ||
4353 | my $devices_list = vm_devices_list($vmid); | |
4354 | foreach my $opt (keys %{$devices_list}) { | |
4355 | if (is_valid_drivename($opt)) { | |
4356 | my $drive = parse_drive($opt, $conf->{$opt}); | |
4357 | if ($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) { | |
4358 | return 1; | |
4359 | } | |
4360 | } | |
4361 | } | |
4362 | ||
4363 | my $scsihwid="scsihw$controller"; | |
4364 | ||
4365 | vm_deviceunplug($vmid, $conf, $scsihwid); | |
4366 | ||
4367 | return 1; | |
4368 | } | |
4369 | ||
4370 | sub qemu_add_pci_bridge { | |
4371 | my ($storecfg, $conf, $vmid, $device, $arch, $machine_type) = @_; | |
4372 | ||
4373 | my $bridges = {}; | |
4374 | ||
4375 | my $bridgeid; | |
4376 | ||
4377 | print_pci_addr($device, $bridges, $arch, $machine_type); | |
4378 | ||
4379 | while (my ($k, $v) = each %$bridges) { | |
4380 | $bridgeid = $k; | |
4381 | } | |
4382 | return 1 if !defined($bridgeid) || $bridgeid < 1; | |
4383 | ||
4384 | my $bridge = "pci.$bridgeid"; | |
4385 | my $devices_list = vm_devices_list($vmid); | |
4386 | ||
4387 | if (!defined($devices_list->{$bridge})) { | |
4388 | vm_deviceplug($storecfg, $conf, $vmid, $bridge, $arch, $machine_type); | |
4389 | } | |
4390 | ||
4391 | return 1; | |
4392 | } | |
4393 | ||
4394 | sub qemu_set_link_status { | |
4395 | my ($vmid, $device, $up) = @_; | |
4396 | ||
4397 | mon_cmd($vmid, "set_link", name => $device, | |
4398 | up => $up ? JSON::true : JSON::false); | |
4399 | } | |
4400 | ||
4401 | sub qemu_netdevadd { | |
4402 | my ($vmid, $conf, $arch, $device, $deviceid) = @_; | |
4403 | ||
4404 | my $netdev = print_netdev_full($vmid, $conf, $arch, $device, $deviceid, 1); | |
4405 | my %options = split(/[=,]/, $netdev); | |
4406 | ||
4407 | if (defined(my $vhost = $options{vhost})) { | |
4408 | $options{vhost} = JSON::boolean(PVE::JSONSchema::parse_boolean($vhost)); | |
4409 | } | |
4410 | ||
4411 | if (defined(my $queues = $options{queues})) { | |
4412 | $options{queues} = $queues + 0; | |
4413 | } | |
4414 | ||
4415 | mon_cmd($vmid, "netdev_add", %options); | |
4416 | return 1; | |
4417 | } | |
4418 | ||
4419 | sub qemu_netdevdel { | |
4420 | my ($vmid, $deviceid) = @_; | |
4421 | ||
4422 | mon_cmd($vmid, "netdev_del", id => $deviceid); | |
4423 | } | |
4424 | ||
4425 | sub qemu_usb_hotplug { | |
4426 | my ($storecfg, $conf, $vmid, $deviceid, $device, $arch, $machine_type) = @_; | |
4427 | ||
4428 | return if !$device; | |
4429 | ||
4430 | # remove the old one first | |
4431 | vm_deviceunplug($vmid, $conf, $deviceid); | |
4432 | ||
4433 | # check if xhci controller is necessary and available | |
4434 | if ($device->{usb3}) { | |
4435 | ||
4436 | my $devicelist = vm_devices_list($vmid); | |
4437 | ||
4438 | if (!$devicelist->{xhci}) { | |
4439 | my $pciaddr = print_pci_addr("xhci", undef, $arch, $machine_type); | |
4440 | qemu_deviceadd($vmid, "nec-usb-xhci,id=xhci$pciaddr"); | |
4441 | } | |
4442 | } | |
4443 | my $d = parse_usb_device($device->{host}); | |
4444 | $d->{usb3} = $device->{usb3}; | |
4445 | ||
4446 | # add the new one | |
4447 | vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $d, $arch, $machine_type); | |
4448 | } | |
4449 | ||
4450 | sub qemu_cpu_hotplug { | |
4451 | my ($vmid, $conf, $vcpus) = @_; | |
4452 | ||
4453 | my $machine_type = PVE::QemuServer::Machine::get_current_qemu_machine($vmid); | |
4454 | ||
4455 | my $sockets = 1; | |
4456 | $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused | |
4457 | $sockets = $conf->{sockets} if $conf->{sockets}; | |
4458 | my $cores = $conf->{cores} || 1; | |
4459 | my $maxcpus = $sockets * $cores; | |
4460 | ||
4461 | $vcpus = $maxcpus if !$vcpus; | |
4462 | ||
4463 | die "you can't add more vcpus than maxcpus\n" | |
4464 | if $vcpus > $maxcpus; | |
4465 | ||
4466 | my $currentvcpus = $conf->{vcpus} || $maxcpus; | |
4467 | ||
4468 | if ($vcpus < $currentvcpus) { | |
4469 | ||
4470 | if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) { | |
4471 | ||
4472 | for (my $i = $currentvcpus; $i > $vcpus; $i--) { | |
4473 | qemu_devicedel($vmid, "cpu$i"); | |
4474 | my $retry = 0; | |
4475 | my $currentrunningvcpus = undef; | |
4476 | while (1) { | |
4477 | $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast"); | |
4478 | last if scalar(@{$currentrunningvcpus}) == $i-1; | |
4479 | raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5; | |
4480 | $retry++; | |
4481 | sleep 1; | |
4482 | } | |
4483 | #update conf after each succesfull cpu unplug | |
4484 | $conf->{vcpus} = scalar(@{$currentrunningvcpus}); | |
4485 | PVE::QemuConfig->write_config($vmid, $conf); | |
4486 | } | |
4487 | } else { | |
4488 | die "cpu hot-unplugging requires qemu version 2.7 or higher\n"; | |
4489 | } | |
4490 | ||
4491 | return; | |
4492 | } | |
4493 | ||
4494 | my $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast"); | |
4495 | die "vcpus in running vm does not match its configuration\n" | |
4496 | if scalar(@{$currentrunningvcpus}) != $currentvcpus; | |
4497 | ||
4498 | if (PVE::QemuServer::Machine::machine_version($machine_type, 2, 7)) { | |
4499 | ||
4500 | for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) { | |
4501 | my $cpustr = print_cpu_device($conf, $i); | |
4502 | qemu_deviceadd($vmid, $cpustr); | |
4503 | ||
4504 | my $retry = 0; | |
4505 | my $currentrunningvcpus = undef; | |
4506 | while (1) { | |
4507 | $currentrunningvcpus = mon_cmd($vmid, "query-cpus-fast"); | |
4508 | last if scalar(@{$currentrunningvcpus}) == $i; | |
4509 | raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10; | |
4510 | sleep 1; | |
4511 | $retry++; | |
4512 | } | |
4513 | #update conf after each succesfull cpu hotplug | |
4514 | $conf->{vcpus} = scalar(@{$currentrunningvcpus}); | |
4515 | PVE::QemuConfig->write_config($vmid, $conf); | |
4516 | } | |
4517 | } else { | |
4518 | ||
4519 | for (my $i = $currentvcpus; $i < $vcpus; $i++) { | |
4520 | mon_cmd($vmid, "cpu-add", id => int($i)); | |
4521 | } | |
4522 | } | |
4523 | } | |
4524 | ||
4525 | sub qemu_block_set_io_throttle { | |
4526 | my ($vmid, $deviceid, | |
4527 | $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr, | |
4528 | $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max, | |
4529 | $bps_max_length, $bps_rd_max_length, $bps_wr_max_length, | |
4530 | $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_; | |
4531 | ||
4532 | return if !check_running($vmid) ; | |
4533 | ||
4534 | mon_cmd($vmid, "block_set_io_throttle", device => $deviceid, | |
4535 | bps => int($bps), | |
4536 | bps_rd => int($bps_rd), | |
4537 | bps_wr => int($bps_wr), | |
4538 | iops => int($iops), | |
4539 | iops_rd => int($iops_rd), | |
4540 | iops_wr => int($iops_wr), | |
4541 | bps_max => int($bps_max), | |
4542 | bps_rd_max => int($bps_rd_max), | |
4543 | bps_wr_max => int($bps_wr_max), | |
4544 | iops_max => int($iops_max), | |
4545 | iops_rd_max => int($iops_rd_max), | |
4546 | iops_wr_max => int($iops_wr_max), | |
4547 | bps_max_length => int($bps_max_length), | |
4548 | bps_rd_max_length => int($bps_rd_max_length), | |
4549 | bps_wr_max_length => int($bps_wr_max_length), | |
4550 | iops_max_length => int($iops_max_length), | |
4551 | iops_rd_max_length => int($iops_rd_max_length), | |
4552 | iops_wr_max_length => int($iops_wr_max_length), | |
4553 | ); | |
4554 | ||
4555 | } | |
4556 | ||
4557 | sub qemu_block_resize { | |
4558 | my ($vmid, $deviceid, $storecfg, $volid, $size) = @_; | |
4559 | ||
4560 | my $running = check_running($vmid); | |
4561 | ||
4562 | $size = 0 if !PVE::Storage::volume_resize($storecfg, $volid, $size, $running); | |
4563 | ||
4564 | return if !$running; | |
4565 | ||
4566 | my $padding = (1024 - $size % 1024) % 1024; | |
4567 | $size = $size + $padding; | |
4568 | ||
4569 | mon_cmd( | |
4570 | $vmid, | |
4571 | "block_resize", | |
4572 | device => $deviceid, | |
4573 | size => int($size), | |
4574 | timeout => 60, | |
4575 | ); | |
4576 | } | |
4577 | ||
4578 | sub qemu_volume_snapshot { | |
4579 | my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_; | |
4580 | ||
4581 | my $running = check_running($vmid); | |
4582 | ||
4583 | if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) { | |
4584 | mon_cmd($vmid, 'blockdev-snapshot-internal-sync', device => $deviceid, name => $snap); | |
4585 | } else { | |
4586 | PVE::Storage::volume_snapshot($storecfg, $volid, $snap); | |
4587 | } | |
4588 | } | |
4589 | ||
4590 | sub qemu_volume_snapshot_delete { | |
4591 | my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_; | |
4592 | ||
4593 | my $running = check_running($vmid); | |
4594 | ||
4595 | if($running) { | |
4596 | ||
4597 | $running = undef; | |
4598 | my $conf = PVE::QemuConfig->load_config($vmid); | |
4599 | PVE::QemuConfig->foreach_volume($conf, sub { | |
4600 | my ($ds, $drive) = @_; | |
4601 | $running = 1 if $drive->{file} eq $volid; | |
4602 | }); | |
4603 | } | |
4604 | ||
4605 | if ($running && do_snapshots_with_qemu($storecfg, $volid, $deviceid)) { | |
4606 | mon_cmd($vmid, 'blockdev-snapshot-delete-internal-sync', device => $deviceid, name => $snap); | |
4607 | } else { | |
4608 | PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running); | |
4609 | } | |
4610 | } | |
4611 | ||
4612 | sub set_migration_caps { | |
4613 | my ($vmid, $savevm) = @_; | |
4614 | ||
4615 | my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") }; | |
4616 | ||
4617 | my $bitmap_prop = $savevm ? 'pbs-dirty-bitmap-savevm' : 'pbs-dirty-bitmap-migration'; | |
4618 | my $dirty_bitmaps = $qemu_support->{$bitmap_prop} ? 1 : 0; | |
4619 | ||
4620 | my $cap_ref = []; | |
4621 | ||
4622 | my $enabled_cap = { | |
4623 | "auto-converge" => 1, | |
4624 | "xbzrle" => 1, | |
4625 | "x-rdma-pin-all" => 0, | |
4626 | "zero-blocks" => 0, | |
4627 | "compress" => 0, | |
4628 | "dirty-bitmaps" => $dirty_bitmaps, | |
4629 | }; | |
4630 | ||
4631 | my $supported_capabilities = mon_cmd($vmid, "query-migrate-capabilities"); | |
4632 | ||
4633 | for my $supported_capability (@$supported_capabilities) { | |
4634 | push @$cap_ref, { | |
4635 | capability => $supported_capability->{capability}, | |
4636 | state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false, | |
4637 | }; | |
4638 | } | |
4639 | ||
4640 | mon_cmd($vmid, "migrate-set-capabilities", capabilities => $cap_ref); | |
4641 | } | |
4642 | ||
4643 | sub foreach_volid { | |
4644 | my ($conf, $func, @param) = @_; | |
4645 | ||
4646 | my $volhash = {}; | |
4647 | ||
4648 | my $test_volid = sub { | |
4649 | my ($key, $drive, $snapname) = @_; | |
4650 | ||
4651 | my $volid = $drive->{file}; | |
4652 | return if !$volid; | |
4653 | ||
4654 | $volhash->{$volid}->{cdrom} //= 1; | |
4655 | $volhash->{$volid}->{cdrom} = 0 if !drive_is_cdrom($drive); | |
4656 | ||
4657 | my $replicate = $drive->{replicate} // 1; | |
4658 | $volhash->{$volid}->{replicate} //= 0; | |
4659 | $volhash->{$volid}->{replicate} = 1 if $replicate; | |
4660 | ||
4661 | $volhash->{$volid}->{shared} //= 0; | |
4662 | $volhash->{$volid}->{shared} = 1 if $drive->{shared}; | |
4663 | ||
4664 | $volhash->{$volid}->{referenced_in_config} //= 0; | |
4665 | $volhash->{$volid}->{referenced_in_config} = 1 if !defined($snapname); | |
4666 | ||
4667 | $volhash->{$volid}->{referenced_in_snapshot}->{$snapname} = 1 | |
4668 | if defined($snapname); | |
4669 | ||
4670 | my $size = $drive->{size}; | |
4671 | $volhash->{$volid}->{size} //= $size if $size; | |
4672 | ||
4673 | $volhash->{$volid}->{is_vmstate} //= 0; | |
4674 | $volhash->{$volid}->{is_vmstate} = 1 if $key eq 'vmstate'; | |
4675 | ||
4676 | $volhash->{$volid}->{is_tpmstate} //= 0; | |
4677 | $volhash->{$volid}->{is_tpmstate} = 1 if $key eq 'tpmstate0'; | |
4678 | ||
4679 | $volhash->{$volid}->{is_unused} //= 0; | |
4680 | $volhash->{$volid}->{is_unused} = 1 if $key =~ /^unused\d+$/; | |
4681 | ||
4682 | $volhash->{$volid}->{drivename} = $key if is_valid_drivename($key); | |
4683 | }; | |
4684 | ||
4685 | my $include_opts = { | |
4686 | extra_keys => ['vmstate'], | |
4687 | include_unused => 1, | |
4688 | }; | |
4689 | ||
4690 | PVE::QemuConfig->foreach_volume_full($conf, $include_opts, $test_volid); | |
4691 | foreach my $snapname (keys %{$conf->{snapshots}}) { | |
4692 | my $snap = $conf->{snapshots}->{$snapname}; | |
4693 | PVE::QemuConfig->foreach_volume_full($snap, $include_opts, $test_volid, $snapname); | |
4694 | } | |
4695 | ||
4696 | foreach my $volid (keys %$volhash) { | |
4697 | &$func($volid, $volhash->{$volid}, @param); | |
4698 | } | |
4699 | } | |
4700 | ||
4701 | my $fast_plug_option = { | |
4702 | 'lock' => 1, | |
4703 | 'name' => 1, | |
4704 | 'onboot' => 1, | |
4705 | 'shares' => 1, | |
4706 | 'startup' => 1, | |
4707 | 'description' => 1, | |
4708 | 'protection' => 1, | |
4709 | 'vmstatestorage' => 1, | |
4710 | 'hookscript' => 1, | |
4711 | 'tags' => 1, | |
4712 | }; | |
4713 | ||
4714 | # hotplug changes in [PENDING] | |
4715 | # $selection hash can be used to only apply specified options, for | |
4716 | # example: { cores => 1 } (only apply changed 'cores') | |
4717 | # $errors ref is used to return error messages | |
4718 | sub vmconfig_hotplug_pending { | |
4719 | my ($vmid, $conf, $storecfg, $selection, $errors) = @_; | |
4720 | ||
4721 | my $defaults = load_defaults(); | |
4722 | my $arch = get_vm_arch($conf); | |
4723 | my $machine_type = get_vm_machine($conf, undef, $arch); | |
4724 | ||
4725 | # commit values which do not have any impact on running VM first | |
4726 | # Note: those option cannot raise errors, we we do not care about | |
4727 | # $selection and always apply them. | |
4728 | ||
4729 | my $add_error = sub { | |
4730 | my ($opt, $msg) = @_; | |
4731 | $errors->{$opt} = "hotplug problem - $msg"; | |
4732 | }; | |
4733 | ||
4734 | my $changes = 0; | |
4735 | foreach my $opt (keys %{$conf->{pending}}) { # add/change | |
4736 | if ($fast_plug_option->{$opt}) { | |
4737 | $conf->{$opt} = $conf->{pending}->{$opt}; | |
4738 | delete $conf->{pending}->{$opt}; | |
4739 | $changes = 1; | |
4740 | } | |
4741 | } | |
4742 | ||
4743 | if ($changes) { | |
4744 | PVE::QemuConfig->write_config($vmid, $conf); | |
4745 | } | |
4746 | ||
4747 | my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1'); | |
4748 | ||
4749 | my $cgroup = PVE::QemuServer::CGroup->new($vmid); | |
4750 | my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete}); | |
4751 | foreach my $opt (sort keys %$pending_delete_hash) { | |
4752 | next if $selection && !$selection->{$opt}; | |
4753 | my $force = $pending_delete_hash->{$opt}->{force}; | |
4754 | eval { | |
4755 | if ($opt eq 'hotplug') { | |
4756 | die "skip\n" if ($conf->{hotplug} =~ /memory/); | |
4757 | } elsif ($opt eq 'tablet') { | |
4758 | die "skip\n" if !$hotplug_features->{usb}; | |
4759 | if ($defaults->{tablet}) { | |
4760 | vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type); | |
4761 | vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type) | |
4762 | if $arch eq 'aarch64'; | |
4763 | } else { | |
4764 | vm_deviceunplug($vmid, $conf, 'tablet'); | |
4765 | vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64'; | |
4766 | } | |
4767 | } elsif ($opt =~ m/^usb\d+/) { | |
4768 | die "skip\n"; | |
4769 | # since we cannot reliably hot unplug usb devices we are disabling it | |
4770 | #die "skip\n" if !$hotplug_features->{usb} || $conf->{$opt} =~ m/spice/i; | |
4771 | #vm_deviceunplug($vmid, $conf, $opt); | |
4772 | } elsif ($opt eq 'vcpus') { | |
4773 | die "skip\n" if !$hotplug_features->{cpu}; | |
4774 | qemu_cpu_hotplug($vmid, $conf, undef); | |
4775 | } elsif ($opt eq 'balloon') { | |
4776 | # enable balloon device is not hotpluggable | |
4777 | die "skip\n" if defined($conf->{balloon}) && $conf->{balloon} == 0; | |
4778 | # here we reset the ballooning value to memory | |
4779 | my $balloon = $conf->{memory} || $defaults->{memory}; | |
4780 | mon_cmd($vmid, "balloon", value => $balloon*1024*1024); | |
4781 | } elsif ($fast_plug_option->{$opt}) { | |
4782 | # do nothing | |
4783 | } elsif ($opt =~ m/^net(\d+)$/) { | |
4784 | die "skip\n" if !$hotplug_features->{network}; | |
4785 | vm_deviceunplug($vmid, $conf, $opt); | |
4786 | } elsif (is_valid_drivename($opt)) { | |
4787 | die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/; | |
4788 | vm_deviceunplug($vmid, $conf, $opt); | |
4789 | vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force); | |
4790 | } elsif ($opt =~ m/^memory$/) { | |
4791 | die "skip\n" if !$hotplug_features->{memory}; | |
4792 | PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt); | |
4793 | } elsif ($opt eq 'cpuunits') { | |
4794 | $cgroup->change_cpu_shares(undef, 1024); | |
4795 | } elsif ($opt eq 'cpulimit') { | |
4796 | $cgroup->change_cpu_quota(undef, undef); # reset, cgroup module can better decide values | |
4797 | } else { | |
4798 | die "skip\n"; | |
4799 | } | |
4800 | }; | |
4801 | if (my $err = $@) { | |
4802 | &$add_error($opt, $err) if $err ne "skip\n"; | |
4803 | } else { | |
4804 | delete $conf->{$opt}; | |
4805 | PVE::QemuConfig->remove_from_pending_delete($conf, $opt); | |
4806 | } | |
4807 | } | |
4808 | ||
4809 | my ($apply_pending_cloudinit, $apply_pending_cloudinit_done); | |
4810 | $apply_pending_cloudinit = sub { | |
4811 | return if $apply_pending_cloudinit_done; # once is enough | |
4812 | $apply_pending_cloudinit_done = 1; # once is enough | |
4813 | ||
4814 | my ($key, $value) = @_; | |
4815 | ||
4816 | my @cloudinit_opts = keys %$confdesc_cloudinit; | |
4817 | foreach my $opt (keys %{$conf->{pending}}) { | |
4818 | next if !grep { $_ eq $opt } @cloudinit_opts; | |
4819 | $conf->{$opt} = delete $conf->{pending}->{$opt}; | |
4820 | } | |
4821 | ||
4822 | my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete}); | |
4823 | foreach my $opt (sort keys %$pending_delete_hash) { | |
4824 | next if !grep { $_ eq $opt } @cloudinit_opts; | |
4825 | PVE::QemuConfig->remove_from_pending_delete($conf, $opt); | |
4826 | delete $conf->{$opt}; | |
4827 | } | |
4828 | ||
4829 | my $new_conf = { %$conf }; | |
4830 | $new_conf->{$key} = $value; | |
4831 | PVE::QemuServer::Cloudinit::generate_cloudinitconfig($new_conf, $vmid); | |
4832 | }; | |
4833 | ||
4834 | foreach my $opt (keys %{$conf->{pending}}) { | |
4835 | next if $selection && !$selection->{$opt}; | |
4836 | my $value = $conf->{pending}->{$opt}; | |
4837 | eval { | |
4838 | if ($opt eq 'hotplug') { | |
4839 | die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/); | |
4840 | } elsif ($opt eq 'tablet') { | |
4841 | die "skip\n" if !$hotplug_features->{usb}; | |
4842 | if ($value == 1) { | |
4843 | vm_deviceplug($storecfg, $conf, $vmid, 'tablet', $arch, $machine_type); | |
4844 | vm_deviceplug($storecfg, $conf, $vmid, 'keyboard', $arch, $machine_type) | |
4845 | if $arch eq 'aarch64'; | |
4846 | } elsif ($value == 0) { | |
4847 | vm_deviceunplug($vmid, $conf, 'tablet'); | |
4848 | vm_deviceunplug($vmid, $conf, 'keyboard') if $arch eq 'aarch64'; | |
4849 | } | |
4850 | } elsif ($opt =~ m/^usb\d+$/) { | |
4851 | die "skip\n"; | |
4852 | # since we cannot reliably hot unplug usb devices we disable it for now | |
4853 | #die "skip\n" if !$hotplug_features->{usb} || $value =~ m/spice/i; | |
4854 | #my $d = eval { parse_property_string($usbdesc->{format}, $value) }; | |
4855 | #die "skip\n" if !$d; | |
4856 | #qemu_usb_hotplug($storecfg, $conf, $vmid, $opt, $d, $arch, $machine_type); | |
4857 | } elsif ($opt eq 'vcpus') { | |
4858 | die "skip\n" if !$hotplug_features->{cpu}; | |
4859 | qemu_cpu_hotplug($vmid, $conf, $value); | |
4860 | } elsif ($opt eq 'balloon') { | |
4861 | # enable/disable balloning device is not hotpluggable | |
4862 | my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon}); | |
4863 | my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon}); | |
4864 | die "skip\n" if $old_balloon_enabled != $new_balloon_enabled; | |
4865 | ||
4866 | # allow manual ballooning if shares is set to zero | |
4867 | if ((defined($conf->{shares}) && ($conf->{shares} == 0))) { | |
4868 | my $balloon = $conf->{pending}->{balloon} || $conf->{memory} || $defaults->{memory}; | |
4869 | mon_cmd($vmid, "balloon", value => $balloon*1024*1024); | |
4870 | } | |
4871 | } elsif ($opt =~ m/^net(\d+)$/) { | |
4872 | # some changes can be done without hotplug | |
4873 | vmconfig_update_net($storecfg, $conf, $hotplug_features->{network}, | |
4874 | $vmid, $opt, $value, $arch, $machine_type); | |
4875 | } elsif (is_valid_drivename($opt)) { | |
4876 | die "skip\n" if $opt eq 'efidisk0' || $opt eq 'tpmstate0'; | |
4877 | # some changes can be done without hotplug | |
4878 | my $drive = parse_drive($opt, $value); | |
4879 | if (drive_is_cloudinit($drive)) { | |
4880 | &$apply_pending_cloudinit($opt, $value); | |
4881 | } | |
4882 | vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk}, | |
4883 | $vmid, $opt, $value, $arch, $machine_type); | |
4884 | } elsif ($opt =~ m/^memory$/) { #dimms | |
4885 | die "skip\n" if !$hotplug_features->{memory}; | |
4886 | $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt, $value); | |
4887 | } elsif ($opt eq 'cpuunits') { | |
4888 | $cgroup->change_cpu_shares($conf->{pending}->{$opt}, 1024); | |
4889 | } elsif ($opt eq 'cpulimit') { | |
4890 | my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000); | |
4891 | $cgroup->change_cpu_quota($cpulimit, 100000); | |
4892 | } elsif ($opt eq 'agent') { | |
4893 | vmconfig_update_agent($conf, $opt, $value); | |
4894 | } else { | |
4895 | die "skip\n"; # skip non-hot-pluggable options | |
4896 | } | |
4897 | }; | |
4898 | if (my $err = $@) { | |
4899 | &$add_error($opt, $err) if $err ne "skip\n"; | |
4900 | } else { | |
4901 | $conf->{$opt} = $value; | |
4902 | delete $conf->{pending}->{$opt}; | |
4903 | } | |
4904 | } | |
4905 | ||
4906 | PVE::QemuConfig->write_config($vmid, $conf); | |
4907 | } | |
4908 | ||
4909 | sub try_deallocate_drive { | |
4910 | my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_; | |
4911 | ||
4912 | if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) { | |
4913 | my $volid = $drive->{file}; | |
4914 | if (vm_is_volid_owner($storecfg, $vmid, $volid)) { | |
4915 | my $sid = PVE::Storage::parse_volume_id($volid); | |
4916 | $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']); | |
4917 | ||
4918 | # check if the disk is really unused | |
4919 | die "unable to delete '$volid' - volume is still in use (snapshot?)\n" | |
4920 | if PVE::QemuServer::Drive::is_volume_in_use($storecfg, $conf, $key, $volid); | |
4921 | PVE::Storage::vdisk_free($storecfg, $volid); | |
4922 | return 1; | |
4923 | } else { | |
4924 | # If vm is not owner of this disk remove from config | |
4925 | return 1; | |
4926 | } | |
4927 | } | |
4928 | ||
4929 | return; | |
4930 | } | |
4931 | ||
4932 | sub vmconfig_delete_or_detach_drive { | |
4933 | my ($vmid, $storecfg, $conf, $opt, $force) = @_; | |
4934 | ||
4935 | my $drive = parse_drive($opt, $conf->{$opt}); | |
4936 | ||
4937 | my $rpcenv = PVE::RPCEnvironment::get(); | |
4938 | my $authuser = $rpcenv->get_user(); | |
4939 | ||
4940 | if ($force) { | |
4941 | $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM.Config.Disk']); | |
4942 | try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force); | |
4943 | } else { | |
4944 | vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive); | |
4945 | } | |
4946 | } | |
4947 | ||
4948 | ||
4949 | ||
4950 | sub vmconfig_apply_pending { | |
4951 | my ($vmid, $conf, $storecfg, $errors) = @_; | |
4952 | ||
4953 | my $add_apply_error = sub { | |
4954 | my ($opt, $msg) = @_; | |
4955 | my $err_msg = "unable to apply pending change $opt : $msg"; | |
4956 | $errors->{$opt} = $err_msg; | |
4957 | warn $err_msg; | |
4958 | }; | |
4959 | ||
4960 | # cold plug | |
4961 | ||
4962 | my $pending_delete_hash = PVE::QemuConfig->parse_pending_delete($conf->{pending}->{delete}); | |
4963 | foreach my $opt (sort keys %$pending_delete_hash) { | |
4964 | my $force = $pending_delete_hash->{$opt}->{force}; | |
4965 | eval { | |
4966 | if ($opt =~ m/^unused/) { | |
4967 | die "internal error"; | |
4968 | } elsif (defined($conf->{$opt}) && is_valid_drivename($opt)) { | |
4969 | vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force); | |
4970 | } | |
4971 | }; | |
4972 | if (my $err = $@) { | |
4973 | $add_apply_error->($opt, $err); | |
4974 | } else { | |
4975 | PVE::QemuConfig->remove_from_pending_delete($conf, $opt); | |
4976 | delete $conf->{$opt}; | |
4977 | } | |
4978 | } | |
4979 | ||
4980 | PVE::QemuConfig->cleanup_pending($conf); | |
4981 | ||
4982 | foreach my $opt (keys %{$conf->{pending}}) { # add/change | |
4983 | next if $opt eq 'delete'; # just to be sure | |
4984 | eval { | |
4985 | if (defined($conf->{$opt}) && is_valid_drivename($opt)) { | |
4986 | vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt})) | |
4987 | } | |
4988 | }; | |
4989 | if (my $err = $@) { | |
4990 | $add_apply_error->($opt, $err); | |
4991 | } else { | |
4992 | $conf->{$opt} = delete $conf->{pending}->{$opt}; | |
4993 | } | |
4994 | } | |
4995 | ||
4996 | # write all changes at once to avoid unnecessary i/o | |
4997 | PVE::QemuConfig->write_config($vmid, $conf); | |
4998 | } | |
4999 | ||
5000 | sub vmconfig_update_net { | |
5001 | my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_; | |
5002 | ||
5003 | my $newnet = parse_net($value); | |
5004 | ||
5005 | if ($conf->{$opt}) { | |
5006 | my $oldnet = parse_net($conf->{$opt}); | |
5007 | ||
5008 | if (safe_string_ne($oldnet->{model}, $newnet->{model}) || | |
5009 | safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) || | |
5010 | safe_num_ne($oldnet->{queues}, $newnet->{queues}) || | |
5011 | !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change | |
5012 | ||
5013 | # for non online change, we try to hot-unplug | |
5014 | die "skip\n" if !$hotplug; | |
5015 | vm_deviceunplug($vmid, $conf, $opt); | |
5016 | } else { | |
5017 | ||
5018 | die "internal error" if $opt !~ m/net(\d+)/; | |
5019 | my $iface = "tap${vmid}i$1"; | |
5020 | ||
5021 | if (safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) || | |
5022 | safe_num_ne($oldnet->{tag}, $newnet->{tag}) || | |
5023 | safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) || | |
5024 | safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) { | |
5025 | PVE::Network::tap_unplug($iface); | |
5026 | ||
5027 | if ($have_sdn) { | |
5028 | PVE::Network::SDN::Zones::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate}); | |
5029 | } else { | |
5030 | PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate}); | |
5031 | } | |
5032 | } elsif (safe_num_ne($oldnet->{rate}, $newnet->{rate})) { | |
5033 | # Rate can be applied on its own but any change above needs to | |
5034 | # include the rate in tap_plug since OVS resets everything. | |
5035 | PVE::Network::tap_rate_limit($iface, $newnet->{rate}); | |
5036 | } | |
5037 | ||
5038 | if (safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) { | |
5039 | qemu_set_link_status($vmid, $opt, !$newnet->{link_down}); | |
5040 | } | |
5041 | ||
5042 | return 1; | |
5043 | } | |
5044 | } | |
5045 | ||
5046 | if ($hotplug) { | |
5047 | vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet, $arch, $machine_type); | |
5048 | } else { | |
5049 | die "skip\n"; | |
5050 | } | |
5051 | } | |
5052 | ||
5053 | sub vmconfig_update_agent { | |
5054 | my ($conf, $opt, $value) = @_; | |
5055 | ||
5056 | die "skip\n" if !$conf->{$opt}; | |
5057 | ||
5058 | my $hotplug_options = { fstrim_cloned_disks => 1 }; | |
5059 | ||
5060 | my $old_agent = parse_guest_agent($conf); | |
5061 | my $agent = parse_guest_agent({$opt => $value}); | |
5062 | ||
5063 | for my $option (keys %$agent) { # added/changed options | |
5064 | next if defined($hotplug_options->{$option}); | |
5065 | die "skip\n" if safe_string_ne($agent->{$option}, $old_agent->{$option}); | |
5066 | } | |
5067 | ||
5068 | for my $option (keys %$old_agent) { # removed options | |
5069 | next if defined($hotplug_options->{$option}); | |
5070 | die "skip\n" if safe_string_ne($old_agent->{$option}, $agent->{$option}); | |
5071 | } | |
5072 | ||
5073 | return; # either no actual change (e.g., format string reordered) or just hotpluggable changes | |
5074 | } | |
5075 | ||
5076 | sub vmconfig_update_disk { | |
5077 | my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $arch, $machine_type) = @_; | |
5078 | ||
5079 | my $drive = parse_drive($opt, $value); | |
5080 | ||
5081 | if ($conf->{$opt} && (my $old_drive = parse_drive($opt, $conf->{$opt}))) { | |
5082 | my $media = $drive->{media} || 'disk'; | |
5083 | my $oldmedia = $old_drive->{media} || 'disk'; | |
5084 | die "unable to change media type\n" if $media ne $oldmedia; | |
5085 | ||
5086 | if (!drive_is_cdrom($old_drive)) { | |
5087 | ||
5088 | if ($drive->{file} ne $old_drive->{file}) { | |
5089 | ||
5090 | die "skip\n" if !$hotplug; | |
5091 | ||
5092 | # unplug and register as unused | |
5093 | vm_deviceunplug($vmid, $conf, $opt); | |
5094 | vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive) | |
5095 | ||
5096 | } else { | |
5097 | # update existing disk | |
5098 | ||
5099 | # skip non hotpluggable value | |
5100 | if (safe_string_ne($drive->{discard}, $old_drive->{discard}) || | |
5101 | safe_string_ne($drive->{iothread}, $old_drive->{iothread}) || | |
5102 | safe_string_ne($drive->{queues}, $old_drive->{queues}) || | |
5103 | safe_string_ne($drive->{cache}, $old_drive->{cache}) || | |
5104 | safe_string_ne($drive->{ssd}, $old_drive->{ssd})) { | |
5105 | die "skip\n"; | |
5106 | } | |
5107 | ||
5108 | # apply throttle | |
5109 | if (safe_num_ne($drive->{mbps}, $old_drive->{mbps}) || | |
5110 | safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) || | |
5111 | safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) || | |
5112 | safe_num_ne($drive->{iops}, $old_drive->{iops}) || | |
5113 | safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) || | |
5114 | safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) || | |
5115 | safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) || | |
5116 | safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) || | |
5117 | safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) || | |
5118 | safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) || | |
5119 | safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) || | |
5120 | safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) || | |
5121 | safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) || | |
5122 | safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) || | |
5123 | safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) || | |
5124 | safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) || | |
5125 | safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) || | |
5126 | safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) { | |
5127 | ||
5128 | qemu_block_set_io_throttle( | |
5129 | $vmid,"drive-$opt", | |
5130 | ($drive->{mbps} || 0)*1024*1024, | |
5131 | ($drive->{mbps_rd} || 0)*1024*1024, | |
5132 | ($drive->{mbps_wr} || 0)*1024*1024, | |
5133 | $drive->{iops} || 0, | |
5134 | $drive->{iops_rd} || 0, | |
5135 | $drive->{iops_wr} || 0, | |
5136 | ($drive->{mbps_max} || 0)*1024*1024, | |
5137 | ($drive->{mbps_rd_max} || 0)*1024*1024, | |
5138 | ($drive->{mbps_wr_max} || 0)*1024*1024, | |
5139 | $drive->{iops_max} || 0, | |
5140 | $drive->{iops_rd_max} || 0, | |
5141 | $drive->{iops_wr_max} || 0, | |
5142 | $drive->{bps_max_length} || 1, | |
5143 | $drive->{bps_rd_max_length} || 1, | |
5144 | $drive->{bps_wr_max_length} || 1, | |
5145 | $drive->{iops_max_length} || 1, | |
5146 | $drive->{iops_rd_max_length} || 1, | |
5147 | $drive->{iops_wr_max_length} || 1, | |
5148 | ); | |
5149 | ||
5150 | } | |
5151 | ||
5152 | return 1; | |
5153 | } | |
5154 | ||
5155 | } else { # cdrom | |
5156 | ||
5157 | if ($drive->{file} eq 'none') { | |
5158 | mon_cmd($vmid, "eject", force => JSON::true, id => "$opt"); | |
5159 | if (drive_is_cloudinit($old_drive)) { | |
5160 | vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive); | |
5161 | } | |
5162 | } else { | |
5163 | my $path = get_iso_path($storecfg, $vmid, $drive->{file}); | |
5164 | ||
5165 | # force eject if locked | |
5166 | mon_cmd($vmid, "eject", force => JSON::true, id => "$opt"); | |
5167 | ||
5168 | if ($path) { | |
5169 | mon_cmd($vmid, "blockdev-change-medium", | |
5170 | id => "$opt", filename => "$path"); | |
5171 | } | |
5172 | } | |
5173 | ||
5174 | return 1; | |
5175 | } | |
5176 | } | |
5177 | ||
5178 | die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/; | |
5179 | # hotplug new disks | |
5180 | PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|; | |
5181 | vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive, $arch, $machine_type); | |
5182 | } | |
5183 | ||
5184 | # called in locked context by incoming migration | |
5185 | sub vm_migrate_get_nbd_disks { | |
5186 | my ($storecfg, $conf, $replicated_volumes) = @_; | |
5187 | ||
5188 | my $local_volumes = {}; | |
5189 | PVE::QemuConfig->foreach_volume($conf, sub { | |
5190 | my ($ds, $drive) = @_; | |
5191 | ||
5192 | return if drive_is_cdrom($drive); | |
5193 | ||
5194 | my $volid = $drive->{file}; | |
5195 | ||
5196 | return if !$volid; | |
5197 | ||
5198 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid); | |
5199 | ||
5200 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
5201 | return if $scfg->{shared}; | |
5202 | ||
5203 | # replicated disks re-use existing state via bitmap | |
5204 | my $use_existing = $replicated_volumes->{$volid} ? 1 : 0; | |
5205 | $local_volumes->{$ds} = [$volid, $storeid, $volname, $drive, $use_existing]; | |
5206 | }); | |
5207 | return $local_volumes; | |
5208 | } | |
5209 | ||
5210 | # called in locked context by incoming migration | |
5211 | sub vm_migrate_alloc_nbd_disks { | |
5212 | my ($storecfg, $vmid, $source_volumes, $storagemap) = @_; | |
5213 | ||
5214 | my $format = undef; | |
5215 | ||
5216 | my $nbd = {}; | |
5217 | foreach my $opt (sort keys %$source_volumes) { | |
5218 | my ($volid, $storeid, $volname, $drive, $use_existing) = @{$source_volumes->{$opt}}; | |
5219 | ||
5220 | if ($use_existing) { | |
5221 | $nbd->{$opt}->{drivestr} = print_drive($drive); | |
5222 | $nbd->{$opt}->{volid} = $volid; | |
5223 | $nbd->{$opt}->{replicated} = 1; | |
5224 | next; | |
5225 | } | |
5226 | ||
5227 | # If a remote storage is specified and the format of the original | |
5228 | # volume is not available there, fall back to the default format. | |
5229 | # Otherwise use the same format as the original. | |
5230 | if (!$storagemap->{identity}) { | |
5231 | $storeid = map_storage($storagemap, $storeid); | |
5232 | my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid); | |
5233 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
5234 | my $fileFormat = qemu_img_format($scfg, $volname); | |
5235 | $format = (grep {$fileFormat eq $_} @{$validFormats}) ? $fileFormat : $defFormat; | |
5236 | } else { | |
5237 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
5238 | $format = qemu_img_format($scfg, $volname); | |
5239 | } | |
5240 | ||
5241 | my $size = $drive->{size} / 1024; | |
5242 | my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, $size); | |
5243 | my $newdrive = $drive; | |
5244 | $newdrive->{format} = $format; | |
5245 | $newdrive->{file} = $newvolid; | |
5246 | my $drivestr = print_drive($newdrive); | |
5247 | $nbd->{$opt}->{drivestr} = $drivestr; | |
5248 | $nbd->{$opt}->{volid} = $newvolid; | |
5249 | } | |
5250 | ||
5251 | return $nbd; | |
5252 | } | |
5253 | ||
5254 | # see vm_start_nolock for parameters, additionally: | |
5255 | # migrate_opts: | |
5256 | # storagemap = parsed storage map for allocating NBD disks | |
5257 | sub vm_start { | |
5258 | my ($storecfg, $vmid, $params, $migrate_opts) = @_; | |
5259 | ||
5260 | return PVE::QemuConfig->lock_config($vmid, sub { | |
5261 | my $conf = PVE::QemuConfig->load_config($vmid, $migrate_opts->{migratedfrom}); | |
5262 | ||
5263 | die "you can't start a vm if it's a template\n" | |
5264 | if !$params->{skiptemplate} && PVE::QemuConfig->is_template($conf); | |
5265 | ||
5266 | my $has_suspended_lock = PVE::QemuConfig->has_lock($conf, 'suspended'); | |
5267 | my $has_backup_lock = PVE::QemuConfig->has_lock($conf, 'backup'); | |
5268 | ||
5269 | my $running = check_running($vmid, undef, $migrate_opts->{migratedfrom}); | |
5270 | ||
5271 | if ($has_backup_lock && $running) { | |
5272 | # a backup is currently running, attempt to start the guest in the | |
5273 | # existing QEMU instance | |
5274 | return vm_resume($vmid); | |
5275 | } | |
5276 | ||
5277 | PVE::QemuConfig->check_lock($conf) | |
5278 | if !($params->{skiplock} || $has_suspended_lock); | |
5279 | ||
5280 | $params->{resume} = $has_suspended_lock || defined($conf->{vmstate}); | |
5281 | ||
5282 | die "VM $vmid already running\n" if $running; | |
5283 | ||
5284 | if (my $storagemap = $migrate_opts->{storagemap}) { | |
5285 | my $replicated = $migrate_opts->{replicated_volumes}; | |
5286 | my $disks = vm_migrate_get_nbd_disks($storecfg, $conf, $replicated); | |
5287 | $migrate_opts->{nbd} = vm_migrate_alloc_nbd_disks($storecfg, $vmid, $disks, $storagemap); | |
5288 | ||
5289 | foreach my $opt (keys %{$migrate_opts->{nbd}}) { | |
5290 | $conf->{$opt} = $migrate_opts->{nbd}->{$opt}->{drivestr}; | |
5291 | } | |
5292 | } | |
5293 | ||
5294 | return vm_start_nolock($storecfg, $vmid, $conf, $params, $migrate_opts); | |
5295 | }); | |
5296 | } | |
5297 | ||
5298 | ||
5299 | # params: | |
5300 | # statefile => 'tcp', 'unix' for migration or path/volid for RAM state | |
5301 | # skiplock => 0/1, skip checking for config lock | |
5302 | # skiptemplate => 0/1, skip checking whether VM is template | |
5303 | # forcemachine => to force Qemu machine (rollback/migration) | |
5304 | # forcecpu => a QEMU '-cpu' argument string to override get_cpu_options | |
5305 | # timeout => in seconds | |
5306 | # paused => start VM in paused state (backup) | |
5307 | # resume => resume from hibernation | |
5308 | # pbs-backing => { | |
5309 | # sata0 => { | |
5310 | # repository | |
5311 | # snapshot | |
5312 | # keyfile | |
5313 | # archive | |
5314 | # }, | |
5315 | # virtio2 => ... | |
5316 | # } | |
5317 | # migrate_opts: | |
5318 | # nbd => volumes for NBD exports (vm_migrate_alloc_nbd_disks) | |
5319 | # migratedfrom => source node | |
5320 | # spice_ticket => used for spice migration, passed via tunnel/stdin | |
5321 | # network => CIDR of migration network | |
5322 | # type => secure/insecure - tunnel over encrypted connection or plain-text | |
5323 | # nbd_proto_version => int, 0 for TCP, 1 for UNIX | |
5324 | # replicated_volumes = which volids should be re-used with bitmaps for nbd migration | |
5325 | sub vm_start_nolock { | |
5326 | my ($storecfg, $vmid, $conf, $params, $migrate_opts) = @_; | |
5327 | ||
5328 | my $statefile = $params->{statefile}; | |
5329 | my $resume = $params->{resume}; | |
5330 | ||
5331 | my $migratedfrom = $migrate_opts->{migratedfrom}; | |
5332 | my $migration_type = $migrate_opts->{type}; | |
5333 | ||
5334 | my $res = {}; | |
5335 | ||
5336 | # clean up leftover reboot request files | |
5337 | eval { clear_reboot_request($vmid); }; | |
5338 | warn $@ if $@; | |
5339 | ||
5340 | if (!$statefile && scalar(keys %{$conf->{pending}})) { | |
5341 | vmconfig_apply_pending($vmid, $conf, $storecfg); | |
5342 | $conf = PVE::QemuConfig->load_config($vmid); # update/reload | |
5343 | } | |
5344 | ||
5345 | # don't regenerate the ISO if the VM is started as part of a live migration | |
5346 | # this way we can reuse the old ISO with the correct config | |
5347 | PVE::QemuServer::Cloudinit::generate_cloudinitconfig($conf, $vmid) if !$migratedfrom; | |
5348 | ||
5349 | my $defaults = load_defaults(); | |
5350 | ||
5351 | # set environment variable useful inside network script | |
5352 | $ENV{PVE_MIGRATED_FROM} = $migratedfrom if $migratedfrom; | |
5353 | ||
5354 | PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1); | |
5355 | ||
5356 | my $forcemachine = $params->{forcemachine}; | |
5357 | my $forcecpu = $params->{forcecpu}; | |
5358 | if ($resume) { | |
5359 | # enforce machine and CPU type on suspended vm to ensure HW compatibility | |
5360 | $forcemachine = $conf->{runningmachine}; | |
5361 | $forcecpu = $conf->{runningcpu}; | |
5362 | print "Resuming suspended VM\n"; | |
5363 | } | |
5364 | ||
5365 | my ($cmd, $vollist, $spice_port) = config_to_command($storecfg, $vmid, | |
5366 | $conf, $defaults, $forcemachine, $forcecpu, $params->{'pbs-backing'}); | |
5367 | ||
5368 | my $migration_ip; | |
5369 | my $get_migration_ip = sub { | |
5370 | my ($nodename) = @_; | |
5371 | ||
5372 | return $migration_ip if defined($migration_ip); | |
5373 | ||
5374 | my $cidr = $migrate_opts->{network}; | |
5375 | ||
5376 | if (!defined($cidr)) { | |
5377 | my $dc_conf = PVE::Cluster::cfs_read_file('datacenter.cfg'); | |
5378 | $cidr = $dc_conf->{migration}->{network}; | |
5379 | } | |
5380 | ||
5381 | if (defined($cidr)) { | |
5382 | my $ips = PVE::Network::get_local_ip_from_cidr($cidr); | |
5383 | ||
5384 | die "could not get IP: no address configured on local " . | |
5385 | "node for network '$cidr'\n" if scalar(@$ips) == 0; | |
5386 | ||
5387 | die "could not get IP: multiple addresses configured on local " . | |
5388 | "node for network '$cidr'\n" if scalar(@$ips) > 1; | |
5389 | ||
5390 | $migration_ip = @$ips[0]; | |
5391 | } | |
5392 | ||
5393 | $migration_ip = PVE::Cluster::remote_node_ip($nodename, 1) | |
5394 | if !defined($migration_ip); | |
5395 | ||
5396 | return $migration_ip; | |
5397 | }; | |
5398 | ||
5399 | my $migrate_uri; | |
5400 | if ($statefile) { | |
5401 | if ($statefile eq 'tcp') { | |
5402 | my $localip = "localhost"; | |
5403 | my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg'); | |
5404 | my $nodename = nodename(); | |
5405 | ||
5406 | if (!defined($migration_type)) { | |
5407 | if (defined($datacenterconf->{migration}->{type})) { | |
5408 | $migration_type = $datacenterconf->{migration}->{type}; | |
5409 | } else { | |
5410 | $migration_type = 'secure'; | |
5411 | } | |
5412 | } | |
5413 | ||
5414 | if ($migration_type eq 'insecure') { | |
5415 | $localip = $get_migration_ip->($nodename); | |
5416 | $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip); | |
5417 | } | |
5418 | ||
5419 | my $pfamily = PVE::Tools::get_host_address_family($nodename); | |
5420 | my $migrate_port = PVE::Tools::next_migrate_port($pfamily); | |
5421 | $migrate_uri = "tcp:${localip}:${migrate_port}"; | |
5422 | push @$cmd, '-incoming', $migrate_uri; | |
5423 | push @$cmd, '-S'; | |
5424 | ||
5425 | } elsif ($statefile eq 'unix') { | |
5426 | # should be default for secure migrations as a ssh TCP forward | |
5427 | # tunnel is not deterministic reliable ready and fails regurarly | |
5428 | # to set up in time, so use UNIX socket forwards | |
5429 | my $socket_addr = "/run/qemu-server/$vmid.migrate"; | |
5430 | unlink $socket_addr; | |
5431 | ||
5432 | $migrate_uri = "unix:$socket_addr"; | |
5433 | ||
5434 | push @$cmd, '-incoming', $migrate_uri; | |
5435 | push @$cmd, '-S'; | |
5436 | ||
5437 | } elsif (-e $statefile) { | |
5438 | push @$cmd, '-loadstate', $statefile; | |
5439 | } else { | |
5440 | my $statepath = PVE::Storage::path($storecfg, $statefile); | |
5441 | push @$vollist, $statefile; | |
5442 | push @$cmd, '-loadstate', $statepath; | |
5443 | } | |
5444 | } elsif ($params->{paused}) { | |
5445 | push @$cmd, '-S'; | |
5446 | } | |
5447 | ||
5448 | my $start_timeout = $params->{timeout} // config_aware_timeout($conf, $resume); | |
5449 | ||
5450 | my $pci_devices = {}; # host pci devices | |
5451 | for (my $i = 0; $i < $PVE::QemuServer::PCI::MAX_HOSTPCI_DEVICES; $i++) { | |
5452 | my $dev = $conf->{"hostpci$i"} or next; | |
5453 | $pci_devices->{$i} = parse_hostpci($dev); | |
5454 | } | |
5455 | ||
5456 | my $pci_id_list = [ map { $_->{id} } map { $_->{pciid}->@* } values $pci_devices->%* ]; | |
5457 | # reserve all PCI IDs before actually doing anything with them | |
5458 | PVE::QemuServer::PCI::reserve_pci_usage($pci_id_list, $vmid, $start_timeout); | |
5459 | ||
5460 | eval { | |
5461 | for my $id (sort keys %$pci_devices) { | |
5462 | my $d = $pci_devices->{$id}; | |
5463 | for my $dev ($d->{pciid}->@*) { | |
5464 | PVE::QemuServer::PCI::prepare_pci_device($vmid, $dev->{id}, $id, $d->{mdev}); | |
5465 | } | |
5466 | } | |
5467 | }; | |
5468 | if (my $err = $@) { | |
5469 | eval { PVE::QemuServer::PCI::remove_pci_reservation($pci_id_list) }; | |
5470 | warn $@ if $@; | |
5471 | die $err; | |
5472 | } | |
5473 | ||
5474 | PVE::Storage::activate_volumes($storecfg, $vollist); | |
5475 | ||
5476 | eval { | |
5477 | run_command(['/bin/systemctl', 'stop', "$vmid.scope"], outfunc => sub{}, errfunc => sub{}); | |
5478 | }; | |
5479 | # Issues with the above 'stop' not being fully completed are extremely rare, a very low | |
5480 | # timeout should be more than enough here... | |
5481 | PVE::Systemd::wait_for_unit_removed("$vmid.scope", 5); | |
5482 | ||
5483 | my $cpuunits = get_cpuunits($conf); | |
5484 | ||
5485 | my %run_params = ( | |
5486 | timeout => $statefile ? undef : $start_timeout, | |
5487 | umask => 0077, | |
5488 | noerr => 1, | |
5489 | ); | |
5490 | ||
5491 | # when migrating, prefix QEMU output so other side can pick up any | |
5492 | # errors that might occur and show the user | |
5493 | if ($migratedfrom) { | |
5494 | $run_params{quiet} = 1; | |
5495 | $run_params{logfunc} = sub { print "QEMU: $_[0]\n" }; | |
5496 | } | |
5497 | ||
5498 | my %systemd_properties = ( | |
5499 | Slice => 'qemu.slice', | |
5500 | KillMode => 'process', | |
5501 | SendSIGKILL => 0, | |
5502 | TimeoutStopUSec => ULONG_MAX, # infinity | |
5503 | ); | |
5504 | ||
5505 | if (PVE::CGroup::cgroup_mode() == 2) { | |
5506 | $cpuunits = 10000 if $cpuunits >= 10000; # else we get an error | |
5507 | $systemd_properties{CPUWeight} = $cpuunits; | |
5508 | } else { | |
5509 | $systemd_properties{CPUShares} = $cpuunits; | |
5510 | } | |
5511 | ||
5512 | if (my $cpulimit = $conf->{cpulimit}) { | |
5513 | $systemd_properties{CPUQuota} = int($cpulimit * 100); | |
5514 | } | |
5515 | $systemd_properties{timeout} = 10 if $statefile; # setting up the scope shoul be quick | |
5516 | ||
5517 | my $run_qemu = sub { | |
5518 | PVE::Tools::run_fork sub { | |
5519 | PVE::Systemd::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %systemd_properties); | |
5520 | ||
5521 | my $tpmpid; | |
5522 | if (my $tpm = $conf->{tpmstate0}) { | |
5523 | # start the TPM emulator so QEMU can connect on start | |
5524 | $tpmpid = start_swtpm($storecfg, $vmid, $tpm, $migratedfrom); | |
5525 | } | |
5526 | ||
5527 | my $exitcode = run_command($cmd, %run_params); | |
5528 | if ($exitcode) { | |
5529 | if ($tpmpid) { | |
5530 | warn "stopping swtpm instance (pid $tpmpid) due to QEMU startup error\n"; | |
5531 | kill 'TERM', $tpmpid; | |
5532 | } | |
5533 | die "QEMU exited with code $exitcode\n"; | |
5534 | } | |
5535 | }; | |
5536 | }; | |
5537 | ||
5538 | if ($conf->{hugepages}) { | |
5539 | ||
5540 | my $code = sub { | |
5541 | my $hugepages_topology = PVE::QemuServer::Memory::hugepages_topology($conf); | |
5542 | my $hugepages_host_topology = PVE::QemuServer::Memory::hugepages_host_topology(); | |
5543 | ||
5544 | PVE::QemuServer::Memory::hugepages_mount(); | |
5545 | PVE::QemuServer::Memory::hugepages_allocate($hugepages_topology, $hugepages_host_topology); | |
5546 | ||
5547 | eval { $run_qemu->() }; | |
5548 | if (my $err = $@) { | |
5549 | PVE::QemuServer::Memory::hugepages_reset($hugepages_host_topology) | |
5550 | if !$conf->{keephugepages}; | |
5551 | die $err; | |
5552 | } | |
5553 | ||
5554 | PVE::QemuServer::Memory::hugepages_pre_deallocate($hugepages_topology) | |
5555 | if !$conf->{keephugepages}; | |
5556 | }; | |
5557 | eval { PVE::QemuServer::Memory::hugepages_update_locked($code); }; | |
5558 | ||
5559 | } else { | |
5560 | eval { $run_qemu->() }; | |
5561 | } | |
5562 | ||
5563 | if (my $err = $@) { | |
5564 | # deactivate volumes if start fails | |
5565 | eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); }; | |
5566 | eval { PVE::QemuServer::PCI::remove_pci_reservation($pci_id_list) }; | |
5567 | ||
5568 | die "start failed: $err"; | |
5569 | } | |
5570 | ||
5571 | # re-reserve all PCI IDs now that we can know the actual VM PID | |
5572 | my $pid = PVE::QemuServer::Helpers::vm_running_locally($vmid); | |
5573 | eval { PVE::QemuServer::PCI::reserve_pci_usage($pci_id_list, $vmid, undef, $pid) }; | |
5574 | warn $@ if $@; | |
5575 | ||
5576 | print "migration listens on $migrate_uri\n" if $migrate_uri; | |
5577 | $res->{migrate_uri} = $migrate_uri; | |
5578 | ||
5579 | if ($statefile && $statefile ne 'tcp' && $statefile ne 'unix') { | |
5580 | eval { mon_cmd($vmid, "cont"); }; | |
5581 | warn $@ if $@; | |
5582 | } | |
5583 | ||
5584 | #start nbd server for storage migration | |
5585 | if (my $nbd = $migrate_opts->{nbd}) { | |
5586 | my $nbd_protocol_version = $migrate_opts->{nbd_proto_version} // 0; | |
5587 | ||
5588 | my $migrate_storage_uri; | |
5589 | # nbd_protocol_version > 0 for unix socket support | |
5590 | if ($nbd_protocol_version > 0 && $migration_type eq 'secure') { | |
5591 | my $socket_path = "/run/qemu-server/$vmid\_nbd.migrate"; | |
5592 | mon_cmd($vmid, "nbd-server-start", addr => { type => 'unix', data => { path => $socket_path } } ); | |
5593 | $migrate_storage_uri = "nbd:unix:$socket_path"; | |
5594 | } else { | |
5595 | my $nodename = nodename(); | |
5596 | my $localip = $get_migration_ip->($nodename); | |
5597 | my $pfamily = PVE::Tools::get_host_address_family($nodename); | |
5598 | my $storage_migrate_port = PVE::Tools::next_migrate_port($pfamily); | |
5599 | ||
5600 | mon_cmd($vmid, "nbd-server-start", addr => { | |
5601 | type => 'inet', | |
5602 | data => { | |
5603 | host => "${localip}", | |
5604 | port => "${storage_migrate_port}", | |
5605 | }, | |
5606 | }); | |
5607 | $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip); | |
5608 | $migrate_storage_uri = "nbd:${localip}:${storage_migrate_port}"; | |
5609 | } | |
5610 | ||
5611 | $res->{migrate_storage_uri} = $migrate_storage_uri; | |
5612 | ||
5613 | foreach my $opt (sort keys %$nbd) { | |
5614 | my $drivestr = $nbd->{$opt}->{drivestr}; | |
5615 | my $volid = $nbd->{$opt}->{volid}; | |
5616 | mon_cmd($vmid, "nbd-server-add", device => "drive-$opt", writable => JSON::true ); | |
5617 | my $nbd_uri = "$migrate_storage_uri:exportname=drive-$opt"; | |
5618 | print "storage migration listens on $nbd_uri volume:$drivestr\n"; | |
5619 | print "re-using replicated volume: $opt - $volid\n" | |
5620 | if $nbd->{$opt}->{replicated}; | |
5621 | ||
5622 | $res->{drives}->{$opt} = $nbd->{$opt}; | |
5623 | $res->{drives}->{$opt}->{nbd_uri} = $nbd_uri; | |
5624 | } | |
5625 | } | |
5626 | ||
5627 | if ($migratedfrom) { | |
5628 | eval { | |
5629 | set_migration_caps($vmid); | |
5630 | }; | |
5631 | warn $@ if $@; | |
5632 | ||
5633 | if ($spice_port) { | |
5634 | print "spice listens on port $spice_port\n"; | |
5635 | $res->{spice_port} = $spice_port; | |
5636 | if ($migrate_opts->{spice_ticket}) { | |
5637 | mon_cmd($vmid, "set_password", protocol => 'spice', password => | |
5638 | $migrate_opts->{spice_ticket}); | |
5639 | mon_cmd($vmid, "expire_password", protocol => 'spice', time => "+30"); | |
5640 | } | |
5641 | } | |
5642 | ||
5643 | } else { | |
5644 | mon_cmd($vmid, "balloon", value => $conf->{balloon}*1024*1024) | |
5645 | if !$statefile && $conf->{balloon}; | |
5646 | ||
5647 | foreach my $opt (keys %$conf) { | |
5648 | next if $opt !~ m/^net\d+$/; | |
5649 | my $nicconf = parse_net($conf->{$opt}); | |
5650 | qemu_set_link_status($vmid, $opt, 0) if $nicconf->{link_down}; | |
5651 | } | |
5652 | } | |
5653 | ||
5654 | mon_cmd($vmid, 'qom-set', | |
5655 | path => "machine/peripheral/balloon0", | |
5656 | property => "guest-stats-polling-interval", | |
5657 | value => 2) if (!defined($conf->{balloon}) || $conf->{balloon}); | |
5658 | ||
5659 | if ($resume) { | |
5660 | print "Resumed VM, removing state\n"; | |
5661 | if (my $vmstate = $conf->{vmstate}) { | |
5662 | PVE::Storage::deactivate_volumes($storecfg, [$vmstate]); | |
5663 | PVE::Storage::vdisk_free($storecfg, $vmstate); | |
5664 | } | |
5665 | delete $conf->@{qw(lock vmstate runningmachine runningcpu)}; | |
5666 | PVE::QemuConfig->write_config($vmid, $conf); | |
5667 | } | |
5668 | ||
5669 | PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start'); | |
5670 | ||
5671 | return $res; | |
5672 | } | |
5673 | ||
5674 | sub vm_commandline { | |
5675 | my ($storecfg, $vmid, $snapname) = @_; | |
5676 | ||
5677 | my $conf = PVE::QemuConfig->load_config($vmid); | |
5678 | ||
5679 | my ($forcemachine, $forcecpu); | |
5680 | if ($snapname) { | |
5681 | my $snapshot = $conf->{snapshots}->{$snapname}; | |
5682 | die "snapshot '$snapname' does not exist\n" if !defined($snapshot); | |
5683 | ||
5684 | # check for machine or CPU overrides in snapshot | |
5685 | $forcemachine = $snapshot->{runningmachine}; | |
5686 | $forcecpu = $snapshot->{runningcpu}; | |
5687 | ||
5688 | $snapshot->{digest} = $conf->{digest}; # keep file digest for API | |
5689 | ||
5690 | $conf = $snapshot; | |
5691 | } | |
5692 | ||
5693 | my $defaults = load_defaults(); | |
5694 | ||
5695 | my $cmd = config_to_command($storecfg, $vmid, $conf, $defaults, $forcemachine, $forcecpu); | |
5696 | ||
5697 | return PVE::Tools::cmd2string($cmd); | |
5698 | } | |
5699 | ||
5700 | sub vm_reset { | |
5701 | my ($vmid, $skiplock) = @_; | |
5702 | ||
5703 | PVE::QemuConfig->lock_config($vmid, sub { | |
5704 | ||
5705 | my $conf = PVE::QemuConfig->load_config($vmid); | |
5706 | ||
5707 | PVE::QemuConfig->check_lock($conf) if !$skiplock; | |
5708 | ||
5709 | mon_cmd($vmid, "system_reset"); | |
5710 | }); | |
5711 | } | |
5712 | ||
5713 | sub get_vm_volumes { | |
5714 | my ($conf) = @_; | |
5715 | ||
5716 | my $vollist = []; | |
5717 | foreach_volid($conf, sub { | |
5718 | my ($volid, $attr) = @_; | |
5719 | ||
5720 | return if $volid =~ m|^/|; | |
5721 | ||
5722 | my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
5723 | return if !$sid; | |
5724 | ||
5725 | push @$vollist, $volid; | |
5726 | }); | |
5727 | ||
5728 | return $vollist; | |
5729 | } | |
5730 | ||
5731 | sub vm_stop_cleanup { | |
5732 | my ($storecfg, $vmid, $conf, $keepActive, $apply_pending_changes) = @_; | |
5733 | ||
5734 | eval { | |
5735 | ||
5736 | if (!$keepActive) { | |
5737 | my $vollist = get_vm_volumes($conf); | |
5738 | PVE::Storage::deactivate_volumes($storecfg, $vollist); | |
5739 | ||
5740 | if (my $tpmdrive = $conf->{tpmstate0}) { | |
5741 | my $tpm = parse_drive("tpmstate0", $tpmdrive); | |
5742 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($tpm->{file}, 1); | |
5743 | if ($storeid) { | |
5744 | PVE::Storage::unmap_volume($storecfg, $tpm->{file}); | |
5745 | } | |
5746 | } | |
5747 | } | |
5748 | ||
5749 | foreach my $ext (qw(mon qmp pid vnc qga)) { | |
5750 | unlink "/var/run/qemu-server/${vmid}.$ext"; | |
5751 | } | |
5752 | ||
5753 | if ($conf->{ivshmem}) { | |
5754 | my $ivshmem = parse_property_string($ivshmem_fmt, $conf->{ivshmem}); | |
5755 | # just delete it for now, VMs which have this already open do not | |
5756 | # are affected, but new VMs will get a separated one. If this | |
5757 | # becomes an issue we either add some sort of ref-counting or just | |
5758 | # add a "don't delete on stop" flag to the ivshmem format. | |
5759 | unlink '/dev/shm/pve-shm-' . ($ivshmem->{name} // $vmid); | |
5760 | } | |
5761 | ||
5762 | my $ids = []; | |
5763 | foreach my $key (keys %$conf) { | |
5764 | next if $key !~ m/^hostpci(\d+)$/; | |
5765 | my $hostpciindex = $1; | |
5766 | my $d = parse_hostpci($conf->{$key}); | |
5767 | my $uuid = PVE::SysFSTools::generate_mdev_uuid($vmid, $hostpciindex); | |
5768 | ||
5769 | foreach my $pci (@{$d->{pciid}}) { | |
5770 | my $pciid = $pci->{id}; | |
5771 | push @$ids, $pci->{id}; | |
5772 | PVE::SysFSTools::pci_cleanup_mdev_device($pciid, $uuid); | |
5773 | } | |
5774 | } | |
5775 | PVE::QemuServer::PCI::remove_pci_reservation($ids); | |
5776 | ||
5777 | vmconfig_apply_pending($vmid, $conf, $storecfg) if $apply_pending_changes; | |
5778 | }; | |
5779 | warn $@ if $@; # avoid errors - just warn | |
5780 | } | |
5781 | ||
5782 | # call only in locked context | |
5783 | sub _do_vm_stop { | |
5784 | my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive) = @_; | |
5785 | ||
5786 | my $pid = check_running($vmid, $nocheck); | |
5787 | return if !$pid; | |
5788 | ||
5789 | my $conf; | |
5790 | if (!$nocheck) { | |
5791 | $conf = PVE::QemuConfig->load_config($vmid); | |
5792 | PVE::QemuConfig->check_lock($conf) if !$skiplock; | |
5793 | if (!defined($timeout) && $shutdown && $conf->{startup}) { | |
5794 | my $opts = PVE::JSONSchema::pve_parse_startup_order($conf->{startup}); | |
5795 | $timeout = $opts->{down} if $opts->{down}; | |
5796 | } | |
5797 | PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop'); | |
5798 | } | |
5799 | ||
5800 | eval { | |
5801 | if ($shutdown) { | |
5802 | if (defined($conf) && get_qga_key($conf, 'enabled')) { | |
5803 | mon_cmd($vmid, "guest-shutdown", timeout => $timeout); | |
5804 | } else { | |
5805 | mon_cmd($vmid, "system_powerdown"); | |
5806 | } | |
5807 | } else { | |
5808 | mon_cmd($vmid, "quit"); | |
5809 | } | |
5810 | }; | |
5811 | my $err = $@; | |
5812 | ||
5813 | if (!$err) { | |
5814 | $timeout = 60 if !defined($timeout); | |
5815 | ||
5816 | my $count = 0; | |
5817 | while (($count < $timeout) && check_running($vmid, $nocheck)) { | |
5818 | $count++; | |
5819 | sleep 1; | |
5820 | } | |
5821 | ||
5822 | if ($count >= $timeout) { | |
5823 | if ($force) { | |
5824 | warn "VM still running - terminating now with SIGTERM\n"; | |
5825 | kill 15, $pid; | |
5826 | } else { | |
5827 | die "VM quit/powerdown failed - got timeout\n"; | |
5828 | } | |
5829 | } else { | |
5830 | vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf; | |
5831 | return; | |
5832 | } | |
5833 | } else { | |
5834 | if (!check_running($vmid, $nocheck)) { | |
5835 | warn "Unexpected: VM shutdown command failed, but VM not running anymore..\n"; | |
5836 | return; | |
5837 | } | |
5838 | if ($force) { | |
5839 | warn "VM quit/powerdown failed - terminating now with SIGTERM\n"; | |
5840 | kill 15, $pid; | |
5841 | } else { | |
5842 | die "VM quit/powerdown failed\n"; | |
5843 | } | |
5844 | } | |
5845 | ||
5846 | # wait again | |
5847 | $timeout = 10; | |
5848 | ||
5849 | my $count = 0; | |
5850 | while (($count < $timeout) && check_running($vmid, $nocheck)) { | |
5851 | $count++; | |
5852 | sleep 1; | |
5853 | } | |
5854 | ||
5855 | if ($count >= $timeout) { | |
5856 | warn "VM still running - terminating now with SIGKILL\n"; | |
5857 | kill 9, $pid; | |
5858 | sleep 1; | |
5859 | } | |
5860 | ||
5861 | vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 1) if $conf; | |
5862 | } | |
5863 | ||
5864 | # Note: use $nocheck to skip tests if VM configuration file exists. | |
5865 | # We need that when migration VMs to other nodes (files already moved) | |
5866 | # Note: we set $keepActive in vzdump stop mode - volumes need to stay active | |
5867 | sub vm_stop { | |
5868 | my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive, $migratedfrom) = @_; | |
5869 | ||
5870 | $force = 1 if !defined($force) && !$shutdown; | |
5871 | ||
5872 | if ($migratedfrom){ | |
5873 | my $pid = check_running($vmid, $nocheck, $migratedfrom); | |
5874 | kill 15, $pid if $pid; | |
5875 | my $conf = PVE::QemuConfig->load_config($vmid, $migratedfrom); | |
5876 | vm_stop_cleanup($storecfg, $vmid, $conf, $keepActive, 0); | |
5877 | return; | |
5878 | } | |
5879 | ||
5880 | PVE::QemuConfig->lock_config($vmid, sub { | |
5881 | _do_vm_stop($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive); | |
5882 | }); | |
5883 | } | |
5884 | ||
5885 | sub vm_reboot { | |
5886 | my ($vmid, $timeout) = @_; | |
5887 | ||
5888 | PVE::QemuConfig->lock_config($vmid, sub { | |
5889 | eval { | |
5890 | ||
5891 | # only reboot if running, as qmeventd starts it again on a stop event | |
5892 | return if !check_running($vmid); | |
5893 | ||
5894 | create_reboot_request($vmid); | |
5895 | ||
5896 | my $storecfg = PVE::Storage::config(); | |
5897 | _do_vm_stop($storecfg, $vmid, undef, undef, $timeout, 1); | |
5898 | ||
5899 | }; | |
5900 | if (my $err = $@) { | |
5901 | # avoid that the next normal shutdown will be confused for a reboot | |
5902 | clear_reboot_request($vmid); | |
5903 | die $err; | |
5904 | } | |
5905 | }); | |
5906 | } | |
5907 | ||
5908 | # note: if using the statestorage parameter, the caller has to check privileges | |
5909 | sub vm_suspend { | |
5910 | my ($vmid, $skiplock, $includestate, $statestorage) = @_; | |
5911 | ||
5912 | my $conf; | |
5913 | my $path; | |
5914 | my $storecfg; | |
5915 | my $vmstate; | |
5916 | ||
5917 | PVE::QemuConfig->lock_config($vmid, sub { | |
5918 | ||
5919 | $conf = PVE::QemuConfig->load_config($vmid); | |
5920 | ||
5921 | my $is_backing_up = PVE::QemuConfig->has_lock($conf, 'backup'); | |
5922 | PVE::QemuConfig->check_lock($conf) | |
5923 | if !($skiplock || $is_backing_up); | |
5924 | ||
5925 | die "cannot suspend to disk during backup\n" | |
5926 | if $is_backing_up && $includestate; | |
5927 | ||
5928 | if ($includestate) { | |
5929 | $conf->{lock} = 'suspending'; | |
5930 | my $date = strftime("%Y-%m-%d", localtime(time())); | |
5931 | $storecfg = PVE::Storage::config(); | |
5932 | if (!$statestorage) { | |
5933 | $statestorage = find_vmstate_storage($conf, $storecfg); | |
5934 | # check permissions for the storage | |
5935 | my $rpcenv = PVE::RPCEnvironment::get(); | |
5936 | if ($rpcenv->{type} ne 'cli') { | |
5937 | my $authuser = $rpcenv->get_user(); | |
5938 | $rpcenv->check($authuser, "/storage/$statestorage", ['Datastore.AllocateSpace']); | |
5939 | } | |
5940 | } | |
5941 | ||
5942 | ||
5943 | $vmstate = PVE::QemuConfig->__snapshot_save_vmstate( | |
5944 | $vmid, $conf, "suspend-$date", $storecfg, $statestorage, 1); | |
5945 | $path = PVE::Storage::path($storecfg, $vmstate); | |
5946 | PVE::QemuConfig->write_config($vmid, $conf); | |
5947 | } else { | |
5948 | mon_cmd($vmid, "stop"); | |
5949 | } | |
5950 | }); | |
5951 | ||
5952 | if ($includestate) { | |
5953 | # save vm state | |
5954 | PVE::Storage::activate_volumes($storecfg, [$vmstate]); | |
5955 | ||
5956 | eval { | |
5957 | set_migration_caps($vmid, 1); | |
5958 | mon_cmd($vmid, "savevm-start", statefile => $path); | |
5959 | for(;;) { | |
5960 | my $state = mon_cmd($vmid, "query-savevm"); | |
5961 | if (!$state->{status}) { | |
5962 | die "savevm not active\n"; | |
5963 | } elsif ($state->{status} eq 'active') { | |
5964 | sleep(1); | |
5965 | next; | |
5966 | } elsif ($state->{status} eq 'completed') { | |
5967 | print "State saved, quitting\n"; | |
5968 | last; | |
5969 | } elsif ($state->{status} eq 'failed' && $state->{error}) { | |
5970 | die "query-savevm failed with error '$state->{error}'\n" | |
5971 | } else { | |
5972 | die "query-savevm returned status '$state->{status}'\n"; | |
5973 | } | |
5974 | } | |
5975 | }; | |
5976 | my $err = $@; | |
5977 | ||
5978 | PVE::QemuConfig->lock_config($vmid, sub { | |
5979 | $conf = PVE::QemuConfig->load_config($vmid); | |
5980 | if ($err) { | |
5981 | # cleanup, but leave suspending lock, to indicate something went wrong | |
5982 | eval { | |
5983 | mon_cmd($vmid, "savevm-end"); | |
5984 | PVE::Storage::deactivate_volumes($storecfg, [$vmstate]); | |
5985 | PVE::Storage::vdisk_free($storecfg, $vmstate); | |
5986 | delete $conf->@{qw(vmstate runningmachine runningcpu)}; | |
5987 | PVE::QemuConfig->write_config($vmid, $conf); | |
5988 | }; | |
5989 | warn $@ if $@; | |
5990 | die $err; | |
5991 | } | |
5992 | ||
5993 | die "lock changed unexpectedly\n" | |
5994 | if !PVE::QemuConfig->has_lock($conf, 'suspending'); | |
5995 | ||
5996 | mon_cmd($vmid, "quit"); | |
5997 | $conf->{lock} = 'suspended'; | |
5998 | PVE::QemuConfig->write_config($vmid, $conf); | |
5999 | }); | |
6000 | } | |
6001 | } | |
6002 | ||
6003 | sub vm_resume { | |
6004 | my ($vmid, $skiplock, $nocheck) = @_; | |
6005 | ||
6006 | PVE::QemuConfig->lock_config($vmid, sub { | |
6007 | my $res = mon_cmd($vmid, 'query-status'); | |
6008 | my $resume_cmd = 'cont'; | |
6009 | my $reset = 0; | |
6010 | ||
6011 | if ($res->{status}) { | |
6012 | return if $res->{status} eq 'running'; # job done, go home | |
6013 | $resume_cmd = 'system_wakeup' if $res->{status} eq 'suspended'; | |
6014 | $reset = 1 if $res->{status} eq 'shutdown'; | |
6015 | } | |
6016 | ||
6017 | if (!$nocheck) { | |
6018 | ||
6019 | my $conf = PVE::QemuConfig->load_config($vmid); | |
6020 | ||
6021 | PVE::QemuConfig->check_lock($conf) | |
6022 | if !($skiplock || PVE::QemuConfig->has_lock($conf, 'backup')); | |
6023 | } | |
6024 | ||
6025 | if ($reset) { | |
6026 | # required if a VM shuts down during a backup and we get a resume | |
6027 | # request before the backup finishes for example | |
6028 | mon_cmd($vmid, "system_reset"); | |
6029 | } | |
6030 | mon_cmd($vmid, $resume_cmd); | |
6031 | }); | |
6032 | } | |
6033 | ||
6034 | sub vm_sendkey { | |
6035 | my ($vmid, $skiplock, $key) = @_; | |
6036 | ||
6037 | PVE::QemuConfig->lock_config($vmid, sub { | |
6038 | ||
6039 | my $conf = PVE::QemuConfig->load_config($vmid); | |
6040 | ||
6041 | # there is no qmp command, so we use the human monitor command | |
6042 | my $res = PVE::QemuServer::Monitor::hmp_cmd($vmid, "sendkey $key"); | |
6043 | die $res if $res ne ''; | |
6044 | }); | |
6045 | } | |
6046 | ||
6047 | # vzdump restore implementaion | |
6048 | ||
6049 | sub tar_archive_read_firstfile { | |
6050 | my $archive = shift; | |
6051 | ||
6052 | die "ERROR: file '$archive' does not exist\n" if ! -f $archive; | |
6053 | ||
6054 | # try to detect archive type first | |
6055 | my $pid = open (my $fh, '-|', 'tar', 'tf', $archive) || | |
6056 | die "unable to open file '$archive'\n"; | |
6057 | my $firstfile = <$fh>; | |
6058 | kill 15, $pid; | |
6059 | close $fh; | |
6060 | ||
6061 | die "ERROR: archive contaions no data\n" if !$firstfile; | |
6062 | chomp $firstfile; | |
6063 | ||
6064 | return $firstfile; | |
6065 | } | |
6066 | ||
6067 | sub tar_restore_cleanup { | |
6068 | my ($storecfg, $statfile) = @_; | |
6069 | ||
6070 | print STDERR "starting cleanup\n"; | |
6071 | ||
6072 | if (my $fd = IO::File->new($statfile, "r")) { | |
6073 | while (defined(my $line = <$fd>)) { | |
6074 | if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) { | |
6075 | my $volid = $2; | |
6076 | eval { | |
6077 | if ($volid =~ m|^/|) { | |
6078 | unlink $volid || die 'unlink failed\n'; | |
6079 | } else { | |
6080 | PVE::Storage::vdisk_free($storecfg, $volid); | |
6081 | } | |
6082 | print STDERR "temporary volume '$volid' sucessfuly removed\n"; | |
6083 | }; | |
6084 | print STDERR "unable to cleanup '$volid' - $@" if $@; | |
6085 | } else { | |
6086 | print STDERR "unable to parse line in statfile - $line"; | |
6087 | } | |
6088 | } | |
6089 | $fd->close(); | |
6090 | } | |
6091 | } | |
6092 | ||
6093 | sub restore_file_archive { | |
6094 | my ($archive, $vmid, $user, $opts) = @_; | |
6095 | ||
6096 | return restore_vma_archive($archive, $vmid, $user, $opts) | |
6097 | if $archive eq '-'; | |
6098 | ||
6099 | my $info = PVE::Storage::archive_info($archive); | |
6100 | my $format = $opts->{format} // $info->{format}; | |
6101 | my $comp = $info->{compression}; | |
6102 | ||
6103 | # try to detect archive format | |
6104 | if ($format eq 'tar') { | |
6105 | return restore_tar_archive($archive, $vmid, $user, $opts); | |
6106 | } else { | |
6107 | return restore_vma_archive($archive, $vmid, $user, $opts, $comp); | |
6108 | } | |
6109 | } | |
6110 | ||
6111 | # hepler to remove disks that will not be used after restore | |
6112 | my $restore_cleanup_oldconf = sub { | |
6113 | my ($storecfg, $vmid, $oldconf, $virtdev_hash) = @_; | |
6114 | ||
6115 | PVE::QemuConfig->foreach_volume($oldconf, sub { | |
6116 | my ($ds, $drive) = @_; | |
6117 | ||
6118 | return if drive_is_cdrom($drive, 1); | |
6119 | ||
6120 | my $volid = $drive->{file}; | |
6121 | return if !$volid || $volid =~ m|^/|; | |
6122 | ||
6123 | my ($path, $owner) = PVE::Storage::path($storecfg, $volid); | |
6124 | return if !$path || !$owner || ($owner != $vmid); | |
6125 | ||
6126 | # Note: only delete disk we want to restore | |
6127 | # other volumes will become unused | |
6128 | if ($virtdev_hash->{$ds}) { | |
6129 | eval { PVE::Storage::vdisk_free($storecfg, $volid); }; | |
6130 | if (my $err = $@) { | |
6131 | warn $err; | |
6132 | } | |
6133 | } | |
6134 | }); | |
6135 | ||
6136 | # delete vmstate files, after the restore we have no snapshots anymore | |
6137 | foreach my $snapname (keys %{$oldconf->{snapshots}}) { | |
6138 | my $snap = $oldconf->{snapshots}->{$snapname}; | |
6139 | if ($snap->{vmstate}) { | |
6140 | eval { PVE::Storage::vdisk_free($storecfg, $snap->{vmstate}); }; | |
6141 | if (my $err = $@) { | |
6142 | warn $err; | |
6143 | } | |
6144 | } | |
6145 | } | |
6146 | }; | |
6147 | ||
6148 | # Helper to parse vzdump backup device hints | |
6149 | # | |
6150 | # $rpcenv: Environment, used to ckeck storage permissions | |
6151 | # $user: User ID, to check storage permissions | |
6152 | # $storecfg: Storage configuration | |
6153 | # $fh: the file handle for reading the configuration | |
6154 | # $devinfo: should contain device sizes for all backu-up'ed devices | |
6155 | # $options: backup options (pool, default storage) | |
6156 | # | |
6157 | # Return: $virtdev_hash, updates $devinfo (add devname, virtdev, format, storeid) | |
6158 | my $parse_backup_hints = sub { | |
6159 | my ($rpcenv, $user, $storecfg, $fh, $devinfo, $options) = @_; | |
6160 | ||
6161 | my $virtdev_hash = {}; | |
6162 | ||
6163 | while (defined(my $line = <$fh>)) { | |
6164 | if ($line =~ m/^\#qmdump\#map:(\S+):(\S+):(\S*):(\S*):$/) { | |
6165 | my ($virtdev, $devname, $storeid, $format) = ($1, $2, $3, $4); | |
6166 | die "archive does not contain data for drive '$virtdev'\n" | |
6167 | if !$devinfo->{$devname}; | |
6168 | ||
6169 | if (defined($options->{storage})) { | |
6170 | $storeid = $options->{storage} || 'local'; | |
6171 | } elsif (!$storeid) { | |
6172 | $storeid = 'local'; | |
6173 | } | |
6174 | $format = 'raw' if !$format; | |
6175 | $devinfo->{$devname}->{devname} = $devname; | |
6176 | $devinfo->{$devname}->{virtdev} = $virtdev; | |
6177 | $devinfo->{$devname}->{format} = $format; | |
6178 | $devinfo->{$devname}->{storeid} = $storeid; | |
6179 | ||
6180 | # check permission on storage | |
6181 | my $pool = $options->{pool}; # todo: do we need that? | |
6182 | if ($user ne 'root@pam') { | |
6183 | $rpcenv->check($user, "/storage/$storeid", ['Datastore.AllocateSpace']); | |
6184 | } | |
6185 | ||
6186 | $virtdev_hash->{$virtdev} = $devinfo->{$devname}; | |
6187 | } elsif ($line =~ m/^((?:ide|sata|scsi)\d+):\s*(.*)\s*$/) { | |
6188 | my $virtdev = $1; | |
6189 | my $drive = parse_drive($virtdev, $2); | |
6190 | if (drive_is_cloudinit($drive)) { | |
6191 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file}); | |
6192 | $storeid = $options->{storage} if defined ($options->{storage}); | |
6193 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
6194 | my $format = qemu_img_format($scfg, $volname); # has 'raw' fallback | |
6195 | ||
6196 | $virtdev_hash->{$virtdev} = { | |
6197 | format => $format, | |
6198 | storeid => $storeid, | |
6199 | size => PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE, | |
6200 | is_cloudinit => 1, | |
6201 | }; | |
6202 | } | |
6203 | } | |
6204 | } | |
6205 | ||
6206 | return $virtdev_hash; | |
6207 | }; | |
6208 | ||
6209 | # Helper to allocate and activate all volumes required for a restore | |
6210 | # | |
6211 | # $storecfg: Storage configuration | |
6212 | # $virtdev_hash: as returned by parse_backup_hints() | |
6213 | # | |
6214 | # Returns: { $virtdev => $volid } | |
6215 | my $restore_allocate_devices = sub { | |
6216 | my ($storecfg, $virtdev_hash, $vmid) = @_; | |
6217 | ||
6218 | my $map = {}; | |
6219 | foreach my $virtdev (sort keys %$virtdev_hash) { | |
6220 | my $d = $virtdev_hash->{$virtdev}; | |
6221 | my $alloc_size = int(($d->{size} + 1024 - 1)/1024); | |
6222 | my $storeid = $d->{storeid}; | |
6223 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
6224 | ||
6225 | # test if requested format is supported | |
6226 | my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid); | |
6227 | my $supported = grep { $_ eq $d->{format} } @$validFormats; | |
6228 | $d->{format} = $defFormat if !$supported; | |
6229 | ||
6230 | my $name; | |
6231 | if ($d->{is_cloudinit}) { | |
6232 | $name = "vm-$vmid-cloudinit"; | |
6233 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
6234 | if ($scfg->{path}) { | |
6235 | $name .= ".$d->{format}"; | |
6236 | } | |
6237 | } | |
6238 | ||
6239 | my $volid = PVE::Storage::vdisk_alloc( | |
6240 | $storecfg, $storeid, $vmid, $d->{format}, $name, $alloc_size); | |
6241 | ||
6242 | print STDERR "new volume ID is '$volid'\n"; | |
6243 | $d->{volid} = $volid; | |
6244 | ||
6245 | PVE::Storage::activate_volumes($storecfg, [$volid]); | |
6246 | ||
6247 | $map->{$virtdev} = $volid; | |
6248 | } | |
6249 | ||
6250 | return $map; | |
6251 | }; | |
6252 | ||
6253 | sub restore_update_config_line { | |
6254 | my ($cookie, $map, $line, $unique) = @_; | |
6255 | ||
6256 | return '' if $line =~ m/^\#qmdump\#/; | |
6257 | return '' if $line =~ m/^\#vzdump\#/; | |
6258 | return '' if $line =~ m/^lock:/; | |
6259 | return '' if $line =~ m/^unused\d+:/; | |
6260 | return '' if $line =~ m/^parent:/; | |
6261 | ||
6262 | my $res = ''; | |
6263 | ||
6264 | my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg'); | |
6265 | if (($line =~ m/^(vlan(\d+)):\s*(\S+)\s*$/)) { | |
6266 | # try to convert old 1.X settings | |
6267 | my ($id, $ind, $ethcfg) = ($1, $2, $3); | |
6268 | foreach my $devconfig (PVE::Tools::split_list($ethcfg)) { | |
6269 | my ($model, $macaddr) = split(/\=/, $devconfig); | |
6270 | $macaddr = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if !$macaddr || $unique; | |
6271 | my $net = { | |
6272 | model => $model, | |
6273 | bridge => "vmbr$ind", | |
6274 | macaddr => $macaddr, | |
6275 | }; | |
6276 | my $netstr = print_net($net); | |
6277 | ||
6278 | $res .= "net$cookie->{netcount}: $netstr\n"; | |
6279 | $cookie->{netcount}++; | |
6280 | } | |
6281 | } elsif (($line =~ m/^(net\d+):\s*(\S+)\s*$/) && $unique) { | |
6282 | my ($id, $netstr) = ($1, $2); | |
6283 | my $net = parse_net($netstr); | |
6284 | $net->{macaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix}) if $net->{macaddr}; | |
6285 | $netstr = print_net($net); | |
6286 | $res .= "$id: $netstr\n"; | |
6287 | } elsif ($line =~ m/^((ide|scsi|virtio|sata|efidisk|tpmstate)\d+):\s*(\S+)\s*$/) { | |
6288 | my $virtdev = $1; | |
6289 | my $value = $3; | |
6290 | my $di = parse_drive($virtdev, $value); | |
6291 | if (defined($di->{backup}) && !$di->{backup}) { | |
6292 | $res .= "#$line"; | |
6293 | } elsif ($map->{$virtdev}) { | |
6294 | delete $di->{format}; # format can change on restore | |
6295 | $di->{file} = $map->{$virtdev}; | |
6296 | $value = print_drive($di); | |
6297 | $res .= "$virtdev: $value\n"; | |
6298 | } else { | |
6299 | $res .= $line; | |
6300 | } | |
6301 | } elsif (($line =~ m/^vmgenid: (.*)/)) { | |
6302 | my $vmgenid = $1; | |
6303 | if ($vmgenid ne '0') { | |
6304 | # always generate a new vmgenid if there was a valid one setup | |
6305 | $vmgenid = generate_uuid(); | |
6306 | } | |
6307 | $res .= "vmgenid: $vmgenid\n"; | |
6308 | } elsif (($line =~ m/^(smbios1: )(.*)/) && $unique) { | |
6309 | my ($uuid, $uuid_str); | |
6310 | UUID::generate($uuid); | |
6311 | UUID::unparse($uuid, $uuid_str); | |
6312 | my $smbios1 = parse_smbios1($2); | |
6313 | $smbios1->{uuid} = $uuid_str; | |
6314 | $res .= $1.print_smbios1($smbios1)."\n"; | |
6315 | } else { | |
6316 | $res .= $line; | |
6317 | } | |
6318 | ||
6319 | return $res; | |
6320 | } | |
6321 | ||
6322 | my $restore_deactivate_volumes = sub { | |
6323 | my ($storecfg, $devinfo) = @_; | |
6324 | ||
6325 | my $vollist = []; | |
6326 | foreach my $devname (keys %$devinfo) { | |
6327 | my $volid = $devinfo->{$devname}->{volid}; | |
6328 | push @$vollist, $volid if $volid; | |
6329 | } | |
6330 | ||
6331 | PVE::Storage::deactivate_volumes($storecfg, $vollist); | |
6332 | }; | |
6333 | ||
6334 | my $restore_destroy_volumes = sub { | |
6335 | my ($storecfg, $devinfo) = @_; | |
6336 | ||
6337 | foreach my $devname (keys %$devinfo) { | |
6338 | my $volid = $devinfo->{$devname}->{volid}; | |
6339 | next if !$volid; | |
6340 | eval { | |
6341 | if ($volid =~ m|^/|) { | |
6342 | unlink $volid || die 'unlink failed\n'; | |
6343 | } else { | |
6344 | PVE::Storage::vdisk_free($storecfg, $volid); | |
6345 | } | |
6346 | print STDERR "temporary volume '$volid' sucessfuly removed\n"; | |
6347 | }; | |
6348 | print STDERR "unable to cleanup '$volid' - $@" if $@; | |
6349 | } | |
6350 | }; | |
6351 | ||
6352 | sub scan_volids { | |
6353 | my ($cfg, $vmid) = @_; | |
6354 | ||
6355 | my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'images'); | |
6356 | ||
6357 | my $volid_hash = {}; | |
6358 | foreach my $storeid (keys %$info) { | |
6359 | foreach my $item (@{$info->{$storeid}}) { | |
6360 | next if !($item->{volid} && $item->{size}); | |
6361 | $item->{path} = PVE::Storage::path($cfg, $item->{volid}); | |
6362 | $volid_hash->{$item->{volid}} = $item; | |
6363 | } | |
6364 | } | |
6365 | ||
6366 | return $volid_hash; | |
6367 | } | |
6368 | ||
6369 | sub update_disk_config { | |
6370 | my ($vmid, $conf, $volid_hash) = @_; | |
6371 | ||
6372 | my $changes; | |
6373 | my $prefix = "VM $vmid"; | |
6374 | ||
6375 | # used and unused disks | |
6376 | my $referenced = {}; | |
6377 | ||
6378 | # Note: it is allowed to define multiple storages with same path (alias), so | |
6379 | # we need to check both 'volid' and real 'path' (two different volid can point | |
6380 | # to the same path). | |
6381 | ||
6382 | my $referencedpath = {}; | |
6383 | ||
6384 | # update size info | |
6385 | PVE::QemuConfig->foreach_volume($conf, sub { | |
6386 | my ($opt, $drive) = @_; | |
6387 | ||
6388 | my $volid = $drive->{file}; | |
6389 | return if !$volid; | |
6390 | my $volume = $volid_hash->{$volid}; | |
6391 | ||
6392 | # mark volid as "in-use" for next step | |
6393 | $referenced->{$volid} = 1; | |
6394 | if ($volume && (my $path = $volume->{path})) { | |
6395 | $referencedpath->{$path} = 1; | |
6396 | } | |
6397 | ||
6398 | return if drive_is_cdrom($drive); | |
6399 | return if !$volume; | |
6400 | ||
6401 | my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $volume->{size}); | |
6402 | if (defined($updated)) { | |
6403 | $changes = 1; | |
6404 | $conf->{$opt} = print_drive($updated); | |
6405 | print "$prefix ($opt): $msg\n"; | |
6406 | } | |
6407 | }); | |
6408 | ||
6409 | # remove 'unusedX' entry if volume is used | |
6410 | PVE::QemuConfig->foreach_unused_volume($conf, sub { | |
6411 | my ($opt, $drive) = @_; | |
6412 | ||
6413 | my $volid = $drive->{file}; | |
6414 | return if !$volid; | |
6415 | ||
6416 | my $path; | |
6417 | $path = $volid_hash->{$volid}->{path} if $volid_hash->{$volid}; | |
6418 | if ($referenced->{$volid} || ($path && $referencedpath->{$path})) { | |
6419 | print "$prefix remove entry '$opt', its volume '$volid' is in use\n"; | |
6420 | $changes = 1; | |
6421 | delete $conf->{$opt}; | |
6422 | } | |
6423 | ||
6424 | $referenced->{$volid} = 1; | |
6425 | $referencedpath->{$path} = 1 if $path; | |
6426 | }); | |
6427 | ||
6428 | foreach my $volid (sort keys %$volid_hash) { | |
6429 | next if $volid =~ m/vm-$vmid-state-/; | |
6430 | next if $referenced->{$volid}; | |
6431 | my $path = $volid_hash->{$volid}->{path}; | |
6432 | next if !$path; # just to be sure | |
6433 | next if $referencedpath->{$path}; | |
6434 | $changes = 1; | |
6435 | my $key = PVE::QemuConfig->add_unused_volume($conf, $volid); | |
6436 | print "$prefix add unreferenced volume '$volid' as '$key' to config\n"; | |
6437 | $referencedpath->{$path} = 1; # avoid to add more than once (aliases) | |
6438 | } | |
6439 | ||
6440 | return $changes; | |
6441 | } | |
6442 | ||
6443 | sub rescan { | |
6444 | my ($vmid, $nolock, $dryrun) = @_; | |
6445 | ||
6446 | my $cfg = PVE::Storage::config(); | |
6447 | ||
6448 | print "rescan volumes...\n"; | |
6449 | my $volid_hash = scan_volids($cfg, $vmid); | |
6450 | ||
6451 | my $updatefn = sub { | |
6452 | my ($vmid) = @_; | |
6453 | ||
6454 | my $conf = PVE::QemuConfig->load_config($vmid); | |
6455 | ||
6456 | PVE::QemuConfig->check_lock($conf); | |
6457 | ||
6458 | my $vm_volids = {}; | |
6459 | foreach my $volid (keys %$volid_hash) { | |
6460 | my $info = $volid_hash->{$volid}; | |
6461 | $vm_volids->{$volid} = $info if $info->{vmid} && $info->{vmid} == $vmid; | |
6462 | } | |
6463 | ||
6464 | my $changes = update_disk_config($vmid, $conf, $vm_volids); | |
6465 | ||
6466 | PVE::QemuConfig->write_config($vmid, $conf) if $changes && !$dryrun; | |
6467 | }; | |
6468 | ||
6469 | if (defined($vmid)) { | |
6470 | if ($nolock) { | |
6471 | &$updatefn($vmid); | |
6472 | } else { | |
6473 | PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid); | |
6474 | } | |
6475 | } else { | |
6476 | my $vmlist = config_list(); | |
6477 | foreach my $vmid (keys %$vmlist) { | |
6478 | if ($nolock) { | |
6479 | &$updatefn($vmid); | |
6480 | } else { | |
6481 | PVE::QemuConfig->lock_config($vmid, $updatefn, $vmid); | |
6482 | } | |
6483 | } | |
6484 | } | |
6485 | } | |
6486 | ||
6487 | sub restore_proxmox_backup_archive { | |
6488 | my ($archive, $vmid, $user, $options) = @_; | |
6489 | ||
6490 | my $storecfg = PVE::Storage::config(); | |
6491 | ||
6492 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($archive); | |
6493 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
6494 | ||
6495 | my $fingerprint = $scfg->{fingerprint}; | |
6496 | my $keyfile = PVE::Storage::PBSPlugin::pbs_encryption_key_file_name($storecfg, $storeid); | |
6497 | ||
6498 | my $repo = PVE::PBSClient::get_repository($scfg); | |
6499 | ||
6500 | # This is only used for `pbs-restore` and the QEMU PBS driver (live-restore) | |
6501 | my $password = PVE::Storage::PBSPlugin::pbs_get_password($scfg, $storeid); | |
6502 | local $ENV{PBS_PASSWORD} = $password; | |
6503 | local $ENV{PBS_FINGERPRINT} = $fingerprint if defined($fingerprint); | |
6504 | ||
6505 | my ($vtype, $pbs_backup_name, undef, undef, undef, undef, $format) = | |
6506 | PVE::Storage::parse_volname($storecfg, $archive); | |
6507 | ||
6508 | die "got unexpected vtype '$vtype'\n" if $vtype ne 'backup'; | |
6509 | ||
6510 | die "got unexpected backup format '$format'\n" if $format ne 'pbs-vm'; | |
6511 | ||
6512 | my $tmpdir = "/var/tmp/vzdumptmp$$"; | |
6513 | rmtree $tmpdir; | |
6514 | mkpath $tmpdir; | |
6515 | ||
6516 | my $conffile = PVE::QemuConfig->config_file($vmid); | |
6517 | # disable interrupts (always do cleanups) | |
6518 | local $SIG{INT} = | |
6519 | local $SIG{TERM} = | |
6520 | local $SIG{QUIT} = | |
6521 | local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; }; | |
6522 | ||
6523 | # Note: $oldconf is undef if VM does not exists | |
6524 | my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid); | |
6525 | my $oldconf = PVE::Cluster::cfs_read_file($cfs_path); | |
6526 | my $new_conf_raw = ''; | |
6527 | ||
6528 | my $rpcenv = PVE::RPCEnvironment::get(); | |
6529 | my $devinfo = {}; | |
6530 | ||
6531 | eval { | |
6532 | # enable interrupts | |
6533 | local $SIG{INT} = | |
6534 | local $SIG{TERM} = | |
6535 | local $SIG{QUIT} = | |
6536 | local $SIG{HUP} = | |
6537 | local $SIG{PIPE} = sub { die "interrupted by signal\n"; }; | |
6538 | ||
6539 | my $cfgfn = "$tmpdir/qemu-server.conf"; | |
6540 | my $firewall_config_fn = "$tmpdir/fw.conf"; | |
6541 | my $index_fn = "$tmpdir/index.json"; | |
6542 | ||
6543 | my $cmd = "restore"; | |
6544 | ||
6545 | my $param = [$pbs_backup_name, "index.json", $index_fn]; | |
6546 | PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param); | |
6547 | my $index = PVE::Tools::file_get_contents($index_fn); | |
6548 | $index = decode_json($index); | |
6549 | ||
6550 | # print Dumper($index); | |
6551 | foreach my $info (@{$index->{files}}) { | |
6552 | if ($info->{filename} =~ m/^(drive-\S+).img.fidx$/) { | |
6553 | my $devname = $1; | |
6554 | if ($info->{size} =~ m/^(\d+)$/) { # untaint size | |
6555 | $devinfo->{$devname}->{size} = $1; | |
6556 | } else { | |
6557 | die "unable to parse file size in 'index.json' - got '$info->{size}'\n"; | |
6558 | } | |
6559 | } | |
6560 | } | |
6561 | ||
6562 | my $is_qemu_server_backup = scalar( | |
6563 | grep { $_->{filename} eq 'qemu-server.conf.blob' } @{$index->{files}} | |
6564 | ); | |
6565 | if (!$is_qemu_server_backup) { | |
6566 | die "backup does not look like a qemu-server backup (missing 'qemu-server.conf' file)\n"; | |
6567 | } | |
6568 | my $has_firewall_config = scalar(grep { $_->{filename} eq 'fw.conf.blob' } @{$index->{files}}); | |
6569 | ||
6570 | $param = [$pbs_backup_name, "qemu-server.conf", $cfgfn]; | |
6571 | PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param); | |
6572 | ||
6573 | if ($has_firewall_config) { | |
6574 | $param = [$pbs_backup_name, "fw.conf", $firewall_config_fn]; | |
6575 | PVE::Storage::PBSPlugin::run_raw_client_cmd($scfg, $storeid, $cmd, $param); | |
6576 | ||
6577 | my $pve_firewall_dir = '/etc/pve/firewall'; | |
6578 | mkdir $pve_firewall_dir; # make sure the dir exists | |
6579 | PVE::Tools::file_copy($firewall_config_fn, "${pve_firewall_dir}/$vmid.fw"); | |
6580 | } | |
6581 | ||
6582 | my $fh = IO::File->new($cfgfn, "r") || | |
6583 | die "unable to read qemu-server.conf - $!\n"; | |
6584 | ||
6585 | my $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $storecfg, $fh, $devinfo, $options); | |
6586 | ||
6587 | # fixme: rate limit? | |
6588 | ||
6589 | # create empty/temp config | |
6590 | PVE::Tools::file_set_contents($conffile, "memory: 128\nlock: create"); | |
6591 | ||
6592 | $restore_cleanup_oldconf->($storecfg, $vmid, $oldconf, $virtdev_hash) if $oldconf; | |
6593 | ||
6594 | # allocate volumes | |
6595 | my $map = $restore_allocate_devices->($storecfg, $virtdev_hash, $vmid); | |
6596 | ||
6597 | foreach my $virtdev (sort keys %$virtdev_hash) { | |
6598 | my $d = $virtdev_hash->{$virtdev}; | |
6599 | next if $d->{is_cloudinit}; # no need to restore cloudinit | |
6600 | ||
6601 | # this fails if storage is unavailable | |
6602 | my $volid = $d->{volid}; | |
6603 | my $path = PVE::Storage::path($storecfg, $volid); | |
6604 | ||
6605 | # for live-restore we only want to preload the efidisk and TPM state | |
6606 | next if $options->{live} && $virtdev ne 'efidisk0' && $virtdev ne 'tpmstate0'; | |
6607 | ||
6608 | my $pbs_restore_cmd = [ | |
6609 | '/usr/bin/pbs-restore', | |
6610 | '--repository', $repo, | |
6611 | $pbs_backup_name, | |
6612 | "$d->{devname}.img.fidx", | |
6613 | $path, | |
6614 | '--verbose', | |
6615 | ]; | |
6616 | ||
6617 | push @$pbs_restore_cmd, '--format', $d->{format} if $d->{format}; | |
6618 | push @$pbs_restore_cmd, '--keyfile', $keyfile if -e $keyfile; | |
6619 | ||
6620 | if (PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $volid)) { | |
6621 | push @$pbs_restore_cmd, '--skip-zero'; | |
6622 | } | |
6623 | ||
6624 | my $dbg_cmdstring = PVE::Tools::cmd2string($pbs_restore_cmd); | |
6625 | print "restore proxmox backup image: $dbg_cmdstring\n"; | |
6626 | run_command($pbs_restore_cmd); | |
6627 | } | |
6628 | ||
6629 | $fh->seek(0, 0) || die "seek failed - $!\n"; | |
6630 | ||
6631 | my $cookie = { netcount => 0 }; | |
6632 | while (defined(my $line = <$fh>)) { | |
6633 | $new_conf_raw .= restore_update_config_line( | |
6634 | $cookie, | |
6635 | $map, | |
6636 | $line, | |
6637 | $options->{unique}, | |
6638 | ); | |
6639 | } | |
6640 | ||
6641 | $fh->close(); | |
6642 | }; | |
6643 | my $err = $@; | |
6644 | ||
6645 | if ($err || !$options->{live}) { | |
6646 | $restore_deactivate_volumes->($storecfg, $devinfo); | |
6647 | } | |
6648 | ||
6649 | rmtree $tmpdir; | |
6650 | ||
6651 | if ($err) { | |
6652 | $restore_destroy_volumes->($storecfg, $devinfo); | |
6653 | die $err; | |
6654 | } | |
6655 | ||
6656 | if ($options->{live}) { | |
6657 | # keep lock during live-restore | |
6658 | $new_conf_raw .= "\nlock: create"; | |
6659 | } | |
6660 | ||
6661 | PVE::Tools::file_set_contents($conffile, $new_conf_raw); | |
6662 | ||
6663 | PVE::Cluster::cfs_update(); # make sure we read new file | |
6664 | ||
6665 | eval { rescan($vmid, 1); }; | |
6666 | warn $@ if $@; | |
6667 | ||
6668 | PVE::AccessControl::add_vm_to_pool($vmid, $options->{pool}) if $options->{pool}; | |
6669 | ||
6670 | if ($options->{live}) { | |
6671 | # enable interrupts | |
6672 | local $SIG{INT} = | |
6673 | local $SIG{TERM} = | |
6674 | local $SIG{QUIT} = | |
6675 | local $SIG{HUP} = | |
6676 | local $SIG{PIPE} = sub { die "got signal ($!) - abort\n"; }; | |
6677 | ||
6678 | my $conf = PVE::QemuConfig->load_config($vmid); | |
6679 | die "cannot do live-restore for template\n" if PVE::QemuConfig->is_template($conf); | |
6680 | ||
6681 | # these special drives are already restored before start | |
6682 | delete $devinfo->{'drive-efidisk0'}; | |
6683 | delete $devinfo->{'drive-tpmstate0-backup'}; | |
6684 | pbs_live_restore($vmid, $conf, $storecfg, $devinfo, $repo, $keyfile, $pbs_backup_name); | |
6685 | ||
6686 | PVE::QemuConfig->remove_lock($vmid, "create"); | |
6687 | } | |
6688 | } | |
6689 | ||
6690 | sub pbs_live_restore { | |
6691 | my ($vmid, $conf, $storecfg, $restored_disks, $repo, $keyfile, $snap) = @_; | |
6692 | ||
6693 | print "starting VM for live-restore\n"; | |
6694 | print "repository: '$repo', snapshot: '$snap'\n"; | |
6695 | ||
6696 | my $pbs_backing = {}; | |
6697 | for my $ds (keys %$restored_disks) { | |
6698 | $ds =~ m/^drive-(.*)$/; | |
6699 | my $confname = $1; | |
6700 | $pbs_backing->{$confname} = { | |
6701 | repository => $repo, | |
6702 | snapshot => $snap, | |
6703 | archive => "$ds.img.fidx", | |
6704 | }; | |
6705 | $pbs_backing->{$confname}->{keyfile} = $keyfile if -e $keyfile; | |
6706 | ||
6707 | my $drive = parse_drive($confname, $conf->{$confname}); | |
6708 | print "restoring '$ds' to '$drive->{file}'\n"; | |
6709 | } | |
6710 | ||
6711 | my $drives_streamed = 0; | |
6712 | eval { | |
6713 | # make sure HA doesn't interrupt our restore by stopping the VM | |
6714 | if (PVE::HA::Config::vm_is_ha_managed($vmid)) { | |
6715 | run_command(['ha-manager', 'set', "vm:$vmid", '--state', 'started']); | |
6716 | } | |
6717 | ||
6718 | # start VM with backing chain pointing to PBS backup, environment vars for PBS driver | |
6719 | # in QEMU (PBS_PASSWORD and PBS_FINGERPRINT) are already set by our caller | |
6720 | vm_start_nolock($storecfg, $vmid, $conf, {paused => 1, 'pbs-backing' => $pbs_backing}, {}); | |
6721 | ||
6722 | my $qmeventd_fd = register_qmeventd_handle($vmid); | |
6723 | ||
6724 | # begin streaming, i.e. data copy from PBS to target disk for every vol, | |
6725 | # this will effectively collapse the backing image chain consisting of | |
6726 | # [target <- alloc-track -> PBS snapshot] to just [target] (alloc-track | |
6727 | # removes itself once all backing images vanish with 'auto-remove=on') | |
6728 | my $jobs = {}; | |
6729 | for my $ds (sort keys %$restored_disks) { | |
6730 | my $job_id = "restore-$ds"; | |
6731 | mon_cmd($vmid, 'block-stream', | |
6732 | 'job-id' => $job_id, | |
6733 | device => "$ds", | |
6734 | ); | |
6735 | $jobs->{$job_id} = {}; | |
6736 | } | |
6737 | ||
6738 | mon_cmd($vmid, 'cont'); | |
6739 | qemu_drive_mirror_monitor($vmid, undef, $jobs, 'auto', 0, 'stream'); | |
6740 | ||
6741 | print "restore-drive jobs finished successfully, removing all tracking block devices" | |
6742 | ." to disconnect from Proxmox Backup Server\n"; | |
6743 | ||
6744 | for my $ds (sort keys %$restored_disks) { | |
6745 | mon_cmd($vmid, 'blockdev-del', 'node-name' => "$ds-pbs"); | |
6746 | } | |
6747 | ||
6748 | close($qmeventd_fd); | |
6749 | }; | |
6750 | ||
6751 | my $err = $@; | |
6752 | ||
6753 | if ($err) { | |
6754 | warn "An error occured during live-restore: $err\n"; | |
6755 | _do_vm_stop($storecfg, $vmid, 1, 1, 10, 0, 1); | |
6756 | die "live-restore failed\n"; | |
6757 | } | |
6758 | } | |
6759 | ||
6760 | sub restore_vma_archive { | |
6761 | my ($archive, $vmid, $user, $opts, $comp) = @_; | |
6762 | ||
6763 | my $readfrom = $archive; | |
6764 | ||
6765 | my $cfg = PVE::Storage::config(); | |
6766 | my $commands = []; | |
6767 | my $bwlimit = $opts->{bwlimit}; | |
6768 | ||
6769 | my $dbg_cmdstring = ''; | |
6770 | my $add_pipe = sub { | |
6771 | my ($cmd) = @_; | |
6772 | push @$commands, $cmd; | |
6773 | $dbg_cmdstring .= ' | ' if length($dbg_cmdstring); | |
6774 | $dbg_cmdstring .= PVE::Tools::cmd2string($cmd); | |
6775 | $readfrom = '-'; | |
6776 | }; | |
6777 | ||
6778 | my $input = undef; | |
6779 | if ($archive eq '-') { | |
6780 | $input = '<&STDIN'; | |
6781 | } else { | |
6782 | # If we use a backup from a PVE defined storage we also consider that | |
6783 | # storage's rate limit: | |
6784 | my (undef, $volid) = PVE::Storage::path_to_volume_id($cfg, $archive); | |
6785 | if (defined($volid)) { | |
6786 | my ($sid, undef) = PVE::Storage::parse_volume_id($volid); | |
6787 | my $readlimit = PVE::Storage::get_bandwidth_limit('restore', [$sid], $bwlimit); | |
6788 | if ($readlimit) { | |
6789 | print STDERR "applying read rate limit: $readlimit\n"; | |
6790 | my $cstream = ['cstream', '-t', $readlimit*1024, '--', $readfrom]; | |
6791 | $add_pipe->($cstream); | |
6792 | } | |
6793 | } | |
6794 | } | |
6795 | ||
6796 | if ($comp) { | |
6797 | my $info = PVE::Storage::decompressor_info('vma', $comp); | |
6798 | my $cmd = $info->{decompressor}; | |
6799 | push @$cmd, $readfrom; | |
6800 | $add_pipe->($cmd); | |
6801 | } | |
6802 | ||
6803 | my $tmpdir = "/var/tmp/vzdumptmp$$"; | |
6804 | rmtree $tmpdir; | |
6805 | ||
6806 | # disable interrupts (always do cleanups) | |
6807 | local $SIG{INT} = | |
6808 | local $SIG{TERM} = | |
6809 | local $SIG{QUIT} = | |
6810 | local $SIG{HUP} = sub { warn "got interrupt - ignored\n"; }; | |
6811 | ||
6812 | my $mapfifo = "/var/tmp/vzdumptmp$$.fifo"; | |
6813 | POSIX::mkfifo($mapfifo, 0600); | |
6814 | my $fifofh; | |
6815 | my $openfifo = sub { open($fifofh, '>', $mapfifo) or die $! }; | |
6816 | ||
6817 | $add_pipe->(['vma', 'extract', '-v', '-r', $mapfifo, $readfrom, $tmpdir]); | |
6818 | ||
6819 | my $oldtimeout; | |
6820 | my $timeout = 5; | |
6821 | ||
6822 | my $devinfo = {}; | |
6823 | ||
6824 | my $rpcenv = PVE::RPCEnvironment::get(); | |
6825 | ||
6826 | my $conffile = PVE::QemuConfig->config_file($vmid); | |
6827 | ||
6828 | # Note: $oldconf is undef if VM does not exist | |
6829 | my $cfs_path = PVE::QemuConfig->cfs_config_path($vmid); | |
6830 | my $oldconf = PVE::Cluster::cfs_read_file($cfs_path); | |
6831 | my $new_conf_raw = ''; | |
6832 | ||
6833 | my %storage_limits; | |
6834 | ||
6835 | my $print_devmap = sub { | |
6836 | my $cfgfn = "$tmpdir/qemu-server.conf"; | |
6837 | ||
6838 | # we can read the config - that is already extracted | |
6839 | my $fh = IO::File->new($cfgfn, "r") || | |
6840 | die "unable to read qemu-server.conf - $!\n"; | |
6841 | ||
6842 | my $fwcfgfn = "$tmpdir/qemu-server.fw"; | |
6843 | if (-f $fwcfgfn) { | |
6844 | my $pve_firewall_dir = '/etc/pve/firewall'; | |
6845 | mkdir $pve_firewall_dir; # make sure the dir exists | |
6846 | PVE::Tools::file_copy($fwcfgfn, "${pve_firewall_dir}/$vmid.fw"); | |
6847 | } | |
6848 | ||
6849 | my $virtdev_hash = $parse_backup_hints->($rpcenv, $user, $cfg, $fh, $devinfo, $opts); | |
6850 | ||
6851 | foreach my $info (values %{$virtdev_hash}) { | |
6852 | my $storeid = $info->{storeid}; | |
6853 | next if defined($storage_limits{$storeid}); | |
6854 | ||
6855 | my $limit = PVE::Storage::get_bandwidth_limit('restore', [$storeid], $bwlimit) // 0; | |
6856 | print STDERR "rate limit for storage $storeid: $limit KiB/s\n" if $limit; | |
6857 | $storage_limits{$storeid} = $limit * 1024; | |
6858 | } | |
6859 | ||
6860 | foreach my $devname (keys %$devinfo) { | |
6861 | die "found no device mapping information for device '$devname'\n" | |
6862 | if !$devinfo->{$devname}->{virtdev}; | |
6863 | } | |
6864 | ||
6865 | # create empty/temp config | |
6866 | if ($oldconf) { | |
6867 | PVE::Tools::file_set_contents($conffile, "memory: 128\n"); | |
6868 | $restore_cleanup_oldconf->($cfg, $vmid, $oldconf, $virtdev_hash); | |
6869 | } | |
6870 | ||
6871 | # allocate volumes | |
6872 | my $map = $restore_allocate_devices->($cfg, $virtdev_hash, $vmid); | |
6873 | ||
6874 | # print restore information to $fifofh | |
6875 | foreach my $virtdev (sort keys %$virtdev_hash) { | |
6876 | my $d = $virtdev_hash->{$virtdev}; | |
6877 | next if $d->{is_cloudinit}; # no need to restore cloudinit | |
6878 | ||
6879 | my $storeid = $d->{storeid}; | |
6880 | my $volid = $d->{volid}; | |
6881 | ||
6882 | my $map_opts = ''; | |
6883 | if (my $limit = $storage_limits{$storeid}) { | |
6884 | $map_opts .= "throttling.bps=$limit:throttling.group=$storeid:"; | |
6885 | } | |
6886 | ||
6887 | my $write_zeros = 1; | |
6888 | if (PVE::Storage::volume_has_feature($cfg, 'sparseinit', $volid)) { | |
6889 | $write_zeros = 0; | |
6890 | } | |
6891 | ||
6892 | my $path = PVE::Storage::path($cfg, $volid); | |
6893 | ||
6894 | print $fifofh "${map_opts}format=$d->{format}:${write_zeros}:$d->{devname}=$path\n"; | |
6895 | ||
6896 | print "map '$d->{devname}' to '$path' (write zeros = ${write_zeros})\n"; | |
6897 | } | |
6898 | ||
6899 | $fh->seek(0, 0) || die "seek failed - $!\n"; | |
6900 | ||
6901 | my $cookie = { netcount => 0 }; | |
6902 | while (defined(my $line = <$fh>)) { | |
6903 | $new_conf_raw .= restore_update_config_line( | |
6904 | $cookie, | |
6905 | $map, | |
6906 | $line, | |
6907 | $opts->{unique}, | |
6908 | ); | |
6909 | } | |
6910 | ||
6911 | $fh->close(); | |
6912 | }; | |
6913 | ||
6914 | eval { | |
6915 | # enable interrupts | |
6916 | local $SIG{INT} = | |
6917 | local $SIG{TERM} = | |
6918 | local $SIG{QUIT} = | |
6919 | local $SIG{HUP} = | |
6920 | local $SIG{PIPE} = sub { die "interrupted by signal\n"; }; | |
6921 | local $SIG{ALRM} = sub { die "got timeout\n"; }; | |
6922 | ||
6923 | $oldtimeout = alarm($timeout); | |
6924 | ||
6925 | my $parser = sub { | |
6926 | my $line = shift; | |
6927 | ||
6928 | print "$line\n"; | |
6929 | ||
6930 | if ($line =~ m/^DEV:\sdev_id=(\d+)\ssize:\s(\d+)\sdevname:\s(\S+)$/) { | |
6931 | my ($dev_id, $size, $devname) = ($1, $2, $3); | |
6932 | $devinfo->{$devname} = { size => $size, dev_id => $dev_id }; | |
6933 | } elsif ($line =~ m/^CTIME: /) { | |
6934 | # we correctly received the vma config, so we can disable | |
6935 | # the timeout now for disk allocation (set to 10 minutes, so | |
6936 | # that we always timeout if something goes wrong) | |
6937 | alarm(600); | |
6938 | &$print_devmap(); | |
6939 | print $fifofh "done\n"; | |
6940 | my $tmp = $oldtimeout || 0; | |
6941 | $oldtimeout = undef; | |
6942 | alarm($tmp); | |
6943 | close($fifofh); | |
6944 | $fifofh = undef; | |
6945 | } | |
6946 | }; | |
6947 | ||
6948 | print "restore vma archive: $dbg_cmdstring\n"; | |
6949 | run_command($commands, input => $input, outfunc => $parser, afterfork => $openfifo); | |
6950 | }; | |
6951 | my $err = $@; | |
6952 | ||
6953 | alarm($oldtimeout) if $oldtimeout; | |
6954 | ||
6955 | $restore_deactivate_volumes->($cfg, $devinfo); | |
6956 | ||
6957 | close($fifofh) if $fifofh; | |
6958 | unlink $mapfifo; | |
6959 | rmtree $tmpdir; | |
6960 | ||
6961 | if ($err) { | |
6962 | $restore_destroy_volumes->($cfg, $devinfo); | |
6963 | die $err; | |
6964 | } | |
6965 | ||
6966 | PVE::Tools::file_set_contents($conffile, $new_conf_raw); | |
6967 | ||
6968 | PVE::Cluster::cfs_update(); # make sure we read new file | |
6969 | ||
6970 | eval { rescan($vmid, 1); }; | |
6971 | warn $@ if $@; | |
6972 | ||
6973 | PVE::AccessControl::add_vm_to_pool($vmid, $opts->{pool}) if $opts->{pool}; | |
6974 | } | |
6975 | ||
6976 | sub restore_tar_archive { | |
6977 | my ($archive, $vmid, $user, $opts) = @_; | |
6978 | ||
6979 | if ($archive ne '-') { | |
6980 | my $firstfile = tar_archive_read_firstfile($archive); | |
6981 | die "ERROR: file '$archive' does not look like a QemuServer vzdump backup\n" | |
6982 | if $firstfile ne 'qemu-server.conf'; | |
6983 | } | |
6984 | ||
6985 | my $storecfg = PVE::Storage::config(); | |
6986 | ||
6987 | # avoid zombie disks when restoring over an existing VM -> cleanup first | |
6988 | # pass keep_empty_config=1 to keep the config (thus VMID) reserved for us | |
6989 | # skiplock=1 because qmrestore has set the 'create' lock itself already | |
6990 | my $vmcfgfn = PVE::QemuConfig->config_file($vmid); | |
6991 | destroy_vm($storecfg, $vmid, 1, { lock => 'restore' }) if -f $vmcfgfn; | |
6992 | ||
6993 | my $tocmd = "/usr/lib/qemu-server/qmextract"; | |
6994 | ||
6995 | $tocmd .= " --storage " . PVE::Tools::shellquote($opts->{storage}) if $opts->{storage}; | |
6996 | $tocmd .= " --pool " . PVE::Tools::shellquote($opts->{pool}) if $opts->{pool}; | |
6997 | $tocmd .= ' --prealloc' if $opts->{prealloc}; | |
6998 | $tocmd .= ' --info' if $opts->{info}; | |
6999 | ||
7000 | # tar option "xf" does not autodetect compression when read from STDIN, | |
7001 | # so we pipe to zcat | |
7002 | my $cmd = "zcat -f|tar xf " . PVE::Tools::shellquote($archive) . " " . | |
7003 | PVE::Tools::shellquote("--to-command=$tocmd"); | |
7004 | ||
7005 | my $tmpdir = "/var/tmp/vzdumptmp$$"; | |
7006 | mkpath $tmpdir; | |
7007 | ||
7008 | local $ENV{VZDUMP_TMPDIR} = $tmpdir; | |
7009 | local $ENV{VZDUMP_VMID} = $vmid; | |
7010 | local $ENV{VZDUMP_USER} = $user; | |
7011 | ||
7012 | my $conffile = PVE::QemuConfig->config_file($vmid); | |
7013 | my $new_conf_raw = ''; | |
7014 | ||
7015 | # disable interrupts (always do cleanups) | |
7016 | local $SIG{INT} = | |
7017 | local $SIG{TERM} = | |
7018 | local $SIG{QUIT} = | |
7019 | local $SIG{HUP} = sub { print STDERR "got interrupt - ignored\n"; }; | |
7020 | ||
7021 | eval { | |
7022 | # enable interrupts | |
7023 | local $SIG{INT} = | |
7024 | local $SIG{TERM} = | |
7025 | local $SIG{QUIT} = | |
7026 | local $SIG{HUP} = | |
7027 | local $SIG{PIPE} = sub { die "interrupted by signal\n"; }; | |
7028 | ||
7029 | if ($archive eq '-') { | |
7030 | print "extracting archive from STDIN\n"; | |
7031 | run_command($cmd, input => "<&STDIN"); | |
7032 | } else { | |
7033 | print "extracting archive '$archive'\n"; | |
7034 | run_command($cmd); | |
7035 | } | |
7036 | ||
7037 | return if $opts->{info}; | |
7038 | ||
7039 | # read new mapping | |
7040 | my $map = {}; | |
7041 | my $statfile = "$tmpdir/qmrestore.stat"; | |
7042 | if (my $fd = IO::File->new($statfile, "r")) { | |
7043 | while (defined (my $line = <$fd>)) { | |
7044 | if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) { | |
7045 | $map->{$1} = $2 if $1; | |
7046 | } else { | |
7047 | print STDERR "unable to parse line in statfile - $line\n"; | |
7048 | } | |
7049 | } | |
7050 | $fd->close(); | |
7051 | } | |
7052 | ||
7053 | my $confsrc = "$tmpdir/qemu-server.conf"; | |
7054 | ||
7055 | my $srcfd = IO::File->new($confsrc, "r") || die "unable to open file '$confsrc'\n"; | |
7056 | ||
7057 | my $cookie = { netcount => 0 }; | |
7058 | while (defined (my $line = <$srcfd>)) { | |
7059 | $new_conf_raw .= restore_update_config_line( | |
7060 | $cookie, | |
7061 | $map, | |
7062 | $line, | |
7063 | $opts->{unique}, | |
7064 | ); | |
7065 | } | |
7066 | ||
7067 | $srcfd->close(); | |
7068 | }; | |
7069 | if (my $err = $@) { | |
7070 | tar_restore_cleanup($storecfg, "$tmpdir/qmrestore.stat") if !$opts->{info}; | |
7071 | die $err; | |
7072 | } | |
7073 | ||
7074 | rmtree $tmpdir; | |
7075 | ||
7076 | PVE::Tools::file_set_contents($conffile, $new_conf_raw); | |
7077 | ||
7078 | PVE::Cluster::cfs_update(); # make sure we read new file | |
7079 | ||
7080 | eval { rescan($vmid, 1); }; | |
7081 | warn $@ if $@; | |
7082 | }; | |
7083 | ||
7084 | sub foreach_storage_used_by_vm { | |
7085 | my ($conf, $func) = @_; | |
7086 | ||
7087 | my $sidhash = {}; | |
7088 | ||
7089 | PVE::QemuConfig->foreach_volume($conf, sub { | |
7090 | my ($ds, $drive) = @_; | |
7091 | return if drive_is_cdrom($drive); | |
7092 | ||
7093 | my $volid = $drive->{file}; | |
7094 | ||
7095 | my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1); | |
7096 | $sidhash->{$sid} = $sid if $sid; | |
7097 | }); | |
7098 | ||
7099 | foreach my $sid (sort keys %$sidhash) { | |
7100 | &$func($sid); | |
7101 | } | |
7102 | } | |
7103 | ||
7104 | my $qemu_snap_storage = { | |
7105 | rbd => 1, | |
7106 | }; | |
7107 | sub do_snapshots_with_qemu { | |
7108 | my ($storecfg, $volid, $deviceid) = @_; | |
7109 | ||
7110 | return if $deviceid =~ m/tpmstate0/; | |
7111 | ||
7112 | my $storage_name = PVE::Storage::parse_volume_id($volid); | |
7113 | my $scfg = $storecfg->{ids}->{$storage_name}; | |
7114 | die "could not find storage '$storage_name'\n" if !defined($scfg); | |
7115 | ||
7116 | if ($qemu_snap_storage->{$scfg->{type}} && !$scfg->{krbd}){ | |
7117 | return 1; | |
7118 | } | |
7119 | ||
7120 | if ($volid =~ m/\.(qcow2|qed)$/){ | |
7121 | return 1; | |
7122 | } | |
7123 | ||
7124 | return; | |
7125 | } | |
7126 | ||
7127 | sub qga_check_running { | |
7128 | my ($vmid, $nowarn) = @_; | |
7129 | ||
7130 | eval { mon_cmd($vmid, "guest-ping", timeout => 3); }; | |
7131 | if ($@) { | |
7132 | warn "Qemu Guest Agent is not running - $@" if !$nowarn; | |
7133 | return 0; | |
7134 | } | |
7135 | return 1; | |
7136 | } | |
7137 | ||
7138 | sub template_create { | |
7139 | my ($vmid, $conf, $disk) = @_; | |
7140 | ||
7141 | my $storecfg = PVE::Storage::config(); | |
7142 | ||
7143 | PVE::QemuConfig->foreach_volume($conf, sub { | |
7144 | my ($ds, $drive) = @_; | |
7145 | ||
7146 | return if drive_is_cdrom($drive); | |
7147 | return if $disk && $ds ne $disk; | |
7148 | ||
7149 | my $volid = $drive->{file}; | |
7150 | return if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid); | |
7151 | ||
7152 | my $voliddst = PVE::Storage::vdisk_create_base($storecfg, $volid); | |
7153 | $drive->{file} = $voliddst; | |
7154 | $conf->{$ds} = print_drive($drive); | |
7155 | PVE::QemuConfig->write_config($vmid, $conf); | |
7156 | }); | |
7157 | } | |
7158 | ||
7159 | sub convert_iscsi_path { | |
7160 | my ($path) = @_; | |
7161 | ||
7162 | if ($path =~ m|^iscsi://([^/]+)/([^/]+)/(.+)$|) { | |
7163 | my $portal = $1; | |
7164 | my $target = $2; | |
7165 | my $lun = $3; | |
7166 | ||
7167 | my $initiator_name = get_initiator_name(); | |
7168 | ||
7169 | return "file.driver=iscsi,file.transport=tcp,file.initiator-name=$initiator_name,". | |
7170 | "file.portal=$portal,file.target=$target,file.lun=$lun,driver=raw"; | |
7171 | } | |
7172 | ||
7173 | die "cannot convert iscsi path '$path', unkown format\n"; | |
7174 | } | |
7175 | ||
7176 | sub qemu_img_convert { | |
7177 | my ($src_volid, $dst_volid, $size, $snapname, $is_zero_initialized) = @_; | |
7178 | ||
7179 | my $storecfg = PVE::Storage::config(); | |
7180 | my ($src_storeid, $src_volname) = PVE::Storage::parse_volume_id($src_volid, 1); | |
7181 | my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid, 1); | |
7182 | ||
7183 | die "destination '$dst_volid' is not a valid volid form qemu-img convert\n" if !$dst_storeid; | |
7184 | ||
7185 | my $cachemode; | |
7186 | my $src_path; | |
7187 | my $src_is_iscsi = 0; | |
7188 | my $src_format; | |
7189 | ||
7190 | if ($src_storeid) { | |
7191 | PVE::Storage::activate_volumes($storecfg, [$src_volid], $snapname); | |
7192 | my $src_scfg = PVE::Storage::storage_config($storecfg, $src_storeid); | |
7193 | $src_format = qemu_img_format($src_scfg, $src_volname); | |
7194 | $src_path = PVE::Storage::path($storecfg, $src_volid, $snapname); | |
7195 | $src_is_iscsi = ($src_path =~ m|^iscsi://|); | |
7196 | $cachemode = 'none' if $src_scfg->{type} eq 'zfspool'; | |
7197 | } elsif (-f $src_volid) { | |
7198 | $src_path = $src_volid; | |
7199 | if ($src_path =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) { | |
7200 | $src_format = $1; | |
7201 | } | |
7202 | } | |
7203 | ||
7204 | die "source '$src_volid' is not a valid volid nor path for qemu-img convert\n" if !$src_path; | |
7205 | ||
7206 | my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid); | |
7207 | my $dst_format = qemu_img_format($dst_scfg, $dst_volname); | |
7208 | my $dst_path = PVE::Storage::path($storecfg, $dst_volid); | |
7209 | my $dst_is_iscsi = ($dst_path =~ m|^iscsi://|); | |
7210 | ||
7211 | my $cmd = []; | |
7212 | push @$cmd, '/usr/bin/qemu-img', 'convert', '-p', '-n'; | |
7213 | push @$cmd, '-l', "snapshot.name=$snapname" | |
7214 | if $snapname && $src_format && $src_format eq "qcow2"; | |
7215 | push @$cmd, '-t', 'none' if $dst_scfg->{type} eq 'zfspool'; | |
7216 | push @$cmd, '-T', $cachemode if defined($cachemode); | |
7217 | ||
7218 | if ($src_is_iscsi) { | |
7219 | push @$cmd, '--image-opts'; | |
7220 | $src_path = convert_iscsi_path($src_path); | |
7221 | } elsif ($src_format) { | |
7222 | push @$cmd, '-f', $src_format; | |
7223 | } | |
7224 | ||
7225 | if ($dst_is_iscsi) { | |
7226 | push @$cmd, '--target-image-opts'; | |
7227 | $dst_path = convert_iscsi_path($dst_path); | |
7228 | } else { | |
7229 | push @$cmd, '-O', $dst_format; | |
7230 | } | |
7231 | ||
7232 | push @$cmd, $src_path; | |
7233 | ||
7234 | if (!$dst_is_iscsi && $is_zero_initialized) { | |
7235 | push @$cmd, "zeroinit:$dst_path"; | |
7236 | } else { | |
7237 | push @$cmd, $dst_path; | |
7238 | } | |
7239 | ||
7240 | my $parser = sub { | |
7241 | my $line = shift; | |
7242 | if($line =~ m/\((\S+)\/100\%\)/){ | |
7243 | my $percent = $1; | |
7244 | my $transferred = int($size * $percent / 100); | |
7245 | my $total_h = render_bytes($size, 1); | |
7246 | my $transferred_h = render_bytes($transferred, 1); | |
7247 | ||
7248 | print "transferred $transferred_h of $total_h ($percent%)\n"; | |
7249 | } | |
7250 | ||
7251 | }; | |
7252 | ||
7253 | eval { run_command($cmd, timeout => undef, outfunc => $parser); }; | |
7254 | my $err = $@; | |
7255 | die "copy failed: $err" if $err; | |
7256 | } | |
7257 | ||
7258 | sub qemu_img_format { | |
7259 | my ($scfg, $volname) = @_; | |
7260 | ||
7261 | if ($scfg->{path} && $volname =~ m/\.($PVE::QemuServer::Drive::QEMU_FORMAT_RE)$/) { | |
7262 | return $1; | |
7263 | } else { | |
7264 | return "raw"; | |
7265 | } | |
7266 | } | |
7267 | ||
7268 | sub qemu_drive_mirror { | |
7269 | my ($vmid, $drive, $dst_volid, $vmiddst, $is_zero_initialized, $jobs, $completion, $qga, $bwlimit, $src_bitmap) = @_; | |
7270 | ||
7271 | $jobs = {} if !$jobs; | |
7272 | ||
7273 | my $qemu_target; | |
7274 | my $format; | |
7275 | $jobs->{"drive-$drive"} = {}; | |
7276 | ||
7277 | if ($dst_volid =~ /^nbd:/) { | |
7278 | $qemu_target = $dst_volid; | |
7279 | $format = "nbd"; | |
7280 | } else { | |
7281 | my $storecfg = PVE::Storage::config(); | |
7282 | my ($dst_storeid, $dst_volname) = PVE::Storage::parse_volume_id($dst_volid); | |
7283 | ||
7284 | my $dst_scfg = PVE::Storage::storage_config($storecfg, $dst_storeid); | |
7285 | ||
7286 | $format = qemu_img_format($dst_scfg, $dst_volname); | |
7287 | ||
7288 | my $dst_path = PVE::Storage::path($storecfg, $dst_volid); | |
7289 | ||
7290 | $qemu_target = $is_zero_initialized ? "zeroinit:$dst_path" : $dst_path; | |
7291 | } | |
7292 | ||
7293 | my $opts = { timeout => 10, device => "drive-$drive", mode => "existing", sync => "full", target => $qemu_target }; | |
7294 | $opts->{format} = $format if $format; | |
7295 | ||
7296 | if (defined($src_bitmap)) { | |
7297 | $opts->{sync} = 'incremental'; | |
7298 | $opts->{bitmap} = $src_bitmap; | |
7299 | print "drive mirror re-using dirty bitmap '$src_bitmap'\n"; | |
7300 | } | |
7301 | ||
7302 | if (defined($bwlimit)) { | |
7303 | $opts->{speed} = $bwlimit * 1024; | |
7304 | print "drive mirror is starting for drive-$drive with bandwidth limit: ${bwlimit} KB/s\n"; | |
7305 | } else { | |
7306 | print "drive mirror is starting for drive-$drive\n"; | |
7307 | } | |
7308 | ||
7309 | # if a job already runs for this device we get an error, catch it for cleanup | |
7310 | eval { mon_cmd($vmid, "drive-mirror", %$opts); }; | |
7311 | if (my $err = $@) { | |
7312 | eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) }; | |
7313 | warn "$@\n" if $@; | |
7314 | die "mirroring error: $err\n"; | |
7315 | } | |
7316 | ||
7317 | qemu_drive_mirror_monitor ($vmid, $vmiddst, $jobs, $completion, $qga); | |
7318 | } | |
7319 | ||
7320 | # $completion can be either | |
7321 | # 'complete': wait until all jobs are ready, block-job-complete them (default) | |
7322 | # 'cancel': wait until all jobs are ready, block-job-cancel them | |
7323 | # 'skip': wait until all jobs are ready, return with block jobs in ready state | |
7324 | # 'auto': wait until all jobs disappear, only use for jobs which complete automatically | |
7325 | sub qemu_drive_mirror_monitor { | |
7326 | my ($vmid, $vmiddst, $jobs, $completion, $qga, $op) = @_; | |
7327 | ||
7328 | $completion //= 'complete'; | |
7329 | $op //= "mirror"; | |
7330 | ||
7331 | eval { | |
7332 | my $err_complete = 0; | |
7333 | ||
7334 | my $starttime = time (); | |
7335 | while (1) { | |
7336 | die "block job ('$op') timed out\n" if $err_complete > 300; | |
7337 | ||
7338 | my $stats = mon_cmd($vmid, "query-block-jobs"); | |
7339 | my $ctime = time(); | |
7340 | ||
7341 | my $running_jobs = {}; | |
7342 | for my $stat (@$stats) { | |
7343 | next if $stat->{type} ne $op; | |
7344 | $running_jobs->{$stat->{device}} = $stat; | |
7345 | } | |
7346 | ||
7347 | my $readycounter = 0; | |
7348 | ||
7349 | for my $job_id (sort keys %$jobs) { | |
7350 | my $job = $running_jobs->{$job_id}; | |
7351 | ||
7352 | my $vanished = !defined($job); | |
7353 | my $complete = defined($jobs->{$job_id}->{complete}) && $vanished; | |
7354 | if($complete || ($vanished && $completion eq 'auto')) { | |
7355 | print "$job_id: $op-job finished\n"; | |
7356 | delete $jobs->{$job_id}; | |
7357 | next; | |
7358 | } | |
7359 | ||
7360 | die "$job_id: '$op' has been cancelled\n" if !defined($job); | |
7361 | ||
7362 | my $busy = $job->{busy}; | |
7363 | my $ready = $job->{ready}; | |
7364 | if (my $total = $job->{len}) { | |
7365 | my $transferred = $job->{offset} || 0; | |
7366 | my $remaining = $total - $transferred; | |
7367 | my $percent = sprintf "%.2f", ($transferred * 100 / $total); | |
7368 | ||
7369 | my $duration = $ctime - $starttime; | |
7370 | my $total_h = render_bytes($total, 1); | |
7371 | my $transferred_h = render_bytes($transferred, 1); | |
7372 | ||
7373 | my $status = sprintf( | |
7374 | "transferred $transferred_h of $total_h ($percent%%) in %s", | |
7375 | render_duration($duration), | |
7376 | ); | |
7377 | ||
7378 | if ($ready) { | |
7379 | if ($busy) { | |
7380 | $status .= ", still busy"; # shouldn't even happen? but mirror is weird | |
7381 | } else { | |
7382 | $status .= ", ready"; | |
7383 | } | |
7384 | } | |
7385 | print "$job_id: $status\n" if !$jobs->{$job_id}->{ready}; | |
7386 | $jobs->{$job_id}->{ready} = $ready; | |
7387 | } | |
7388 | ||
7389 | $readycounter++ if $job->{ready}; | |
7390 | } | |
7391 | ||
7392 | last if scalar(keys %$jobs) == 0; | |
7393 | ||
7394 | if ($readycounter == scalar(keys %$jobs)) { | |
7395 | print "all '$op' jobs are ready\n"; | |
7396 | ||
7397 | # do the complete later (or has already been done) | |
7398 | last if $completion eq 'skip' || $completion eq 'auto'; | |
7399 | ||
7400 | if ($vmiddst && $vmiddst != $vmid) { | |
7401 | my $agent_running = $qga && qga_check_running($vmid); | |
7402 | if ($agent_running) { | |
7403 | print "freeze filesystem\n"; | |
7404 | eval { mon_cmd($vmid, "guest-fsfreeze-freeze"); }; | |
7405 | } else { | |
7406 | print "suspend vm\n"; | |
7407 | eval { PVE::QemuServer::vm_suspend($vmid, 1); }; | |
7408 | } | |
7409 | ||
7410 | # if we clone a disk for a new target vm, we don't switch the disk | |
7411 | PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs); | |
7412 | ||
7413 | if ($agent_running) { | |
7414 | print "unfreeze filesystem\n"; | |
7415 | eval { mon_cmd($vmid, "guest-fsfreeze-thaw"); }; | |
7416 | } else { | |
7417 | print "resume vm\n"; | |
7418 | eval { PVE::QemuServer::vm_resume($vmid, 1, 1); }; | |
7419 | } | |
7420 | ||
7421 | last; | |
7422 | } else { | |
7423 | ||
7424 | for my $job_id (sort keys %$jobs) { | |
7425 | # try to switch the disk if source and destination are on the same guest | |
7426 | print "$job_id: Completing block job_id...\n"; | |
7427 | ||
7428 | my $op; | |
7429 | if ($completion eq 'complete') { | |
7430 | $op = 'block-job-complete'; | |
7431 | } elsif ($completion eq 'cancel') { | |
7432 | $op = 'block-job-cancel'; | |
7433 | } else { | |
7434 | die "invalid completion value: $completion\n"; | |
7435 | } | |
7436 | eval { mon_cmd($vmid, $op, device => $job_id) }; | |
7437 | if ($@ =~ m/cannot be completed/) { | |
7438 | print "$job_id: block job cannot be completed, trying again.\n"; | |
7439 | $err_complete++; | |
7440 | }else { | |
7441 | print "$job_id: Completed successfully.\n"; | |
7442 | $jobs->{$job_id}->{complete} = 1; | |
7443 | } | |
7444 | } | |
7445 | } | |
7446 | } | |
7447 | sleep 1; | |
7448 | } | |
7449 | }; | |
7450 | my $err = $@; | |
7451 | ||
7452 | if ($err) { | |
7453 | eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $jobs) }; | |
7454 | die "block job ($op) error: $err"; | |
7455 | } | |
7456 | } | |
7457 | ||
7458 | sub qemu_blockjobs_cancel { | |
7459 | my ($vmid, $jobs) = @_; | |
7460 | ||
7461 | foreach my $job (keys %$jobs) { | |
7462 | print "$job: Cancelling block job\n"; | |
7463 | eval { mon_cmd($vmid, "block-job-cancel", device => $job); }; | |
7464 | $jobs->{$job}->{cancel} = 1; | |
7465 | } | |
7466 | ||
7467 | while (1) { | |
7468 | my $stats = mon_cmd($vmid, "query-block-jobs"); | |
7469 | ||
7470 | my $running_jobs = {}; | |
7471 | foreach my $stat (@$stats) { | |
7472 | $running_jobs->{$stat->{device}} = $stat; | |
7473 | } | |
7474 | ||
7475 | foreach my $job (keys %$jobs) { | |
7476 | ||
7477 | if (defined($jobs->{$job}->{cancel}) && !defined($running_jobs->{$job})) { | |
7478 | print "$job: Done.\n"; | |
7479 | delete $jobs->{$job}; | |
7480 | } | |
7481 | } | |
7482 | ||
7483 | last if scalar(keys %$jobs) == 0; | |
7484 | ||
7485 | sleep 1; | |
7486 | } | |
7487 | } | |
7488 | ||
7489 | sub clone_disk { | |
7490 | my ($storecfg, $vmid, $running, $drivename, $drive, $snapname, | |
7491 | $newvmid, $storage, $format, $full, $newvollist, $jobs, $completion, $qga, $bwlimit, $conf) = @_; | |
7492 | ||
7493 | my $newvolid; | |
7494 | ||
7495 | if (!$full) { | |
7496 | print "create linked clone of drive $drivename ($drive->{file})\n"; | |
7497 | $newvolid = PVE::Storage::vdisk_clone($storecfg, $drive->{file}, $newvmid, $snapname); | |
7498 | push @$newvollist, $newvolid; | |
7499 | } else { | |
7500 | ||
7501 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file}); | |
7502 | $storeid = $storage if $storage; | |
7503 | ||
7504 | my $dst_format = resolve_dst_disk_format($storecfg, $storeid, $volname, $format); | |
7505 | ||
7506 | print "create full clone of drive $drivename ($drive->{file})\n"; | |
7507 | my $name = undef; | |
7508 | my $size = undef; | |
7509 | if (drive_is_cloudinit($drive)) { | |
7510 | $name = "vm-$newvmid-cloudinit"; | |
7511 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
7512 | if ($scfg->{path}) { | |
7513 | $name .= ".$dst_format"; | |
7514 | } | |
7515 | $snapname = undef; | |
7516 | $size = PVE::QemuServer::Cloudinit::CLOUDINIT_DISK_SIZE; | |
7517 | } elsif ($drivename eq 'efidisk0') { | |
7518 | $size = get_efivars_size($conf); | |
7519 | } elsif ($drivename eq 'tpmstate0') { | |
7520 | $size = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE; | |
7521 | } else { | |
7522 | ($size) = PVE::Storage::volume_size_info($storecfg, $drive->{file}, 10); | |
7523 | } | |
7524 | $newvolid = PVE::Storage::vdisk_alloc( | |
7525 | $storecfg, $storeid, $newvmid, $dst_format, $name, ($size/1024) | |
7526 | ); | |
7527 | push @$newvollist, $newvolid; | |
7528 | ||
7529 | PVE::Storage::activate_volumes($storecfg, [$newvolid]); | |
7530 | ||
7531 | if (drive_is_cloudinit($drive)) { | |
7532 | # when cloning multiple disks (e.g. during clone_vm) it might be the last disk | |
7533 | # if this is the case, we have to complete any block-jobs still there from | |
7534 | # previous drive-mirrors | |
7535 | if (($completion eq 'complete') && (scalar(keys %$jobs) > 0)) { | |
7536 | qemu_drive_mirror_monitor($vmid, $newvmid, $jobs, $completion, $qga); | |
7537 | } | |
7538 | goto no_data_clone; | |
7539 | } | |
7540 | ||
7541 | my $sparseinit = PVE::Storage::volume_has_feature($storecfg, 'sparseinit', $newvolid); | |
7542 | if (!$running || $snapname) { | |
7543 | # TODO: handle bwlimits | |
7544 | if ($drivename eq 'efidisk0') { | |
7545 | # the relevant data on the efidisk may be smaller than the source | |
7546 | # e.g. on RBD/ZFS, so we use dd to copy only the amount | |
7547 | # that is given by the OVMF_VARS.fd | |
7548 | my $src_path = PVE::Storage::path($storecfg, $drive->{file}); | |
7549 | my $dst_path = PVE::Storage::path($storecfg, $newvolid); | |
7550 | ||
7551 | # better for Ceph if block size is not too small, see bug #3324 | |
7552 | my $bs = 1024*1024; | |
7553 | ||
7554 | run_command(['qemu-img', 'dd', '-n', '-O', $dst_format, "bs=$bs", "osize=$size", | |
7555 | "if=$src_path", "of=$dst_path"]); | |
7556 | } else { | |
7557 | qemu_img_convert($drive->{file}, $newvolid, $size, $snapname, $sparseinit); | |
7558 | } | |
7559 | } else { | |
7560 | ||
7561 | die "cannot move TPM state while VM is running\n" if $drivename eq 'tpmstate0'; | |
7562 | ||
7563 | my $kvmver = get_running_qemu_version ($vmid); | |
7564 | if (!min_version($kvmver, 2, 7)) { | |
7565 | die "drive-mirror with iothread requires qemu version 2.7 or higher\n" | |
7566 | if $drive->{iothread}; | |
7567 | } | |
7568 | ||
7569 | qemu_drive_mirror($vmid, $drivename, $newvolid, $newvmid, $sparseinit, $jobs, | |
7570 | $completion, $qga, $bwlimit); | |
7571 | } | |
7572 | } | |
7573 | ||
7574 | no_data_clone: | |
7575 | my ($size) = eval { PVE::Storage::volume_size_info($storecfg, $newvolid, 10) }; | |
7576 | ||
7577 | my $disk = $drive; | |
7578 | $disk->{format} = undef; | |
7579 | $disk->{file} = $newvolid; | |
7580 | $disk->{size} = $size if defined($size); | |
7581 | ||
7582 | return $disk; | |
7583 | } | |
7584 | ||
7585 | sub get_running_qemu_version { | |
7586 | my ($vmid) = @_; | |
7587 | my $res = mon_cmd($vmid, "query-version"); | |
7588 | return "$res->{qemu}->{major}.$res->{qemu}->{minor}"; | |
7589 | } | |
7590 | ||
7591 | sub qemu_use_old_bios_files { | |
7592 | my ($machine_type) = @_; | |
7593 | ||
7594 | return if !$machine_type; | |
7595 | ||
7596 | my $use_old_bios_files = undef; | |
7597 | ||
7598 | if ($machine_type =~ m/^(\S+)\.pxe$/) { | |
7599 | $machine_type = $1; | |
7600 | $use_old_bios_files = 1; | |
7601 | } else { | |
7602 | my $version = extract_version($machine_type, kvm_user_version()); | |
7603 | # Note: kvm version < 2.4 use non-efi pxe files, and have problems when we | |
7604 | # load new efi bios files on migration. So this hack is required to allow | |
7605 | # live migration from qemu-2.2 to qemu-2.4, which is sometimes used when | |
7606 | # updrading from proxmox-ve-3.X to proxmox-ve 4.0 | |
7607 | $use_old_bios_files = !min_version($version, 2, 4); | |
7608 | } | |
7609 | ||
7610 | return ($use_old_bios_files, $machine_type); | |
7611 | } | |
7612 | ||
7613 | sub get_efivars_size { | |
7614 | my ($conf) = @_; | |
7615 | my $arch = get_vm_arch($conf); | |
7616 | my $efidisk = $conf->{efidisk0} ? parse_drive('efidisk0', $conf->{efidisk0}) : undef; | |
7617 | my $smm = PVE::QemuServer::Machine::machine_type_is_q35($conf); | |
7618 | my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm); | |
7619 | die "uefi vars image '$ovmf_vars' not found\n" if ! -f $ovmf_vars; | |
7620 | return -s $ovmf_vars; | |
7621 | } | |
7622 | ||
7623 | sub update_efidisk_size { | |
7624 | my ($conf) = @_; | |
7625 | ||
7626 | return if !defined($conf->{efidisk0}); | |
7627 | ||
7628 | my $disk = PVE::QemuServer::parse_drive('efidisk0', $conf->{efidisk0}); | |
7629 | $disk->{size} = get_efivars_size($conf); | |
7630 | $conf->{efidisk0} = print_drive($disk); | |
7631 | ||
7632 | return; | |
7633 | } | |
7634 | ||
7635 | sub update_tpmstate_size { | |
7636 | my ($conf) = @_; | |
7637 | ||
7638 | my $disk = PVE::QemuServer::parse_drive('tpmstate0', $conf->{tpmstate0}); | |
7639 | $disk->{size} = PVE::QemuServer::Drive::TPMSTATE_DISK_SIZE; | |
7640 | $conf->{tpmstate0} = print_drive($disk); | |
7641 | } | |
7642 | ||
7643 | sub create_efidisk($$$$$$$) { | |
7644 | my ($storecfg, $storeid, $vmid, $fmt, $arch, $efidisk, $smm) = @_; | |
7645 | ||
7646 | my (undef, $ovmf_vars) = get_ovmf_files($arch, $efidisk, $smm); | |
7647 | die "EFI vars default image not found\n" if ! -f $ovmf_vars; | |
7648 | ||
7649 | my $vars_size_b = -s $ovmf_vars; | |
7650 | my $vars_size = PVE::Tools::convert_size($vars_size_b, 'b' => 'kb'); | |
7651 | my $volid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $fmt, undef, $vars_size); | |
7652 | PVE::Storage::activate_volumes($storecfg, [$volid]); | |
7653 | ||
7654 | qemu_img_convert($ovmf_vars, $volid, $vars_size_b, undef, 0); | |
7655 | my ($size) = PVE::Storage::volume_size_info($storecfg, $volid, 3); | |
7656 | ||
7657 | return ($volid, $size/1024); | |
7658 | } | |
7659 | ||
7660 | sub vm_iothreads_list { | |
7661 | my ($vmid) = @_; | |
7662 | ||
7663 | my $res = mon_cmd($vmid, 'query-iothreads'); | |
7664 | ||
7665 | my $iothreads = {}; | |
7666 | foreach my $iothread (@$res) { | |
7667 | $iothreads->{ $iothread->{id} } = $iothread->{"thread-id"}; | |
7668 | } | |
7669 | ||
7670 | return $iothreads; | |
7671 | } | |
7672 | ||
7673 | sub scsihw_infos { | |
7674 | my ($conf, $drive) = @_; | |
7675 | ||
7676 | my $maxdev = 0; | |
7677 | ||
7678 | if (!$conf->{scsihw} || ($conf->{scsihw} =~ m/^lsi/)) { | |
7679 | $maxdev = 7; | |
7680 | } elsif ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) { | |
7681 | $maxdev = 1; | |
7682 | } else { | |
7683 | $maxdev = 256; | |
7684 | } | |
7685 | ||
7686 | my $controller = int($drive->{index} / $maxdev); | |
7687 | my $controller_prefix = ($conf->{scsihw} && $conf->{scsihw} eq 'virtio-scsi-single') | |
7688 | ? "virtioscsi" | |
7689 | : "scsihw"; | |
7690 | ||
7691 | return ($maxdev, $controller, $controller_prefix); | |
7692 | } | |
7693 | ||
7694 | sub windows_version { | |
7695 | my ($ostype) = @_; | |
7696 | ||
7697 | return 0 if !$ostype; | |
7698 | ||
7699 | my $winversion = 0; | |
7700 | ||
7701 | if($ostype eq 'wxp' || $ostype eq 'w2k3' || $ostype eq 'w2k') { | |
7702 | $winversion = 5; | |
7703 | } elsif($ostype eq 'w2k8' || $ostype eq 'wvista') { | |
7704 | $winversion = 6; | |
7705 | } elsif ($ostype =~ m/^win(\d+)$/) { | |
7706 | $winversion = $1; | |
7707 | } | |
7708 | ||
7709 | return $winversion; | |
7710 | } | |
7711 | ||
7712 | sub resolve_dst_disk_format { | |
7713 | my ($storecfg, $storeid, $src_volname, $format) = @_; | |
7714 | my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid); | |
7715 | ||
7716 | if (!$format) { | |
7717 | # if no target format is specified, use the source disk format as hint | |
7718 | if ($src_volname) { | |
7719 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
7720 | $format = qemu_img_format($scfg, $src_volname); | |
7721 | } else { | |
7722 | return $defFormat; | |
7723 | } | |
7724 | } | |
7725 | ||
7726 | # test if requested format is supported - else use default | |
7727 | my $supported = grep { $_ eq $format } @$validFormats; | |
7728 | $format = $defFormat if !$supported; | |
7729 | return $format; | |
7730 | } | |
7731 | ||
7732 | # NOTE: if this logic changes, please update docs & possibly gui logic | |
7733 | sub find_vmstate_storage { | |
7734 | my ($conf, $storecfg) = @_; | |
7735 | ||
7736 | # first, return storage from conf if set | |
7737 | return $conf->{vmstatestorage} if $conf->{vmstatestorage}; | |
7738 | ||
7739 | my ($target, $shared, $local); | |
7740 | ||
7741 | foreach_storage_used_by_vm($conf, sub { | |
7742 | my ($sid) = @_; | |
7743 | my $scfg = PVE::Storage::storage_config($storecfg, $sid); | |
7744 | my $dst = $scfg->{shared} ? \$shared : \$local; | |
7745 | $$dst = $sid if !$$dst || $scfg->{path}; # prefer file based storage | |
7746 | }); | |
7747 | ||
7748 | # second, use shared storage where VM has at least one disk | |
7749 | # third, use local storage where VM has at least one disk | |
7750 | # fall back to local storage | |
7751 | $target = $shared // $local // 'local'; | |
7752 | ||
7753 | return $target; | |
7754 | } | |
7755 | ||
7756 | sub generate_uuid { | |
7757 | my ($uuid, $uuid_str); | |
7758 | UUID::generate($uuid); | |
7759 | UUID::unparse($uuid, $uuid_str); | |
7760 | return $uuid_str; | |
7761 | } | |
7762 | ||
7763 | sub generate_smbios1_uuid { | |
7764 | return "uuid=".generate_uuid(); | |
7765 | } | |
7766 | ||
7767 | sub nbd_stop { | |
7768 | my ($vmid) = @_; | |
7769 | ||
7770 | mon_cmd($vmid, 'nbd-server-stop'); | |
7771 | } | |
7772 | ||
7773 | sub create_reboot_request { | |
7774 | my ($vmid) = @_; | |
7775 | open(my $fh, '>', "/run/qemu-server/$vmid.reboot") | |
7776 | or die "failed to create reboot trigger file: $!\n"; | |
7777 | close($fh); | |
7778 | } | |
7779 | ||
7780 | sub clear_reboot_request { | |
7781 | my ($vmid) = @_; | |
7782 | my $path = "/run/qemu-server/$vmid.reboot"; | |
7783 | my $res = 0; | |
7784 | ||
7785 | $res = unlink($path); | |
7786 | die "could not remove reboot request for $vmid: $!" | |
7787 | if !$res && $! != POSIX::ENOENT; | |
7788 | ||
7789 | return $res; | |
7790 | } | |
7791 | ||
7792 | sub bootorder_from_legacy { | |
7793 | my ($conf, $bootcfg) = @_; | |
7794 | ||
7795 | my $boot = $bootcfg->{legacy} || $boot_fmt->{legacy}->{default}; | |
7796 | my $bootindex_hash = {}; | |
7797 | my $i = 1; | |
7798 | foreach my $o (split(//, $boot)) { | |
7799 | $bootindex_hash->{$o} = $i*100; | |
7800 | $i++; | |
7801 | } | |
7802 | ||
7803 | my $bootorder = {}; | |
7804 | ||
7805 | PVE::QemuConfig->foreach_volume($conf, sub { | |
7806 | my ($ds, $drive) = @_; | |
7807 | ||
7808 | if (drive_is_cdrom ($drive, 1)) { | |
7809 | if ($bootindex_hash->{d}) { | |
7810 | $bootorder->{$ds} = $bootindex_hash->{d}; | |
7811 | $bootindex_hash->{d} += 1; | |
7812 | } | |
7813 | } elsif ($bootindex_hash->{c}) { | |
7814 | $bootorder->{$ds} = $bootindex_hash->{c} | |
7815 | if $conf->{bootdisk} && $conf->{bootdisk} eq $ds; | |
7816 | $bootindex_hash->{c} += 1; | |
7817 | } | |
7818 | }); | |
7819 | ||
7820 | if ($bootindex_hash->{n}) { | |
7821 | for (my $i = 0; $i < $MAX_NETS; $i++) { | |
7822 | my $netname = "net$i"; | |
7823 | next if !$conf->{$netname}; | |
7824 | $bootorder->{$netname} = $bootindex_hash->{n}; | |
7825 | $bootindex_hash->{n} += 1; | |
7826 | } | |
7827 | } | |
7828 | ||
7829 | return $bootorder; | |
7830 | } | |
7831 | ||
7832 | # Generate default device list for 'boot: order=' property. Matches legacy | |
7833 | # default boot order, but with explicit device names. This is important, since | |
7834 | # the fallback for when neither 'order' nor the old format is specified relies | |
7835 | # on 'bootorder_from_legacy' above, and it would be confusing if this diverges. | |
7836 | sub get_default_bootdevices { | |
7837 | my ($conf) = @_; | |
7838 | ||
7839 | my @ret = (); | |
7840 | ||
7841 | # harddisk | |
7842 | my $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 0); | |
7843 | push @ret, $first if $first; | |
7844 | ||
7845 | # cdrom | |
7846 | $first = PVE::QemuServer::Drive::resolve_first_disk($conf, 1); | |
7847 | push @ret, $first if $first; | |
7848 | ||
7849 | # network | |
7850 | for (my $i = 0; $i < $MAX_NETS; $i++) { | |
7851 | my $netname = "net$i"; | |
7852 | next if !$conf->{$netname}; | |
7853 | push @ret, $netname; | |
7854 | last; | |
7855 | } | |
7856 | ||
7857 | return \@ret; | |
7858 | } | |
7859 | ||
7860 | sub device_bootorder { | |
7861 | my ($conf) = @_; | |
7862 | ||
7863 | return bootorder_from_legacy($conf) if !defined($conf->{boot}); | |
7864 | ||
7865 | my $boot = parse_property_string($boot_fmt, $conf->{boot}); | |
7866 | ||
7867 | my $bootorder = {}; | |
7868 | if (!defined($boot) || $boot->{legacy}) { | |
7869 | $bootorder = bootorder_from_legacy($conf, $boot); | |
7870 | } elsif ($boot->{order}) { | |
7871 | my $i = 100; # start at 100 to allow user to insert devices before us with -args | |
7872 | for my $dev (PVE::Tools::split_list($boot->{order})) { | |
7873 | $bootorder->{$dev} = $i++; | |
7874 | } | |
7875 | } | |
7876 | ||
7877 | return $bootorder; | |
7878 | } | |
7879 | ||
7880 | sub register_qmeventd_handle { | |
7881 | my ($vmid) = @_; | |
7882 | ||
7883 | my $fh; | |
7884 | my $peer = "/var/run/qmeventd.sock"; | |
7885 | my $count = 0; | |
7886 | ||
7887 | for (;;) { | |
7888 | $count++; | |
7889 | $fh = IO::Socket::UNIX->new(Peer => $peer, Blocking => 0, Timeout => 1); | |
7890 | last if $fh; | |
7891 | if ($! != EINTR && $! != EAGAIN) { | |
7892 | die "unable to connect to qmeventd socket (vmid: $vmid) - $!\n"; | |
7893 | } | |
7894 | if ($count > 4) { | |
7895 | die "unable to connect to qmeventd socket (vmid: $vmid) - timeout " | |
7896 | . "after $count retries\n"; | |
7897 | } | |
7898 | usleep(25000); | |
7899 | } | |
7900 | ||
7901 | # send handshake to mark VM as backing up | |
7902 | print $fh to_json({vzdump => {vmid => "$vmid"}}); | |
7903 | ||
7904 | # return handle to be closed later when inhibit is no longer required | |
7905 | return $fh; | |
7906 | } | |
7907 | ||
7908 | # bash completion helper | |
7909 | ||
7910 | sub complete_backup_archives { | |
7911 | my ($cmdname, $pname, $cvalue) = @_; | |
7912 | ||
7913 | my $cfg = PVE::Storage::config(); | |
7914 | ||
7915 | my $storeid; | |
7916 | ||
7917 | if ($cvalue =~ m/^([^:]+):/) { | |
7918 | $storeid = $1; | |
7919 | } | |
7920 | ||
7921 | my $data = PVE::Storage::template_list($cfg, $storeid, 'backup'); | |
7922 | ||
7923 | my $res = []; | |
7924 | foreach my $id (keys %$data) { | |
7925 | foreach my $item (@{$data->{$id}}) { | |
7926 | next if $item->{format} !~ m/^vma\.(${\PVE::Storage::Plugin::COMPRESSOR_RE})$/; | |
7927 | push @$res, $item->{volid} if defined($item->{volid}); | |
7928 | } | |
7929 | } | |
7930 | ||
7931 | return $res; | |
7932 | } | |
7933 | ||
7934 | my $complete_vmid_full = sub { | |
7935 | my ($running) = @_; | |
7936 | ||
7937 | my $idlist = vmstatus(); | |
7938 | ||
7939 | my $res = []; | |
7940 | ||
7941 | foreach my $id (keys %$idlist) { | |
7942 | my $d = $idlist->{$id}; | |
7943 | if (defined($running)) { | |
7944 | next if $d->{template}; | |
7945 | next if $running && $d->{status} ne 'running'; | |
7946 | next if !$running && $d->{status} eq 'running'; | |
7947 | } | |
7948 | push @$res, $id; | |
7949 | ||
7950 | } | |
7951 | return $res; | |
7952 | }; | |
7953 | ||
7954 | sub complete_vmid { | |
7955 | return &$complete_vmid_full(); | |
7956 | } | |
7957 | ||
7958 | sub complete_vmid_stopped { | |
7959 | return &$complete_vmid_full(0); | |
7960 | } | |
7961 | ||
7962 | sub complete_vmid_running { | |
7963 | return &$complete_vmid_full(1); | |
7964 | } | |
7965 | ||
7966 | sub complete_storage { | |
7967 | ||
7968 | my $cfg = PVE::Storage::config(); | |
7969 | my $ids = $cfg->{ids}; | |
7970 | ||
7971 | my $res = []; | |
7972 | foreach my $sid (keys %$ids) { | |
7973 | next if !PVE::Storage::storage_check_enabled($cfg, $sid, undef, 1); | |
7974 | next if !$ids->{$sid}->{content}->{images}; | |
7975 | push @$res, $sid; | |
7976 | } | |
7977 | ||
7978 | return $res; | |
7979 | } | |
7980 | ||
7981 | sub complete_migration_storage { | |
7982 | my ($cmd, $param, $current_value, $all_args) = @_; | |
7983 | ||
7984 | my $targetnode = @$all_args[1]; | |
7985 | ||
7986 | my $cfg = PVE::Storage::config(); | |
7987 | my $ids = $cfg->{ids}; | |
7988 | ||
7989 | my $res = []; | |
7990 | foreach my $sid (keys %$ids) { | |
7991 | next if !PVE::Storage::storage_check_enabled($cfg, $sid, $targetnode, 1); | |
7992 | next if !$ids->{$sid}->{content}->{images}; | |
7993 | push @$res, $sid; | |
7994 | } | |
7995 | ||
7996 | return $res; | |
7997 | } | |
7998 | ||
7999 | sub vm_is_paused { | |
8000 | my ($vmid) = @_; | |
8001 | my $qmpstatus = eval { | |
8002 | PVE::QemuConfig::assert_config_exists_on_node($vmid); | |
8003 | mon_cmd($vmid, "query-status"); | |
8004 | }; | |
8005 | warn "$@\n" if $@; | |
8006 | return $qmpstatus && $qmpstatus->{status} eq "paused"; | |
8007 | } | |
8008 | ||
8009 | sub check_volume_storage_type { | |
8010 | my ($storecfg, $vol) = @_; | |
8011 | ||
8012 | my ($storeid, $volname) = PVE::Storage::parse_volume_id($vol); | |
8013 | my $scfg = PVE::Storage::storage_config($storecfg, $storeid); | |
8014 | my ($vtype) = PVE::Storage::parse_volname($storecfg, $vol); | |
8015 | ||
8016 | die "storage '$storeid' does not support content-type '$vtype'\n" | |
8017 | if !$scfg->{content}->{$vtype}; | |
8018 | ||
8019 | return 1; | |
8020 | } | |
8021 | ||
8022 | 1; |