1 package PVE
::QemuServer
;
22 use Storable
qw(dclone);
23 use PVE
::Exception
qw(raise raise_param_exc);
25 use PVE
::Tools
qw(run_command lock_file lock_file_full file_read_firstline dir_glob_foreach);
26 use PVE
::JSONSchema
qw(get_standard_option);
27 use PVE
::Cluster
qw(cfs_register_file cfs_read_file cfs_write_file cfs_lock_file);
32 use PVE
::RPCEnvironment
;
33 use PVE
::QemuServer
::PCI
qw(print_pci_addr print_pcie_addr);
34 use PVE
::QemuServer
::Memory
;
35 use PVE
::QemuServer
::USB
qw(parse_usb_device);
36 use Time
::HiRes
qw(gettimeofday);
37 use File
::Copy
qw(copy);
40 my $OVMF_CODE = '/usr/share/kvm/OVMF_CODE-pure-efi.fd';
41 my $OVMF_VARS = '/usr/share/kvm/OVMF_VARS-pure-efi.fd';
42 my $OVMF_IMG = '/usr/share/kvm/OVMF-pure-efi.fd';
44 my $qemu_snap_storage = {rbd
=> 1, sheepdog
=> 1};
46 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
48 # Note about locking: we use flock on the config file protect
49 # against concurent actions.
50 # Aditionaly, we have a 'lock' setting in the config file. This
51 # can be set to 'migrate', 'backup', 'snapshot' or 'rollback'. Most actions are not
52 # allowed when such lock is set. But you can ignore this kind of
53 # lock with the --skiplock flag.
55 cfs_register_file
('/qemu-server/',
59 PVE
::JSONSchema
::register_standard_option
('pve-qm-stateuri', {
60 description
=> "Some command save/restore state from this location.",
66 PVE
::JSONSchema
::register_standard_option
('pve-snapshot-name', {
67 description
=> "The name of the snapshot.",
68 type
=> 'string', format
=> 'pve-configid',
72 PVE
::JSONSchema
::register_standard_option
('pve-qm-image-format', {
74 enum
=> [qw(raw cow qcow qed qcow2 vmdk cloop)],
75 description
=> "The drive's backing file's data format.",
79 #no warnings 'redefine';
82 my ($controller, $vmid, $option, $value) = @_;
84 my $path = "/sys/fs/cgroup/$controller/qemu.slice/$vmid.scope/$option";
85 PVE
::ProcFSTools
::write_proc_entry
($path, $value);
89 my $nodename = PVE
::INotify
::nodename
();
91 mkdir "/etc/pve/nodes/$nodename";
92 my $confdir = "/etc/pve/nodes/$nodename/qemu-server";
95 my $var_run_tmpdir = "/var/run/qemu-server";
96 mkdir $var_run_tmpdir;
98 my $lock_dir = "/var/lock/qemu-server";
101 my $pcisysfs = "/sys/bus/pci";
103 my $cpu_vendor_list = {
105 486 => 'GenuineIntel',
106 pentium
=> 'GenuineIntel',
107 pentium2
=> 'GenuineIntel',
108 pentium3
=> 'GenuineIntel',
109 coreduo
=> 'GenuineIntel',
110 core2duo
=> 'GenuineIntel',
111 Conroe
=> 'GenuineIntel',
112 Penryn
=> 'GenuineIntel',
113 Nehalem
=> 'GenuineIntel',
114 Westmere
=> 'GenuineIntel',
115 SandyBridge
=> 'GenuineIntel',
116 IvyBridge
=> 'GenuineIntel',
117 Haswell
=> 'GenuineIntel',
118 'Haswell-noTSX' => 'GenuineIntel',
119 Broadwell
=> 'GenuineIntel',
120 'Broadwell-noTSX' => 'GenuineIntel',
121 'Skylake-Client' => 'GenuineIntel',
124 athlon
=> 'AuthenticAMD',
125 phenom
=> 'AuthenticAMD',
126 Opteron_G1
=> 'AuthenticAMD',
127 Opteron_G2
=> 'AuthenticAMD',
128 Opteron_G3
=> 'AuthenticAMD',
129 Opteron_G4
=> 'AuthenticAMD',
130 Opteron_G5
=> 'AuthenticAMD',
132 # generic types, use vendor from host node
142 description
=> "Emulated CPU type.",
144 enum
=> [ sort { "\L$a" cmp "\L$b" } keys %$cpu_vendor_list ],
149 description
=> "Do not identify as a KVM virtual machine.",
160 enum
=> [qw(i6300esb ib700)],
161 description
=> "Watchdog type to emulate.",
162 default => 'i6300esb',
167 enum
=> [qw(reset shutdown poweroff pause debug none)],
168 description
=> "The action to perform if after activation the guest fails to poll the watchdog in time.",
172 PVE
::JSONSchema
::register_format
('pve-qm-watchdog', $watchdog_fmt);
178 description
=> "Specifies whether a VM will be started during system bootup.",
184 description
=> "Automatic restart after crash (currently ignored).",
189 type
=> 'string', format
=> 'pve-hotplug-features',
190 description
=> "Selectively enable hotplug features. This is a comma separated list of hotplug features: 'network', 'disk', 'cpu', 'memory' and 'usb'. Use '0' to disable hotplug completely. Value '1' is an alias for the default 'network,disk,usb'.",
191 default => 'network,disk,usb',
196 description
=> "Allow reboot. If set to '0' the VM exit on reboot.",
202 description
=> "Lock/unlock the VM.",
203 enum
=> [qw(migrate backup snapshot rollback)],
208 description
=> "Limit of CPU usage.",
209 verbose_description
=> "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has total of '2' CPU time. Value '0' indicates no CPU limit.",
217 description
=> "CPU weight for a VM.",
218 verbose_description
=> "CPU weight for a VM. Argument is used in the kernel fair scheduler. The larger the number is, the more CPU time this VM gets. Number is relative to weights of all the other running VMs.\n\nNOTE: You can disable fair-scheduler configuration by setting this to 0.",
226 description
=> "Amount of RAM for the VM in MB. This is the maximum available memory when you use the balloon device.",
233 description
=> "Amount of target RAM for the VM in MB. Using zero disables the ballon driver.",
239 description
=> "Amount of memory shares for auto-ballooning. The larger the number is, the more memory this VM gets. Number is relative to weights of all other running VMs. Using zero disables auto-ballooning",
247 description
=> "Keybord layout for vnc server. Default is read from the '/etc/pve/datacenter.conf' configuration file.",
248 enum
=> PVE
::Tools
::kvmkeymaplist
(),
253 type
=> 'string', format
=> 'dns-name',
254 description
=> "Set a name for the VM. Only used on the configuration web interface.",
259 description
=> "SCSI controller model",
260 enum
=> [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)],
266 description
=> "Description for the VM. Only used on the configuration web interface. This is saved as comment inside the configuration file.",
271 enum
=> [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 l24 l26 solaris)],
272 description
=> "Specify guest operating system.",
273 verbose_description
=> <<EODESC,
274 Specify guest operating system. This is used to enable special
275 optimization/features for specific operating systems:
278 other;; unspecified OS
279 wxp;; Microsoft Windows XP
280 w2k;; Microsoft Windows 2000
281 w2k3;; Microsoft Windows 2003
282 w2k8;; Microsoft Windows 2008
283 wvista;; Microsoft Windows Vista
284 win7;; Microsoft Windows 7
285 win8;; Microsoft Windows 8/2012
286 l24;; Linux 2.4 Kernel
287 l26;; Linux 2.6/3.X Kernel
288 solaris;; Solaris/OpenSolaris/OpenIndiania kernel
294 description
=> "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n).",
295 pattern
=> '[acdn]{1,4}',
300 type
=> 'string', format
=> 'pve-qm-bootdisk',
301 description
=> "Enable booting from specified disk.",
302 pattern
=> '(ide|sata|scsi|virtio)\d+',
307 description
=> "The number of CPUs. Please use option -sockets instead.",
314 description
=> "The number of CPU sockets.",
321 description
=> "The number of cores per socket.",
328 description
=> "Enable/disable NUMA.",
334 description
=> "Enable/disable hugepages memory.",
335 enum
=> [qw(any 2 1024)],
340 description
=> "Number of hotplugged vcpus.",
347 description
=> "Enable/disable ACPI.",
353 description
=> "Enable/disable Qemu GuestAgent.",
359 description
=> "Enable/disable KVM hardware virtualization.",
365 description
=> "Enable/disable time drift fix.",
371 description
=> "Set the real time clock to local time. This is enabled by default if ostype indicates a Microsoft OS.",
376 description
=> "Freeze CPU at startup (use 'c' monitor command to start execution).",
381 description
=> "Select the VGA type.",
382 verbose_description
=> "Select the VGA type. If you want to use high resolution" .
383 " modes (>= 1280x1024x16) then you should use the options " .
384 "'std' or 'vmware'. Default is 'std' for win8/win7/w2k8, and " .
385 "'cirrus' for other OS types. The 'qxl' option enables the SPICE " .
386 "display sever. For win* OS you can select how many independent " .
387 "displays you want, Linux guests can add displays them self. " .
388 "You can also run without any graphic card, using a serial device" .
390 enum
=> [qw(std cirrus vmware qxl serial0 serial1 serial2 serial3 qxl2 qxl3 qxl4)],
394 type
=> 'string', format
=> 'pve-qm-watchdog',
395 description
=> "Create a virtual hardware watchdog device.",
396 verbose_description
=> "Create a virtual hardware watchdog device. Once enabled" .
397 " (by a guest action), the watchdog must be periodically polled " .
398 "by an agent inside the guest or else the watchdog will reset " .
399 "the guest (or execute the respective action specified)",
404 typetext
=> "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)",
405 description
=> "Set the initial date of the real time clock. Valid format for date are: 'now' or '2006-06-17T16:01:21' or '2006-06-17'.",
406 pattern
=> '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)',
409 startup
=> get_standard_option
('pve-startup-order'),
413 description
=> "Enable/disable Template.",
419 description
=> "Arbitrary arguments passed to kvm.",
420 verbose_description
=> <<EODESCR,
421 Arbitrary arguments passed to kvm, for example:
423 args: -no-reboot -no-hpet
425 NOTE: this option is for experts only.
432 description
=> "Enable/disable the USB tablet device.",
433 verbose_description
=> "Enable/disable the USB tablet device. This device is " .
434 "usually needed to allow absolute mouse positioning with VNC. " .
435 "Else the mouse runs out of sync with normal VNC clients. " .
436 "If you're running lots of console-only guests on one host, " .
437 "you may consider disabling this to save some context switches. " .
438 "This is turned off by default if you use spice (-vga=qxl).",
443 description
=> "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.",
447 migrate_downtime
=> {
450 description
=> "Set maximum tolerated downtime (in seconds) for migrations.",
456 type
=> 'string', format
=> 'pve-qm-ide',
457 typetext
=> '<volume>',
458 description
=> "This is an alias for option -ide2",
462 description
=> "Emulated CPU type.",
466 parent
=> get_standard_option
('pve-snapshot-name', {
468 description
=> "Parent snapshot name. This is used internally, and should not be modified.",
472 description
=> "Timestamp for snapshots.",
478 type
=> 'string', format
=> 'pve-volume-id',
479 description
=> "Reference to a volume which stores the VM state. This is used internally for snapshots.",
482 description
=> "Specific the Qemu machine type.",
484 pattern
=> '(pc|pc(-i440fx)?-\d+\.\d+(\.pxe)?|q35|pc-q35-\d+\.\d+(\.pxe)?)',
489 description
=> "Specify SMBIOS type 1 fields.",
490 type
=> 'string', format
=> 'pve-qm-smbios1',
496 description
=> "Storage replica for local storage.",
500 replica_rate_limit
=> {
502 description
=> "Storage replica rate limit in KBytes/s.",
506 replica_interval
=> {
508 description
=> "Storage replica sync interval",
516 description
=> "Storage replica taget node.",
522 description
=> "Sets the protection flag of the VM. This will disable the remove VM and remove disk operations.",
528 enum
=> [ qw(seabios ovmf) ],
529 description
=> "Select BIOS implementation.",
530 default => 'seabios',
534 # what about other qemu settings ?
536 #machine => 'string',
549 ##soundhw => 'string',
551 while (my ($k, $v) = each %$confdesc) {
552 PVE
::JSONSchema
::register_standard_option
("pve-qm-$k", $v);
555 my $MAX_IDE_DISKS = 4;
556 my $MAX_SCSI_DISKS = 14;
557 my $MAX_VIRTIO_DISKS = 16;
558 my $MAX_SATA_DISKS = 6;
559 my $MAX_USB_DEVICES = 5;
561 my $MAX_UNUSED_DISKS = 8;
562 my $MAX_HOSTPCI_DEVICES = 4;
563 my $MAX_SERIAL_PORTS = 4;
564 my $MAX_PARALLEL_PORTS = 3;
570 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
571 description
=> "CPUs accessing this NUMA node.",
572 format_description
=> "id[-id];...",
576 description
=> "Amount of memory this NUMA node provides.",
581 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
582 description
=> "Host NUMA nodes to use.",
583 format_description
=> "id[-id];...",
588 enum
=> [qw(preferred bind interleave)],
589 description
=> "NUMA allocation policy.",
593 PVE
::JSONSchema
::register_format
('pve-qm-numanode', $numa_fmt);
596 type
=> 'string', format
=> $numa_fmt,
597 description
=> "NUMA topology.",
599 PVE
::JSONSchema
::register_standard_option
("pve-qm-numanode", $numadesc);
601 for (my $i = 0; $i < $MAX_NUMA; $i++) {
602 $confdesc->{"numa$i"} = $numadesc;
605 my $nic_model_list = ['rtl8139', 'ne2k_pci', 'e1000', 'pcnet', 'virtio',
606 'ne2k_isa', 'i82551', 'i82557b', 'i82559er', 'vmxnet3',
607 'e1000-82540em', 'e1000-82544gc', 'e1000-82545em'];
608 my $nic_model_list_txt = join(' ', sort @$nic_model_list);
610 my $net_fmt_bridge_descr = <<__EOD__;
611 Bridge to attach the network device to. The Proxmox VE standard bridge
614 If you do not specify a bridge, we create a kvm user (NATed) network
615 device, which provides DHCP and DNS services. The following addresses
622 The DHCP server assign addresses to the guest starting from 10.0.2.15.
628 pattern
=> qr/[0-9a-f]{2}(?::[0-9a-f]{2}){5}/i,
629 description
=> "MAC address. That address must be unique withing your network. This is automatically generated if not specified.",
630 format_description
=> "XX:XX:XX:XX:XX:XX",
635 description
=> "Network Card Model. The 'virtio' model provides the best performance with very low CPU overhead. If your guest does not support this driver, it is usually best to use 'e1000'.",
636 enum
=> $nic_model_list,
639 (map { $_ => { keyAlias
=> 'model', alias
=> 'macaddr' }} @$nic_model_list),
642 description
=> $net_fmt_bridge_descr,
643 format_description
=> 'bridge',
648 minimum
=> 0, maximum
=> 16,
649 description
=> 'Number of packet queues to be used on the device.',
655 description
=> "Rate limit in mbps (megabytes per second) as floating point number.",
660 minimum
=> 1, maximum
=> 4094,
661 description
=> 'VLAN tag to apply to packets on this interface.',
666 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
667 description
=> 'VLAN trunks to pass through this interface.',
668 format_description
=> 'vlanid[;vlanid...]',
673 description
=> 'Whether this interface should be protected by the firewall.',
678 description
=> 'Whether this interface should be disconnected (like pulling the plug).',
685 type
=> 'string', format
=> $net_fmt,
686 description
=> "Specify network devices.",
689 PVE
::JSONSchema
::register_standard_option
("pve-qm-net", $netdesc);
691 for (my $i = 0; $i < $MAX_NETS; $i++) {
692 $confdesc->{"net$i"} = $netdesc;
695 PVE
::JSONSchema
::register_format
('pve-volume-id-or-qm-path', \
&verify_volume_id_or_qm_path
);
696 sub verify_volume_id_or_qm_path
{
697 my ($volid, $noerr) = @_;
699 if ($volid eq 'none' || $volid eq 'cdrom' || $volid =~ m
|^/|) {
703 # if its neither 'none' nor 'cdrom' nor a path, check if its a volume-id
704 $volid = eval { PVE
::JSONSchema
::check_format
('pve-volume-id', $volid, '') };
706 return undef if $noerr;
714 my %drivedesc_base = (
715 volume
=> { alias
=> 'file' },
718 format
=> 'pve-volume-id-or-qm-path',
720 format_description
=> 'volume',
721 description
=> "The drive's backing volume.",
725 enum
=> [qw(cdrom disk)],
726 description
=> "The drive's media type.",
732 description
=> "Force the drive's physical geometry to have a specific cylinder count.",
737 description
=> "Force the drive's physical geometry to have a specific head count.",
742 description
=> "Force the drive's physical geometry to have a specific sector count.",
747 enum
=> [qw(none lba auto)],
748 description
=> "Force disk geometry bios translation mode.",
753 description
=> "Whether the drive should be included when making snapshots.",
758 enum
=> [qw(none writethrough writeback unsafe directsync)],
759 description
=> "The drive's cache mode",
762 format
=> get_standard_option
('pve-qm-image-format'),
765 format
=> 'disk-size',
766 format_description
=> 'DiskSize',
767 description
=> "Disk size. This is purely informational and has no effect.",
772 description
=> "Whether the drive should be included when making backups.",
777 description
=> 'Will include this drive to an storage replical job.',
783 enum
=> [qw(ignore report stop)],
784 description
=> 'Read error action.',
789 enum
=> [qw(enospc ignore report stop)],
790 description
=> 'Write error action.',
795 enum
=> [qw(native threads)],
796 description
=> 'AIO type to use.',
801 enum
=> [qw(ignore on)],
802 description
=> 'Controls whether to pass discard/trim requests to the underlying storage.',
807 description
=> 'Controls whether to detect and try to optimize writes of zeroes.',
812 format
=> 'urlencoded',
813 format_description
=> 'serial',
814 maxLength
=> 20*3, # *3 since it's %xx url enoded
815 description
=> "The drive's reported serial number, url-encoded, up to 20 bytes long.",
820 my %iothread_fmt = ( iothread
=> {
822 description
=> "Whether to use iothreads for this drive",
829 format
=> 'urlencoded',
830 format_description
=> 'model',
831 maxLength
=> 40*3, # *3 since it's %xx url enoded
832 description
=> "The drive's reported model name, url-encoded, up to 40 bytes long.",
840 description
=> "Number of queues.",
846 my %scsiblock_fmt = (
849 description
=> "whether to use scsi-block for full passthrough of host block device\n\nWARNING: can lead to I/O errors in combination with low memory or high memory fragmentation on host",
855 my $add_throttle_desc = sub {
856 my ($key, $type, $what, $unit, $longunit, $minimum) = @_;
859 format_description
=> $unit,
860 description
=> "Maximum $what in $longunit.",
863 $d->{minimum
} = $minimum if defined($minimum);
864 $drivedesc_base{$key} = $d;
866 # throughput: (leaky bucket)
867 $add_throttle_desc->('bps', 'integer', 'r/w speed', 'bps', 'bytes per second');
868 $add_throttle_desc->('bps_rd', 'integer', 'read speed', 'bps', 'bytes per second');
869 $add_throttle_desc->('bps_wr', 'integer', 'write speed', 'bps', 'bytes per second');
870 $add_throttle_desc->('mbps', 'number', 'r/w speed', 'mbps', 'megabytes per second');
871 $add_throttle_desc->('mbps_rd', 'number', 'read speed', 'mbps', 'megabytes per second');
872 $add_throttle_desc->('mbps_wr', 'number', 'write speed', 'mbps', 'megabytes per second');
873 $add_throttle_desc->('iops', 'integer', 'r/w I/O', 'iops', 'operations per second');
874 $add_throttle_desc->('iops_rd', 'integer', 'read I/O', 'iops', 'operations per second');
875 $add_throttle_desc->('iops_wr', 'integer', 'write I/O', 'iops', 'operations per second');
877 # pools: (pool of IO before throttling starts taking effect)
878 $add_throttle_desc->('mbps_max', 'number', 'unthrottled r/w pool', 'mbps', 'megabytes per second');
879 $add_throttle_desc->('mbps_rd_max', 'number', 'unthrottled read pool', 'mbps', 'megabytes per second');
880 $add_throttle_desc->('mbps_wr_max', 'number', 'unthrottled write pool', 'mbps', 'megabytes per second');
881 $add_throttle_desc->('iops_max', 'integer', 'unthrottled r/w I/O pool', 'iops', 'operations per second');
882 $add_throttle_desc->('iops_rd_max', 'integer', 'unthrottled read I/O pool', 'iops', 'operations per second');
883 $add_throttle_desc->('iops_wr_max', 'integer', 'unthrottled write I/O pool', 'iops', 'operations per second');
886 $add_throttle_desc->('bps_max_length', 'integer', 'length of I/O bursts', 'seconds', 'seconds', 1);
887 $add_throttle_desc->('bps_rd_length', 'integer', 'length of read I/O bursts', 'seconds', 'seconds', 1);
888 $add_throttle_desc->('bps_wr_length', 'integer', 'length of write I/O bursts', 'seconds', 'seconds', 1);
889 $add_throttle_desc->('iops_max_length', 'integer', 'length of I/O bursts', 'seconds', 'seconds', 1);
890 $add_throttle_desc->('iops_rd_length', 'integer', 'length of read I/O bursts', 'seconds', 'seconds', 1);
891 $add_throttle_desc->('iops_wr_length', 'integer', 'length of write I/O bursts', 'seconds', 'seconds', 1);
897 PVE
::JSONSchema
::register_format
("pve-qm-ide", $ide_fmt);
901 type
=> 'string', format
=> $ide_fmt,
902 description
=> "Use volume as IDE hard disk or CD-ROM (n is 0 to " .($MAX_IDE_DISKS -1) . ").",
904 PVE
::JSONSchema
::register_standard_option
("pve-qm-ide", $idedesc);
914 type
=> 'string', format
=> $scsi_fmt,
915 description
=> "Use volume as SCSI hard disk or CD-ROM (n is 0 to " . ($MAX_SCSI_DISKS - 1) . ").",
917 PVE
::JSONSchema
::register_standard_option
("pve-qm-scsi", $scsidesc);
924 type
=> 'string', format
=> $sata_fmt,
925 description
=> "Use volume as SATA hard disk or CD-ROM (n is 0 to " . ($MAX_SATA_DISKS - 1). ").",
927 PVE
::JSONSchema
::register_standard_option
("pve-qm-sata", $satadesc);
935 type
=> 'string', format
=> $virtio_fmt,
936 description
=> "Use volume as VIRTIO hard disk (n is 0 to " . ($MAX_VIRTIO_DISKS - 1) . ").",
938 PVE
::JSONSchema
::register_standard_option
("pve-qm-virtio", $virtiodesc);
949 volume
=> { alias
=> 'file' },
952 format
=> 'pve-volume-id-or-qm-path',
954 format_description
=> 'volume',
955 description
=> "The drive's backing volume.",
957 format
=> get_standard_option
('pve-qm-image-format'),
960 format
=> 'disk-size',
961 format_description
=> 'DiskSize',
962 description
=> "Disk size. This is purely informational and has no effect.",
969 type
=> 'string', format
=> $efidisk_fmt,
970 description
=> "Configure a Disk for storing EFI vars",
973 PVE
::JSONSchema
::register_standard_option
("pve-qm-efidisk", $efidisk_desc);
978 type
=> 'string', format
=> 'pve-qm-usb-device',
979 format_description
=> 'HOSTUSBDEVICE|spice',
980 description
=> <<EODESCR,
981 The Host USB device or port or the value 'spice'. HOSTUSBDEVICE syntax is:
983 'bus-port(.port)*' (decimal numbers) or
984 'vendor_id:product_id' (hexadeciaml numbers) or
987 You can use the 'lsusb -t' command to list existing usb devices.
989 NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.
991 The value 'spice' can be used to add a usb redirection devices for spice.
997 description
=> "Specifies whether if given host option is a USB3 device or port (this does currently not work reliably with spice redirection and is then ignored).",
1004 type
=> 'string', format
=> $usb_fmt,
1005 description
=> "Configure an USB device (n is 0 to 4).",
1007 PVE
::JSONSchema
::register_standard_option
("pve-qm-usb", $usbdesc);
1009 # NOTE: the match-groups of this regex are used in parse_hostpci
1010 my $PCIRE = qr/([a-f0-9]{2}:[a-f0-9]{2})(?:\.([a-f0-9]))?/;
1015 pattern
=> qr/$PCIRE(;$PCIRE)*/,
1016 format_description
=> 'HOSTPCIID[;HOSTPCIID2...]',
1017 description
=> <<EODESCR,
1018 Host PCI device pass through. The PCI ID of a host's PCI device or a list
1019 of PCI virtual functions of the host. HOSTPCIID syntax is:
1021 'bus:dev.func' (hexadecimal numbers)
1023 You can us the 'lspci' command to list existing PCI devices.
1028 description
=> "Specify whether or not the device's ROM will be visible in the guest's memory map.",
1034 pattern
=> '[^,;]+',
1035 format_description
=> 'string',
1036 description
=> "Custom pci device rom filename (must be located in /usr/share/kvm/).",
1041 description
=> "Choose the PCI-express bus (needs the 'q35' machine model).",
1047 description
=> "Enable vfio-vga device support.",
1052 PVE
::JSONSchema
::register_format
('pve-qm-hostpci', $hostpci_fmt);
1056 type
=> 'string', format
=> 'pve-qm-hostpci',
1057 description
=> "Map host PCI devices into guest.",
1058 verbose_description
=> <<EODESCR,
1059 Map host PCI devices into guest.
1061 NOTE: This option allows direct access to host hardware. So it is no longer
1062 possible to migrate such machines - use with special care.
1064 CAUTION: Experimental! User reported problems with this option.
1067 PVE
::JSONSchema
::register_standard_option
("pve-qm-hostpci", $hostpcidesc);
1072 pattern
=> '(/dev/.+|socket)',
1073 description
=> "Create a serial device inside the VM (n is 0 to 3)",
1074 verbose_description
=> <<EODESCR,
1075 Create a serial device inside the VM (n is 0 to 3), and pass through a
1076 host serial device (i.e. /dev/ttyS0), or create a unix socket on the
1077 host side (use 'qm terminal' to open a terminal connection).
1079 NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines - use with special care.
1081 CAUTION: Experimental! User reported problems with this option.
1088 pattern
=> '/dev/parport\d+|/dev/usb/lp\d+',
1089 description
=> "Map host parallel devices (n is 0 to 2).",
1090 verbose_description
=> <<EODESCR,
1091 Map host parallel devices (n is 0 to 2).
1093 NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.
1095 CAUTION: Experimental! User reported problems with this option.
1099 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
1100 $confdesc->{"parallel$i"} = $paralleldesc;
1103 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
1104 $confdesc->{"serial$i"} = $serialdesc;
1107 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
1108 $confdesc->{"hostpci$i"} = $hostpcidesc;
1111 for (my $i = 0; $i < $MAX_IDE_DISKS; $i++) {
1112 $drivename_hash->{"ide$i"} = 1;
1113 $confdesc->{"ide$i"} = $idedesc;
1116 for (my $i = 0; $i < $MAX_SATA_DISKS; $i++) {
1117 $drivename_hash->{"sata$i"} = 1;
1118 $confdesc->{"sata$i"} = $satadesc;
1121 for (my $i = 0; $i < $MAX_SCSI_DISKS; $i++) {
1122 $drivename_hash->{"scsi$i"} = 1;
1123 $confdesc->{"scsi$i"} = $scsidesc ;
1126 for (my $i = 0; $i < $MAX_VIRTIO_DISKS; $i++) {
1127 $drivename_hash->{"virtio$i"} = 1;
1128 $confdesc->{"virtio$i"} = $virtiodesc;
1131 $drivename_hash->{efidisk0
} = 1;
1132 $confdesc->{efidisk0
} = $efidisk_desc;
1134 for (my $i = 0; $i < $MAX_USB_DEVICES; $i++) {
1135 $confdesc->{"usb$i"} = $usbdesc;
1140 type
=> 'string', format
=> 'pve-volume-id',
1141 description
=> "Reference to unused volumes. This is used internally, and should not be modified manually.",
1144 for (my $i = 0; $i < $MAX_UNUSED_DISKS; $i++) {
1145 $confdesc->{"unused$i"} = $unuseddesc;
1148 my $kvm_api_version = 0;
1152 return $kvm_api_version if $kvm_api_version;
1154 my $fh = IO
::File-
>new("</dev/kvm") ||
1157 if (my $v = $fh->ioctl(KVM_GET_API_VERSION
(), 0)) {
1158 $kvm_api_version = $v;
1163 return $kvm_api_version;
1166 my $kvm_user_version;
1168 sub kvm_user_version
{
1170 return $kvm_user_version if $kvm_user_version;
1172 $kvm_user_version = 'unknown';
1176 if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) {
1177 $kvm_user_version = $2;
1181 eval { run_command
("kvm -version", outfunc
=> $code); };
1184 return $kvm_user_version;
1188 my $kernel_has_vhost_net = -c
'/dev/vhost-net';
1190 sub valid_drive_names
{
1191 # order is important - used to autoselect boot disk
1192 return ((map { "ide$_" } (0 .. ($MAX_IDE_DISKS - 1))),
1193 (map { "scsi$_" } (0 .. ($MAX_SCSI_DISKS - 1))),
1194 (map { "virtio$_" } (0 .. ($MAX_VIRTIO_DISKS - 1))),
1195 (map { "sata$_" } (0 .. ($MAX_SATA_DISKS - 1))),
1199 sub is_valid_drivename
{
1202 return defined($drivename_hash->{$dev});
1207 return defined($confdesc->{$key});
1211 return $nic_model_list;
1214 sub os_list_description
{
1218 wxp
=> 'Windows XP',
1219 w2k
=> 'Windows 2000',
1220 w2k3
=>, 'Windows 2003',
1221 w2k8
=> 'Windows 2008',
1222 wvista
=> 'Windows Vista',
1223 win7
=> 'Windows 7',
1224 win8
=> 'Windows 8/2012',
1225 win10
=> 'Windows 10/2016',
1233 sub get_cdrom_path
{
1235 return $cdrom_path if $cdrom_path;
1237 return $cdrom_path = "/dev/cdrom" if -l
"/dev/cdrom";
1238 return $cdrom_path = "/dev/cdrom1" if -l
"/dev/cdrom1";
1239 return $cdrom_path = "/dev/cdrom2" if -l
"/dev/cdrom2";
1243 my ($storecfg, $vmid, $cdrom) = @_;
1245 if ($cdrom eq 'cdrom') {
1246 return get_cdrom_path
();
1247 } elsif ($cdrom eq 'none') {
1249 } elsif ($cdrom =~ m
|^/|) {
1252 return PVE
::Storage
::path
($storecfg, $cdrom);
1256 # try to convert old style file names to volume IDs
1257 sub filename_to_volume_id
{
1258 my ($vmid, $file, $media) = @_;
1260 if (!($file eq 'none' || $file eq 'cdrom' ||
1261 $file =~ m
|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) {
1263 return undef if $file =~ m
|/|;
1265 if ($media && $media eq 'cdrom') {
1266 $file = "local:iso/$file";
1268 $file = "local:$vmid/$file";
1275 sub verify_media_type
{
1276 my ($opt, $vtype, $media) = @_;
1281 if ($media eq 'disk') {
1283 } elsif ($media eq 'cdrom') {
1286 die "internal error";
1289 return if ($vtype eq $etype);
1291 raise_param_exc
({ $opt => "unexpected media type ($vtype != $etype)" });
1294 sub cleanup_drive_path
{
1295 my ($opt, $storecfg, $drive) = @_;
1297 # try to convert filesystem paths to volume IDs
1299 if (($drive->{file
} !~ m/^(cdrom|none)$/) &&
1300 ($drive->{file
} !~ m
|^/dev/.+|) &&
1301 ($drive->{file
} !~ m/^([^:]+):(.+)$/) &&
1302 ($drive->{file
} !~ m/^\d+$/)) {
1303 my ($vtype, $volid) = PVE
::Storage
::path_to_volume_id
($storecfg, $drive->{file
});
1304 raise_param_exc
({ $opt => "unable to associate path '$drive->{file}' to any storage"}) if !$vtype;
1305 $drive->{media
} = 'cdrom' if !$drive->{media
} && $vtype eq 'iso';
1306 verify_media_type
($opt, $vtype, $drive->{media
});
1307 $drive->{file
} = $volid;
1310 $drive->{media
} = 'cdrom' if !$drive->{media
} && $drive->{file
} =~ m/^(cdrom|none)$/;
1313 sub parse_hotplug_features
{
1318 return $res if $data eq '0';
1320 $data = $confdesc->{hotplug
}->{default} if $data eq '1';
1322 foreach my $feature (PVE
::Tools
::split_list
($data)) {
1323 if ($feature =~ m/^(network|disk|cpu|memory|usb)$/) {
1326 die "invalid hotplug feature '$feature'\n";
1332 PVE
::JSONSchema
::register_format
('pve-hotplug-features', \
&pve_verify_hotplug_features
);
1333 sub pve_verify_hotplug_features
{
1334 my ($value, $noerr) = @_;
1336 return $value if parse_hotplug_features
($value);
1338 return undef if $noerr;
1340 die "unable to parse hotplug option\n";
1343 # ideX = [volume=]volume-id[,media=d][,cyls=c,heads=h,secs=s[,trans=t]]
1344 # [,snapshot=on|off][,cache=on|off][,format=f][,backup=yes|no]
1345 # [,rerror=ignore|report|stop][,werror=enospc|ignore|report|stop]
1346 # [,aio=native|threads][,discard=ignore|on][,detect_zeroes=on|off]
1347 # [,iothread=on][,serial=serial][,model=model]
1350 my ($key, $data) = @_;
1352 my ($interface, $index);
1354 if ($key =~ m/^([^\d]+)(\d+)$/) {
1361 my $desc = $key =~ /^unused\d+$/ ?
$alldrive_fmt
1362 : $confdesc->{$key}->{format
};
1364 warn "invalid drive key: $key\n";
1367 my $res = eval { PVE
::JSONSchema
::parse_property_string
($desc, $data) };
1368 return undef if !$res;
1369 $res->{interface
} = $interface;
1370 $res->{index} = $index;
1373 foreach my $opt (qw(bps bps_rd bps_wr)) {
1374 if (my $bps = defined(delete $res->{$opt})) {
1375 if (defined($res->{"m$opt"})) {
1376 warn "both $opt and m$opt specified\n";
1380 $res->{"m$opt"} = sprintf("%.3f", $bps / (1024*1024.0));
1384 # can't use the schema's 'requires' because of the mbps* => bps* "transforming aliases"
1385 for my $requirement (
1386 [bps_max_length
=> 'mbps_max'],
1387 [bps_rd_max_length
=> 'mbps_rd_max'],
1388 [bps_wr_max_length
=> 'mbps_wr_max'],
1389 [iops_max_length
=> 'iops_max'],
1390 [iops_rd_max_length
=> 'iops_rd_max'],
1391 [iops_wr_max_length
=> 'iops_wr_max']) {
1392 my ($option, $requires) = @$requirement;
1393 if ($res->{$option} && !$res->{$requires}) {
1394 warn "$option requires $requires\n";
1399 return undef if $error;
1401 return undef if $res->{mbps_rd
} && $res->{mbps
};
1402 return undef if $res->{mbps_wr
} && $res->{mbps
};
1403 return undef if $res->{iops_rd
} && $res->{iops
};
1404 return undef if $res->{iops_wr
} && $res->{iops
};
1406 if ($res->{media
} && ($res->{media
} eq 'cdrom')) {
1407 return undef if $res->{snapshot
} || $res->{trans
} || $res->{format
};
1408 return undef if $res->{heads
} || $res->{secs
} || $res->{cyls
};
1409 return undef if $res->{interface
} eq 'virtio';
1412 if (my $size = $res->{size
}) {
1413 return undef if !defined($res->{size
} = PVE
::JSONSchema
::parse_size
($size));
1420 my ($vmid, $drive) = @_;
1421 my $data = { %$drive };
1422 delete $data->{$_} for qw(index interface);
1423 return PVE
::JSONSchema
::print_property_string
($data, $alldrive_fmt);
1427 my($fh, $noerr) = @_;
1430 my $SG_GET_VERSION_NUM = 0x2282;
1432 my $versionbuf = "\x00" x
8;
1433 my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
1435 die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
1438 my $version = unpack("I", $versionbuf);
1439 if ($version < 30000) {
1440 die "scsi generic interface too old\n" if !$noerr;
1444 my $buf = "\x00" x
36;
1445 my $sensebuf = "\x00" x
8;
1446 my $cmd = pack("C x3 C x1", 0x12, 36);
1448 # see /usr/include/scsi/sg.h
1449 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";
1451 my $packet = pack($sg_io_hdr_t, ord('S'), -3, length($cmd),
1452 length($sensebuf), 0, length($buf), $buf,
1453 $cmd, $sensebuf, 6000);
1455 $ret = ioctl($fh, $SG_IO, $packet);
1457 die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
1461 my @res = unpack($sg_io_hdr_t, $packet);
1462 if ($res[17] || $res[18]) {
1463 die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
1468 (my $byte0, my $byte1, $res->{vendor
},
1469 $res->{product
}, $res->{revision
}) = unpack("C C x6 A8 A16 A4", $buf);
1471 $res->{removable
} = $byte1 & 128 ?
1 : 0;
1472 $res->{type
} = $byte0 & 31;
1480 my $fh = IO
::File-
>new("+<$path") || return undef;
1481 my $res = scsi_inquiry
($fh, 1);
1487 sub machine_type_is_q35
{
1490 return $conf->{machine
} && ($conf->{machine
} =~ m/q35/) ?
1 : 0;
1493 sub print_tabletdevice_full
{
1496 my $q35 = machine_type_is_q35
($conf);
1498 # we use uhci for old VMs because tablet driver was buggy in older qemu
1499 my $usbbus = $q35 ?
"ehci" : "uhci";
1501 return "usb-tablet,id=tablet,bus=$usbbus.0,port=1";
1504 sub print_drivedevice_full
{
1505 my ($storecfg, $conf, $vmid, $drive, $bridges) = @_;
1510 if ($drive->{interface
} eq 'virtio') {
1511 my $pciaddr = print_pci_addr
("$drive->{interface}$drive->{index}", $bridges);
1512 $device = "virtio-blk-pci,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}$pciaddr";
1513 $device .= ",iothread=iothread-$drive->{interface}$drive->{index}" if $drive->{iothread
};
1514 } elsif ($drive->{interface
} eq 'scsi') {
1516 my ($maxdev, $controller, $controller_prefix) = scsihw_infos
($conf, $drive);
1517 my $unit = $drive->{index} % $maxdev;
1518 my $devicetype = 'hd';
1520 if (drive_is_cdrom
($drive)) {
1523 if ($drive->{file
} =~ m
|^/|) {
1524 $path = $drive->{file
};
1525 if (my $info = path_is_scsi
($path)) {
1526 if ($info->{type
} == 0 && $drive->{scsiblock
}) {
1527 $devicetype = 'block';
1528 } elsif ($info->{type
} == 1) { # tape
1529 $devicetype = 'generic';
1533 $path = PVE
::Storage
::path
($storecfg, $drive->{file
});
1536 if($path =~ m/^iscsi\:\/\
//){
1537 $devicetype = 'generic';
1541 if (!$conf->{scsihw
} || ($conf->{scsihw
} =~ m/^lsi/)){
1542 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1544 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,channel=0,scsi-id=0,lun=$drive->{index},drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1547 } elsif ($drive->{interface
} eq 'ide'){
1549 my $controller = int($drive->{index} / $maxdev);
1550 my $unit = $drive->{index} % $maxdev;
1551 my $devicetype = ($drive->{media
} && $drive->{media
} eq 'cdrom') ?
"cd" : "hd";
1553 $device = "ide-$devicetype,bus=ide.$controller,unit=$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1554 if ($devicetype eq 'hd' && (my $model = $drive->{model
})) {
1555 $model = URI
::Escape
::uri_unescape
($model);
1556 $device .= ",model=$model";
1558 } elsif ($drive->{interface
} eq 'sata'){
1559 my $controller = int($drive->{index} / $MAX_SATA_DISKS);
1560 my $unit = $drive->{index} % $MAX_SATA_DISKS;
1561 $device = "ide-drive,bus=ahci$controller.$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1562 } elsif ($drive->{interface
} eq 'usb') {
1564 # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
1566 die "unsupported interface type";
1569 $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex
};
1574 sub get_initiator_name
{
1577 my $fh = IO
::File-
>new('/etc/iscsi/initiatorname.iscsi') || return undef;
1578 while (defined(my $line = <$fh>)) {
1579 next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/;
1588 sub print_drive_full
{
1589 my ($storecfg, $vmid, $drive) = @_;
1592 my $volid = $drive->{file
};
1595 if (drive_is_cdrom
($drive)) {
1596 $path = get_iso_path
($storecfg, $vmid, $volid);
1598 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1600 $path = PVE
::Storage
::path
($storecfg, $volid);
1601 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
1602 $format = qemu_img_format
($scfg, $volname);
1610 my @qemu_drive_options = qw(heads secs cyls trans media format cache snapshot rerror werror aio discard iops iops_rd iops_wr iops_max iops_rd_max iops_wr_max);
1611 foreach my $o (@qemu_drive_options) {
1612 $opts .= ",$o=$drive->{$o}" if $drive->{$o};
1614 if (my $serial = $drive->{serial
}) {
1615 $serial = URI
::Escape
::uri_unescape
($serial);
1616 $opts .= ",serial=$serial";
1619 $opts .= ",format=$format" if $format && !$drive->{format
};
1621 foreach my $o (qw(bps bps_rd bps_wr)) {
1622 my $v = $drive->{"m$o"};
1623 $opts .= ",$o=" . int($v*1024*1024) if $v;
1626 my $cache_direct = 0;
1628 if (my $cache = $drive->{cache
}) {
1629 $cache_direct = $cache =~ /^(?:off|none|directsync)$/;
1630 } elsif (!drive_is_cdrom
($drive)) {
1631 $opts .= ",cache=none";
1635 # aio native works only with O_DIRECT
1636 if (!$drive->{aio
}) {
1638 $opts .= ",aio=native";
1640 $opts .= ",aio=threads";
1644 if (!drive_is_cdrom
($drive)) {
1646 if (defined($drive->{detect_zeroes
}) && !$drive->{detect_zeroes
}) {
1647 $detectzeroes = 'off';
1648 } elsif ($drive->{discard
}) {
1649 $detectzeroes = $drive->{discard
} eq 'on' ?
'unmap' : 'on';
1651 # This used to be our default with discard not being specified:
1652 $detectzeroes = 'on';
1654 $opts .= ",detect-zeroes=$detectzeroes" if $detectzeroes;
1657 my $pathinfo = $path ?
"file=$path," : '';
1659 return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts";
1662 sub print_netdevice_full
{
1663 my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files) = @_;
1665 my $bootorder = $conf->{boot
} || $confdesc->{boot
}->{default};
1667 my $device = $net->{model
};
1668 if ($net->{model
} eq 'virtio') {
1669 $device = 'virtio-net-pci';
1672 my $pciaddr = print_pci_addr
("$netid", $bridges);
1673 my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid";
1674 if ($net->{queues
} && $net->{queues
} > 1 && $net->{model
} eq 'virtio'){
1675 #Consider we have N queues, the number of vectors needed is 2*N + 2 (plus one config interrupt and control vq)
1676 my $vectors = $net->{queues
} * 2 + 2;
1677 $tmpstr .= ",vectors=$vectors,mq=on";
1679 $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex
} ;
1681 if ($use_old_bios_files) {
1683 if ($device eq 'virtio-net-pci') {
1684 $romfile = 'pxe-virtio.rom';
1685 } elsif ($device eq 'e1000') {
1686 $romfile = 'pxe-e1000.rom';
1687 } elsif ($device eq 'ne2k') {
1688 $romfile = 'pxe-ne2k_pci.rom';
1689 } elsif ($device eq 'pcnet') {
1690 $romfile = 'pxe-pcnet.rom';
1691 } elsif ($device eq 'rtl8139') {
1692 $romfile = 'pxe-rtl8139.rom';
1694 $tmpstr .= ",romfile=$romfile" if $romfile;
1700 sub print_netdev_full
{
1701 my ($vmid, $conf, $net, $netid, $hotplug) = @_;
1704 if ($netid =~ m/^net(\d+)$/) {
1708 die "got strange net id '$i'\n" if $i >= ${MAX_NETS
};
1710 my $ifname = "tap${vmid}i$i";
1712 # kvm uses TUNSETIFF ioctl, and that limits ifname length
1713 die "interface name '$ifname' is too long (max 15 character)\n"
1714 if length($ifname) >= 16;
1716 my $vhostparam = '';
1717 $vhostparam = ',vhost=on' if $kernel_has_vhost_net && $net->{model
} eq 'virtio';
1719 my $vmname = $conf->{name
} || "vm$vmid";
1722 my $script = $hotplug ?
"pve-bridge-hotplug" : "pve-bridge";
1724 if ($net->{bridge
}) {
1725 $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script,downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam";
1727 $netdev = "type=user,id=$netid,hostname=$vmname";
1730 $netdev .= ",queues=$net->{queues}" if ($net->{queues
} && $net->{model
} eq 'virtio');
1736 sub print_cpu_device
{
1737 my ($conf, $id) = @_;
1739 my $nokvm = defined($conf->{kvm
}) && $conf->{kvm
} == 0 ?
1 : 0;
1740 my $cpu = $nokvm ?
"qemu64" : "kvm64";
1741 if (my $cputype = $conf->{cpu
}) {
1742 my $cpuconf = PVE
::JSONSchema
::parse_property_string
($cpu_fmt, $cputype)
1743 or die "Cannot parse cpu description: $cputype\n";
1744 $cpu = $cpuconf->{cputype
};
1748 $sockets = $conf->{sockets
} if $conf->{sockets
};
1749 my $cores = $conf->{cores
} || 1;
1751 my $current_core = ($id - 1) % $cores;
1752 my $current_socket = int(($id - $current_core)/$cores);
1754 return "$cpu-x86_64-cpu,id=cpu$id,socket-id=$current_socket,core-id=$current_core,thread-id=0";
1757 sub drive_is_cdrom
{
1760 return $drive && $drive->{media
} && ($drive->{media
} eq 'cdrom');
1764 sub parse_number_sets
{
1767 foreach my $part (split(/;/, $set)) {
1768 if ($part =~ /^\s*(\d+)(?:-(\d+))?\s*$/) {
1769 die "invalid range: $part ($2 < $1)\n" if defined($2) && $2 < $1;
1770 push @$res, [ $1, $2 ];
1772 die "invalid range: $part\n";
1781 my $res = PVE
::JSONSchema
::parse_property_string
($numa_fmt, $data);
1782 $res->{cpus
} = parse_number_sets
($res->{cpus
}) if defined($res->{cpus
});
1783 $res->{hostnodes
} = parse_number_sets
($res->{hostnodes
}) if defined($res->{hostnodes
});
1790 return undef if !$value;
1792 my $res = PVE
::JSONSchema
::parse_property_string
($hostpci_fmt, $value);
1794 my @idlist = split(/;/, $res->{host
});
1795 delete $res->{host
};
1796 foreach my $id (@idlist) {
1797 if ($id =~ /^$PCIRE$/) {
1799 push @{$res->{pciid
}}, { id
=> $1, function
=> $2 };
1801 my $pcidevices = lspci
($1);
1802 $res->{pciid
} = $pcidevices->{$1};
1805 # should have been caught by parse_property_string already
1806 die "failed to parse PCI id: $id\n";
1812 # netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps>
1816 my $res = eval { PVE
::JSONSchema
::parse_property_string
($net_fmt, $data) };
1821 if (!defined($res->{macaddr
})) {
1822 my $dc = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1823 $res->{macaddr
} = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
});
1831 return PVE
::JSONSchema
::print_property_string
($net, $net_fmt);
1834 sub add_random_macs
{
1835 my ($settings) = @_;
1837 foreach my $opt (keys %$settings) {
1838 next if $opt !~ m/^net(\d+)$/;
1839 my $net = parse_net
($settings->{$opt});
1841 $settings->{$opt} = print_net
($net);
1845 sub vm_is_volid_owner
{
1846 my ($storecfg, $vmid, $volid) = @_;
1848 if ($volid !~ m
|^/|) {
1850 eval { ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid); };
1851 if ($owner && ($owner == $vmid)) {
1859 sub split_flagged_list
{
1860 my $text = shift || '';
1861 $text =~ s/[,;]/ /g;
1863 return { map { /^(!?)(.*)$/ && ($2, $1) } ($text =~ /\S+/g) };
1866 sub join_flagged_list
{
1867 my ($how, $lst) = @_;
1868 join $how, map { $lst->{$_} . $_ } keys %$lst;
1871 sub vmconfig_delete_pending_option
{
1872 my ($conf, $key, $force) = @_;
1874 delete $conf->{pending
}->{$key};
1875 my $pending_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1876 $pending_delete_hash->{$key} = $force ?
'!' : '';
1877 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1880 sub vmconfig_undelete_pending_option
{
1881 my ($conf, $key) = @_;
1883 my $pending_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1884 delete $pending_delete_hash->{$key};
1886 if (%$pending_delete_hash) {
1887 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1889 delete $conf->{pending
}->{delete};
1893 sub vmconfig_register_unused_drive
{
1894 my ($storecfg, $vmid, $conf, $drive) = @_;
1896 if (!drive_is_cdrom
($drive)) {
1897 my $volid = $drive->{file
};
1898 if (vm_is_volid_owner
($storecfg, $vmid, $volid)) {
1899 PVE
::QemuConfig-
>add_unused_volume($conf, $volid, $vmid);
1904 sub vmconfig_cleanup_pending
{
1907 # remove pending changes when nothing changed
1909 foreach my $opt (keys %{$conf->{pending
}}) {
1910 if (defined($conf->{$opt}) && ($conf->{pending
}->{$opt} eq $conf->{$opt})) {
1912 delete $conf->{pending
}->{$opt};
1916 my $current_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1917 my $pending_delete_hash = {};
1918 while (my ($opt, $force) = each %$current_delete_hash) {
1919 if (defined($conf->{$opt})) {
1920 $pending_delete_hash->{$opt} = $force;
1926 if (%$pending_delete_hash) {
1927 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1929 delete $conf->{pending
}->{delete};
1935 # smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str]
1939 pattern
=> '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}',
1940 format_description
=> 'UUID',
1941 description
=> "Set SMBIOS1 UUID.",
1947 format_description
=> 'string',
1948 description
=> "Set SMBIOS1 version.",
1954 format_description
=> 'string',
1955 description
=> "Set SMBIOS1 serial number.",
1961 format_description
=> 'string',
1962 description
=> "Set SMBIOS1 manufacturer.",
1968 format_description
=> 'string',
1969 description
=> "Set SMBIOS1 product ID.",
1975 format_description
=> 'string',
1976 description
=> "Set SMBIOS1 SKU string.",
1982 format_description
=> 'string',
1983 description
=> "Set SMBIOS1 family string.",
1991 my $res = eval { PVE
::JSONSchema
::parse_property_string
($smbios1_fmt, $data) };
1998 return PVE
::JSONSchema
::print_property_string
($smbios1, $smbios1_fmt);
2001 PVE
::JSONSchema
::register_format
('pve-qm-smbios1', $smbios1_fmt);
2003 PVE
::JSONSchema
::register_format
('pve-qm-bootdisk', \
&verify_bootdisk
);
2004 sub verify_bootdisk
{
2005 my ($value, $noerr) = @_;
2007 return $value if is_valid_drivename
($value);
2009 return undef if $noerr;
2011 die "invalid boot disk '$value'\n";
2014 sub parse_watchdog
{
2017 return undef if !$value;
2019 my $res = eval { PVE
::JSONSchema
::parse_property_string
($watchdog_fmt, $value) };
2024 PVE
::JSONSchema
::register_format
('pve-qm-usb-device', \
&verify_usb_device
);
2025 sub verify_usb_device
{
2026 my ($value, $noerr) = @_;
2028 return $value if parse_usb_device
($value);
2030 return undef if $noerr;
2032 die "unable to parse usb device\n";
2035 # add JSON properties for create and set function
2036 sub json_config_properties
{
2039 foreach my $opt (keys %$confdesc) {
2040 next if $opt eq 'parent' || $opt eq 'snaptime' || $opt eq 'vmstate';
2041 $prop->{$opt} = $confdesc->{$opt};
2048 my ($key, $value) = @_;
2050 die "unknown setting '$key'\n" if !$confdesc->{$key};
2052 my $type = $confdesc->{$key}->{type
};
2054 if (!defined($value)) {
2055 die "got undefined value\n";
2058 if ($value =~ m/[\n\r]/) {
2059 die "property contains a line feed\n";
2062 if ($type eq 'boolean') {
2063 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
2064 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
2065 die "type check ('boolean') failed - got '$value'\n";
2066 } elsif ($type eq 'integer') {
2067 return int($1) if $value =~ m/^(\d+)$/;
2068 die "type check ('integer') failed - got '$value'\n";
2069 } elsif ($type eq 'number') {
2070 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
2071 die "type check ('number') failed - got '$value'\n";
2072 } elsif ($type eq 'string') {
2073 if (my $fmt = $confdesc->{$key}->{format
}) {
2074 PVE
::JSONSchema
::check_format
($fmt, $value);
2077 $value =~ s/^\"(.*)\"$/$1/;
2080 die "internal error"
2084 sub check_iommu_support
{
2085 #fixme : need to check IOMMU support
2086 #http://www.linux-kvm.org/page/How_to_assign_devices_with_VT-d_in_KVM
2096 my $conf = PVE
::QemuConfig-
>config_file($vmid);
2097 utime undef, undef, $conf;
2101 my ($storecfg, $vmid, $keep_empty_config, $skiplock) = @_;
2103 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
2105 my $conf = PVE
::QemuConfig-
>load_config($vmid);
2107 PVE
::QemuConfig-
>check_lock($conf) if !$skiplock;
2109 # only remove disks owned by this VM
2110 foreach_drive
($conf, sub {
2111 my ($ds, $drive) = @_;
2113 return if drive_is_cdrom
($drive);
2115 my $volid = $drive->{file
};
2117 return if !$volid || $volid =~ m
|^/|;
2119 my ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid);
2120 return if !$path || !$owner || ($owner != $vmid);
2123 PVE
::Storage
::vdisk_free
($storecfg, $volid);
2125 warn "Could not remove disk '$volid', check manually: $@" if $@;
2129 if ($keep_empty_config) {
2130 PVE
::Tools
::file_set_contents
($conffile, "memory: 128\n");
2135 # also remove unused disk
2137 my $dl = PVE
::Storage
::vdisk_list
($storecfg, undef, $vmid);
2140 PVE
::Storage
::foreach_volid
($dl, sub {
2141 my ($volid, $sid, $volname, $d) = @_;
2142 PVE
::Storage
::vdisk_free
($storecfg, $volid);
2151 sub parse_vm_config
{
2152 my ($filename, $raw) = @_;
2154 return undef if !defined($raw);
2157 digest
=> Digest
::SHA
::sha1_hex
($raw),
2162 $filename =~ m
|/qemu-server/(\d
+)\
.conf
$|
2163 || die "got strange filename '$filename'";
2171 my @lines = split(/\n/, $raw);
2172 foreach my $line (@lines) {
2173 next if $line =~ m/^\s*$/;
2175 if ($line =~ m/^\[PENDING\]\s*$/i) {
2176 $section = 'pending';
2177 if (defined($descr)) {
2179 $conf->{description
} = $descr;
2182 $conf = $res->{$section} = {};
2185 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
2187 if (defined($descr)) {
2189 $conf->{description
} = $descr;
2192 $conf = $res->{snapshots
}->{$section} = {};
2196 if ($line =~ m/^\#(.*)\s*$/) {
2197 $descr = '' if !defined($descr);
2198 $descr .= PVE
::Tools
::decode_text
($1) . "\n";
2202 if ($line =~ m/^(description):\s*(.*\S)\s*$/) {
2203 $descr = '' if !defined($descr);
2204 $descr .= PVE
::Tools
::decode_text
($2);
2205 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
2206 $conf->{snapstate
} = $1;
2207 } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) {
2210 $conf->{$key} = $value;
2211 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
2213 if ($section eq 'pending') {
2214 $conf->{delete} = $value; # we parse this later
2216 warn "vm $vmid - propertry 'delete' is only allowed in [PENDING]\n";
2218 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(\S+)\s*$/) {
2221 eval { $value = check_type
($key, $value); };
2223 warn "vm $vmid - unable to parse value of '$key' - $@";
2225 $key = 'ide2' if $key eq 'cdrom';
2226 my $fmt = $confdesc->{$key}->{format
};
2227 if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) {
2228 my $v = parse_drive
($key, $value);
2229 if (my $volid = filename_to_volume_id
($vmid, $v->{file
}, $v->{media
})) {
2230 $v->{file
} = $volid;
2231 $value = print_drive
($vmid, $v);
2233 warn "vm $vmid - unable to parse value of '$key'\n";
2238 $conf->{$key} = $value;
2243 if (defined($descr)) {
2245 $conf->{description
} = $descr;
2247 delete $res->{snapstate
}; # just to be sure
2252 sub write_vm_config
{
2253 my ($filename, $conf) = @_;
2255 delete $conf->{snapstate
}; # just to be sure
2257 if ($conf->{cdrom
}) {
2258 die "option ide2 conflicts with cdrom\n" if $conf->{ide2
};
2259 $conf->{ide2
} = $conf->{cdrom
};
2260 delete $conf->{cdrom
};
2263 # we do not use 'smp' any longer
2264 if ($conf->{sockets
}) {
2265 delete $conf->{smp
};
2266 } elsif ($conf->{smp
}) {
2267 $conf->{sockets
} = $conf->{smp
};
2268 delete $conf->{cores
};
2269 delete $conf->{smp
};
2272 my $used_volids = {};
2274 my $cleanup_config = sub {
2275 my ($cref, $pending, $snapname) = @_;
2277 foreach my $key (keys %$cref) {
2278 next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' ||
2279 $key eq 'snapstate' || $key eq 'pending';
2280 my $value = $cref->{$key};
2281 if ($key eq 'delete') {
2282 die "propertry 'delete' is only allowed in [PENDING]\n"
2284 # fixme: check syntax?
2287 eval { $value = check_type
($key, $value); };
2288 die "unable to parse value of '$key' - $@" if $@;
2290 $cref->{$key} = $value;
2292 if (!$snapname && is_valid_drivename
($key)) {
2293 my $drive = parse_drive
($key, $value);
2294 $used_volids->{$drive->{file
}} = 1 if $drive && $drive->{file
};
2299 &$cleanup_config($conf);
2301 &$cleanup_config($conf->{pending
}, 1);
2303 foreach my $snapname (keys %{$conf->{snapshots
}}) {
2304 die "internal error" if $snapname eq 'pending';
2305 &$cleanup_config($conf->{snapshots
}->{$snapname}, undef, $snapname);
2308 # remove 'unusedX' settings if we re-add a volume
2309 foreach my $key (keys %$conf) {
2310 my $value = $conf->{$key};
2311 if ($key =~ m/^unused/ && $used_volids->{$value}) {
2312 delete $conf->{$key};
2316 my $generate_raw_config = sub {
2317 my ($conf, $pending) = @_;
2321 # add description as comment to top of file
2322 if (defined(my $descr = $conf->{description
})) {
2324 foreach my $cl (split(/\n/, $descr)) {
2325 $raw .= '#' . PVE
::Tools
::encode_text
($cl) . "\n";
2328 $raw .= "#\n" if $pending;
2332 foreach my $key (sort keys %$conf) {
2333 next if $key eq 'digest' || $key eq 'description' || $key eq 'pending' || $key eq 'snapshots';
2334 $raw .= "$key: $conf->{$key}\n";
2339 my $raw = &$generate_raw_config($conf);
2341 if (scalar(keys %{$conf->{pending
}})){
2342 $raw .= "\n[PENDING]\n";
2343 $raw .= &$generate_raw_config($conf->{pending
}, 1);
2346 foreach my $snapname (sort keys %{$conf->{snapshots
}}) {
2347 $raw .= "\n[$snapname]\n";
2348 $raw .= &$generate_raw_config($conf->{snapshots
}->{$snapname});
2358 # we use static defaults from our JSON schema configuration
2359 foreach my $key (keys %$confdesc) {
2360 if (defined(my $default = $confdesc->{$key}->{default})) {
2361 $res->{$key} = $default;
2365 my $conf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
2366 $res->{keyboard
} = $conf->{keyboard
} if $conf->{keyboard
};
2372 my $vmlist = PVE
::Cluster
::get_vmlist
();
2374 return $res if !$vmlist || !$vmlist->{ids
};
2375 my $ids = $vmlist->{ids
};
2377 foreach my $vmid (keys %$ids) {
2378 my $d = $ids->{$vmid};
2379 next if !$d->{node
} || $d->{node
} ne $nodename;
2380 next if !$d->{type
} || $d->{type
} ne 'qemu';
2381 $res->{$vmid}->{exists} = 1;
2386 # test if VM uses local resources (to prevent migration)
2387 sub check_local_resources
{
2388 my ($conf, $noerr) = @_;
2392 $loc_res = 1 if $conf->{hostusb
}; # old syntax
2393 $loc_res = 1 if $conf->{hostpci
}; # old syntax
2395 foreach my $k (keys %$conf) {
2396 next if $k =~ m/^usb/ && ($conf->{$k} eq 'spice');
2397 # sockets are safe: they will recreated be on the target side post-migrate
2398 next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket');
2399 $loc_res = 1 if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/;
2402 die "VM uses local resources\n" if $loc_res && !$noerr;
2407 # check if used storages are available on all nodes (use by migrate)
2408 sub check_storage_availability
{
2409 my ($storecfg, $conf, $node) = @_;
2411 foreach_drive
($conf, sub {
2412 my ($ds, $drive) = @_;
2414 my $volid = $drive->{file
};
2417 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2420 # check if storage is available on both nodes
2421 my $scfg = PVE
::Storage
::storage_check_node
($storecfg, $sid);
2422 PVE
::Storage
::storage_check_node
($storecfg, $sid, $node);
2426 # list nodes where all VM images are available (used by has_feature API)
2428 my ($conf, $storecfg) = @_;
2430 my $nodelist = PVE
::Cluster
::get_nodelist
();
2431 my $nodehash = { map { $_ => 1 } @$nodelist };
2432 my $nodename = PVE
::INotify
::nodename
();
2434 foreach_drive
($conf, sub {
2435 my ($ds, $drive) = @_;
2437 my $volid = $drive->{file
};
2440 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2442 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
2443 if ($scfg->{disable
}) {
2445 } elsif (my $avail = $scfg->{nodes
}) {
2446 foreach my $node (keys %$nodehash) {
2447 delete $nodehash->{$node} if !$avail->{$node};
2449 } elsif (!$scfg->{shared
}) {
2450 foreach my $node (keys %$nodehash) {
2451 delete $nodehash->{$node} if $node ne $nodename
2461 my ($pidfile, $pid) = @_;
2463 my $fh = IO
::File-
>new("/proc/$pid/cmdline", "r");
2467 return undef if !$line;
2468 my @param = split(/\0/, $line);
2470 my $cmd = $param[0];
2471 return if !$cmd || ($cmd !~ m
|kvm
$| && $cmd !~ m
|qemu-system-x86_64
$|);
2473 for (my $i = 0; $i < scalar (@param); $i++) {
2476 if (($p eq '-pidfile') || ($p eq '--pidfile')) {
2477 my $p = $param[$i+1];
2478 return 1 if $p && ($p eq $pidfile);
2487 my ($vmid, $nocheck, $node) = @_;
2489 my $filename = PVE
::QemuConfig-
>config_file($vmid, $node);
2491 die "unable to find configuration file for VM $vmid - no such machine\n"
2492 if !$nocheck && ! -f
$filename;
2494 my $pidfile = pidfile_name
($vmid);
2496 if (my $fd = IO
::File-
>new("<$pidfile")) {
2501 my $mtime = $st->mtime;
2502 if ($mtime > time()) {
2503 warn "file '$filename' modified in future\n";
2506 if ($line =~ m/^(\d+)$/) {
2508 if (check_cmdline
($pidfile, $pid)) {
2509 if (my $pinfo = PVE
::ProcFSTools
::check_process_running
($pid)) {
2521 my $vzlist = config_list
();
2523 my $fd = IO
::Dir-
>new($var_run_tmpdir) || return $vzlist;
2525 while (defined(my $de = $fd->read)) {
2526 next if $de !~ m/^(\d+)\.pid$/;
2528 next if !defined($vzlist->{$vmid});
2529 if (my $pid = check_running
($vmid)) {
2530 $vzlist->{$vmid}->{pid
} = $pid;
2538 my ($storecfg, $conf) = @_;
2540 my $bootdisk = $conf->{bootdisk
};
2541 return undef if !$bootdisk;
2542 return undef if !is_valid_drivename
($bootdisk);
2544 return undef if !$conf->{$bootdisk};
2546 my $drive = parse_drive
($bootdisk, $conf->{$bootdisk});
2547 return undef if !defined($drive);
2549 return undef if drive_is_cdrom
($drive);
2551 my $volid = $drive->{file
};
2552 return undef if !$volid;
2554 return $drive->{size
};
2557 my $last_proc_pid_stat;
2559 # get VM status information
2560 # This must be fast and should not block ($full == false)
2561 # We only query KVM using QMP if $full == true (this can be slow)
2563 my ($opt_vmid, $full) = @_;
2567 my $storecfg = PVE
::Storage
::config
();
2569 my $list = vzlist
();
2570 my ($uptime) = PVE
::ProcFSTools
::read_proc_uptime
(1);
2572 my $cpucount = $cpuinfo->{cpus
} || 1;
2574 foreach my $vmid (keys %$list) {
2575 next if $opt_vmid && ($vmid ne $opt_vmid);
2577 my $cfspath = PVE
::QemuConfig-
>cfs_config_path($vmid);
2578 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
2581 $d->{pid
} = $list->{$vmid}->{pid
};
2583 # fixme: better status?
2584 $d->{status
} = $list->{$vmid}->{pid
} ?
'running' : 'stopped';
2586 my $size = disksize
($storecfg, $conf);
2587 if (defined($size)) {
2588 $d->{disk
} = 0; # no info available
2589 $d->{maxdisk
} = $size;
2595 $d->{cpus
} = ($conf->{sockets
} || 1) * ($conf->{cores
} || 1);
2596 $d->{cpus
} = $cpucount if $d->{cpus
} > $cpucount;
2597 $d->{cpus
} = $conf->{vcpus
} if $conf->{vcpus
};
2599 $d->{name
} = $conf->{name
} || "VM $vmid";
2600 $d->{maxmem
} = $conf->{memory
} ?
$conf->{memory
}*(1024*1024) : 0;
2602 if ($conf->{balloon
}) {
2603 $d->{balloon_min
} = $conf->{balloon
}*(1024*1024);
2604 $d->{shares
} = defined($conf->{shares
}) ?
$conf->{shares
} : 1000;
2615 $d->{diskwrite
} = 0;
2617 $d->{template
} = PVE
::QemuConfig-
>is_template($conf);
2622 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
2623 foreach my $dev (keys %$netdev) {
2624 next if $dev !~ m/^tap([1-9]\d*)i/;
2626 my $d = $res->{$vmid};
2629 $d->{netout
} += $netdev->{$dev}->{receive
};
2630 $d->{netin
} += $netdev->{$dev}->{transmit
};
2633 $d->{nics
}->{$dev}->{netout
} = $netdev->{$dev}->{receive
};
2634 $d->{nics
}->{$dev}->{netin
} = $netdev->{$dev}->{transmit
};
2639 my $ctime = gettimeofday
;
2641 foreach my $vmid (keys %$list) {
2643 my $d = $res->{$vmid};
2644 my $pid = $d->{pid
};
2647 my $pstat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
2648 next if !$pstat; # not running
2650 my $used = $pstat->{utime} + $pstat->{stime
};
2652 $d->{uptime
} = int(($uptime - $pstat->{starttime
})/$cpuinfo->{user_hz
});
2654 if ($pstat->{vsize
}) {
2655 $d->{mem
} = int(($pstat->{rss
}/$pstat->{vsize
})*$d->{maxmem
});
2658 my $old = $last_proc_pid_stat->{$pid};
2660 $last_proc_pid_stat->{$pid} = {
2668 my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
2670 if ($dtime > 1000) {
2671 my $dutime = $used - $old->{used
};
2673 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
2674 $last_proc_pid_stat->{$pid} = {
2680 $d->{cpu
} = $old->{cpu
};
2684 return $res if !$full;
2686 my $qmpclient = PVE
::QMPClient-
>new();
2688 my $ballooncb = sub {
2689 my ($vmid, $resp) = @_;
2691 my $info = $resp->{'return'};
2692 return if !$info->{max_mem
};
2694 my $d = $res->{$vmid};
2696 # use memory assigned to VM
2697 $d->{maxmem
} = $info->{max_mem
};
2698 $d->{balloon
} = $info->{actual
};
2700 if (defined($info->{total_mem
}) && defined($info->{free_mem
})) {
2701 $d->{mem
} = $info->{total_mem
} - $info->{free_mem
};
2702 $d->{freemem
} = $info->{free_mem
};
2705 $d->{ballooninfo
} = $info;
2708 my $blockstatscb = sub {
2709 my ($vmid, $resp) = @_;
2710 my $data = $resp->{'return'} || [];
2711 my $totalrdbytes = 0;
2712 my $totalwrbytes = 0;
2714 for my $blockstat (@$data) {
2715 $totalrdbytes = $totalrdbytes + $blockstat->{stats
}->{rd_bytes
};
2716 $totalwrbytes = $totalwrbytes + $blockstat->{stats
}->{wr_bytes
};
2718 $blockstat->{device
} =~ s/drive-//;
2719 $res->{$vmid}->{blockstat
}->{$blockstat->{device
}} = $blockstat->{stats
};
2721 $res->{$vmid}->{diskread
} = $totalrdbytes;
2722 $res->{$vmid}->{diskwrite
} = $totalwrbytes;
2725 my $statuscb = sub {
2726 my ($vmid, $resp) = @_;
2728 $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats');
2729 # this fails if ballon driver is not loaded, so this must be
2730 # the last commnand (following command are aborted if this fails).
2731 $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon');
2733 my $status = 'unknown';
2734 if (!defined($status = $resp->{'return'}->{status
})) {
2735 warn "unable to get VM status\n";
2739 $res->{$vmid}->{qmpstatus
} = $resp->{'return'}->{status
};
2742 foreach my $vmid (keys %$list) {
2743 next if $opt_vmid && ($vmid ne $opt_vmid);
2744 next if !$res->{$vmid}->{pid
}; # not running
2745 $qmpclient->queue_cmd($vmid, $statuscb, 'query-status');
2748 $qmpclient->queue_execute(undef, 2);
2750 foreach my $vmid (keys %$list) {
2751 next if $opt_vmid && ($vmid ne $opt_vmid);
2752 $res->{$vmid}->{qmpstatus
} = $res->{$vmid}->{status
} if !$res->{$vmid}->{qmpstatus
};
2759 my ($conf, $func, @param) = @_;
2761 foreach my $ds (valid_drive_names
()) {
2762 next if !defined($conf->{$ds});
2764 my $drive = parse_drive
($ds, $conf->{$ds});
2767 &$func($ds, $drive, @param);
2772 my ($conf, $func, @param) = @_;
2776 my $test_volid = sub {
2777 my ($volid, $is_cdrom) = @_;
2781 $volhash->{$volid} = $is_cdrom || 0;
2784 foreach_drive
($conf, sub {
2785 my ($ds, $drive) = @_;
2786 &$test_volid($drive->{file
}, drive_is_cdrom
($drive));
2789 foreach my $snapname (keys %{$conf->{snapshots
}}) {
2790 my $snap = $conf->{snapshots
}->{$snapname};
2791 &$test_volid($snap->{vmstate
}, 0);
2792 foreach_drive
($snap, sub {
2793 my ($ds, $drive) = @_;
2794 &$test_volid($drive->{file
}, drive_is_cdrom
($drive));
2798 foreach my $volid (keys %$volhash) {
2799 &$func($volid, $volhash->{$volid}, @param);
2803 sub vga_conf_has_spice
{
2806 return 0 if !$vga || $vga !~ m/^qxl([234])?$/;
2811 sub config_to_command
{
2812 my ($storecfg, $vmid, $conf, $defaults, $forcemachine) = @_;
2815 my $globalFlags = [];
2816 my $machineFlags = [];
2822 my $kvmver = kvm_user_version
();
2823 my $vernum = 0; # unknown
2824 my $ostype = $conf->{ostype
};
2825 my $winversion = windows_version
($ostype);
2827 if ($kvmver =~ m/^(\d+)\.(\d+)$/) {
2828 $vernum = $1*1000000+$2*1000;
2829 } elsif ($kvmver =~ m/^(\d+)\.(\d+)\.(\d+)$/) {
2830 $vernum = $1*1000000+$2*1000+$3;
2833 die "detected old qemu-kvm binary ($kvmver)\n" if $vernum < 15000;
2835 my $have_ovz = -f
'/proc/vz/vestat';
2837 my $q35 = machine_type_is_q35
($conf);
2838 my $hotplug_features = parse_hotplug_features
(defined($conf->{hotplug
}) ?
$conf->{hotplug
} : '1');
2839 my $machine_type = $forcemachine || $conf->{machine
};
2840 my $use_old_bios_files = undef;
2841 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files
($machine_type);
2843 my $cpuunits = defined($conf->{cpuunits
}) ?
2844 $conf->{cpuunits
} : $defaults->{cpuunits
};
2846 push @$cmd, '/usr/bin/kvm';
2848 push @$cmd, '-id', $vmid;
2852 my $qmpsocket = qmp_socket
($vmid);
2853 push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server,nowait";
2854 push @$cmd, '-mon', "chardev=qmp,mode=control";
2857 push @$cmd, '-pidfile' , pidfile_name
($vmid);
2859 push @$cmd, '-daemonize';
2861 if ($conf->{smbios1
}) {
2862 push @$cmd, '-smbios', "type=1,$conf->{smbios1}";
2865 if ($conf->{bios
} && $conf->{bios
} eq 'ovmf') {
2868 # prefer the OVMF_CODE variant
2869 if (-f
$OVMF_CODE) {
2870 $ovmfbase = $OVMF_CODE;
2871 } elsif (-f
$OVMF_IMG) {
2872 $ovmfbase = $OVMF_IMG;
2875 die "no uefi base img found\n" if !$ovmfbase;
2876 push @$cmd, '-drive', "if=pflash,unit=0,format=raw,readonly,file=$ovmfbase";
2878 if (defined($conf->{efidisk0
}) && ($ovmfbase eq $OVMF_CODE)) {
2879 my $d = PVE
::JSONSchema
::parse_property_string
($efidisk_fmt, $conf->{efidisk0
});
2880 my $format = $d->{format
} // 'raw';
2882 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($d->{file
}, 1);
2884 $path = PVE
::Storage
::path
($storecfg, $d->{file
});
2885 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
2886 $format = qemu_img_format
($scfg, $volname);
2891 push @$cmd, '-drive', "if=pflash,unit=1,id=drive-efidisk0,format=$format,file=$path";
2892 } elsif ($ovmfbase eq $OVMF_CODE) {
2893 warn "using uefi without permanent efivars disk\n";
2894 my $ovmfvar_dst = "/tmp/$vmid-ovmf.fd";
2895 PVE
::Tools
::file_copy
($OVMF_VARS, $ovmfvar_dst, 256*1024);
2896 push @$cmd, '-drive', "if=pflash,unit=1,format=raw,file=$ovmfvar_dst";
2898 # if the base img is not OVMF_CODE, we do not have to bother
2899 # to create/use a vars image, since it will not be used anyway
2900 # this can only happen if someone manually deletes the OVMF_CODE image
2901 # or has an old pve-qemu-kvm version installed.
2902 # both should not happen, but we ignore it here
2907 # add usb controllers
2908 my @usbcontrollers = PVE
::QemuServer
::USB
::get_usb_controllers
($conf, $bridges, $q35, $usbdesc->{format
}, $MAX_USB_DEVICES);
2909 push @$devices, @usbcontrollers if @usbcontrollers;
2910 my $vga = $conf->{vga
};
2912 my $qxlnum = vga_conf_has_spice
($vga);
2913 $vga = 'qxl' if $qxlnum;
2916 $vga = $winversion >= 6 ?
'std' : 'cirrus';
2919 # enable absolute mouse coordinates (needed by vnc)
2921 if (defined($conf->{tablet
})) {
2922 $tablet = $conf->{tablet
};
2924 $tablet = $defaults->{tablet
};
2925 $tablet = 0 if $qxlnum; # disable for spice because it is not needed
2926 $tablet = 0 if $vga =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card)
2929 push @$devices, '-device', print_tabletdevice_full
($conf) if $tablet;
2932 my $gpu_passthrough;
2935 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
2936 my $d = parse_hostpci
($conf->{"hostpci$i"});
2939 my $pcie = $d->{pcie
};
2941 die "q35 machine model is not enabled" if !$q35;
2942 $pciaddr = print_pcie_addr
("hostpci$i");
2944 $pciaddr = print_pci_addr
("hostpci$i", $bridges);
2947 my $rombar = defined($d->{rombar
}) && !$d->{rombar
} ?
',rombar=0' : '';
2948 my $romfile = $d->{romfile
};
2951 if ($d->{'x-vga'}) {
2952 $xvga = ',x-vga=on';
2955 $gpu_passthrough = 1;
2957 if ($conf->{bios
} && $conf->{bios
} eq 'ovmf') {
2961 my $pcidevices = $d->{pciid
};
2962 my $multifunction = 1 if @$pcidevices > 1;
2965 foreach my $pcidevice (@$pcidevices) {
2967 my $id = "hostpci$i";
2968 $id .= ".$j" if $multifunction;
2969 my $addr = $pciaddr;
2970 $addr .= ".$j" if $multifunction;
2971 my $devicestr = "vfio-pci,host=$pcidevice->{id}.$pcidevice->{function},id=$id$addr";
2974 $devicestr .= "$rombar$xvga";
2975 $devicestr .= ",multifunction=on" if $multifunction;
2976 $devicestr .= ",romfile=/usr/share/kvm/$romfile" if $romfile;
2979 push @$devices, '-device', $devicestr;
2985 my @usbdevices = PVE
::QemuServer
::USB
::get_usb_devices
($conf, $usbdesc->{format
}, $MAX_USB_DEVICES);
2986 push @$devices, @usbdevices if @usbdevices;
2988 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
2989 if (my $path = $conf->{"serial$i"}) {
2990 if ($path eq 'socket') {
2991 my $socket = "/var/run/qemu-server/${vmid}.serial$i";
2992 push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server,nowait";
2993 push @$devices, '-device', "isa-serial,chardev=serial$i";
2995 die "no such serial device\n" if ! -c
$path;
2996 push @$devices, '-chardev', "tty,id=serial$i,path=$path";
2997 push @$devices, '-device', "isa-serial,chardev=serial$i";
3003 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
3004 if (my $path = $conf->{"parallel$i"}) {
3005 die "no such parallel device\n" if ! -c
$path;
3006 my $devtype = $path =~ m!^/dev/usb/lp! ?
'tty' : 'parport';
3007 push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path";
3008 push @$devices, '-device', "isa-parallel,chardev=parallel$i";
3012 my $vmname = $conf->{name
} || "vm$vmid";
3014 push @$cmd, '-name', $vmname;
3017 $sockets = $conf->{smp
} if $conf->{smp
}; # old style - no longer iused
3018 $sockets = $conf->{sockets
} if $conf->{sockets
};
3020 my $cores = $conf->{cores
} || 1;
3022 my $maxcpus = $sockets * $cores;
3024 my $vcpus = $conf->{vcpus
} ?
$conf->{vcpus
} : $maxcpus;
3026 my $allowed_vcpus = $cpuinfo->{cpus
};
3028 die "MAX $allowed_vcpus vcpus allowed per VM on this node\n"
3029 if ($allowed_vcpus < $maxcpus);
3031 if($hotplug_features->{cpu
} && qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 7)) {
3033 push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3034 for (my $i = 2; $i <= $vcpus; $i++) {
3035 my $cpustr = print_cpu_device
($conf,$i);
3036 push @$cmd, '-device', $cpustr;
3041 push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3043 push @$cmd, '-nodefaults';
3045 my $bootorder = $conf->{boot
} || $confdesc->{boot
}->{default};
3047 my $bootindex_hash = {};
3049 foreach my $o (split(//, $bootorder)) {
3050 $bootindex_hash->{$o} = $i*100;
3054 push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg";
3056 push @$cmd, '-no-acpi' if defined($conf->{acpi
}) && $conf->{acpi
} == 0;
3058 push @$cmd, '-no-reboot' if defined($conf->{reboot
}) && $conf->{reboot
} == 0;
3060 push @$cmd, '-vga', $vga if $vga && $vga !~ m/^serial\d+$/; # for kvm 77 and later
3062 if ($vga && $vga !~ m/^serial\d+$/ && $vga ne 'none'){
3063 my $socket = vnc_socket
($vmid);
3064 push @$cmd, '-vnc', "unix:$socket,x509,password";
3066 push @$cmd, '-nographic';
3070 my $tdf = defined($conf->{tdf
}) ?
$conf->{tdf
} : $defaults->{tdf
};
3072 my $nokvm = defined($conf->{kvm
}) && $conf->{kvm
} == 0 ?
1 : 0;
3073 my $useLocaltime = $conf->{localtime};
3075 if ($winversion >= 5) { # windows
3076 $useLocaltime = 1 if !defined($conf->{localtime});
3078 # use time drift fix when acpi is enabled
3079 if (!(defined($conf->{acpi
}) && $conf->{acpi
} == 0)) {
3080 $tdf = 1 if !defined($conf->{tdf
});
3084 if ($winversion >= 6) {
3085 push @$globalFlags, 'kvm-pit.lost_tick_policy=discard';
3086 push @$cmd, '-no-hpet';
3089 push @$rtcFlags, 'driftfix=slew' if $tdf;
3092 push @$machineFlags, 'accel=tcg';
3094 die "No accelerator found!\n" if !$cpuinfo->{hvm
};
3097 if ($machine_type) {
3098 push @$machineFlags, "type=${machine_type}";
3101 if ($conf->{startdate
}) {
3102 push @$rtcFlags, "base=$conf->{startdate}";
3103 } elsif ($useLocaltime) {
3104 push @$rtcFlags, 'base=localtime';
3107 my $cpu = $nokvm ?
"qemu64" : "kvm64";
3108 if (my $cputype = $conf->{cpu
}) {
3109 my $cpuconf = PVE
::JSONSchema
::parse_property_string
($cpu_fmt, $cputype)
3110 or die "Cannot parse cpu description: $cputype\n";
3111 $cpu = $cpuconf->{cputype
};
3112 $kvm_off = 1 if $cpuconf->{hidden
};
3115 push @$cpuFlags , '+lahf_lm' if $cpu eq 'kvm64';
3117 push @$cpuFlags , '-x2apic'
3118 if $conf->{ostype
} && $conf->{ostype
} eq 'solaris';
3120 push @$cpuFlags, '+sep' if $cpu eq 'kvm64' || $cpu eq 'kvm32';
3122 push @$cpuFlags, '-rdtscp' if $cpu =~ m/^Opteron/;
3124 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
3126 push @$cpuFlags , '+kvm_pv_unhalt' if !$nokvm;
3127 push @$cpuFlags , '+kvm_pv_eoi' if !$nokvm;
3130 add_hyperv_enlighments
($cpuFlags, $winversion, $machine_type, $kvmver, $nokvm, $conf->{bios
}, $gpu_passthrough);
3132 push @$cpuFlags, 'enforce' if $cpu ne 'host' && !$nokvm;
3134 push @$cpuFlags, 'kvm=off' if $kvm_off;
3136 my $cpu_vendor = $cpu_vendor_list->{$cpu} ||
3137 die "internal error"; # should not happen
3139 push @$cpuFlags, "vendor=${cpu_vendor}"
3140 if $cpu_vendor ne 'default';
3142 $cpu .= "," . join(',', @$cpuFlags) if scalar(@$cpuFlags);
3144 push @$cmd, '-cpu', $cpu;
3146 PVE
::QemuServer
::Memory
::config
($conf, $vmid, $sockets, $cores, $defaults, $hotplug_features, $cmd);
3148 push @$cmd, '-S' if $conf->{freeze
};
3150 # set keyboard layout
3151 my $kb = $conf->{keyboard
} || $defaults->{keyboard
};
3152 push @$cmd, '-k', $kb if $kb;
3155 #my $soundhw = $conf->{soundhw} || $defaults->{soundhw};
3156 #push @$cmd, '-soundhw', 'es1370';
3157 #push @$cmd, '-soundhw', $soundhw if $soundhw;
3159 if($conf->{agent
}) {
3160 my $qgasocket = qmp_socket
($vmid, 1);
3161 my $pciaddr = print_pci_addr
("qga0", $bridges);
3162 push @$devices, '-chardev', "socket,path=$qgasocket,server,nowait,id=qga0";
3163 push @$devices, '-device', "virtio-serial,id=qga0$pciaddr";
3164 push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0';
3172 for(my $i = 1; $i < $qxlnum; $i++){
3173 my $pciaddr = print_pci_addr
("vga$i", $bridges);
3174 push @$cmd, '-device', "qxl,id=vga$i,ram_size=67108864,vram_size=33554432$pciaddr";
3177 # assume other OS works like Linux
3178 push @$cmd, '-global', 'qxl-vga.ram_size=134217728';
3179 push @$cmd, '-global', 'qxl-vga.vram_size=67108864';
3183 my $pciaddr = print_pci_addr
("spice", $bridges);
3185 my $nodename = PVE
::INotify
::nodename
();
3186 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
3187 $spice_port = PVE
::Tools
::next_spice_port
($pfamily);
3189 push @$devices, '-spice', "tls-port=${spice_port},addr=localhost,tls-ciphers=HIGH,seamless-migration=on";
3191 push @$devices, '-device', "virtio-serial,id=spice$pciaddr";
3192 push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent";
3193 push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0";
3196 # enable balloon by default, unless explicitly disabled
3197 if (!defined($conf->{balloon
}) || $conf->{balloon
}) {
3198 $pciaddr = print_pci_addr
("balloon0", $bridges);
3199 push @$devices, '-device', "virtio-balloon-pci,id=balloon0$pciaddr";
3202 if ($conf->{watchdog
}) {
3203 my $wdopts = parse_watchdog
($conf->{watchdog
});
3204 $pciaddr = print_pci_addr
("watchdog", $bridges);
3205 my $watchdog = $wdopts->{model
} || 'i6300esb';
3206 push @$devices, '-device', "$watchdog$pciaddr";
3207 push @$devices, '-watchdog-action', $wdopts->{action
} if $wdopts->{action
};
3211 my $scsicontroller = {};
3212 my $ahcicontroller = {};
3213 my $scsihw = defined($conf->{scsihw
}) ?
$conf->{scsihw
} : $defaults->{scsihw
};
3215 # Add iscsi initiator name if available
3216 if (my $initiator = get_initiator_name
()) {
3217 push @$devices, '-iscsi', "initiator-name=$initiator";
3220 foreach_drive
($conf, sub {
3221 my ($ds, $drive) = @_;
3223 if (PVE
::Storage
::parse_volume_id
($drive->{file
}, 1)) {
3224 push @$vollist, $drive->{file
};
3227 $use_virtio = 1 if $ds =~ m/^virtio/;
3229 if (drive_is_cdrom
($drive)) {
3230 if ($bootindex_hash->{d
}) {
3231 $drive->{bootindex
} = $bootindex_hash->{d
};
3232 $bootindex_hash->{d
} += 1;
3235 if ($bootindex_hash->{c
}) {
3236 $drive->{bootindex
} = $bootindex_hash->{c
} if $conf->{bootdisk
} && ($conf->{bootdisk
} eq $ds);
3237 $bootindex_hash->{c
} += 1;
3241 if($drive->{interface
} eq 'virtio'){
3242 push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread
};
3245 if ($drive->{interface
} eq 'scsi') {
3247 my ($maxdev, $controller, $controller_prefix) = scsihw_infos
($conf, $drive);
3249 $pciaddr = print_pci_addr
("$controller_prefix$controller", $bridges);
3250 my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ?
"virtio-scsi-pci" : $scsihw;
3253 if($conf->{scsihw
} && $conf->{scsihw
} eq "virtio-scsi-single" && $drive->{iothread
}){
3254 $iothread .= ",iothread=iothread-$controller_prefix$controller";
3255 push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller";
3256 } elsif ($drive->{iothread
}) {
3257 warn "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n";
3261 if($conf->{scsihw
} && $conf->{scsihw
} eq "virtio-scsi-single" && $drive->{queues
}){
3262 $queues = ",num_queues=$drive->{queues}";
3265 push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues" if !$scsicontroller->{$controller};
3266 $scsicontroller->{$controller}=1;
3269 if ($drive->{interface
} eq 'sata') {
3270 my $controller = int($drive->{index} / $MAX_SATA_DISKS);
3271 $pciaddr = print_pci_addr
("ahci$controller", $bridges);
3272 push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr" if !$ahcicontroller->{$controller};
3273 $ahcicontroller->{$controller}=1;
3276 if ($drive->{interface
} eq 'efidisk') {
3277 # this will be added somewhere else
3281 my $drive_cmd = print_drive_full
($storecfg, $vmid, $drive);
3282 push @$devices, '-drive',$drive_cmd;
3283 push @$devices, '-device', print_drivedevice_full
($storecfg, $conf, $vmid, $drive, $bridges);
3286 for (my $i = 0; $i < $MAX_NETS; $i++) {
3287 next if !$conf->{"net$i"};
3288 my $d = parse_net
($conf->{"net$i"});
3291 $use_virtio = 1 if $d->{model
} eq 'virtio';
3293 if ($bootindex_hash->{n
}) {
3294 $d->{bootindex
} = $bootindex_hash->{n
};
3295 $bootindex_hash->{n
} += 1;
3298 my $netdevfull = print_netdev_full
($vmid,$conf,$d,"net$i");
3299 push @$devices, '-netdev', $netdevfull;
3301 my $netdevicefull = print_netdevice_full
($vmid, $conf, $d, "net$i", $bridges, $use_old_bios_files);
3302 push @$devices, '-device', $netdevicefull;
3307 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
3312 $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/;
3314 while (my ($k, $v) = each %$bridges) {
3315 $pciaddr = print_pci_addr
("pci.$k");
3316 unshift @$devices, '-device', "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr" if $k > 0;
3321 if ($conf->{args
}) {
3322 my $aa = PVE
::Tools
::split_args
($conf->{args
});
3326 push @$cmd, @$devices;
3327 push @$cmd, '-rtc', join(',', @$rtcFlags)
3328 if scalar(@$rtcFlags);
3329 push @$cmd, '-machine', join(',', @$machineFlags)
3330 if scalar(@$machineFlags);
3331 push @$cmd, '-global', join(',', @$globalFlags)
3332 if scalar(@$globalFlags);
3334 return wantarray ?
($cmd, $vollist, $spice_port) : $cmd;
3339 return "${var_run_tmpdir}/$vmid.vnc";
3345 my $res = vm_mon_cmd
($vmid, 'query-spice');
3347 return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n";
3351 my ($vmid, $qga) = @_;
3352 my $sockettype = $qga ?
'qga' : 'qmp';
3353 return "${var_run_tmpdir}/$vmid.$sockettype";
3358 return "${var_run_tmpdir}/$vmid.pid";
3361 sub vm_devices_list
{
3364 my $res = vm_mon_cmd
($vmid, 'query-pci');
3366 foreach my $pcibus (@$res) {
3367 foreach my $device (@{$pcibus->{devices
}}) {
3368 next if !$device->{'qdev_id'};
3369 if ($device->{'pci_bridge'}) {
3370 $devices->{$device->{'qdev_id'}} = 1;
3371 foreach my $bridge_device (@{$device->{'pci_bridge'}->{devices
}}) {
3372 next if !$bridge_device->{'qdev_id'};
3373 $devices->{$bridge_device->{'qdev_id'}} = 1;
3374 $devices->{$device->{'qdev_id'}}++;
3377 $devices->{$device->{'qdev_id'}} = 1;
3382 my $resblock = vm_mon_cmd
($vmid, 'query-block');
3383 foreach my $block (@$resblock) {
3384 if($block->{device
} =~ m/^drive-(\S+)/){
3389 my $resmice = vm_mon_cmd
($vmid, 'query-mice');
3390 foreach my $mice (@$resmice) {
3391 if ($mice->{name
} eq 'QEMU HID Tablet') {
3392 $devices->{tablet
} = 1;
3397 # for usb devices there is no query-usb
3398 # but we can iterate over the entries in
3399 # qom-list path=/machine/peripheral
3400 my $resperipheral = vm_mon_cmd
($vmid, 'qom-list', path
=> '/machine/peripheral');
3401 foreach my $per (@$resperipheral) {
3402 if ($per->{name
} =~ m/^usb\d+$/) {
3403 $devices->{$per->{name
}} = 1;
3411 my ($storecfg, $conf, $vmid, $deviceid, $device) = @_;
3413 my $q35 = machine_type_is_q35
($conf);
3415 my $devices_list = vm_devices_list
($vmid);
3416 return 1 if defined($devices_list->{$deviceid});
3418 qemu_add_pci_bridge
($storecfg, $conf, $vmid, $deviceid); # add PCI bridge if we need it for the device
3420 if ($deviceid eq 'tablet') {
3422 qemu_deviceadd
($vmid, print_tabletdevice_full
($conf));
3424 } elsif ($deviceid =~ m/^usb(\d+)$/) {
3426 die "usb hotplug currently not reliable\n";
3427 # since we can't reliably hot unplug all added usb devices
3428 # and usb passthrough disables live migration
3429 # we disable usb hotplugging for now
3430 qemu_deviceadd
($vmid, PVE
::QemuServer
::USB
::print_usbdevice_full
($conf, $deviceid, $device));
3432 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
3434 qemu_iothread_add
($vmid, $deviceid, $device);
3436 qemu_driveadd
($storecfg, $vmid, $device);
3437 my $devicefull = print_drivedevice_full
($storecfg, $conf, $vmid, $device);
3439 qemu_deviceadd
($vmid, $devicefull);
3440 eval { qemu_deviceaddverify
($vmid, $deviceid); };
3442 eval { qemu_drivedel
($vmid, $deviceid); };
3447 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3450 my $scsihw = defined($conf->{scsihw
}) ?
$conf->{scsihw
} : "lsi";
3451 my $pciaddr = print_pci_addr
($deviceid);
3452 my $scsihw_type = $scsihw eq 'virtio-scsi-single' ?
"virtio-scsi-pci" : $scsihw;
3454 my $devicefull = "$scsihw_type,id=$deviceid$pciaddr";
3456 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread
}) {
3457 qemu_iothread_add
($vmid, $deviceid, $device);
3458 $devicefull .= ",iothread=iothread-$deviceid";
3461 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues
}) {
3462 $devicefull .= ",num_queues=$device->{queues}";
3465 qemu_deviceadd
($vmid, $devicefull);
3466 qemu_deviceaddverify
($vmid, $deviceid);
3468 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
3470 qemu_findorcreatescsihw
($storecfg,$conf, $vmid, $device);
3471 qemu_driveadd
($storecfg, $vmid, $device);
3473 my $devicefull = print_drivedevice_full
($storecfg, $conf, $vmid, $device);
3474 eval { qemu_deviceadd
($vmid, $devicefull); };
3476 eval { qemu_drivedel
($vmid, $deviceid); };
3481 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
3483 return undef if !qemu_netdevadd
($vmid, $conf, $device, $deviceid);
3485 my $machine_type = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
3486 my $use_old_bios_files = undef;
3487 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files
($machine_type);
3489 my $netdevicefull = print_netdevice_full
($vmid, $conf, $device, $deviceid, undef, $use_old_bios_files);
3490 qemu_deviceadd
($vmid, $netdevicefull);
3491 eval { qemu_deviceaddverify
($vmid, $deviceid); };
3493 eval { qemu_netdevdel
($vmid, $deviceid); };
3498 } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) {
3501 my $pciaddr = print_pci_addr
($deviceid);
3502 my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr";
3504 qemu_deviceadd
($vmid, $devicefull);
3505 qemu_deviceaddverify
($vmid, $deviceid);
3508 die "can't hotplug device '$deviceid'\n";
3514 # fixme: this should raise exceptions on error!
3515 sub vm_deviceunplug
{
3516 my ($vmid, $conf, $deviceid) = @_;
3518 my $devices_list = vm_devices_list
($vmid);
3519 return 1 if !defined($devices_list->{$deviceid});
3521 die "can't unplug bootdisk" if $conf->{bootdisk
} && $conf->{bootdisk
} eq $deviceid;
3523 if ($deviceid eq 'tablet') {
3525 qemu_devicedel
($vmid, $deviceid);
3527 } elsif ($deviceid =~ m/^usb\d+$/) {
3529 die "usb hotplug currently not reliable\n";
3530 # when unplugging usb devices this way,
3531 # there may be remaining usb controllers/hubs
3532 # so we disable it for now
3533 qemu_devicedel
($vmid, $deviceid);
3534 qemu_devicedelverify
($vmid, $deviceid);
3536 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
3538 qemu_devicedel
($vmid, $deviceid);
3539 qemu_devicedelverify
($vmid, $deviceid);
3540 qemu_drivedel
($vmid, $deviceid);
3541 qemu_iothread_del
($conf, $vmid, $deviceid);
3543 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3545 qemu_devicedel
($vmid, $deviceid);
3546 qemu_devicedelverify
($vmid, $deviceid);
3547 qemu_iothread_del
($conf, $vmid, $deviceid);
3549 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
3551 #qemu 2.3 segfault on drive_del with virtioscsi + iothread
3552 my $device = parse_drive
($deviceid, $conf->{$deviceid});
3553 die "virtioscsi with iothread is not hot-unplugglable currently" if $device->{iothread
};
3555 qemu_devicedel
($vmid, $deviceid);
3556 qemu_drivedel
($vmid, $deviceid);
3557 qemu_deletescsihw
($conf, $vmid, $deviceid);
3559 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
3561 qemu_devicedel
($vmid, $deviceid);
3562 qemu_devicedelverify
($vmid, $deviceid);
3563 qemu_netdevdel
($vmid, $deviceid);
3566 die "can't unplug device '$deviceid'\n";
3572 sub qemu_deviceadd
{
3573 my ($vmid, $devicefull) = @_;
3575 $devicefull = "driver=".$devicefull;
3576 my %options = split(/[=,]/, $devicefull);
3578 vm_mon_cmd
($vmid, "device_add" , %options);
3581 sub qemu_devicedel
{
3582 my ($vmid, $deviceid) = @_;
3584 my $ret = vm_mon_cmd
($vmid, "device_del", id
=> $deviceid);
3587 sub qemu_iothread_add
{
3588 my($vmid, $deviceid, $device) = @_;
3590 if ($device->{iothread
}) {
3591 my $iothreads = vm_iothreads_list
($vmid);
3592 qemu_objectadd
($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"};
3596 sub qemu_iothread_del
{
3597 my($conf, $vmid, $deviceid) = @_;
3599 my $device = parse_drive
($deviceid, $conf->{$deviceid});
3600 if ($device->{iothread
}) {
3601 my $iothreads = vm_iothreads_list
($vmid);
3602 qemu_objectdel
($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"};
3606 sub qemu_objectadd
{
3607 my($vmid, $objectid, $qomtype) = @_;
3609 vm_mon_cmd
($vmid, "object-add", id
=> $objectid, "qom-type" => $qomtype);
3614 sub qemu_objectdel
{
3615 my($vmid, $objectid) = @_;
3617 vm_mon_cmd
($vmid, "object-del", id
=> $objectid);
3623 my ($storecfg, $vmid, $device) = @_;
3625 my $drive = print_drive_full
($storecfg, $vmid, $device);
3626 $drive =~ s/\\/\\\\/g;
3627 my $ret = vm_human_monitor_command
($vmid, "drive_add auto \"$drive\"");
3629 # If the command succeeds qemu prints: "OK
"
3630 return 1 if $ret =~ m/OK/s;
3632 die "adding drive failed
: $ret\n";
3636 my($vmid, $deviceid) = @_;
3638 my $ret = vm_human_monitor_command($vmid, "drive_del drive-
$deviceid");
3641 return 1 if $ret eq "";
3643 # NB: device not found errors mean the drive was auto-deleted and we ignore the error
3644 return 1 if $ret =~ m/Device \'.*?\' not found/s;
3646 die "deleting drive
$deviceid failed
: $ret\n";
3649 sub qemu_deviceaddverify {
3650 my ($vmid, $deviceid) = @_;
3652 for (my $i = 0; $i <= 5; $i++) {
3653 my $devices_list = vm_devices_list($vmid);
3654 return 1 if defined($devices_list->{$deviceid});
3658 die "error on hotplug device
'$deviceid'\n";
3662 sub qemu_devicedelverify {
3663 my ($vmid, $deviceid) = @_;
3665 # need to verify that the device is correctly removed as device_del
3666 # is async and empty return is not reliable
3668 for (my $i = 0; $i <= 5; $i++) {
3669 my $devices_list = vm_devices_list($vmid);
3670 return 1 if !defined($devices_list->{$deviceid});
3674 die "error on hot-unplugging device
'$deviceid'\n";
3677 sub qemu_findorcreatescsihw {
3678 my ($storecfg, $conf, $vmid, $device) = @_;
3680 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
3682 my $scsihwid="$controller_prefix$controller";
3683 my $devices_list = vm_devices_list($vmid);
3685 if(!defined($devices_list->{$scsihwid})) {
3686 vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device);
3692 sub qemu_deletescsihw {
3693 my ($conf, $vmid, $opt) = @_;
3695 my $device = parse_drive($opt, $conf->{$opt});
3697 if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
3698 vm_deviceunplug($vmid, $conf, "virtioscsi
$device->{index}");
3702 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
3704 my $devices_list = vm_devices_list($vmid);
3705 foreach my $opt (keys %{$devices_list}) {
3706 if (PVE::QemuServer::is_valid_drivename($opt)) {
3707 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
3708 if($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) {
3714 my $scsihwid="scsihw
$controller";
3716 vm_deviceunplug($vmid, $conf, $scsihwid);
3721 sub qemu_add_pci_bridge {
3722 my ($storecfg, $conf, $vmid, $device) = @_;
3728 print_pci_addr($device, $bridges);
3730 while (my ($k, $v) = each %$bridges) {
3733 return 1 if !defined($bridgeid) || $bridgeid < 1;
3735 my $bridge = "pci
.$bridgeid";
3736 my $devices_list = vm_devices_list($vmid);
3738 if (!defined($devices_list->{$bridge})) {
3739 vm_deviceplug($storecfg, $conf, $vmid, $bridge);
3745 sub qemu_set_link_status {
3746 my ($vmid, $device, $up) = @_;
3748 vm_mon_cmd($vmid, "set_link
", name => $device,
3749 up => $up ? JSON::true : JSON::false);
3752 sub qemu_netdevadd {
3753 my ($vmid, $conf, $device, $deviceid) = @_;
3755 my $netdev = print_netdev_full($vmid, $conf, $device, $deviceid, 1);
3756 my %options = split(/[=,]/, $netdev);
3758 vm_mon_cmd($vmid, "netdev_add
", %options);
3762 sub qemu_netdevdel {
3763 my ($vmid, $deviceid) = @_;
3765 vm_mon_cmd($vmid, "netdev_del
", id => $deviceid);
3768 sub qemu_usb_hotplug {
3769 my ($storecfg, $conf, $vmid, $deviceid, $device) = @_;
3773 # remove the old one first
3774 vm_deviceunplug($vmid, $conf, $deviceid);
3776 # check if xhci controller is necessary and available
3777 if ($device->{usb3}) {
3779 my $devicelist = vm_devices_list($vmid);
3781 if (!$devicelist->{xhci}) {
3782 my $pciaddr = print_pci_addr("xhci
");
3783 qemu_deviceadd($vmid, "nec-usb-xhci
,id
=xhci
$pciaddr");
3786 my $d = parse_usb_device($device->{host});
3787 $d->{usb3} = $device->{usb3};
3790 vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $d);
3793 sub qemu_cpu_hotplug {
3794 my ($vmid, $conf, $vcpus) = @_;
3796 my $machine_type = PVE::QemuServer::get_current_qemu_machine($vmid);
3799 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
3800 $sockets = $conf->{sockets} if $conf->{sockets};
3801 my $cores = $conf->{cores} || 1;
3802 my $maxcpus = $sockets * $cores;
3804 $vcpus = $maxcpus if !$vcpus;
3806 die "you can
't add more vcpus than maxcpus\n"
3807 if $vcpus > $maxcpus;
3809 my $currentvcpus = $conf->{vcpus} || $maxcpus;
3811 if ($vcpus < $currentvcpus) {
3813 if (qemu_machine_feature_enabled ($machine_type, undef, 2, 7)) {
3815 for (my $i = $currentvcpus; $i > $vcpus; $i--) {
3816 qemu_devicedel($vmid, "cpu$i");
3818 my $currentrunningvcpus = undef;
3820 $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3821 last if scalar(@{$currentrunningvcpus}) == $i-1;
3822 raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5;
3826 #update conf after each succesfull cpu unplug
3827 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
3828 PVE::QemuConfig->write_config($vmid, $conf);
3831 die "cpu hot-unplugging requires qemu version 2.7 or higher\n";
3837 my $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3838 die "vcpus in running vm does not match its configuration\n"
3839 if scalar(@{$currentrunningvcpus}) != $currentvcpus;
3841 if (qemu_machine_feature_enabled ($machine_type, undef, 2, 7)) {
3843 for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) {
3844 my $cpustr = print_cpu_device($conf, $i);
3845 qemu_deviceadd($vmid, $cpustr);
3848 my $currentrunningvcpus = undef;
3850 $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3851 last if scalar(@{$currentrunningvcpus}) == $i;
3852 raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10;
3856 #update conf after each succesfull cpu hotplug
3857 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
3858 PVE::QemuConfig->write_config($vmid, $conf);
3862 for (my $i = $currentvcpus; $i < $vcpus; $i++) {
3863 vm_mon_cmd($vmid, "cpu-add", id => int($i));
3868 sub qemu_block_set_io_throttle {
3869 my ($vmid, $deviceid,
3870 $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr,
3871 $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max,
3872 $bps_max_length, $bps_rd_max_length, $bps_wr_max_length,
3873 $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_;
3875 return if !check_running($vmid) ;
3877 vm_mon_cmd($vmid, "block_set_io_throttle", device => $deviceid,
3879 bps_rd => int($bps_rd),
3880 bps_wr => int($bps_wr),
3882 iops_rd => int($iops_rd),
3883 iops_wr => int($iops_wr),
3884 bps_max => int($bps_max),
3885 bps_rd_max => int($bps_rd_max),
3886 bps_wr_max => int($bps_wr_max),
3887 iops_max => int($iops_max),
3888 iops_rd_max => int($iops_rd_max),
3889 iops_wr_max => int($iops_wr_max),
3890 bps_max_length => int($bps_max_length),
3891 bps_rd_max_length => int($bps_rd_max_length),
3892 bps_wr_max_length => int($bps_wr_max_length),
3893 iops_max_length => int($iops_max_length),
3894 iops_rd_max_length => int($iops_rd_max_length),
3895 iops_wr_max_length => int($iops_wr_max_length),
3900 # old code, only used to shutdown old VM after update
3902 my ($fh, $timeout) = @_;
3904 my $sel = new IO::Select;
3911 while (scalar (@ready = $sel->can_read($timeout))) {
3913 if ($count = $fh->sysread($buf, 8192)) {
3914 if ($buf =~ /^(.*)\(qemu\) $/s) {
3921 if (!defined($count)) {
3928 die "monitor read timeout\n" if !scalar(@ready);
3933 # old code, only used to shutdown old VM after update
3934 sub vm_monitor_command {
3935 my ($vmid, $cmdstr, $nocheck) = @_;
3940 die "VM $vmid not running\n" if !check_running($vmid, $nocheck);
3942 my $sname = "${var_run_tmpdir}/$vmid.mon";
3944 my $sock = IO::Socket::UNIX->new( Peer => $sname ) ||
3945 die "unable to connect to VM $vmid socket - $!\n";
3949 # hack: migrate sometime blocks the monitor (when migrate_downtime
3951 if ($cmdstr =~ m/^(info\s+migrate|migrate\s)/) {
3952 $timeout = 60*60; # 1 hour
3956 my $data = __read_avail($sock, $timeout);
3958 if ($data !~ m/^QEMU\s+(\S+)\s+monitor\s/) {
3959 die "got unexpected qemu monitor banner\n";
3962 my $sel = new IO::Select;
3965 if (!scalar(my @ready = $sel->can_write($timeout))) {
3966 die "monitor write error - timeout";
3969 my $fullcmd = "$cmdstr\r";
3971 # syslog('info
', "VM $vmid monitor command: $cmdstr");
3974 if (!($b = $sock->syswrite($fullcmd)) || ($b != length($fullcmd))) {
3975 die "monitor write error - $!";
3978 return if ($cmdstr eq 'q
') || ($cmdstr eq 'quit
');
3982 if ($cmdstr =~ m/^(info\s+migrate|migrate\s)/) {
3983 $timeout = 60*60; # 1 hour
3984 } elsif ($cmdstr =~ m/^(eject|change)/) {
3985 $timeout = 60; # note: cdrom mount command is slow
3987 if ($res = __read_avail($sock, $timeout)) {
3989 my @lines = split("\r?\n", $res);
3991 shift @lines if $lines[0] !~ m/^unknown command/; # skip echo
3993 $res = join("\n", @lines);
4001 syslog("err", "VM $vmid monitor command failed - $err");
4008 sub qemu_block_resize {
4009 my ($vmid, $deviceid, $storecfg, $volid, $size) = @_;
4011 my $running = check_running($vmid);
4013 $size = 0 if !PVE::Storage::volume_resize($storecfg, $volid, $size, $running);
4015 return if !$running;
4017 vm_mon_cmd($vmid, "block_resize", device => $deviceid, size => int($size));
4021 sub qemu_volume_snapshot {
4022 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4024 my $running = check_running($vmid);
4026 if ($running && do_snapshots_with_qemu($storecfg, $volid)){
4027 vm_mon_cmd($vmid, "snapshot-drive", device => $deviceid, name => $snap);
4029 PVE::Storage::volume_snapshot($storecfg, $volid, $snap);
4033 sub qemu_volume_snapshot_delete {
4034 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4036 my $running = check_running($vmid);
4038 if ($running && do_snapshots_with_qemu($storecfg, $volid)){
4039 vm_mon_cmd($vmid, "delete-drive-snapshot", device => $deviceid, name => $snap);
4041 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running);
4045 sub set_migration_caps {
4051 "auto-converge" => 1,
4053 "x-rdma-pin-all" => 0,
4058 my $supported_capabilities = vm_mon_cmd_nocheck($vmid, "query-migrate-capabilities");
4060 for my $supported_capability (@$supported_capabilities) {
4062 capability => $supported_capability->{capability},
4063 state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false,
4067 vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => $cap_ref);
4070 my $fast_plug_option = {
4080 # hotplug changes in [PENDING]
4081 # $selection hash can be used to only apply specified options, for
4082 # example: { cores => 1 } (only apply changed 'cores
')
4083 # $errors ref is used to return error messages
4084 sub vmconfig_hotplug_pending {
4085 my ($vmid, $conf, $storecfg, $selection, $errors) = @_;
4087 my $defaults = load_defaults();
4089 # commit values which do not have any impact on running VM first
4090 # Note: those option cannot raise errors, we we do not care about
4091 # $selection and always apply them.
4093 my $add_error = sub {
4094 my ($opt, $msg) = @_;
4095 $errors->{$opt} = "hotplug problem - $msg";
4099 foreach my $opt (keys %{$conf->{pending}}) { # add/change
4100 if ($fast_plug_option->{$opt}) {
4101 $conf->{$opt} = $conf->{pending}->{$opt};
4102 delete $conf->{pending}->{$opt};
4108 PVE::QemuConfig->write_config($vmid, $conf);
4109 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4112 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
4114 my $pending_delete_hash = split_flagged_list($conf->{pending}->{delete});
4115 while (my ($opt, $force) = each %$pending_delete_hash) {
4116 next if $selection && !$selection->{$opt};
4118 if ($opt eq 'hotplug
') {
4119 die "skip\n" if ($conf->{hotplug} =~ /memory/);
4120 } elsif ($opt eq 'tablet
') {
4121 die "skip\n" if !$hotplug_features->{usb};
4122 if ($defaults->{tablet}) {
4123 vm_deviceplug($storecfg, $conf, $vmid, $opt);
4125 vm_deviceunplug($vmid, $conf, $opt);
4127 } elsif ($opt =~ m/^usb\d+/) {
4129 # since we cannot reliably hot unplug usb devices
4130 # we are disabling it
4131 die "skip\n" if !$hotplug_features->{usb} || $conf->{$opt} =~ m/spice/i;
4132 vm_deviceunplug($vmid, $conf, $opt);
4133 } elsif ($opt eq 'vcpus
') {
4134 die "skip\n" if !$hotplug_features->{cpu};
4135 qemu_cpu_hotplug($vmid, $conf, undef);
4136 } elsif ($opt eq 'balloon
') {
4137 # enable balloon device is not hotpluggable
4138 die "skip\n" if !defined($conf->{balloon}) || $conf->{balloon};
4139 } elsif ($fast_plug_option->{$opt}) {
4141 } elsif ($opt =~ m/^net(\d+)$/) {
4142 die "skip\n" if !$hotplug_features->{network};
4143 vm_deviceunplug($vmid, $conf, $opt);
4144 } elsif (is_valid_drivename($opt)) {
4145 die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/;
4146 vm_deviceunplug($vmid, $conf, $opt);
4147 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4148 } elsif ($opt =~ m/^memory$/) {
4149 die "skip\n" if !$hotplug_features->{memory};
4150 PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt);
4151 } elsif ($opt eq 'cpuunits
') {
4152 cgroups_write("cpu", $vmid, "cpu.shares", $defaults->{cpuunits});
4153 } elsif ($opt eq 'cpulimit
') {
4154 cgroups_write("cpu", $vmid, "cpu.cfs_quota_us", -1);
4160 &$add_error($opt, $err) if $err ne "skip\n";
4162 # save new config if hotplug was successful
4163 delete $conf->{$opt};
4164 vmconfig_undelete_pending_option($conf, $opt);
4165 PVE::QemuConfig->write_config($vmid, $conf);
4166 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4170 foreach my $opt (keys %{$conf->{pending}}) {
4171 next if $selection && !$selection->{$opt};
4172 my $value = $conf->{pending}->{$opt};
4174 if ($opt eq 'hotplug
') {
4175 die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/);
4176 } elsif ($opt eq 'tablet
') {
4177 die "skip\n" if !$hotplug_features->{usb};
4179 vm_deviceplug($storecfg, $conf, $vmid, $opt);
4180 } elsif ($value == 0) {
4181 vm_deviceunplug($vmid, $conf, $opt);
4183 } elsif ($opt =~ m/^usb\d+$/) {
4185 # since we cannot reliably hot unplug usb devices
4186 # we are disabling it
4187 die "skip\n" if !$hotplug_features->{usb} || $value =~ m/spice/i;
4188 my $d = eval { PVE::JSONSchema::parse_property_string($usbdesc->{format}, $value) };
4189 die "skip\n" if !$d;
4190 qemu_usb_hotplug($storecfg, $conf, $vmid, $opt, $d);
4191 } elsif ($opt eq 'vcpus
') {
4192 die "skip\n" if !$hotplug_features->{cpu};
4193 qemu_cpu_hotplug($vmid, $conf, $value);
4194 } elsif ($opt eq 'balloon
') {
4195 # enable/disable balloning device is not hotpluggable
4196 my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon});
4197 my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon});
4198 die "skip\n" if $old_balloon_enabled != $new_balloon_enabled;
4200 # allow manual ballooning if shares is set to zero
4201 if ((defined($conf->{shares}) && ($conf->{shares} == 0))) {
4202 my $balloon = $conf->{pending}->{balloon} || $conf->{memory} || $defaults->{memory};
4203 vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
4205 } elsif ($opt =~ m/^net(\d+)$/) {
4206 # some changes can be done without hotplug
4207 vmconfig_update_net($storecfg, $conf, $hotplug_features->{network},
4208 $vmid, $opt, $value);
4209 } elsif (is_valid_drivename($opt)) {
4210 # some changes can be done without hotplug
4211 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
4212 $vmid, $opt, $value, 1);
4213 } elsif ($opt =~ m/^memory$/) { #dimms
4214 die "skip\n" if !$hotplug_features->{memory};
4215 $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt, $value);
4216 } elsif ($opt eq 'cpuunits
') {
4217 cgroups_write("cpu", $vmid, "cpu.shares", $conf->{pending}->{$opt});
4218 } elsif ($opt eq 'cpulimit
') {
4219 my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000);
4220 cgroups_write("cpu", $vmid, "cpu.cfs_quota_us", $cpulimit);
4222 die "skip\n"; # skip non-hot-pluggable options
4226 &$add_error($opt, $err) if $err ne "skip\n";
4228 # save new config if hotplug was successful
4229 $conf->{$opt} = $value;
4230 delete $conf->{pending}->{$opt};
4231 PVE::QemuConfig->write_config($vmid, $conf);
4232 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4237 sub try_deallocate_drive {
4238 my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_;
4240 if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) {
4241 my $volid = $drive->{file};
4242 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
4243 my $sid = PVE::Storage::parse_volume_id($volid);
4244 $rpcenv->check($authuser, "/storage/$sid", ['Datastore
.AllocateSpace
']);
4246 # check if the disk is really unused
4247 die "unable to delete '$volid' - volume is still in use (snapshot?)\n"
4248 if is_volume_in_use($storecfg, $conf, $key, $volid);
4249 PVE::Storage::vdisk_free($storecfg, $volid);
4252 # If vm is not owner of this disk remove from config
4260 sub vmconfig_delete_or_detach_drive {
4261 my ($vmid, $storecfg, $conf, $opt, $force) = @_;
4263 my $drive = parse_drive($opt, $conf->{$opt});
4265 my $rpcenv = PVE::RPCEnvironment::get();
4266 my $authuser = $rpcenv->get_user();
4269 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM
.Config
.Disk
']);
4270 try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force);
4272 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive);
4276 sub vmconfig_apply_pending {
4277 my ($vmid, $conf, $storecfg) = @_;
4281 my $pending_delete_hash = split_flagged_list($conf->{pending}->{delete});
4282 while (my ($opt, $force) = each %$pending_delete_hash) {
4283 die "internal error" if $opt =~ m/^unused/;
4284 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4285 if (!defined($conf->{$opt})) {
4286 vmconfig_undelete_pending_option($conf, $opt);
4287 PVE::QemuConfig->write_config($vmid, $conf);
4288 } elsif (is_valid_drivename($opt)) {
4289 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4290 vmconfig_undelete_pending_option($conf, $opt);
4291 delete $conf->{$opt};
4292 PVE::QemuConfig->write_config($vmid, $conf);
4294 vmconfig_undelete_pending_option($conf, $opt);
4295 delete $conf->{$opt};
4296 PVE::QemuConfig->write_config($vmid, $conf);
4300 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4302 foreach my $opt (keys %{$conf->{pending}}) { # add/change
4303 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4305 if (defined($conf->{$opt}) && ($conf->{$opt} eq $conf->{pending}->{$opt})) {
4306 # skip if nothing changed
4307 } elsif (is_valid_drivename($opt)) {
4308 vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt}))
4309 if defined($conf->{$opt});
4310 $conf->{$opt} = $conf->{pending}->{$opt};
4312 $conf->{$opt} = $conf->{pending}->{$opt};
4315 delete $conf->{pending}->{$opt};
4316 PVE::QemuConfig->write_config($vmid, $conf);
4320 my $safe_num_ne = sub {
4323 return 0 if !defined($a) && !defined($b);
4324 return 1 if !defined($a);
4325 return 1 if !defined($b);
4330 my $safe_string_ne = sub {
4333 return 0 if !defined($a) && !defined($b);
4334 return 1 if !defined($a);
4335 return 1 if !defined($b);
4340 sub vmconfig_update_net {
4341 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value) = @_;
4343 my $newnet = parse_net($value);
4345 if ($conf->{$opt}) {
4346 my $oldnet = parse_net($conf->{$opt});
4348 if (&$safe_string_ne($oldnet->{model}, $newnet->{model}) ||
4349 &$safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) ||
4350 &$safe_num_ne($oldnet->{queues}, $newnet->{queues}) ||
4351 !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change
4353 # for non online change, we try to hot-unplug
4354 die "skip\n" if !$hotplug;
4355 vm_deviceunplug($vmid, $conf, $opt);
4358 die "internal error" if $opt !~ m/net(\d+)/;
4359 my $iface = "tap${vmid}i$1";
4361 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
4362 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
4363 &$safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) ||
4364 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
4365 PVE::Network::tap_unplug($iface);
4366 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
4367 } elsif (&$safe_num_ne($oldnet->{rate}, $newnet->{rate})) {
4368 # Rate can be applied on its own but any change above needs to
4369 # include the rate in tap_plug since OVS resets everything.
4370 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
4373 if (&$safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) {
4374 qemu_set_link_status($vmid, $opt, !$newnet->{link_down});
4382 vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet);
4388 sub vmconfig_update_disk {
4389 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $force) = @_;
4391 # fixme: do we need force?
4393 my $drive = parse_drive($opt, $value);
4395 if ($conf->{$opt}) {
4397 if (my $old_drive = parse_drive($opt, $conf->{$opt})) {
4399 my $media = $drive->{media} || 'disk
';
4400 my $oldmedia = $old_drive->{media} || 'disk
';
4401 die "unable to change media type\n" if $media ne $oldmedia;
4403 if (!drive_is_cdrom($old_drive)) {
4405 if ($drive->{file} ne $old_drive->{file}) {
4407 die "skip\n" if !$hotplug;
4409 # unplug and register as unused
4410 vm_deviceunplug($vmid, $conf, $opt);
4411 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive)
4414 # update existing disk
4416 # skip non hotpluggable value
4417 if (&$safe_string_ne($drive->{discard}, $old_drive->{discard}) ||
4418 &$safe_string_ne($drive->{iothread}, $old_drive->{iothread}) ||
4419 &$safe_string_ne($drive->{queues}, $old_drive->{queues}) ||
4420 &$safe_string_ne($drive->{cache}, $old_drive->{cache})) {
4425 if (&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
4426 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
4427 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
4428 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
4429 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
4430 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) ||
4431 &$safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) ||
4432 &$safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) ||
4433 &$safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) ||
4434 &$safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) ||
4435 &$safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) ||
4436 &$safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) ||
4437 &$safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) ||
4438 &$safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) ||
4439 &$safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) ||
4440 &$safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) ||
4441 &$safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) ||
4442 &$safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) {
4444 qemu_block_set_io_throttle($vmid,"drive-$opt",
4445 ($drive->{mbps} || 0)*1024*1024,
4446 ($drive->{mbps_rd} || 0)*1024*1024,
4447 ($drive->{mbps_wr} || 0)*1024*1024,
4448 $drive->{iops} || 0,
4449 $drive->{iops_rd} || 0,
4450 $drive->{iops_wr} || 0,
4451 ($drive->{mbps_max} || 0)*1024*1024,
4452 ($drive->{mbps_rd_max} || 0)*1024*1024,
4453 ($drive->{mbps_wr_max} || 0)*1024*1024,
4454 $drive->{iops_max} || 0,
4455 $drive->{iops_rd_max} || 0,
4456 $drive->{iops_wr_max} || 0,
4457 $drive->{bps_max_length} || 1,
4458 $drive->{bps_rd_max_length} || 1,
4459 $drive->{bps_wr_max_length} || 1,
4460 $drive->{iops_max_length} || 1,
4461 $drive->{iops_rd_max_length} || 1,
4462 $drive->{iops_wr_max_length} || 1);
4471 if ($drive->{file} eq 'none
') {
4472 vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
4474 my $path = get_iso_path($storecfg, $vmid, $drive->{file});
4475 vm_mon_cmd($vmid, "eject", force => JSON::true,device => "drive-$opt"); # force eject if locked
4476 vm_mon_cmd($vmid, "change", device => "drive-$opt",target => "$path") if $path;
4484 die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/;
4486 PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|;
4487 vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
4491 my ($storecfg, $vmid, $statefile, $skiplock, $migratedfrom, $paused,
4492 $forcemachine, $spice_ticket, $migration_network, $migration_type, $targetstorage) = @_;
4494 PVE::QemuConfig->lock_config($vmid, sub {
4495 my $conf = PVE::QemuConfig->load_config($vmid, $migratedfrom);
4497 die "you can't start a vm
if it
's a template\n" if PVE::QemuConfig->is_template($conf);
4499 PVE::QemuConfig->check_lock($conf) if !$skiplock;
4501 die "VM $vmid already running\n" if check_running($vmid, undef, $migratedfrom);
4503 if (!$statefile && scalar(keys %{$conf->{pending}})) {
4504 vmconfig_apply_pending($vmid, $conf, $storecfg);
4505 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4508 my $defaults = load_defaults();
4510 # set environment variable useful inside network script
4511 $ENV{PVE_MIGRATED_FROM} = $migratedfrom if $migratedfrom;
4513 my $local_volumes = {};
4515 if ($targetstorage) {
4516 foreach_drive($conf, sub {
4517 my ($ds, $drive) = @_;
4519 return if drive_is_cdrom($drive);
4521 my $volid = $drive->{file};
4525 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
4527 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
4528 return if $scfg->{shared};
4529 $local_volumes->{$ds} = [$volid, $storeid, $volname];
4534 foreach my $opt (sort keys %$local_volumes) {
4536 my ($volid, $storeid, $volname) = @{$local_volumes->{$opt}};
4537 my $drive = parse_drive($opt, $conf->{$opt});
4539 #if remote storage is specified, use default format
4540 if ($targetstorage && $targetstorage ne "1") {
4541 $storeid = $targetstorage;
4542 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
4543 $format = $defFormat;
4545 #else we use same format than original
4546 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
4547 $format = qemu_img_format($scfg, $volid);
4550 my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, ($drive->{size}/1024));
4551 my $newdrive = $drive;
4552 $newdrive->{format} = $format;
4553 $newdrive->{file} = $newvolid;
4554 my $drivestr = PVE::QemuServer::print_drive($vmid, $newdrive);
4555 $local_volumes->{$opt} = $drivestr;
4556 #pass drive to conf for command line
4557 $conf->{$opt} = $drivestr;
4561 my ($cmd, $vollist, $spice_port) = config_to_command($storecfg, $vmid, $conf, $defaults, $forcemachine);
4563 my $migrate_port = 0;
4566 if ($statefile eq 'tcp
') {
4567 my $localip = "localhost";
4568 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter
.cfg
');
4569 my $nodename = PVE::INotify::nodename();
4571 if (!defined($migration_type)) {
4572 if (defined($datacenterconf->{migration}->{type})) {
4573 $migration_type = $datacenterconf->{migration}->{type};
4575 $migration_type = 'secure
';
4579 if ($migration_type eq 'insecure
') {
4580 my $migrate_network_addr = PVE::Cluster::get_local_migration_ip($migration_network);
4581 if ($migrate_network_addr) {
4582 $localip = $migrate_network_addr;
4584 $localip = PVE::Cluster::remote_node_ip($nodename, 1);
4587 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
4590 my $pfamily = PVE::Tools::get_host_address_family($nodename);
4591 $migrate_port = PVE::Tools::next_migrate_port($pfamily);
4592 $migrate_uri = "tcp:${localip}:${migrate_port}";
4593 push @$cmd, '-incoming
', $migrate_uri;
4596 } elsif ($statefile eq 'unix
') {
4597 # should be default for secure migrations as a ssh TCP forward
4598 # tunnel is not deterministic reliable ready and fails regurarly
4599 # to set up in time, so use UNIX socket forwards
4600 my $socket_addr = "/run/qemu-server/$vmid.migrate";
4601 unlink $socket_addr;
4603 $migrate_uri = "unix:$socket_addr";
4605 push @$cmd, '-incoming
', $migrate_uri;
4609 push @$cmd, '-loadstate
', $statefile;
4616 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
4617 my $d = parse_hostpci($conf->{"hostpci$i"});
4619 my $pcidevices = $d->{pciid};
4620 foreach my $pcidevice (@$pcidevices) {
4621 my $pciid = $pcidevice->{id}.".".$pcidevice->{function};
4623 my $info = pci_device_info("0000:$pciid");
4624 die "IOMMU not present\n" if !check_iommu_support();
4625 die "no pci device info for device '$pciid'\n" if !$info;
4626 die "can't unbind
/bind pci group to vfio
'$pciid'\n" if !pci_dev_group_bind_to_vfio($pciid);
4627 die "can
't reset pci device '$pciid'\n" if $info->{has_fl_reset} and !pci_dev_reset($info);
4631 PVE::Storage::activate_volumes($storecfg, $vollist);
4633 if (!check_running($vmid, 1) && -d "/sys/fs/cgroup/systemd/qemu.slice/$vmid.scope") {
4635 push @$cmd, '/bin/systemctl
', 'stop
', "$vmid.scope";
4636 eval { run_command($cmd); };
4639 my $cpuunits = defined($conf->{cpuunits}) ? $conf->{cpuunits}
4640 : $defaults->{cpuunits};
4642 my %run_params = (timeout => $statefile ? undef : 30, umask => 0077);
4645 Slice => 'qemu
.slice
',
4647 CPUShares => $cpuunits
4650 if (my $cpulimit = $conf->{cpulimit}) {
4651 $properties{CPUQuota} = int($cpulimit * 100);
4653 $properties{timeout} = 10 if $statefile; # setting up the scope shoul be quick
4655 if ($conf->{hugepages}) {
4658 my $hugepages_topology = PVE::QemuServer::Memory::hugepages_topology($conf);
4659 my $hugepages_host_topology = PVE::QemuServer::Memory::hugepages_host_topology();
4661 PVE::QemuServer::Memory::hugepages_mount();
4662 PVE::QemuServer::Memory::hugepages_allocate($hugepages_topology, $hugepages_host_topology);
4665 PVE::Tools::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %properties);
4666 run_command($cmd, %run_params);
4670 PVE::QemuServer::Memory::hugepages_reset($hugepages_host_topology);
4674 PVE::QemuServer::Memory::hugepages_pre_deallocate($hugepages_topology);
4676 eval { PVE::QemuServer::Memory::hugepages_update_locked($code); };
4680 PVE::Tools::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %properties);
4681 run_command($cmd, %run_params);
4686 # deactivate volumes if start fails
4687 eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); };
4688 die "start failed: $err";
4691 print "migration listens on $migrate_uri\n" if $migrate_uri;
4693 if ($statefile && $statefile ne 'tcp
' && $statefile ne 'unix
') {
4694 eval { vm_mon_cmd_nocheck($vmid, "cont"); };
4698 #start nbd server for storage migration
4699 if ($targetstorage) {
4700 my $nodename = PVE::INotify::nodename();
4701 my $migrate_network_addr = PVE::Cluster::get_local_migration_ip($migration_network);
4702 my $localip = $migrate_network_addr ? $migrate_network_addr : PVE::Cluster::remote_node_ip($nodename, 1);
4703 my $pfamily = PVE::Tools::get_host_address_family($nodename);
4704 $migrate_port = PVE::Tools::next_migrate_port($pfamily);
4706 vm_mon_cmd_nocheck($vmid, "nbd-server-start", addr => { type => 'inet
', data => { host => "${localip}", port => "${migrate_port}" } } );
4708 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
4710 foreach my $opt (sort keys %$local_volumes) {
4711 my $volid = $local_volumes->{$opt};
4712 vm_mon_cmd_nocheck($vmid, "nbd-server-add", device => "drive-$opt", writable => JSON::true );
4713 my $migrate_storage_uri = "nbd:${localip}:${migrate_port}:exportname=drive-$opt";
4714 print "storage migration listens on $migrate_storage_uri volume:$volid\n";
4718 if ($migratedfrom) {
4720 set_migration_caps($vmid);
4725 print "spice listens on port $spice_port\n";
4726 if ($spice_ticket) {
4727 vm_mon_cmd_nocheck($vmid, "set_password", protocol => 'spice
', password => $spice_ticket);
4728 vm_mon_cmd_nocheck($vmid, "expire_password", protocol => 'spice
', time => "+30");
4733 if (!$statefile && (!defined($conf->{balloon}) || $conf->{balloon})) {
4734 vm_mon_cmd_nocheck($vmid, "balloon", value => $conf->{balloon}*1024*1024)
4735 if $conf->{balloon};
4738 foreach my $opt (keys %$conf) {
4739 next if $opt !~ m/^net\d+$/;
4740 my $nicconf = parse_net($conf->{$opt});
4741 qemu_set_link_status($vmid, $opt, 0) if $nicconf->{link_down};
4745 vm_mon_cmd_nocheck($vmid, 'qom-set
',
4746 path => "machine/peripheral/balloon0",
4747 property => "guest-stats-polling-interval",
4748 value => 2) if (!defined($conf->{balloon}) || $conf->{balloon});
4754 my ($vmid, $execute, %params) = @_;
4756 my $cmd = { execute => $execute, arguments => \%params };
4757 vm_qmp_command($vmid, $cmd);
4760 sub vm_mon_cmd_nocheck {
4761 my ($vmid, $execute, %params) = @_;
4763 my $cmd = { execute => $execute, arguments => \%params };
4764 vm_qmp_command($vmid, $cmd, 1);
4767 sub vm_qmp_command {
4768 my ($vmid, $cmd, $nocheck) = @_;
4773 if ($cmd->{arguments} && $cmd->{arguments}->{timeout}) {
4774 $timeout = $cmd->{arguments}->{timeout};
4775 delete $cmd->{arguments}->{timeout};
4779 die "VM $vmid not running\n" if !check_running($vmid, $nocheck);
4780 my $sname = qmp_socket($vmid);
4781 if (-e $sname) { # test if VM is reasonambe new and supports qmp/qga
4782 my $qmpclient = PVE::QMPClient->new();
4784 $res = $qmpclient->cmd($vmid, $cmd, $timeout);
4785 } elsif (-e "${var_run_tmpdir}/$vmid.mon") {
4786 die "can't execute complex command on old monitor
- stop
/start your vm to fix the problem
\n"
4787 if scalar(%{$cmd->{arguments}});
4788 vm_monitor_command($vmid, $cmd->{execute}, $nocheck);
4790 die "unable to
open monitor
socket\n";
4794 syslog("err
", "VM
$vmid qmp command failed
- $err");
4801 sub vm_human_monitor_command {
4802 my ($vmid, $cmdline) = @_;
4807 execute => 'human-monitor-command',
4808 arguments => { 'command-line' => $cmdline},
4811 return vm_qmp_command($vmid, $cmd);
4814 sub vm_commandline {
4815 my ($storecfg, $vmid) = @_;
4817 my $conf = PVE::QemuConfig->load_config($vmid);
4819 my $defaults = load_defaults();
4821 my $cmd = config_to_command($storecfg, $vmid, $conf, $defaults);
4823 return PVE::Tools::cmd2string($cmd);
4827 my ($vmid, $skiplock) = @_;
4829 PVE::QemuConfig->lock_config($vmid, sub {
4831 my $conf = PVE::QemuConfig->load_config($vmid);
4833 PVE::QemuConfig->check_lock($conf) if !$skiplock;
4835 vm_mon_cmd($vmid, "system_reset
");
4839 sub get_vm_volumes {
4843 foreach_volid($conf, sub {
4844 my ($volid, $is_cdrom) = @_;
4846 return if $volid =~ m|^/|;
4848 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
4851 push @$vollist, $volid;
4857 sub vm_stop_cleanup {
4858 my ($storecfg, $vmid, $conf, $keepActive, $apply_pending_changes) = @_;
4863 my $vollist = get_vm_volumes($conf);
4864 PVE::Storage::deactivate_volumes($storecfg, $vollist);
4867 foreach my $ext (qw(mon qmp pid vnc qga)) {
4868 unlink "/var/run/qemu-server/${vmid}.$ext";
4871 vmconfig_apply_pending
($vmid, $conf, $storecfg) if $apply_pending_changes;
4873 warn $@ if $@; # avoid errors - just warn
4876 # Note: use $nockeck to skip tests if VM configuration file exists.
4877 # We need that when migration VMs to other nodes (files already moved)
4878 # Note: we set $keepActive in vzdump stop mode - volumes need to stay active
4880 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive, $migratedfrom) = @_;
4882 $force = 1 if !defined($force) && !$shutdown;
4885 my $pid = check_running
($vmid, $nocheck, $migratedfrom);
4886 kill 15, $pid if $pid;
4887 my $conf = PVE
::QemuConfig-
>load_config($vmid, $migratedfrom);
4888 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 0);
4892 PVE
::QemuConfig-
>lock_config($vmid, sub {
4894 my $pid = check_running
($vmid, $nocheck);
4899 $conf = PVE
::QemuConfig-
>load_config($vmid);
4900 PVE
::QemuConfig-
>check_lock($conf) if !$skiplock;
4901 if (!defined($timeout) && $shutdown && $conf->{startup
}) {
4902 my $opts = PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
});
4903 $timeout = $opts->{down
} if $opts->{down
};
4907 $timeout = 60 if !defined($timeout);
4911 if (defined($conf) && $conf->{agent
}) {
4912 vm_qmp_command
($vmid, { execute
=> "guest-shutdown" }, $nocheck);
4914 vm_qmp_command
($vmid, { execute
=> "system_powerdown" }, $nocheck);
4917 vm_qmp_command
($vmid, { execute
=> "quit" }, $nocheck);
4924 while (($count < $timeout) && check_running
($vmid, $nocheck)) {
4929 if ($count >= $timeout) {
4931 warn "VM still running - terminating now with SIGTERM\n";
4934 die "VM quit/powerdown failed - got timeout\n";
4937 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
4942 warn "VM quit/powerdown failed - terminating now with SIGTERM\n";
4945 die "VM quit/powerdown failed\n";
4953 while (($count < $timeout) && check_running
($vmid, $nocheck)) {
4958 if ($count >= $timeout) {
4959 warn "VM still running - terminating now with SIGKILL\n";
4964 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
4969 my ($vmid, $skiplock) = @_;
4971 PVE
::QemuConfig-
>lock_config($vmid, sub {
4973 my $conf = PVE
::QemuConfig-
>load_config($vmid);
4975 PVE
::QemuConfig-
>check_lock($conf)
4976 if !($skiplock || PVE
::QemuConfig-
>has_lock($conf, 'backup'));
4978 vm_mon_cmd
($vmid, "stop");
4983 my ($vmid, $skiplock, $nocheck) = @_;
4985 PVE
::QemuConfig-
>lock_config($vmid, sub {
4989 my $conf = PVE
::QemuConfig-
>load_config($vmid);
4991 PVE
::QemuConfig-
>check_lock($conf)
4992 if !($skiplock || PVE
::QemuConfig-
>has_lock($conf, 'backup'));
4994 vm_mon_cmd
($vmid, "cont");
4997 vm_mon_cmd_nocheck
($vmid, "cont");
5003 my ($vmid, $skiplock, $key) = @_;
5005 PVE
::QemuConfig-
>lock_config($vmid, sub {
5007 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5009 # there is no qmp command, so we use the human monitor command
5010 vm_human_monitor_command
($vmid, "sendkey $key");
5015 my ($storecfg, $vmid, $skiplock) = @_;
5017 PVE
::QemuConfig-
>lock_config($vmid, sub {
5019 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5021 if (!check_running
($vmid)) {
5022 destroy_vm
($storecfg, $vmid, undef, $skiplock);
5024 die "VM $vmid is running - destroy failed\n";
5032 my ($filename, $buf) = @_;
5034 my $fh = IO
::File-
>new($filename, "w");
5035 return undef if !$fh;
5037 my $res = print $fh $buf;
5044 sub pci_device_info
{
5049 return undef if $name !~ m/^([a-f0-9]{4}):([a-f0-9]{2}):([a-f0-9]{2})\.([a-f0-9])$/;
5050 my ($domain, $bus, $slot, $func) = ($1, $2, $3, $4);
5052 my $irq = file_read_firstline
("$pcisysfs/devices/$name/irq");
5053 return undef if !defined($irq) || $irq !~ m/^\d+$/;
5055 my $vendor = file_read_firstline
("$pcisysfs/devices/$name/vendor");
5056 return undef if !defined($vendor) || $vendor !~ s/^0x//;
5058 my $product = file_read_firstline
("$pcisysfs/devices/$name/device");
5059 return undef if !defined($product) || $product !~ s/^0x//;
5064 product
=> $product,
5070 has_fl_reset
=> -f
"$pcisysfs/devices/$name/reset" || 0,
5079 my $name = $dev->{name
};
5081 my $fn = "$pcisysfs/devices/$name/reset";
5083 return file_write
($fn, "1");
5086 sub pci_dev_bind_to_vfio
{
5089 my $name = $dev->{name
};
5091 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
5093 if (!-d
$vfio_basedir) {
5094 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
5096 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
5098 my $testdir = "$vfio_basedir/$name";
5099 return 1 if -d
$testdir;
5101 my $data = "$dev->{vendor} $dev->{product}";
5102 return undef if !file_write
("$vfio_basedir/new_id", $data);
5104 my $fn = "$pcisysfs/devices/$name/driver/unbind";
5105 if (!file_write
($fn, $name)) {
5106 return undef if -f
$fn;
5109 $fn = "$vfio_basedir/bind";
5110 if (! -d
$testdir) {
5111 return undef if !file_write
($fn, $name);
5117 sub pci_dev_group_bind_to_vfio
{
5120 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
5122 if (!-d
$vfio_basedir) {
5123 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
5125 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
5127 # get IOMMU group devices
5128 opendir(my $D, "$pcisysfs/devices/0000:$pciid/iommu_group/devices/") || die "Cannot open iommu_group: $!\n";
5129 my @devs = grep /^0000:/, readdir($D);
5132 foreach my $pciid (@devs) {
5133 $pciid =~ m/^([:\.\da-f]+)$/ or die "PCI ID $pciid not valid!\n";
5135 # pci bridges, switches or root ports are not supported
5136 # they have a pci_bus subdirectory so skip them
5137 next if (-e
"$pcisysfs/devices/$pciid/pci_bus");
5139 my $info = pci_device_info
($1);
5140 pci_dev_bind_to_vfio
($info) || die "Cannot bind $pciid to vfio\n";
5146 # vzdump restore implementaion
5148 sub tar_archive_read_firstfile
{
5149 my $archive = shift;
5151 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
5153 # try to detect archive type first
5154 my $pid = open (my $fh, '-|', 'tar', 'tf', $archive) ||
5155 die "unable to open file '$archive'\n";
5156 my $firstfile = <$fh>;
5160 die "ERROR: archive contaions no data\n" if !$firstfile;
5166 sub tar_restore_cleanup
{
5167 my ($storecfg, $statfile) = @_;
5169 print STDERR
"starting cleanup\n";
5171 if (my $fd = IO
::File-
>new($statfile, "r")) {
5172 while (defined(my $line = <$fd>)) {
5173 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
5176 if ($volid =~ m
|^/|) {
5177 unlink $volid || die 'unlink failed\n';
5179 PVE
::Storage
::vdisk_free
($storecfg, $volid);
5181 print STDERR
"temporary volume '$volid' sucessfuly removed\n";
5183 print STDERR
"unable to cleanup '$volid' - $@" if $@;
5185 print STDERR
"unable to parse line in statfile - $line";
5192 sub restore_archive
{
5193 my ($archive, $vmid, $user, $opts) = @_;
5195 my $format = $opts->{format
};
5198 if ($archive =~ m/\.tgz$/ || $archive =~ m/\.tar\.gz$/) {
5199 $format = 'tar' if !$format;
5201 } elsif ($archive =~ m/\.tar$/) {
5202 $format = 'tar' if !$format;
5203 } elsif ($archive =~ m/.tar.lzo$/) {
5204 $format = 'tar' if !$format;
5206 } elsif ($archive =~ m/\.vma$/) {
5207 $format = 'vma' if !$format;
5208 } elsif ($archive =~ m/\.vma\.gz$/) {
5209 $format = 'vma' if !$format;
5211 } elsif ($archive =~ m/\.vma\.lzo$/) {
5212 $format = 'vma' if !$format;
5215 $format = 'vma' if !$format; # default
5218 # try to detect archive format
5219 if ($format eq 'tar') {
5220 return restore_tar_archive
($archive, $vmid, $user, $opts);
5222 return restore_vma_archive
($archive, $vmid, $user, $opts, $comp);
5226 sub restore_update_config_line
{
5227 my ($outfd, $cookie, $vmid, $map, $line, $unique) = @_;
5229 return if $line =~ m/^\#qmdump\#/;
5230 return if $line =~ m/^\#vzdump\#/;
5231 return if $line =~ m/^lock:/;
5232 return if $line =~ m/^unused\d+:/;
5233 return if $line =~ m/^parent:/;
5234 return if $line =~ m/^template:/; # restored VM is never a template
5236 my $dc = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
5237 if (($line =~ m/^(vlan(\d+)):\s*(\S+)\s*$/)) {
5238 # try to convert old 1.X settings
5239 my ($id, $ind, $ethcfg) = ($1, $2, $3);
5240 foreach my $devconfig (PVE
::Tools
::split_list
($ethcfg)) {
5241 my ($model, $macaddr) = split(/\=/, $devconfig);
5242 $macaddr = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
}) if !$macaddr || $unique;
5245 bridge
=> "vmbr$ind",
5246 macaddr
=> $macaddr,
5248 my $netstr = print_net
($net);
5250 print $outfd "net$cookie->{netcount}: $netstr\n";
5251 $cookie->{netcount
}++;
5253 } elsif (($line =~ m/^(net\d+):\s*(\S+)\s*$/) && $unique) {
5254 my ($id, $netstr) = ($1, $2);
5255 my $net = parse_net
($netstr);
5256 $net->{macaddr
} = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
}) if $net->{macaddr
};
5257 $netstr = print_net
($net);
5258 print $outfd "$id: $netstr\n";
5259 } elsif ($line =~ m/^((ide|scsi|virtio|sata|efidisk)\d+):\s*(\S+)\s*$/) {
5262 my $di = parse_drive
($virtdev, $value);
5263 if (defined($di->{backup
}) && !$di->{backup
}) {
5264 print $outfd "#$line";
5265 } elsif ($map->{$virtdev}) {
5266 delete $di->{format
}; # format can change on restore
5267 $di->{file
} = $map->{$virtdev};
5268 $value = print_drive
($vmid, $di);
5269 print $outfd "$virtdev: $value\n";
5279 my ($cfg, $vmid) = @_;
5281 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
5283 my $volid_hash = {};
5284 foreach my $storeid (keys %$info) {
5285 foreach my $item (@{$info->{$storeid}}) {
5286 next if !($item->{volid
} && $item->{size
});
5287 $item->{path
} = PVE
::Storage
::path
($cfg, $item->{volid
});
5288 $volid_hash->{$item->{volid
}} = $item;
5295 sub is_volume_in_use
{
5296 my ($storecfg, $conf, $skip_drive, $volid) = @_;
5298 my $path = PVE
::Storage
::path
($storecfg, $volid);
5300 my $scan_config = sub {
5301 my ($cref, $snapname) = @_;
5303 foreach my $key (keys %$cref) {
5304 my $value = $cref->{$key};
5305 if (is_valid_drivename
($key)) {
5306 next if $skip_drive && $key eq $skip_drive;
5307 my $drive = parse_drive
($key, $value);
5308 next if !$drive || !$drive->{file
} || drive_is_cdrom
($drive);
5309 return 1 if $volid eq $drive->{file
};
5310 if ($drive->{file
} =~ m!^/!) {
5311 return 1 if $drive->{file
} eq $path;
5313 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
}, 1);
5315 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid, 1);
5317 return 1 if $path eq PVE
::Storage
::path
($storecfg, $drive->{file
}, $snapname);
5325 return 1 if &$scan_config($conf);
5329 foreach my $snapname (keys %{$conf->{snapshots
}}) {
5330 return 1 if &$scan_config($conf->{snapshots
}->{$snapname}, $snapname);
5336 sub update_disksize
{
5337 my ($vmid, $conf, $volid_hash) = @_;
5343 # Note: it is allowed to define multiple storages with same path (alias), so
5344 # we need to check both 'volid' and real 'path' (two different volid can point
5345 # to the same path).
5350 foreach my $opt (keys %$conf) {
5351 if (is_valid_drivename
($opt)) {
5352 my $drive = parse_drive
($opt, $conf->{$opt});
5353 my $volid = $drive->{file
};
5356 $used->{$volid} = 1;
5357 if ($volid_hash->{$volid} &&
5358 (my $path = $volid_hash->{$volid}->{path
})) {
5359 $usedpath->{$path} = 1;
5362 next if drive_is_cdrom
($drive);
5363 next if !$volid_hash->{$volid};
5365 $drive->{size
} = $volid_hash->{$volid}->{size
};
5366 my $new = print_drive
($vmid, $drive);
5367 if ($new ne $conf->{$opt}) {
5369 $conf->{$opt} = $new;
5374 # remove 'unusedX' entry if volume is used
5375 foreach my $opt (keys %$conf) {
5376 next if $opt !~ m/^unused\d+$/;
5377 my $volid = $conf->{$opt};
5378 my $path = $volid_hash->{$volid}->{path
} if $volid_hash->{$volid};
5379 if ($used->{$volid} || ($path && $usedpath->{$path})) {
5381 delete $conf->{$opt};
5385 foreach my $volid (sort keys %$volid_hash) {
5386 next if $volid =~ m/vm-$vmid-state-/;
5387 next if $used->{$volid};
5388 my $path = $volid_hash->{$volid}->{path
};
5389 next if !$path; # just to be sure
5390 next if $usedpath->{$path};
5392 PVE
::QemuConfig-
>add_unused_volume($conf, $volid);
5393 $usedpath->{$path} = 1; # avoid to add more than once (aliases)
5400 my ($vmid, $nolock) = @_;
5402 my $cfg = PVE
::Storage
::config
();
5404 my $volid_hash = scan_volids
($cfg, $vmid);
5406 my $updatefn = sub {
5409 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5411 PVE
::QemuConfig-
>check_lock($conf);
5414 foreach my $volid (keys %$volid_hash) {
5415 my $info = $volid_hash->{$volid};
5416 $vm_volids->{$volid} = $info if $info->{vmid
} && $info->{vmid
} == $vmid;
5419 my $changes = update_disksize
($vmid, $conf, $vm_volids);
5421 PVE
::QemuConfig-
>write_config($vmid, $conf) if $changes;
5424 if (defined($vmid)) {
5428 PVE
::QemuConfig-
>lock_config($vmid, $updatefn, $vmid);
5431 my $vmlist = config_list
();
5432 foreach my $vmid (keys %$vmlist) {
5436 PVE
::QemuConfig-
>lock_config($vmid, $updatefn, $vmid);
5442 sub restore_vma_archive
{
5443 my ($archive, $vmid, $user, $opts, $comp) = @_;
5445 my $input = $archive eq '-' ?
"<&STDIN" : undef;
5446 my $readfrom = $archive;
5451 my $qarchive = PVE
::Tools
::shellquote
($archive);
5452 if ($comp eq 'gzip') {
5453 $uncomp = "zcat $qarchive|";
5454 } elsif ($comp eq 'lzop') {
5455 $uncomp = "lzop -d -c $qarchive|";
5457 die "unknown compression method '$comp'\n";
5462 my $tmpdir = "/var/tmp/vzdumptmp$$";
5465 # disable interrupts (always do cleanups)
5466 local $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = sub {
5467 warn "got interrupt - ignored\n";
5470 my $mapfifo = "/var/tmp/vzdumptmp$$.fifo";
5471 POSIX
::mkfifo
($mapfifo, 0600);
5474 my $openfifo = sub {
5475 open($fifofh, '>', $mapfifo) || die $!;
5478 my $cmd = "${uncomp}vma extract -v -r $mapfifo $readfrom $tmpdir";
5485 my $rpcenv = PVE
::RPCEnvironment
::get
();
5487 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
5488 my $tmpfn = "$conffile.$$.tmp";
5490 # Note: $oldconf is undef if VM does not exists
5491 my $cfs_path = PVE
::QemuConfig-
>cfs_config_path($vmid);
5492 my $oldconf = PVE
::Cluster
::cfs_read_file
($cfs_path);
5494 my $print_devmap = sub {
5495 my $virtdev_hash = {};
5497 my $cfgfn = "$tmpdir/qemu-server.conf";
5499 # we can read the config - that is already extracted
5500 my $fh = IO
::File-
>new($cfgfn, "r") ||
5501 "unable to read qemu-server.conf - $!\n";
5503 my $fwcfgfn = "$tmpdir/qemu-server.fw";
5505 my $pve_firewall_dir = '/etc/pve/firewall';
5506 mkdir $pve_firewall_dir; # make sure the dir exists
5507 PVE
::Tools
::file_copy
($fwcfgfn, "${pve_firewall_dir}/$vmid.fw");
5510 while (defined(my $line = <$fh>)) {
5511 if ($line =~ m/^\#qmdump\#map:(\S+):(\S+):(\S*):(\S*):$/) {
5512 my ($virtdev, $devname, $storeid, $format) = ($1, $2, $3, $4);
5513 die "archive does not contain data for drive '$virtdev'\n"
5514 if !$devinfo->{$devname};
5515 if (defined($opts->{storage
})) {
5516 $storeid = $opts->{storage
} || 'local';
5517 } elsif (!$storeid) {
5520 $format = 'raw' if !$format;
5521 $devinfo->{$devname}->{devname
} = $devname;
5522 $devinfo->{$devname}->{virtdev
} = $virtdev;
5523 $devinfo->{$devname}->{format
} = $format;
5524 $devinfo->{$devname}->{storeid
} = $storeid;
5526 # check permission on storage
5527 my $pool = $opts->{pool
}; # todo: do we need that?
5528 if ($user ne 'root@pam') {
5529 $rpcenv->check($user, "/storage/$storeid", ['Datastore.AllocateSpace']);
5532 $virtdev_hash->{$virtdev} = $devinfo->{$devname};
5536 foreach my $devname (keys %$devinfo) {
5537 die "found no device mapping information for device '$devname'\n"
5538 if !$devinfo->{$devname}->{virtdev
};
5541 my $cfg = PVE
::Storage
::config
();
5543 # create empty/temp config
5545 PVE
::Tools
::file_set_contents
($conffile, "memory: 128\n");
5546 foreach_drive
($oldconf, sub {
5547 my ($ds, $drive) = @_;
5549 return if drive_is_cdrom
($drive);
5551 my $volid = $drive->{file
};
5553 return if !$volid || $volid =~ m
|^/|;
5555 my ($path, $owner) = PVE
::Storage
::path
($cfg, $volid);
5556 return if !$path || !$owner || ($owner != $vmid);
5558 # Note: only delete disk we want to restore
5559 # other volumes will become unused
5560 if ($virtdev_hash->{$ds}) {
5561 eval { PVE
::Storage
::vdisk_free
($cfg, $volid); };
5568 # delete vmstate files
5569 # since after the restore we have no snapshots anymore
5570 foreach my $snapname (keys %{$oldconf->{snapshots
}}) {
5571 my $snap = $oldconf->{snapshots
}->{$snapname};
5572 if ($snap->{vmstate
}) {
5573 eval { PVE
::Storage
::vdisk_free
($cfg, $snap->{vmstate
}); };
5582 foreach my $virtdev (sort keys %$virtdev_hash) {
5583 my $d = $virtdev_hash->{$virtdev};
5584 my $alloc_size = int(($d->{size
} + 1024 - 1)/1024);
5585 my $scfg = PVE
::Storage
::storage_config
($cfg, $d->{storeid
});
5587 # test if requested format is supported
5588 my ($defFormat, $validFormats) = PVE
::Storage
::storage_default_format
($cfg, $d->{storeid
});
5589 my $supported = grep { $_ eq $d->{format
} } @$validFormats;
5590 $d->{format
} = $defFormat if !$supported;
5592 my $volid = PVE
::Storage
::vdisk_alloc
($cfg, $d->{storeid
}, $vmid,
5593 $d->{format
}, undef, $alloc_size);
5594 print STDERR
"new volume ID is '$volid'\n";
5595 $d->{volid
} = $volid;
5596 my $path = PVE
::Storage
::path
($cfg, $volid);
5598 PVE
::Storage
::activate_volumes
($cfg,[$volid]);
5600 my $write_zeros = 1;
5601 if (PVE
::Storage
::volume_has_feature
($cfg, 'sparseinit', $volid)) {
5605 print $fifofh "format=$d->{format}:${write_zeros}:$d->{devname}=$path\n";
5607 print "map '$d->{devname}' to '$path' (write zeros = ${write_zeros})\n";
5608 $map->{$virtdev} = $volid;
5611 $fh->seek(0, 0) || die "seek failed - $!\n";
5613 my $outfd = new IO
::File
($tmpfn, "w") ||
5614 die "unable to write config for VM $vmid\n";
5616 my $cookie = { netcount
=> 0 };
5617 while (defined(my $line = <$fh>)) {
5618 restore_update_config_line
($outfd, $cookie, $vmid, $map, $line, $opts->{unique
});
5627 local $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
5628 die "interrupted by signal\n";
5630 local $SIG{ALRM
} = sub { die "got timeout\n"; };
5632 $oldtimeout = alarm($timeout);
5639 if ($line =~ m/^DEV:\sdev_id=(\d+)\ssize:\s(\d+)\sdevname:\s(\S+)$/) {
5640 my ($dev_id, $size, $devname) = ($1, $2, $3);
5641 $devinfo->{$devname} = { size
=> $size, dev_id
=> $dev_id };
5642 } elsif ($line =~ m/^CTIME: /) {
5643 # we correctly received the vma config, so we can disable
5644 # the timeout now for disk allocation (set to 10 minutes, so
5645 # that we always timeout if something goes wrong)
5648 print $fifofh "done\n";
5649 my $tmp = $oldtimeout || 0;
5650 $oldtimeout = undef;
5656 print "restore vma archive: $cmd\n";
5657 run_command
($cmd, input
=> $input, outfunc
=> $parser, afterfork
=> $openfifo);
5661 alarm($oldtimeout) if $oldtimeout;
5664 foreach my $devname (keys %$devinfo) {
5665 my $volid = $devinfo->{$devname}->{volid
};
5666 push @$vollist, $volid if $volid;
5669 my $cfg = PVE
::Storage
::config
();
5670 PVE
::Storage
::deactivate_volumes
($cfg, $vollist);
5678 foreach my $devname (keys %$devinfo) {
5679 my $volid = $devinfo->{$devname}->{volid
};
5682 if ($volid =~ m
|^/|) {
5683 unlink $volid || die 'unlink failed\n';
5685 PVE
::Storage
::vdisk_free
($cfg, $volid);
5687 print STDERR
"temporary volume '$volid' sucessfuly removed\n";
5689 print STDERR
"unable to cleanup '$volid' - $@" if $@;
5696 rename($tmpfn, $conffile) ||
5697 die "unable to commit configuration file '$conffile'\n";
5699 PVE
::Cluster
::cfs_update
(); # make sure we read new file
5701 eval { rescan
($vmid, 1); };
5705 sub restore_tar_archive
{
5706 my ($archive, $vmid, $user, $opts) = @_;
5708 if ($archive ne '-') {
5709 my $firstfile = tar_archive_read_firstfile
($archive);
5710 die "ERROR: file '$archive' dos not lock like a QemuServer vzdump backup\n"
5711 if $firstfile ne 'qemu-server.conf';
5714 my $storecfg = PVE
::Storage
::config
();
5716 # destroy existing data - keep empty config
5717 my $vmcfgfn = PVE
::QemuConfig-
>config_file($vmid);
5718 destroy_vm
($storecfg, $vmid, 1) if -f
$vmcfgfn;
5720 my $tocmd = "/usr/lib/qemu-server/qmextract";
5722 $tocmd .= " --storage " . PVE
::Tools
::shellquote
($opts->{storage
}) if $opts->{storage
};
5723 $tocmd .= " --pool " . PVE
::Tools
::shellquote
($opts->{pool
}) if $opts->{pool
};
5724 $tocmd .= ' --prealloc' if $opts->{prealloc
};
5725 $tocmd .= ' --info' if $opts->{info
};
5727 # tar option "xf" does not autodetect compression when read from STDIN,
5728 # so we pipe to zcat
5729 my $cmd = "zcat -f|tar xf " . PVE
::Tools
::shellquote
($archive) . " " .
5730 PVE
::Tools
::shellquote
("--to-command=$tocmd");
5732 my $tmpdir = "/var/tmp/vzdumptmp$$";
5735 local $ENV{VZDUMP_TMPDIR
} = $tmpdir;
5736 local $ENV{VZDUMP_VMID
} = $vmid;
5737 local $ENV{VZDUMP_USER
} = $user;
5739 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
5740 my $tmpfn = "$conffile.$$.tmp";
5742 # disable interrupts (always do cleanups)
5743 local $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = sub {
5744 print STDERR
"got interrupt - ignored\n";
5749 local $SIG{INT
} = $SIG{TERM
} = $SIG{QUIT
} = $SIG{HUP
} = $SIG{PIPE
} = sub {
5750 die "interrupted by signal\n";
5753 if ($archive eq '-') {
5754 print "extracting archive from STDIN\n";
5755 run_command
($cmd, input
=> "<&STDIN");
5757 print "extracting archive '$archive'\n";
5761 return if $opts->{info
};
5765 my $statfile = "$tmpdir/qmrestore.stat";
5766 if (my $fd = IO
::File-
>new($statfile, "r")) {
5767 while (defined (my $line = <$fd>)) {
5768 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
5769 $map->{$1} = $2 if $1;
5771 print STDERR
"unable to parse line in statfile - $line\n";
5777 my $confsrc = "$tmpdir/qemu-server.conf";
5779 my $srcfd = new IO
::File
($confsrc, "r") ||
5780 die "unable to open file '$confsrc'\n";
5782 my $outfd = new IO
::File
($tmpfn, "w") ||
5783 die "unable to write config for VM $vmid\n";
5785 my $cookie = { netcount
=> 0 };
5786 while (defined (my $line = <$srcfd>)) {
5787 restore_update_config_line
($outfd, $cookie, $vmid, $map, $line, $opts->{unique
});
5799 tar_restore_cleanup
($storecfg, "$tmpdir/qmrestore.stat") if !$opts->{info
};
5806 rename $tmpfn, $conffile ||
5807 die "unable to commit configuration file '$conffile'\n";
5809 PVE
::Cluster
::cfs_update
(); # make sure we read new file
5811 eval { rescan
($vmid, 1); };
5815 sub foreach_writable_storage
{
5816 my ($conf, $func) = @_;
5820 foreach my $ds (keys %$conf) {
5821 next if !is_valid_drivename
($ds);
5823 my $drive = parse_drive
($ds, $conf->{$ds});
5825 next if drive_is_cdrom
($drive);
5827 my $volid = $drive->{file
};
5829 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
5830 $sidhash->{$sid} = $sid if $sid;
5833 foreach my $sid (sort keys %$sidhash) {
5838 sub do_snapshots_with_qemu
{
5839 my ($storecfg, $volid) = @_;
5841 my $storage_name = PVE
::Storage
::parse_volume_id
($volid);
5843 if ($qemu_snap_storage->{$storecfg->{ids
}->{$storage_name}->{type
}}
5844 && !$storecfg->{ids
}->{$storage_name}->{krbd
}){
5848 if ($volid =~ m/\.(qcow2|qed)$/){
5855 sub qga_check_running
{
5858 eval { vm_mon_cmd
($vmid, "guest-ping", timeout
=> 3); };
5860 warn "Qemu Guest Agent are not running - $@";
5866 sub template_create
{
5867 my ($vmid, $conf, $disk) = @_;
5869 my $storecfg = PVE
::Storage
::config
();
5871 foreach_drive
($conf, sub {
5872 my ($ds, $drive) = @_;
5874 return if drive_is_cdrom
($drive);
5875 return if $disk && $ds ne $disk;
5877 my $volid = $drive->{file
};
5878 return if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
5880 my $voliddst = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
5881 $drive->{file
} = $voliddst;
5882 $conf->{$ds} = print_drive
($vmid, $drive);
5883 PVE
::QemuConfig-
>write_config($vmid, $conf);
5887 sub qemu_img_convert
{
5888 my ($src_volid, $dst_volid, $size, $snapname, $is_zero_initialized) = @_;
5890 my $storecfg = PVE
::Storage
::config
();
5891 my ($src_storeid, $src_volname) = PVE
::Storage
::parse_volume_id
($src_volid, 1);
5892 my ($dst_storeid, $dst_volname) = PVE
::Storage
::parse_volume_id
($dst_volid, 1);
5894 if ($src_storeid && $dst_storeid) {
5896 PVE
::Storage
::activate_volumes
($storecfg, [$src_volid], $snapname);
5898 my $src_scfg = PVE
::Storage
::storage_config
($storecfg, $src_storeid);
5899 my $dst_scfg = PVE
::Storage
::storage_config
($storecfg, $dst_storeid);
5901 my $src_format = qemu_img_format
($src_scfg, $src_volname);
5902 my $dst_format = qemu_img_format
($dst_scfg, $dst_volname);
5904 my $src_path = PVE
::Storage
::path
($storecfg, $src_volid, $snapname);
5905 my $dst_path = PVE
::Storage
::path
($storecfg, $dst_volid);
5908 push @$cmd, '/usr/bin/qemu-img', 'convert', '-p', '-n';
5909 push @$cmd, '-s', $snapname if($snapname && $src_format eq "qcow2");
5910 push @$cmd, '-f', $src_format, '-O', $dst_format, $src_path;
5911 if ($is_zero_initialized) {
5912 push @$cmd, "zeroinit:$dst_path";
5914 push @$cmd, $dst_path;
5919 if($line =~ m/\((\S+)\/100\
%\)/){
5921 my $transferred = int($size * $percent / 100);
5922 my $remaining = $size - $transferred;
5924 print "transferred: $transferred bytes remaining: $remaining bytes total: $size bytes progression: $percent %\n";
5929 eval { run_command
($cmd, timeout
=> undef, outfunc
=> $parser); };
5931 die "copy failed: $err" if $err;
5935 sub qemu_img_format
{
5936 my ($scfg, $volname) = @_;
5938 if ($scfg->{path
} && $volname =~ m/\.(raw|cow|qcow|qcow2|qed|vmdk|cloop)$/) {
5945 sub qemu_drive_mirror
{
5946 my ($vmid, $drive, $dst_volid, $vmiddst, $is_zero_initialized, $jobs, $skipcomplete, $qga) = @_;
5948 $jobs = {} if !$jobs;
5952 $jobs->{"drive-$drive"} = {};
5954 if ($dst_volid =~ /^nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+)/) {
5957 my $exportname = $3;
5960 my $unixsocket = "/run/qemu-server/$vmid.mirror-drive-$drive";
5961 $qemu_target = "nbd+unix:///$exportname?socket=$unixsocket";
5962 my $cmd = ['socat', '-T30', "UNIX-LISTEN:$unixsocket,fork", "TCP:$server:$2,connect-timeout=5"];
5965 if (!defined($pid)) {
5966 die "forking socat tunnel failed\n";
5967 } elsif ($pid == 0) {
5969 warn "exec failed: $!\n";
5972 $jobs->{"drive-$drive"}->{pid
} = $pid;
5975 while (!-S
$unixsocket) {
5976 die "nbd connection helper timed out\n"
5981 my $storecfg = PVE
::Storage
::config
();
5982 my ($dst_storeid, $dst_volname) = PVE
::Storage
::parse_volume_id
($dst_volid);
5984 my $dst_scfg = PVE
::Storage
::storage_config
($storecfg, $dst_storeid);
5986 $format = qemu_img_format
($dst_scfg, $dst_volname);
5988 my $dst_path = PVE
::Storage
::path
($storecfg, $dst_volid);
5990 $qemu_target = $is_zero_initialized ?
"zeroinit:$dst_path" : $dst_path;
5993 my $opts = { timeout
=> 10, device
=> "drive-$drive", mode
=> "existing", sync
=> "full", target
=> $qemu_target };
5994 $opts->{format
} = $format if $format;
5996 print "drive mirror is starting for drive-$drive\n";
5998 eval { vm_mon_cmd
($vmid, "drive-mirror", %$opts); }; #if a job already run for this device,it's throw an error
6001 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs) };
6002 die "mirroring error: $err";
6005 qemu_drive_mirror_monitor
($vmid, $vmiddst, $jobs, $skipcomplete, $qga);
6008 sub qemu_drive_mirror_monitor
{
6009 my ($vmid, $vmiddst, $jobs, $skipcomplete, $qga) = @_;
6012 my $err_complete = 0;
6015 die "storage migration timed out\n" if $err_complete > 300;
6017 my $stats = vm_mon_cmd
($vmid, "query-block-jobs");
6019 my $running_mirror_jobs = {};
6020 foreach my $stat (@$stats) {
6021 next if $stat->{type
} ne 'mirror';
6022 $running_mirror_jobs->{$stat->{device
}} = $stat;
6025 my $readycounter = 0;
6027 foreach my $job (keys %$jobs) {
6029 if(defined($jobs->{$job}->{complete
}) && !defined($running_mirror_jobs->{$job})) {
6030 print "$job : finished\n";
6031 delete $jobs->{$job};
6035 die "$job: mirroring has been cancelled\n" if !defined($running_mirror_jobs->{$job});
6037 my $busy = $running_mirror_jobs->{$job}->{busy
};
6038 my $ready = $running_mirror_jobs->{$job}->{ready
};
6039 if (my $total = $running_mirror_jobs->{$job}->{len
}) {
6040 my $transferred = $running_mirror_jobs->{$job}->{offset
} || 0;
6041 my $remaining = $total - $transferred;
6042 my $percent = sprintf "%.2f", ($transferred * 100 / $total);
6044 print "$job: transferred: $transferred bytes remaining: $remaining bytes total: $total bytes progression: $percent % busy: $busy ready: $ready \n";
6047 $readycounter++ if $running_mirror_jobs->{$job}->{ready
};
6050 last if scalar(keys %$jobs) == 0;
6052 if ($readycounter == scalar(keys %$jobs)) {
6053 print "all mirroring jobs are ready \n";
6054 last if $skipcomplete; #do the complete later
6056 if ($vmiddst && $vmiddst != $vmid) {
6058 print "freeze filesystem\n";
6059 eval { PVE
::QemuServer
::vm_mon_cmd
($vmid, "guest-fsfreeze-freeze"); };
6061 print "suspend vm\n";
6062 eval { PVE
::QemuServer
::vm_suspend
($vmid, 1); };
6065 # if we clone a disk for a new target vm, we don't switch the disk
6066 PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs);
6069 print "unfreeze filesystem\n";
6070 eval { PVE
::QemuServer
::vm_mon_cmd
($vmid, "guest-fsfreeze-thaw"); };
6072 print "resume vm\n";
6073 eval { PVE
::QemuServer
::vm_resume
($vmid, 1, 1); };
6079 foreach my $job (keys %$jobs) {
6080 # try to switch the disk if source and destination are on the same guest
6081 print "$job: Completing block job...\n";
6083 eval { vm_mon_cmd
($vmid, "block-job-complete", device
=> $job) };
6084 if ($@ =~ m/cannot be completed/) {
6085 print "$job: Block job cannot be completed, try again.\n";
6088 print "$job: Completed successfully.\n";
6089 $jobs->{$job}->{complete
} = 1;
6090 eval { qemu_blockjobs_finish_tunnel
($vmid, $job, $jobs->{$job}->{pid
}) } ;
6101 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs) };
6102 die "mirroring error: $err";
6107 sub qemu_blockjobs_cancel
{
6108 my ($vmid, $jobs) = @_;
6110 foreach my $job (keys %$jobs) {
6111 print "$job: Cancelling block job\n";
6112 eval { vm_mon_cmd
($vmid, "block-job-cancel", device
=> $job); };
6113 $jobs->{$job}->{cancel
} = 1;
6117 my $stats = vm_mon_cmd
($vmid, "query-block-jobs");
6119 my $running_jobs = {};
6120 foreach my $stat (@$stats) {
6121 $running_jobs->{$stat->{device
}} = $stat;
6124 foreach my $job (keys %$jobs) {
6126 if (defined($jobs->{$job}->{cancel
}) && !defined($running_jobs->{$job})) {
6127 print "$job: Done.\n";
6128 eval { qemu_blockjobs_finish_tunnel
($vmid, $job, $jobs->{$job}->{pid
}) } ;
6129 delete $jobs->{$job};
6133 last if scalar(keys %$jobs) == 0;
6139 sub qemu_blockjobs_finish_tunnel
{
6140 my ($vmid, $job, $cpid) = @_;
6144 for (my $i = 1; $i < 20; $i++) {
6145 my $waitpid = waitpid($cpid, WNOHANG
);
6146 last if (defined($waitpid) && ($waitpid == $cpid));
6150 } elsif ($i >= 15) {
6155 unlink "/run/qemu-server/$vmid.mirror-$job";
6159 my ($storecfg, $vmid, $running, $drivename, $drive, $snapname,
6160 $newvmid, $storage, $format, $full, $newvollist, $jobs, $skipcomplete, $qga) = @_;
6165 print "create linked clone of drive $drivename ($drive->{file})\n";
6166 $newvolid = PVE
::Storage
::vdisk_clone
($storecfg, $drive->{file
}, $newvmid, $snapname);
6167 push @$newvollist, $newvolid;
6170 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
6171 $storeid = $storage if $storage;
6173 my ($defFormat, $validFormats) = PVE
::Storage
::storage_default_format
($storecfg, $storeid);
6175 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
6176 $format = qemu_img_format
($scfg, $volname);
6179 # test if requested format is supported - else use default
6180 my $supported = grep { $_ eq $format } @$validFormats;
6181 $format = $defFormat if !$supported;
6183 my ($size) = PVE
::Storage
::volume_size_info
($storecfg, $drive->{file
}, 3);
6185 print "create full clone of drive $drivename ($drive->{file})\n";
6186 $newvolid = PVE
::Storage
::vdisk_alloc
($storecfg, $storeid, $newvmid, $format, undef, ($size/1024));
6187 push @$newvollist, $newvolid;
6189 PVE
::Storage
::activate_volumes
($storecfg, [$newvolid]);
6191 my $sparseinit = PVE
::Storage
::volume_has_feature
($storecfg, 'sparseinit', $newvolid);
6192 if (!$running || $snapname) {
6193 qemu_img_convert
($drive->{file
}, $newvolid, $size, $snapname, $sparseinit);
6196 my $kvmver = get_running_qemu_version
($vmid);
6197 if (!qemu_machine_feature_enabled
(undef, $kvmver, 2, 7)) {
6198 die "drive-mirror with iothread requires qemu version 2.7 or higher\n"
6199 if $drive->{iothread
};
6202 qemu_drive_mirror
($vmid, $drivename, $newvolid, $newvmid, $sparseinit, $jobs, $skipcomplete, $qga);
6206 my ($size) = PVE
::Storage
::volume_size_info
($storecfg, $newvolid, 3);
6209 $disk->{format
} = undef;
6210 $disk->{file
} = $newvolid;
6211 $disk->{size
} = $size;
6216 # this only works if VM is running
6217 sub get_current_qemu_machine
{
6220 my $cmd = { execute
=> 'query-machines', arguments
=> {} };
6221 my $res = vm_qmp_command
($vmid, $cmd);
6223 my ($current, $default);
6224 foreach my $e (@$res) {
6225 $default = $e->{name
} if $e->{'is-default'};
6226 $current = $e->{name
} if $e->{'is-current'};
6229 # fallback to the default machine if current is not supported by qemu
6230 return $current || $default || 'pc';
6233 sub get_running_qemu_version
{
6235 my $cmd = { execute
=> 'query-version', arguments
=> {} };
6236 my $res = vm_qmp_command
($vmid, $cmd);
6237 return "$res->{qemu}->{major}.$res->{qemu}->{minor}";
6240 sub qemu_machine_feature_enabled
{
6241 my ($machine, $kvmver, $version_major, $version_minor) = @_;
6246 if ($machine && $machine =~ m/^(pc(-i440fx|-q35)?-(\d+)\.(\d+))/) {
6248 $current_major = $3;
6249 $current_minor = $4;
6251 } elsif ($kvmver =~ m/^(\d+)\.(\d+)/) {
6253 $current_major = $1;
6254 $current_minor = $2;
6257 return 1 if $current_major >= $version_major && $current_minor >= $version_minor;
6262 sub qemu_machine_pxe
{
6263 my ($vmid, $conf, $machine) = @_;
6265 $machine = PVE
::QemuServer
::get_current_qemu_machine
($vmid) if !$machine;
6267 foreach my $opt (keys %$conf) {
6268 next if $opt !~ m/^net(\d+)$/;
6269 my $net = PVE
::QemuServer
::parse_net
($conf->{$opt});
6271 my $romfile = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'qom-get', path
=> $opt, property
=> 'romfile');
6272 return $machine.".pxe" if $romfile =~ m/pxe/;
6279 sub qemu_use_old_bios_files
{
6280 my ($machine_type) = @_;
6282 return if !$machine_type;
6284 my $use_old_bios_files = undef;
6286 if ($machine_type =~ m/^(\S+)\.pxe$/) {
6288 $use_old_bios_files = 1;
6290 my $kvmver = kvm_user_version
();
6291 # Note: kvm version < 2.4 use non-efi pxe files, and have problems when we
6292 # load new efi bios files on migration. So this hack is required to allow
6293 # live migration from qemu-2.2 to qemu-2.4, which is sometimes used when
6294 # updrading from proxmox-ve-3.X to proxmox-ve 4.0
6295 $use_old_bios_files = !qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 4);
6298 return ($use_old_bios_files, $machine_type);
6305 dir_glob_foreach
("$pcisysfs/devices", '[a-f0-9]{4}:([a-f0-9]{2}:[a-f0-9]{2})\.([0-9])', sub {
6306 my (undef, $id, $function) = @_;
6307 my $res = { id
=> $id, function
=> $function};
6308 push @{$devices->{$id}}, $res;
6314 sub vm_iothreads_list
{
6317 my $res = vm_mon_cmd
($vmid, 'query-iothreads');
6320 foreach my $iothread (@$res) {
6321 $iothreads->{ $iothread->{id
} } = $iothread->{"thread-id"};
6328 my ($conf, $drive) = @_;
6332 if (!$conf->{scsihw
} || ($conf->{scsihw
} =~ m/^lsi/)) {
6334 } elsif ($conf->{scsihw
} && ($conf->{scsihw
} eq 'virtio-scsi-single')) {
6340 my $controller = int($drive->{index} / $maxdev);
6341 my $controller_prefix = ($conf->{scsihw
} && $conf->{scsihw
} eq 'virtio-scsi-single') ?
"virtioscsi" : "scsihw";
6343 return ($maxdev, $controller, $controller_prefix);
6346 sub add_hyperv_enlighments
{
6347 my ($cpuFlags, $winversion, $machine_type, $kvmver, $nokvm, $bios, $gpu_passthrough) = @_;
6350 return if $winversion < 6;
6351 return if $bios && $bios eq 'ovmf' && $winversion < 8;
6353 push @$cpuFlags , 'hv_vendor_id=proxmox' if $gpu_passthrough;
6355 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
6356 push @$cpuFlags , 'hv_spinlocks=0x1fff';
6357 push @$cpuFlags , 'hv_vapic';
6358 push @$cpuFlags , 'hv_time';
6360 push @$cpuFlags , 'hv_spinlocks=0xffff';
6363 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 6)) {
6364 push @$cpuFlags , 'hv_reset';
6365 push @$cpuFlags , 'hv_vpindex';
6366 push @$cpuFlags , 'hv_runtime';
6369 if ($winversion >= 7) {
6370 push @$cpuFlags , 'hv_relaxed';
6374 sub windows_version
{
6377 return 0 if !$ostype;
6381 if($ostype eq 'wxp' || $ostype eq 'w2k3' || $ostype eq 'w2k') {
6383 } elsif($ostype eq 'w2k8' || $ostype eq 'wvista') {
6385 } elsif ($ostype =~ m/^win(\d+)$/) {
6392 # bash completion helper
6394 sub complete_backup_archives
{
6395 my ($cmdname, $pname, $cvalue) = @_;
6397 my $cfg = PVE
::Storage
::config
();
6401 if ($cvalue =~ m/^([^:]+):/) {
6405 my $data = PVE
::Storage
::template_list
($cfg, $storeid, 'backup');
6408 foreach my $id (keys %$data) {
6409 foreach my $item (@{$data->{$id}}) {
6410 next if $item->{format
} !~ m/^vma\.(gz|lzo)$/;
6411 push @$res, $item->{volid
} if defined($item->{volid
});
6418 my $complete_vmid_full = sub {
6421 my $idlist = vmstatus
();
6425 foreach my $id (keys %$idlist) {
6426 my $d = $idlist->{$id};
6427 if (defined($running)) {
6428 next if $d->{template
};
6429 next if $running && $d->{status
} ne 'running';
6430 next if !$running && $d->{status
} eq 'running';
6439 return &$complete_vmid_full();
6442 sub complete_vmid_stopped
{
6443 return &$complete_vmid_full(0);
6446 sub complete_vmid_running
{
6447 return &$complete_vmid_full(1);
6450 sub complete_storage
{
6452 my $cfg = PVE
::Storage
::config
();
6453 my $ids = $cfg->{ids
};
6456 foreach my $sid (keys %$ids) {
6457 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, undef, 1);
6458 next if !$ids->{$sid}->{content
}->{images
};
6468 vm_mon_cmd
($vmid, 'nbd-server-stop');