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';
43 my $qemu_snap_storage = {rbd
=> 1, sheepdog
=> 1};
45 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
47 # Note about locking: we use flock on the config file protect
48 # against concurent actions.
49 # Aditionaly, we have a 'lock' setting in the config file. This
50 # can be set to 'migrate', 'backup', 'snapshot' or 'rollback'. Most actions are not
51 # allowed when such lock is set. But you can ignore this kind of
52 # lock with the --skiplock flag.
54 cfs_register_file
('/qemu-server/',
58 PVE
::JSONSchema
::register_standard_option
('pve-qm-stateuri', {
59 description
=> "Some command save/restore state from this location.",
65 PVE
::JSONSchema
::register_standard_option
('pve-snapshot-name', {
66 description
=> "The name of the snapshot.",
67 type
=> 'string', format
=> 'pve-configid',
71 PVE
::JSONSchema
::register_standard_option
('pve-qm-image-format', {
73 enum
=> [qw(raw cow qcow qed qcow2 vmdk cloop)],
74 description
=> "The drive's backing file's data format.",
78 #no warnings 'redefine';
81 my ($controller, $vmid, $option, $value) = @_;
83 my $path = "/sys/fs/cgroup/$controller/qemu.slice/$vmid.scope/$option";
84 PVE
::ProcFSTools
::write_proc_entry
($path, $value);
88 my $nodename = PVE
::INotify
::nodename
();
90 mkdir "/etc/pve/nodes/$nodename";
91 my $confdir = "/etc/pve/nodes/$nodename/qemu-server";
94 my $var_run_tmpdir = "/var/run/qemu-server";
95 mkdir $var_run_tmpdir;
97 my $lock_dir = "/var/lock/qemu-server";
100 my $pcisysfs = "/sys/bus/pci";
102 my $cpu_vendor_list = {
104 486 => 'GenuineIntel',
105 pentium
=> 'GenuineIntel',
106 pentium2
=> 'GenuineIntel',
107 pentium3
=> 'GenuineIntel',
108 coreduo
=> 'GenuineIntel',
109 core2duo
=> 'GenuineIntel',
110 Conroe
=> 'GenuineIntel',
111 Penryn
=> 'GenuineIntel',
112 Nehalem
=> 'GenuineIntel',
113 'Nehalem-IBRS' => 'GenuineIntel',
114 Westmere
=> 'GenuineIntel',
115 'Westmere-IBRS' => 'GenuineIntel',
116 SandyBridge
=> 'GenuineIntel',
117 'SandyBridge-IBRS' => 'GenuineIntel',
118 IvyBridge
=> 'GenuineIntel',
119 'IvyBridge-IBRS' => 'GenuineIntel',
120 Haswell
=> 'GenuineIntel',
121 'Haswell-IBRS' => 'GenuineIntel',
122 'Haswell-noTSX' => 'GenuineIntel',
123 'Haswell-noTSX-IBRS' => 'GenuineIntel',
124 Broadwell
=> 'GenuineIntel',
125 'Broadwell-IBRS' => 'GenuineIntel',
126 'Broadwell-noTSX' => 'GenuineIntel',
127 'Broadwell-noTSX-IBRS' => 'GenuineIntel',
128 'Skylake-Client' => 'GenuineIntel',
129 'Skylake-Client-IBRS' => 'GenuineIntel',
130 'Skylake-Server' => 'GenuineIntel',
131 'Skylake-Server-IBRS' => 'GenuineIntel',
134 athlon
=> 'AuthenticAMD',
135 phenom
=> 'AuthenticAMD',
136 Opteron_G1
=> 'AuthenticAMD',
137 Opteron_G2
=> 'AuthenticAMD',
138 Opteron_G3
=> 'AuthenticAMD',
139 Opteron_G4
=> 'AuthenticAMD',
140 Opteron_G5
=> 'AuthenticAMD',
141 EPYC
=> 'AuthenticAMD',
142 'EPYC-IBPB' => 'AuthenticAMD',
144 # generic types, use vendor from host node
153 my $cpu_flag = qr/[+-](pcid|spec-ctrl)/;
157 description
=> "Emulated CPU type.",
159 enum
=> [ sort { "\L$a" cmp "\L$b" } keys %$cpu_vendor_list ],
164 description
=> "Do not identify as a KVM virtual machine.",
170 description
=> "List of additional CPU flags separated by ';'."
171 . " Use '+FLAG' to enable, '-FLAG' to disable a flag."
172 . " Currently supported flags: 'pcid', 'spec-ctrl'.",
173 format_description
=> '+FLAG[;-FLAG...]',
175 pattern
=> qr/$cpu_flag(;$cpu_flag)*/,
184 enum
=> [qw(i6300esb ib700)],
185 description
=> "Watchdog type to emulate.",
186 default => 'i6300esb',
191 enum
=> [qw(reset shutdown poweroff pause debug none)],
192 description
=> "The action to perform if after activation the guest fails to poll the watchdog in time.",
196 PVE
::JSONSchema
::register_format
('pve-qm-watchdog', $watchdog_fmt);
202 description
=> "Specifies whether a VM will be started during system bootup.",
208 description
=> "Automatic restart after crash (currently ignored).",
213 type
=> 'string', format
=> 'pve-hotplug-features',
214 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'.",
215 default => 'network,disk,usb',
220 description
=> "Allow reboot. If set to '0' the VM exit on reboot.",
226 description
=> "Lock/unlock the VM.",
227 enum
=> [qw(migrate backup snapshot rollback)],
232 description
=> "Limit of CPU usage.",
233 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.",
241 description
=> "CPU weight for a VM.",
242 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.",
250 description
=> "Amount of RAM for the VM in MB. This is the maximum available memory when you use the balloon device.",
257 description
=> "Amount of target RAM for the VM in MB. Using zero disables the ballon driver.",
263 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",
271 description
=> "Keybord layout for vnc server. Default is read from the '/etc/pve/datacenter.conf' configuration file.".
272 "It should not be necessary to set it.",
273 enum
=> PVE
::Tools
::kvmkeymaplist
(),
278 type
=> 'string', format
=> 'dns-name',
279 description
=> "Set a name for the VM. Only used on the configuration web interface.",
284 description
=> "SCSI controller model",
285 enum
=> [qw(lsi lsi53c810 virtio-scsi-pci virtio-scsi-single megasas pvscsi)],
291 description
=> "Description for the VM. Only used on the configuration web interface. This is saved as comment inside the configuration file.",
296 enum
=> [qw(other wxp w2k w2k3 w2k8 wvista win7 win8 win10 l24 l26 solaris)],
297 description
=> "Specify guest operating system.",
298 verbose_description
=> <<EODESC,
299 Specify guest operating system. This is used to enable special
300 optimization/features for specific operating systems:
303 other;; unspecified OS
304 wxp;; Microsoft Windows XP
305 w2k;; Microsoft Windows 2000
306 w2k3;; Microsoft Windows 2003
307 w2k8;; Microsoft Windows 2008
308 wvista;; Microsoft Windows Vista
309 win7;; Microsoft Windows 7
310 win8;; Microsoft Windows 8/2012/2012r2
311 win10;; Microsoft Windows 10/2016
312 l24;; Linux 2.4 Kernel
313 l26;; Linux 2.6/3.X Kernel
314 solaris;; Solaris/OpenSolaris/OpenIndiania kernel
320 description
=> "Boot on floppy (a), hard disk (c), CD-ROM (d), or network (n).",
321 pattern
=> '[acdn]{1,4}',
326 type
=> 'string', format
=> 'pve-qm-bootdisk',
327 description
=> "Enable booting from specified disk.",
328 pattern
=> '(ide|sata|scsi|virtio)\d+',
333 description
=> "The number of CPUs. Please use option -sockets instead.",
340 description
=> "The number of CPU sockets.",
347 description
=> "The number of cores per socket.",
354 description
=> "Enable/disable NUMA.",
360 description
=> "Enable/disable hugepages memory.",
361 enum
=> [qw(any 2 1024)],
366 description
=> "Number of hotplugged vcpus.",
373 description
=> "Enable/disable ACPI.",
379 description
=> "Enable/disable Qemu GuestAgent.",
385 description
=> "Enable/disable KVM hardware virtualization.",
391 description
=> "Enable/disable time drift fix.",
397 description
=> "Set the real time clock to local time. This is enabled by default if ostype indicates a Microsoft OS.",
402 description
=> "Freeze CPU at startup (use 'c' monitor command to start execution).",
407 description
=> "Select the VGA type.",
408 verbose_description
=> "Select the VGA type. If you want to use high resolution" .
409 " modes (>= 1280x1024x16) then you should use the options " .
410 "'std' or 'vmware'. Default is 'std' for win8/win7/w2k8, and " .
411 "'cirrus' for other OS types. The 'qxl' option enables the SPICE " .
412 "display sever. For win* OS you can select how many independent " .
413 "displays you want, Linux guests can add displays them self. " .
414 "You can also run without any graphic card, using a serial device" .
416 enum
=> [qw(std cirrus vmware qxl serial0 serial1 serial2 serial3 qxl2 qxl3 qxl4)],
420 type
=> 'string', format
=> 'pve-qm-watchdog',
421 description
=> "Create a virtual hardware watchdog device.",
422 verbose_description
=> "Create a virtual hardware watchdog device. Once enabled" .
423 " (by a guest action), the watchdog must be periodically polled " .
424 "by an agent inside the guest or else the watchdog will reset " .
425 "the guest (or execute the respective action specified)",
430 typetext
=> "(now | YYYY-MM-DD | YYYY-MM-DDTHH:MM:SS)",
431 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'.",
432 pattern
=> '(now|\d{4}-\d{1,2}-\d{1,2}(T\d{1,2}:\d{1,2}:\d{1,2})?)',
435 startup
=> get_standard_option
('pve-startup-order'),
439 description
=> "Enable/disable Template.",
445 description
=> "Arbitrary arguments passed to kvm.",
446 verbose_description
=> <<EODESCR,
447 Arbitrary arguments passed to kvm, for example:
449 args: -no-reboot -no-hpet
451 NOTE: this option is for experts only.
458 description
=> "Enable/disable the USB tablet device.",
459 verbose_description
=> "Enable/disable the USB tablet device. This device is " .
460 "usually needed to allow absolute mouse positioning with VNC. " .
461 "Else the mouse runs out of sync with normal VNC clients. " .
462 "If you're running lots of console-only guests on one host, " .
463 "you may consider disabling this to save some context switches. " .
464 "This is turned off by default if you use spice (-vga=qxl).",
469 description
=> "Set maximum speed (in MB/s) for migrations. Value 0 is no limit.",
473 migrate_downtime
=> {
476 description
=> "Set maximum tolerated downtime (in seconds) for migrations.",
482 type
=> 'string', format
=> 'pve-qm-ide',
483 typetext
=> '<volume>',
484 description
=> "This is an alias for option -ide2",
488 description
=> "Emulated CPU type.",
492 parent
=> get_standard_option
('pve-snapshot-name', {
494 description
=> "Parent snapshot name. This is used internally, and should not be modified.",
498 description
=> "Timestamp for snapshots.",
504 type
=> 'string', format
=> 'pve-volume-id',
505 description
=> "Reference to a volume which stores the VM state. This is used internally for snapshots.",
507 vmstatestorage
=> get_standard_option
('pve-storage-id', {
508 description
=> "Default storage for VM state volumes/files.",
512 description
=> "Specific the Qemu machine type.",
514 pattern
=> '(pc|pc(-i440fx)?-\d+\.\d+(\.pxe)?|q35|pc-q35-\d+\.\d+(\.pxe)?)',
519 description
=> "Specify SMBIOS type 1 fields.",
520 type
=> 'string', format
=> 'pve-qm-smbios1',
527 description
=> "Sets the protection flag of the VM. This will disable the remove VM and remove disk operations.",
533 enum
=> [ qw(seabios ovmf) ],
534 description
=> "Select BIOS implementation.",
535 default => 'seabios',
539 # what about other qemu settings ?
541 #machine => 'string',
554 ##soundhw => 'string',
556 while (my ($k, $v) = each %$confdesc) {
557 PVE
::JSONSchema
::register_standard_option
("pve-qm-$k", $v);
560 my $MAX_IDE_DISKS = 4;
561 my $MAX_SCSI_DISKS = 14;
562 my $MAX_VIRTIO_DISKS = 16;
563 my $MAX_SATA_DISKS = 6;
564 my $MAX_USB_DEVICES = 5;
566 my $MAX_UNUSED_DISKS = 8;
567 my $MAX_HOSTPCI_DEVICES = 4;
568 my $MAX_SERIAL_PORTS = 4;
569 my $MAX_PARALLEL_PORTS = 3;
575 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
576 description
=> "CPUs accessing this NUMA node.",
577 format_description
=> "id[-id];...",
581 description
=> "Amount of memory this NUMA node provides.",
586 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
587 description
=> "Host NUMA nodes to use.",
588 format_description
=> "id[-id];...",
593 enum
=> [qw(preferred bind interleave)],
594 description
=> "NUMA allocation policy.",
598 PVE
::JSONSchema
::register_format
('pve-qm-numanode', $numa_fmt);
601 type
=> 'string', format
=> $numa_fmt,
602 description
=> "NUMA topology.",
604 PVE
::JSONSchema
::register_standard_option
("pve-qm-numanode", $numadesc);
606 for (my $i = 0; $i < $MAX_NUMA; $i++) {
607 $confdesc->{"numa$i"} = $numadesc;
610 my $nic_model_list = ['rtl8139', 'ne2k_pci', 'e1000', 'pcnet', 'virtio',
611 'ne2k_isa', 'i82551', 'i82557b', 'i82559er', 'vmxnet3',
612 'e1000-82540em', 'e1000-82544gc', 'e1000-82545em'];
613 my $nic_model_list_txt = join(' ', sort @$nic_model_list);
615 my $net_fmt_bridge_descr = <<__EOD__;
616 Bridge to attach the network device to. The Proxmox VE standard bridge
619 If you do not specify a bridge, we create a kvm user (NATed) network
620 device, which provides DHCP and DNS services. The following addresses
627 The DHCP server assign addresses to the guest starting from 10.0.2.15.
633 pattern
=> qr/[0-9a-f]{2}(?::[0-9a-f]{2}){5}/i,
634 description
=> "MAC address. That address must be unique withing your network. This is automatically generated if not specified.",
635 format_description
=> "XX:XX:XX:XX:XX:XX",
640 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'.",
641 enum
=> $nic_model_list,
644 (map { $_ => { keyAlias
=> 'model', alias
=> 'macaddr' }} @$nic_model_list),
647 description
=> $net_fmt_bridge_descr,
648 format_description
=> 'bridge',
653 minimum
=> 0, maximum
=> 16,
654 description
=> 'Number of packet queues to be used on the device.',
660 description
=> "Rate limit in mbps (megabytes per second) as floating point number.",
665 minimum
=> 1, maximum
=> 4094,
666 description
=> 'VLAN tag to apply to packets on this interface.',
671 pattern
=> qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
672 description
=> 'VLAN trunks to pass through this interface.',
673 format_description
=> 'vlanid[;vlanid...]',
678 description
=> 'Whether this interface should be protected by the firewall.',
683 description
=> 'Whether this interface should be disconnected (like pulling the plug).',
690 type
=> 'string', format
=> $net_fmt,
691 description
=> "Specify network devices.",
694 PVE
::JSONSchema
::register_standard_option
("pve-qm-net", $netdesc);
696 for (my $i = 0; $i < $MAX_NETS; $i++) {
697 $confdesc->{"net$i"} = $netdesc;
700 PVE
::JSONSchema
::register_format
('pve-volume-id-or-qm-path', \
&verify_volume_id_or_qm_path
);
701 sub verify_volume_id_or_qm_path
{
702 my ($volid, $noerr) = @_;
704 if ($volid eq 'none' || $volid eq 'cdrom' || $volid =~ m
|^/|) {
708 # if its neither 'none' nor 'cdrom' nor a path, check if its a volume-id
709 $volid = eval { PVE
::JSONSchema
::check_format
('pve-volume-id', $volid, '') };
711 return undef if $noerr;
719 my %drivedesc_base = (
720 volume
=> { alias
=> 'file' },
723 format
=> 'pve-volume-id-or-qm-path',
725 format_description
=> 'volume',
726 description
=> "The drive's backing volume.",
730 enum
=> [qw(cdrom disk)],
731 description
=> "The drive's media type.",
737 description
=> "Force the drive's physical geometry to have a specific cylinder count.",
742 description
=> "Force the drive's physical geometry to have a specific head count.",
747 description
=> "Force the drive's physical geometry to have a specific sector count.",
752 enum
=> [qw(none lba auto)],
753 description
=> "Force disk geometry bios translation mode.",
758 description
=> "Controls qemu's snapshot mode feature."
759 . " If activated, changes made to the disk are temporary and will"
760 . " be discarded when the VM is shutdown.",
765 enum
=> [qw(none writethrough writeback unsafe directsync)],
766 description
=> "The drive's cache mode",
769 format
=> get_standard_option
('pve-qm-image-format'),
772 format
=> 'disk-size',
773 format_description
=> 'DiskSize',
774 description
=> "Disk size. This is purely informational and has no effect.",
779 description
=> "Whether the drive should be included when making backups.",
784 description
=> 'Whether the drive should considered for replication jobs.',
790 enum
=> [qw(ignore report stop)],
791 description
=> 'Read error action.',
796 enum
=> [qw(enospc ignore report stop)],
797 description
=> 'Write error action.',
802 enum
=> [qw(native threads)],
803 description
=> 'AIO type to use.',
808 enum
=> [qw(ignore on)],
809 description
=> 'Controls whether to pass discard/trim requests to the underlying storage.',
814 description
=> 'Controls whether to detect and try to optimize writes of zeroes.',
819 format
=> 'urlencoded',
820 format_description
=> 'serial',
821 maxLength
=> 20*3, # *3 since it's %xx url enoded
822 description
=> "The drive's reported serial number, url-encoded, up to 20 bytes long.",
827 description
=> 'Mark this locally-managed volume as available on all nodes',
828 verbose_description
=> "Mark this locally-managed volume as available on all nodes.\n\nWARNING: This option does not share the volume automatically, it assumes it is shared already!",
834 my %iothread_fmt = ( iothread
=> {
836 description
=> "Whether to use iothreads for this drive",
843 format
=> 'urlencoded',
844 format_description
=> 'model',
845 maxLength
=> 40*3, # *3 since it's %xx url enoded
846 description
=> "The drive's reported model name, url-encoded, up to 40 bytes long.",
854 description
=> "Number of queues.",
860 my %scsiblock_fmt = (
863 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",
869 my $add_throttle_desc = sub {
870 my ($key, $type, $what, $unit, $longunit, $minimum) = @_;
873 format_description
=> $unit,
874 description
=> "Maximum $what in $longunit.",
877 $d->{minimum
} = $minimum if defined($minimum);
878 $drivedesc_base{$key} = $d;
880 # throughput: (leaky bucket)
881 $add_throttle_desc->('bps', 'integer', 'r/w speed', 'bps', 'bytes per second');
882 $add_throttle_desc->('bps_rd', 'integer', 'read speed', 'bps', 'bytes per second');
883 $add_throttle_desc->('bps_wr', 'integer', 'write speed', 'bps', 'bytes per second');
884 $add_throttle_desc->('mbps', 'number', 'r/w speed', 'mbps', 'megabytes per second');
885 $add_throttle_desc->('mbps_rd', 'number', 'read speed', 'mbps', 'megabytes per second');
886 $add_throttle_desc->('mbps_wr', 'number', 'write speed', 'mbps', 'megabytes per second');
887 $add_throttle_desc->('iops', 'integer', 'r/w I/O', 'iops', 'operations per second');
888 $add_throttle_desc->('iops_rd', 'integer', 'read I/O', 'iops', 'operations per second');
889 $add_throttle_desc->('iops_wr', 'integer', 'write I/O', 'iops', 'operations per second');
891 # pools: (pool of IO before throttling starts taking effect)
892 $add_throttle_desc->('mbps_max', 'number', 'unthrottled r/w pool', 'mbps', 'megabytes per second');
893 $add_throttle_desc->('mbps_rd_max', 'number', 'unthrottled read pool', 'mbps', 'megabytes per second');
894 $add_throttle_desc->('mbps_wr_max', 'number', 'unthrottled write pool', 'mbps', 'megabytes per second');
895 $add_throttle_desc->('iops_max', 'integer', 'unthrottled r/w I/O pool', 'iops', 'operations per second');
896 $add_throttle_desc->('iops_rd_max', 'integer', 'unthrottled read I/O pool', 'iops', 'operations per second');
897 $add_throttle_desc->('iops_wr_max', 'integer', 'unthrottled write I/O pool', 'iops', 'operations per second');
900 $add_throttle_desc->('bps_max_length', 'integer', 'length of I/O bursts', 'seconds', 'seconds', 1);
901 $add_throttle_desc->('bps_rd_max_length', 'integer', 'length of read I/O bursts', 'seconds', 'seconds', 1);
902 $add_throttle_desc->('bps_wr_max_length', 'integer', 'length of write I/O bursts', 'seconds', 'seconds', 1);
903 $add_throttle_desc->('iops_max_length', 'integer', 'length of I/O bursts', 'seconds', 'seconds', 1);
904 $add_throttle_desc->('iops_rd_max_length', 'integer', 'length of read I/O bursts', 'seconds', 'seconds', 1);
905 $add_throttle_desc->('iops_wr_max_length', 'integer', 'length of write I/O bursts', 'seconds', 'seconds', 1);
908 $drivedesc_base{'bps_rd_length'} = { alias
=> 'bps_rd_max_length' };
909 $drivedesc_base{'bps_wr_length'} = { alias
=> 'bps_wr_max_length' };
910 $drivedesc_base{'iops_rd_length'} = { alias
=> 'iops_rd_max_length' };
911 $drivedesc_base{'iops_wr_length'} = { alias
=> 'iops_wr_max_length' };
917 PVE
::JSONSchema
::register_format
("pve-qm-ide", $ide_fmt);
921 type
=> 'string', format
=> $ide_fmt,
922 description
=> "Use volume as IDE hard disk or CD-ROM (n is 0 to " .($MAX_IDE_DISKS -1) . ").",
924 PVE
::JSONSchema
::register_standard_option
("pve-qm-ide", $idedesc);
934 type
=> 'string', format
=> $scsi_fmt,
935 description
=> "Use volume as SCSI hard disk or CD-ROM (n is 0 to " . ($MAX_SCSI_DISKS - 1) . ").",
937 PVE
::JSONSchema
::register_standard_option
("pve-qm-scsi", $scsidesc);
944 type
=> 'string', format
=> $sata_fmt,
945 description
=> "Use volume as SATA hard disk or CD-ROM (n is 0 to " . ($MAX_SATA_DISKS - 1). ").",
947 PVE
::JSONSchema
::register_standard_option
("pve-qm-sata", $satadesc);
955 type
=> 'string', format
=> $virtio_fmt,
956 description
=> "Use volume as VIRTIO hard disk (n is 0 to " . ($MAX_VIRTIO_DISKS - 1) . ").",
958 PVE
::JSONSchema
::register_standard_option
("pve-qm-virtio", $virtiodesc);
969 volume
=> { alias
=> 'file' },
972 format
=> 'pve-volume-id-or-qm-path',
974 format_description
=> 'volume',
975 description
=> "The drive's backing volume.",
977 format
=> get_standard_option
('pve-qm-image-format'),
980 format
=> 'disk-size',
981 format_description
=> 'DiskSize',
982 description
=> "Disk size. This is purely informational and has no effect.",
989 type
=> 'string', format
=> $efidisk_fmt,
990 description
=> "Configure a Disk for storing EFI vars",
993 PVE
::JSONSchema
::register_standard_option
("pve-qm-efidisk", $efidisk_desc);
998 type
=> 'string', format
=> 'pve-qm-usb-device',
999 format_description
=> 'HOSTUSBDEVICE|spice',
1000 description
=> <<EODESCR,
1001 The Host USB device or port or the value 'spice'. HOSTUSBDEVICE syntax is:
1003 'bus-port(.port)*' (decimal numbers) or
1004 'vendor_id:product_id' (hexadeciaml numbers) or
1007 You can use the 'lsusb -t' command to list existing usb devices.
1009 NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.
1011 The value 'spice' can be used to add a usb redirection devices for spice.
1017 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).",
1024 type
=> 'string', format
=> $usb_fmt,
1025 description
=> "Configure an USB device (n is 0 to 4).",
1027 PVE
::JSONSchema
::register_standard_option
("pve-qm-usb", $usbdesc);
1029 # NOTE: the match-groups of this regex are used in parse_hostpci
1030 my $PCIRE = qr/([a-f0-9]{2}:[a-f0-9]{2})(?:\.([a-f0-9]))?/;
1035 pattern
=> qr/$PCIRE(;$PCIRE)*/,
1036 format_description
=> 'HOSTPCIID[;HOSTPCIID2...]',
1037 description
=> <<EODESCR,
1038 Host PCI device pass through. The PCI ID of a host's PCI device or a list
1039 of PCI virtual functions of the host. HOSTPCIID syntax is:
1041 'bus:dev.func' (hexadecimal numbers)
1043 You can us the 'lspci' command to list existing PCI devices.
1048 description
=> "Specify whether or not the device's ROM will be visible in the guest's memory map.",
1054 pattern
=> '[^,;]+',
1055 format_description
=> 'string',
1056 description
=> "Custom pci device rom filename (must be located in /usr/share/kvm/).",
1061 description
=> "Choose the PCI-express bus (needs the 'q35' machine model).",
1067 description
=> "Enable vfio-vga device support.",
1072 PVE
::JSONSchema
::register_format
('pve-qm-hostpci', $hostpci_fmt);
1076 type
=> 'string', format
=> 'pve-qm-hostpci',
1077 description
=> "Map host PCI devices into guest.",
1078 verbose_description
=> <<EODESCR,
1079 Map host PCI devices into guest.
1081 NOTE: This option allows direct access to host hardware. So it is no longer
1082 possible to migrate such machines - use with special care.
1084 CAUTION: Experimental! User reported problems with this option.
1087 PVE
::JSONSchema
::register_standard_option
("pve-qm-hostpci", $hostpcidesc);
1092 pattern
=> '(/dev/.+|socket)',
1093 description
=> "Create a serial device inside the VM (n is 0 to 3)",
1094 verbose_description
=> <<EODESCR,
1095 Create a serial device inside the VM (n is 0 to 3), and pass through a
1096 host serial device (i.e. /dev/ttyS0), or create a unix socket on the
1097 host side (use 'qm terminal' to open a terminal connection).
1099 NOTE: If you pass through a host serial device, it is no longer possible to migrate such machines - use with special care.
1101 CAUTION: Experimental! User reported problems with this option.
1108 pattern
=> '/dev/parport\d+|/dev/usb/lp\d+',
1109 description
=> "Map host parallel devices (n is 0 to 2).",
1110 verbose_description
=> <<EODESCR,
1111 Map host parallel devices (n is 0 to 2).
1113 NOTE: This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.
1115 CAUTION: Experimental! User reported problems with this option.
1119 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
1120 $confdesc->{"parallel$i"} = $paralleldesc;
1123 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
1124 $confdesc->{"serial$i"} = $serialdesc;
1127 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
1128 $confdesc->{"hostpci$i"} = $hostpcidesc;
1131 for (my $i = 0; $i < $MAX_IDE_DISKS; $i++) {
1132 $drivename_hash->{"ide$i"} = 1;
1133 $confdesc->{"ide$i"} = $idedesc;
1136 for (my $i = 0; $i < $MAX_SATA_DISKS; $i++) {
1137 $drivename_hash->{"sata$i"} = 1;
1138 $confdesc->{"sata$i"} = $satadesc;
1141 for (my $i = 0; $i < $MAX_SCSI_DISKS; $i++) {
1142 $drivename_hash->{"scsi$i"} = 1;
1143 $confdesc->{"scsi$i"} = $scsidesc ;
1146 for (my $i = 0; $i < $MAX_VIRTIO_DISKS; $i++) {
1147 $drivename_hash->{"virtio$i"} = 1;
1148 $confdesc->{"virtio$i"} = $virtiodesc;
1151 $drivename_hash->{efidisk0
} = 1;
1152 $confdesc->{efidisk0
} = $efidisk_desc;
1154 for (my $i = 0; $i < $MAX_USB_DEVICES; $i++) {
1155 $confdesc->{"usb$i"} = $usbdesc;
1160 type
=> 'string', format
=> 'pve-volume-id',
1161 description
=> "Reference to unused volumes. This is used internally, and should not be modified manually.",
1164 for (my $i = 0; $i < $MAX_UNUSED_DISKS; $i++) {
1165 $confdesc->{"unused$i"} = $unuseddesc;
1168 my $kvm_api_version = 0;
1172 return $kvm_api_version if $kvm_api_version;
1174 my $fh = IO
::File-
>new("</dev/kvm") ||
1177 if (my $v = $fh->ioctl(KVM_GET_API_VERSION
(), 0)) {
1178 $kvm_api_version = $v;
1183 return $kvm_api_version;
1186 my $kvm_user_version;
1188 sub kvm_user_version
{
1190 return $kvm_user_version if $kvm_user_version;
1192 $kvm_user_version = 'unknown';
1196 if ($line =~ m/^QEMU( PC)? emulator version (\d+\.\d+(\.\d+)?)(\.\d+)?[,\s]/) {
1197 $kvm_user_version = $2;
1201 eval { run_command
("kvm -version", outfunc
=> $code); };
1204 return $kvm_user_version;
1208 my $kernel_has_vhost_net = -c
'/dev/vhost-net';
1210 sub valid_drive_names
{
1211 # order is important - used to autoselect boot disk
1212 return ((map { "ide$_" } (0 .. ($MAX_IDE_DISKS - 1))),
1213 (map { "scsi$_" } (0 .. ($MAX_SCSI_DISKS - 1))),
1214 (map { "virtio$_" } (0 .. ($MAX_VIRTIO_DISKS - 1))),
1215 (map { "sata$_" } (0 .. ($MAX_SATA_DISKS - 1))),
1219 sub is_valid_drivename
{
1222 return defined($drivename_hash->{$dev});
1227 return defined($confdesc->{$key});
1231 return $nic_model_list;
1234 sub os_list_description
{
1238 wxp
=> 'Windows XP',
1239 w2k
=> 'Windows 2000',
1240 w2k3
=>, 'Windows 2003',
1241 w2k8
=> 'Windows 2008',
1242 wvista
=> 'Windows Vista',
1243 win7
=> 'Windows 7',
1244 win8
=> 'Windows 8/2012',
1245 win10
=> 'Windows 10/2016',
1253 sub get_cdrom_path
{
1255 return $cdrom_path if $cdrom_path;
1257 return $cdrom_path = "/dev/cdrom" if -l
"/dev/cdrom";
1258 return $cdrom_path = "/dev/cdrom1" if -l
"/dev/cdrom1";
1259 return $cdrom_path = "/dev/cdrom2" if -l
"/dev/cdrom2";
1263 my ($storecfg, $vmid, $cdrom) = @_;
1265 if ($cdrom eq 'cdrom') {
1266 return get_cdrom_path
();
1267 } elsif ($cdrom eq 'none') {
1269 } elsif ($cdrom =~ m
|^/|) {
1272 return PVE
::Storage
::path
($storecfg, $cdrom);
1276 # try to convert old style file names to volume IDs
1277 sub filename_to_volume_id
{
1278 my ($vmid, $file, $media) = @_;
1280 if (!($file eq 'none' || $file eq 'cdrom' ||
1281 $file =~ m
|^/dev/.+| || $file =~ m/^([^:]+):(.+)$/)) {
1283 return undef if $file =~ m
|/|;
1285 if ($media && $media eq 'cdrom') {
1286 $file = "local:iso/$file";
1288 $file = "local:$vmid/$file";
1295 sub verify_media_type
{
1296 my ($opt, $vtype, $media) = @_;
1301 if ($media eq 'disk') {
1303 } elsif ($media eq 'cdrom') {
1306 die "internal error";
1309 return if ($vtype eq $etype);
1311 raise_param_exc
({ $opt => "unexpected media type ($vtype != $etype)" });
1314 sub cleanup_drive_path
{
1315 my ($opt, $storecfg, $drive) = @_;
1317 # try to convert filesystem paths to volume IDs
1319 if (($drive->{file
} !~ m/^(cdrom|none)$/) &&
1320 ($drive->{file
} !~ m
|^/dev/.+|) &&
1321 ($drive->{file
} !~ m/^([^:]+):(.+)$/) &&
1322 ($drive->{file
} !~ m/^\d+$/)) {
1323 my ($vtype, $volid) = PVE
::Storage
::path_to_volume_id
($storecfg, $drive->{file
});
1324 raise_param_exc
({ $opt => "unable to associate path '$drive->{file}' to any storage"}) if !$vtype;
1325 $drive->{media
} = 'cdrom' if !$drive->{media
} && $vtype eq 'iso';
1326 verify_media_type
($opt, $vtype, $drive->{media
});
1327 $drive->{file
} = $volid;
1330 $drive->{media
} = 'cdrom' if !$drive->{media
} && $drive->{file
} =~ m/^(cdrom|none)$/;
1333 sub parse_hotplug_features
{
1338 return $res if $data eq '0';
1340 $data = $confdesc->{hotplug
}->{default} if $data eq '1';
1342 foreach my $feature (PVE
::Tools
::split_list
($data)) {
1343 if ($feature =~ m/^(network|disk|cpu|memory|usb)$/) {
1346 die "invalid hotplug feature '$feature'\n";
1352 PVE
::JSONSchema
::register_format
('pve-hotplug-features', \
&pve_verify_hotplug_features
);
1353 sub pve_verify_hotplug_features
{
1354 my ($value, $noerr) = @_;
1356 return $value if parse_hotplug_features
($value);
1358 return undef if $noerr;
1360 die "unable to parse hotplug option\n";
1363 # ideX = [volume=]volume-id[,media=d][,cyls=c,heads=h,secs=s[,trans=t]]
1364 # [,snapshot=on|off][,cache=on|off][,format=f][,backup=yes|no]
1365 # [,rerror=ignore|report|stop][,werror=enospc|ignore|report|stop]
1366 # [,aio=native|threads][,discard=ignore|on][,detect_zeroes=on|off]
1367 # [,iothread=on][,serial=serial][,model=model]
1370 my ($key, $data) = @_;
1372 my ($interface, $index);
1374 if ($key =~ m/^([^\d]+)(\d+)$/) {
1381 my $desc = $key =~ /^unused\d+$/ ?
$alldrive_fmt
1382 : $confdesc->{$key}->{format
};
1384 warn "invalid drive key: $key\n";
1387 my $res = eval { PVE
::JSONSchema
::parse_property_string
($desc, $data) };
1388 return undef if !$res;
1389 $res->{interface
} = $interface;
1390 $res->{index} = $index;
1393 foreach my $opt (qw(bps bps_rd bps_wr)) {
1394 if (my $bps = defined(delete $res->{$opt})) {
1395 if (defined($res->{"m$opt"})) {
1396 warn "both $opt and m$opt specified\n";
1400 $res->{"m$opt"} = sprintf("%.3f", $bps / (1024*1024.0));
1404 # can't use the schema's 'requires' because of the mbps* => bps* "transforming aliases"
1405 for my $requirement (
1406 [mbps_max
=> 'mbps'],
1407 [mbps_rd_max
=> 'mbps_rd'],
1408 [mbps_wr_max
=> 'mbps_wr'],
1409 [miops_max
=> 'miops'],
1410 [miops_rd_max
=> 'miops_rd'],
1411 [miops_wr_max
=> 'miops_wr'],
1412 [bps_max_length
=> 'mbps_max'],
1413 [bps_rd_max_length
=> 'mbps_rd_max'],
1414 [bps_wr_max_length
=> 'mbps_wr_max'],
1415 [iops_max_length
=> 'iops_max'],
1416 [iops_rd_max_length
=> 'iops_rd_max'],
1417 [iops_wr_max_length
=> 'iops_wr_max']) {
1418 my ($option, $requires) = @$requirement;
1419 if ($res->{$option} && !$res->{$requires}) {
1420 warn "$option requires $requires\n";
1425 return undef if $error;
1427 return undef if $res->{mbps_rd
} && $res->{mbps
};
1428 return undef if $res->{mbps_wr
} && $res->{mbps
};
1429 return undef if $res->{iops_rd
} && $res->{iops
};
1430 return undef if $res->{iops_wr
} && $res->{iops
};
1432 if ($res->{media
} && ($res->{media
} eq 'cdrom')) {
1433 return undef if $res->{snapshot
} || $res->{trans
} || $res->{format
};
1434 return undef if $res->{heads
} || $res->{secs
} || $res->{cyls
};
1435 return undef if $res->{interface
} eq 'virtio';
1438 if (my $size = $res->{size
}) {
1439 return undef if !defined($res->{size
} = PVE
::JSONSchema
::parse_size
($size));
1446 my ($vmid, $drive) = @_;
1447 my $data = { %$drive };
1448 delete $data->{$_} for qw(index interface);
1449 return PVE
::JSONSchema
::print_property_string
($data, $alldrive_fmt);
1453 my($fh, $noerr) = @_;
1456 my $SG_GET_VERSION_NUM = 0x2282;
1458 my $versionbuf = "\x00" x
8;
1459 my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
1461 die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
1464 my $version = unpack("I", $versionbuf);
1465 if ($version < 30000) {
1466 die "scsi generic interface too old\n" if !$noerr;
1470 my $buf = "\x00" x
36;
1471 my $sensebuf = "\x00" x
8;
1472 my $cmd = pack("C x3 C x1", 0x12, 36);
1474 # see /usr/include/scsi/sg.h
1475 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";
1477 my $packet = pack($sg_io_hdr_t, ord('S'), -3, length($cmd),
1478 length($sensebuf), 0, length($buf), $buf,
1479 $cmd, $sensebuf, 6000);
1481 $ret = ioctl($fh, $SG_IO, $packet);
1483 die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
1487 my @res = unpack($sg_io_hdr_t, $packet);
1488 if ($res[17] || $res[18]) {
1489 die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
1494 (my $byte0, my $byte1, $res->{vendor
},
1495 $res->{product
}, $res->{revision
}) = unpack("C C x6 A8 A16 A4", $buf);
1497 $res->{removable
} = $byte1 & 128 ?
1 : 0;
1498 $res->{type
} = $byte0 & 31;
1506 my $fh = IO
::File-
>new("+<$path") || return undef;
1507 my $res = scsi_inquiry
($fh, 1);
1513 sub machine_type_is_q35
{
1516 return $conf->{machine
} && ($conf->{machine
} =~ m/q35/) ?
1 : 0;
1519 sub print_tabletdevice_full
{
1522 my $q35 = machine_type_is_q35
($conf);
1524 # we use uhci for old VMs because tablet driver was buggy in older qemu
1525 my $usbbus = $q35 ?
"ehci" : "uhci";
1527 return "usb-tablet,id=tablet,bus=$usbbus.0,port=1";
1530 sub print_drivedevice_full
{
1531 my ($storecfg, $conf, $vmid, $drive, $bridges) = @_;
1536 if ($drive->{interface
} eq 'virtio') {
1537 my $pciaddr = print_pci_addr
("$drive->{interface}$drive->{index}", $bridges);
1538 $device = "virtio-blk-pci,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}$pciaddr";
1539 $device .= ",iothread=iothread-$drive->{interface}$drive->{index}" if $drive->{iothread
};
1540 } elsif ($drive->{interface
} eq 'scsi') {
1542 my ($maxdev, $controller, $controller_prefix) = scsihw_infos
($conf, $drive);
1543 my $unit = $drive->{index} % $maxdev;
1544 my $devicetype = 'hd';
1546 if (drive_is_cdrom
($drive)) {
1549 if ($drive->{file
} =~ m
|^/|) {
1550 $path = $drive->{file
};
1551 if (my $info = path_is_scsi
($path)) {
1552 if ($info->{type
} == 0 && $drive->{scsiblock
}) {
1553 $devicetype = 'block';
1554 } elsif ($info->{type
} == 1) { # tape
1555 $devicetype = 'generic';
1559 $path = PVE
::Storage
::path
($storecfg, $drive->{file
});
1562 if($path =~ m/^iscsi\:\/\
//){
1563 $devicetype = 'generic';
1567 if (!$conf->{scsihw
} || ($conf->{scsihw
} =~ m/^lsi/)){
1568 $device = "scsi-$devicetype,bus=$controller_prefix$controller.0,scsi-id=$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1570 $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}";
1573 } elsif ($drive->{interface
} eq 'ide'){
1575 my $controller = int($drive->{index} / $maxdev);
1576 my $unit = $drive->{index} % $maxdev;
1577 my $devicetype = ($drive->{media
} && $drive->{media
} eq 'cdrom') ?
"cd" : "hd";
1579 $device = "ide-$devicetype,bus=ide.$controller,unit=$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1580 if ($devicetype eq 'hd' && (my $model = $drive->{model
})) {
1581 $model = URI
::Escape
::uri_unescape
($model);
1582 $device .= ",model=$model";
1584 } elsif ($drive->{interface
} eq 'sata'){
1585 my $controller = int($drive->{index} / $MAX_SATA_DISKS);
1586 my $unit = $drive->{index} % $MAX_SATA_DISKS;
1587 $device = "ide-drive,bus=ahci$controller.$unit,drive=drive-$drive->{interface}$drive->{index},id=$drive->{interface}$drive->{index}";
1588 } elsif ($drive->{interface
} eq 'usb') {
1590 # -device ide-drive,bus=ide.1,unit=0,drive=drive-ide0-1-0,id=ide0-1-0
1592 die "unsupported interface type";
1595 $device .= ",bootindex=$drive->{bootindex}" if $drive->{bootindex
};
1600 sub get_initiator_name
{
1603 my $fh = IO
::File-
>new('/etc/iscsi/initiatorname.iscsi') || return undef;
1604 while (defined(my $line = <$fh>)) {
1605 next if $line !~ m/^\s*InitiatorName\s*=\s*([\.\-:\w]+)/;
1614 sub print_drive_full
{
1615 my ($storecfg, $vmid, $drive) = @_;
1618 my $volid = $drive->{file
};
1621 if (drive_is_cdrom
($drive)) {
1622 $path = get_iso_path
($storecfg, $vmid, $volid);
1624 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
1626 $path = PVE
::Storage
::path
($storecfg, $volid);
1627 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
1628 $format = qemu_img_format
($scfg, $volname);
1636 my @qemu_drive_options = qw(heads secs cyls trans media format cache rerror werror aio discard);
1637 foreach my $o (@qemu_drive_options) {
1638 $opts .= ",$o=$drive->{$o}" if defined($drive->{$o});
1641 # snapshot only accepts on|off
1642 if (defined($drive->{snapshot
})) {
1643 my $v = $drive->{snapshot
} ?
'on' : 'off';
1644 $opts .= ",snapshot=$v";
1647 foreach my $type (['', '-total'], [_rd
=> '-read'], [_wr
=> '-write']) {
1648 my ($dir, $qmpname) = @$type;
1649 if (my $v = $drive->{"mbps$dir"}) {
1650 $opts .= ",throttling.bps$qmpname=".int($v*1024*1024);
1652 if (my $v = $drive->{"mbps${dir}_max"}) {
1653 $opts .= ",throttling.bps$qmpname-max=".int($v*1024*1024);
1655 if (my $v = $drive->{"bps${dir}_max_length"}) {
1656 $opts .= ",throttling.bps$qmpname-max-length=$v";
1658 if (my $v = $drive->{"iops${dir}"}) {
1659 $opts .= ",throttling.iops$qmpname=$v";
1661 if (my $v = $drive->{"iops${dir}_max"}) {
1662 $opts .= ",throttling.iops$qmpname-max=$v";
1664 if (my $v = $drive->{"iops${dir}_max_length"}) {
1665 $opts .= ",throttling.iops$qmpname-max-length=$v";
1669 if (my $serial = $drive->{serial
}) {
1670 $serial = URI
::Escape
::uri_unescape
($serial);
1671 $opts .= ",serial=$serial";
1674 $opts .= ",format=$format" if $format && !$drive->{format
};
1676 my $cache_direct = 0;
1678 if (my $cache = $drive->{cache
}) {
1679 $cache_direct = $cache =~ /^(?:off|none|directsync)$/;
1680 } elsif (!drive_is_cdrom
($drive)) {
1681 $opts .= ",cache=none";
1685 # aio native works only with O_DIRECT
1686 if (!$drive->{aio
}) {
1688 $opts .= ",aio=native";
1690 $opts .= ",aio=threads";
1694 if (!drive_is_cdrom
($drive)) {
1696 if (defined($drive->{detect_zeroes
}) && !$drive->{detect_zeroes
}) {
1697 $detectzeroes = 'off';
1698 } elsif ($drive->{discard
}) {
1699 $detectzeroes = $drive->{discard
} eq 'on' ?
'unmap' : 'on';
1701 # This used to be our default with discard not being specified:
1702 $detectzeroes = 'on';
1704 $opts .= ",detect-zeroes=$detectzeroes" if $detectzeroes;
1707 my $pathinfo = $path ?
"file=$path," : '';
1709 return "${pathinfo}if=none,id=drive-$drive->{interface}$drive->{index}$opts";
1712 sub print_netdevice_full
{
1713 my ($vmid, $conf, $net, $netid, $bridges, $use_old_bios_files) = @_;
1715 my $bootorder = $conf->{boot
} || $confdesc->{boot
}->{default};
1717 my $device = $net->{model
};
1718 if ($net->{model
} eq 'virtio') {
1719 $device = 'virtio-net-pci';
1722 my $pciaddr = print_pci_addr
("$netid", $bridges);
1723 my $tmpstr = "$device,mac=$net->{macaddr},netdev=$netid$pciaddr,id=$netid";
1724 if ($net->{queues
} && $net->{queues
} > 1 && $net->{model
} eq 'virtio'){
1725 #Consider we have N queues, the number of vectors needed is 2*N + 2 (plus one config interrupt and control vq)
1726 my $vectors = $net->{queues
} * 2 + 2;
1727 $tmpstr .= ",vectors=$vectors,mq=on";
1729 $tmpstr .= ",bootindex=$net->{bootindex}" if $net->{bootindex
} ;
1731 if ($use_old_bios_files) {
1733 if ($device eq 'virtio-net-pci') {
1734 $romfile = 'pxe-virtio.rom';
1735 } elsif ($device eq 'e1000') {
1736 $romfile = 'pxe-e1000.rom';
1737 } elsif ($device eq 'ne2k') {
1738 $romfile = 'pxe-ne2k_pci.rom';
1739 } elsif ($device eq 'pcnet') {
1740 $romfile = 'pxe-pcnet.rom';
1741 } elsif ($device eq 'rtl8139') {
1742 $romfile = 'pxe-rtl8139.rom';
1744 $tmpstr .= ",romfile=$romfile" if $romfile;
1750 sub print_netdev_full
{
1751 my ($vmid, $conf, $net, $netid, $hotplug) = @_;
1754 if ($netid =~ m/^net(\d+)$/) {
1758 die "got strange net id '$i'\n" if $i >= ${MAX_NETS
};
1760 my $ifname = "tap${vmid}i$i";
1762 # kvm uses TUNSETIFF ioctl, and that limits ifname length
1763 die "interface name '$ifname' is too long (max 15 character)\n"
1764 if length($ifname) >= 16;
1766 my $vhostparam = '';
1767 $vhostparam = ',vhost=on' if $kernel_has_vhost_net && $net->{model
} eq 'virtio';
1769 my $vmname = $conf->{name
} || "vm$vmid";
1772 my $script = $hotplug ?
"pve-bridge-hotplug" : "pve-bridge";
1774 if ($net->{bridge
}) {
1775 $netdev = "type=tap,id=$netid,ifname=${ifname},script=/var/lib/qemu-server/$script,downscript=/var/lib/qemu-server/pve-bridgedown$vhostparam";
1777 $netdev = "type=user,id=$netid,hostname=$vmname";
1780 $netdev .= ",queues=$net->{queues}" if ($net->{queues
} && $net->{model
} eq 'virtio');
1786 sub print_cpu_device
{
1787 my ($conf, $id) = @_;
1789 my $kvm = $conf->{kvm
} // 1;
1790 my $cpu = $kvm ?
"kvm64" : "qemu64";
1791 if (my $cputype = $conf->{cpu
}) {
1792 my $cpuconf = PVE
::JSONSchema
::parse_property_string
($cpu_fmt, $cputype)
1793 or die "Cannot parse cpu description: $cputype\n";
1794 $cpu = $cpuconf->{cputype
};
1797 my $cores = $conf->{cores
} || 1;
1799 my $current_core = ($id - 1) % $cores;
1800 my $current_socket = int(($id - 1 - $current_core)/$cores);
1802 return "$cpu-x86_64-cpu,id=cpu$id,socket-id=$current_socket,core-id=$current_core,thread-id=0";
1805 sub drive_is_cdrom
{
1808 return $drive && $drive->{media
} && ($drive->{media
} eq 'cdrom');
1812 sub parse_number_sets
{
1815 foreach my $part (split(/;/, $set)) {
1816 if ($part =~ /^\s*(\d+)(?:-(\d+))?\s*$/) {
1817 die "invalid range: $part ($2 < $1)\n" if defined($2) && $2 < $1;
1818 push @$res, [ $1, $2 ];
1820 die "invalid range: $part\n";
1829 my $res = PVE
::JSONSchema
::parse_property_string
($numa_fmt, $data);
1830 $res->{cpus
} = parse_number_sets
($res->{cpus
}) if defined($res->{cpus
});
1831 $res->{hostnodes
} = parse_number_sets
($res->{hostnodes
}) if defined($res->{hostnodes
});
1838 return undef if !$value;
1840 my $res = PVE
::JSONSchema
::parse_property_string
($hostpci_fmt, $value);
1842 my @idlist = split(/;/, $res->{host
});
1843 delete $res->{host
};
1844 foreach my $id (@idlist) {
1845 if ($id =~ /^$PCIRE$/) {
1847 push @{$res->{pciid
}}, { id
=> $1, function
=> $2 };
1849 my $pcidevices = lspci
($1);
1850 $res->{pciid
} = $pcidevices->{$1};
1853 # should have been caught by parse_property_string already
1854 die "failed to parse PCI id: $id\n";
1860 # netX: e1000=XX:XX:XX:XX:XX:XX,bridge=vmbr0,rate=<mbps>
1864 my $res = eval { PVE
::JSONSchema
::parse_property_string
($net_fmt, $data) };
1869 if (!defined($res->{macaddr
})) {
1870 my $dc = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1871 $res->{macaddr
} = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
});
1879 return PVE
::JSONSchema
::print_property_string
($net, $net_fmt);
1882 sub add_random_macs
{
1883 my ($settings) = @_;
1885 foreach my $opt (keys %$settings) {
1886 next if $opt !~ m/^net(\d+)$/;
1887 my $net = parse_net
($settings->{$opt});
1889 $settings->{$opt} = print_net
($net);
1893 sub vm_is_volid_owner
{
1894 my ($storecfg, $vmid, $volid) = @_;
1896 if ($volid !~ m
|^/|) {
1898 eval { ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid); };
1899 if ($owner && ($owner == $vmid)) {
1907 sub split_flagged_list
{
1908 my $text = shift || '';
1909 $text =~ s/[,;]/ /g;
1911 return { map { /^(!?)(.*)$/ && ($2, $1) } ($text =~ /\S+/g) };
1914 sub join_flagged_list
{
1915 my ($how, $lst) = @_;
1916 join $how, map { $lst->{$_} . $_ } keys %$lst;
1919 sub vmconfig_delete_pending_option
{
1920 my ($conf, $key, $force) = @_;
1922 delete $conf->{pending
}->{$key};
1923 my $pending_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1924 $pending_delete_hash->{$key} = $force ?
'!' : '';
1925 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1928 sub vmconfig_undelete_pending_option
{
1929 my ($conf, $key) = @_;
1931 my $pending_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1932 delete $pending_delete_hash->{$key};
1934 if (%$pending_delete_hash) {
1935 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1937 delete $conf->{pending
}->{delete};
1941 sub vmconfig_register_unused_drive
{
1942 my ($storecfg, $vmid, $conf, $drive) = @_;
1944 if (!drive_is_cdrom
($drive)) {
1945 my $volid = $drive->{file
};
1946 if (vm_is_volid_owner
($storecfg, $vmid, $volid)) {
1947 PVE
::QemuConfig-
>add_unused_volume($conf, $volid, $vmid);
1952 sub vmconfig_cleanup_pending
{
1955 # remove pending changes when nothing changed
1957 foreach my $opt (keys %{$conf->{pending
}}) {
1958 if (defined($conf->{$opt}) && ($conf->{pending
}->{$opt} eq $conf->{$opt})) {
1960 delete $conf->{pending
}->{$opt};
1964 my $current_delete_hash = split_flagged_list
($conf->{pending
}->{delete});
1965 my $pending_delete_hash = {};
1966 while (my ($opt, $force) = each %$current_delete_hash) {
1967 if (defined($conf->{$opt})) {
1968 $pending_delete_hash->{$opt} = $force;
1974 if (%$pending_delete_hash) {
1975 $conf->{pending
}->{delete} = join_flagged_list
(',', $pending_delete_hash);
1977 delete $conf->{pending
}->{delete};
1983 # smbios: [manufacturer=str][,product=str][,version=str][,serial=str][,uuid=uuid][,sku=str][,family=str]
1987 pattern
=> '[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}',
1988 format_description
=> 'UUID',
1989 description
=> "Set SMBIOS1 UUID.",
1995 format_description
=> 'string',
1996 description
=> "Set SMBIOS1 version.",
2002 format_description
=> 'string',
2003 description
=> "Set SMBIOS1 serial number.",
2009 format_description
=> 'string',
2010 description
=> "Set SMBIOS1 manufacturer.",
2016 format_description
=> 'string',
2017 description
=> "Set SMBIOS1 product ID.",
2023 format_description
=> 'string',
2024 description
=> "Set SMBIOS1 SKU string.",
2030 format_description
=> 'string',
2031 description
=> "Set SMBIOS1 family string.",
2039 my $res = eval { PVE
::JSONSchema
::parse_property_string
($smbios1_fmt, $data) };
2046 return PVE
::JSONSchema
::print_property_string
($smbios1, $smbios1_fmt);
2049 PVE
::JSONSchema
::register_format
('pve-qm-smbios1', $smbios1_fmt);
2051 PVE
::JSONSchema
::register_format
('pve-qm-bootdisk', \
&verify_bootdisk
);
2052 sub verify_bootdisk
{
2053 my ($value, $noerr) = @_;
2055 return $value if is_valid_drivename
($value);
2057 return undef if $noerr;
2059 die "invalid boot disk '$value'\n";
2062 sub parse_watchdog
{
2065 return undef if !$value;
2067 my $res = eval { PVE
::JSONSchema
::parse_property_string
($watchdog_fmt, $value) };
2072 PVE
::JSONSchema
::register_format
('pve-qm-usb-device', \
&verify_usb_device
);
2073 sub verify_usb_device
{
2074 my ($value, $noerr) = @_;
2076 return $value if parse_usb_device
($value);
2078 return undef if $noerr;
2080 die "unable to parse usb device\n";
2083 # add JSON properties for create and set function
2084 sub json_config_properties
{
2087 foreach my $opt (keys %$confdesc) {
2088 next if $opt eq 'parent' || $opt eq 'snaptime' || $opt eq 'vmstate';
2089 $prop->{$opt} = $confdesc->{$opt};
2096 my ($key, $value) = @_;
2098 die "unknown setting '$key'\n" if !$confdesc->{$key};
2100 my $type = $confdesc->{$key}->{type
};
2102 if (!defined($value)) {
2103 die "got undefined value\n";
2106 if ($value =~ m/[\n\r]/) {
2107 die "property contains a line feed\n";
2110 if ($type eq 'boolean') {
2111 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
2112 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
2113 die "type check ('boolean') failed - got '$value'\n";
2114 } elsif ($type eq 'integer') {
2115 return int($1) if $value =~ m/^(\d+)$/;
2116 die "type check ('integer') failed - got '$value'\n";
2117 } elsif ($type eq 'number') {
2118 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
2119 die "type check ('number') failed - got '$value'\n";
2120 } elsif ($type eq 'string') {
2121 if (my $fmt = $confdesc->{$key}->{format
}) {
2122 PVE
::JSONSchema
::check_format
($fmt, $value);
2125 $value =~ s/^\"(.*)\"$/$1/;
2128 die "internal error"
2132 sub check_iommu_support
{
2133 #fixme : need to check IOMMU support
2134 #http://www.linux-kvm.org/page/How_to_assign_devices_with_VT-d_in_KVM
2144 my $conf = PVE
::QemuConfig-
>config_file($vmid);
2145 utime undef, undef, $conf;
2149 my ($storecfg, $vmid, $keep_empty_config, $skiplock) = @_;
2151 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
2153 my $conf = PVE
::QemuConfig-
>load_config($vmid);
2155 PVE
::QemuConfig-
>check_lock($conf) if !$skiplock;
2157 if ($conf->{template
}) {
2158 # check if any base image is still used by a linked clone
2159 foreach_drive
($conf, sub {
2160 my ($ds, $drive) = @_;
2162 return if drive_is_cdrom
($drive);
2164 my $volid = $drive->{file
};
2166 return if !$volid || $volid =~ m
|^/|;
2168 die "base volume '$volid' is still in use by linked cloned\n"
2169 if PVE
::Storage
::volume_is_base_and_used
($storecfg, $volid);
2174 # only remove disks owned by this VM
2175 foreach_drive
($conf, sub {
2176 my ($ds, $drive) = @_;
2178 return if drive_is_cdrom
($drive);
2180 my $volid = $drive->{file
};
2182 return if !$volid || $volid =~ m
|^/|;
2184 my ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid);
2185 return if !$path || !$owner || ($owner != $vmid);
2188 PVE
::Storage
::vdisk_free
($storecfg, $volid);
2190 warn "Could not remove disk '$volid', check manually: $@" if $@;
2194 if ($keep_empty_config) {
2195 PVE
::Tools
::file_set_contents
($conffile, "memory: 128\n");
2200 # also remove unused disk
2202 my $dl = PVE
::Storage
::vdisk_list
($storecfg, undef, $vmid);
2205 PVE
::Storage
::foreach_volid
($dl, sub {
2206 my ($volid, $sid, $volname, $d) = @_;
2207 PVE
::Storage
::vdisk_free
($storecfg, $volid);
2216 sub parse_vm_config
{
2217 my ($filename, $raw) = @_;
2219 return undef if !defined($raw);
2222 digest
=> Digest
::SHA
::sha1_hex
($raw),
2227 $filename =~ m
|/qemu-server/(\d
+)\
.conf
$|
2228 || die "got strange filename '$filename'";
2236 my @lines = split(/\n/, $raw);
2237 foreach my $line (@lines) {
2238 next if $line =~ m/^\s*$/;
2240 if ($line =~ m/^\[PENDING\]\s*$/i) {
2241 $section = 'pending';
2242 if (defined($descr)) {
2244 $conf->{description
} = $descr;
2247 $conf = $res->{$section} = {};
2250 } elsif ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
2252 if (defined($descr)) {
2254 $conf->{description
} = $descr;
2257 $conf = $res->{snapshots
}->{$section} = {};
2261 if ($line =~ m/^\#(.*)\s*$/) {
2262 $descr = '' if !defined($descr);
2263 $descr .= PVE
::Tools
::decode_text
($1) . "\n";
2267 if ($line =~ m/^(description):\s*(.*\S)\s*$/) {
2268 $descr = '' if !defined($descr);
2269 $descr .= PVE
::Tools
::decode_text
($2);
2270 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
2271 $conf->{snapstate
} = $1;
2272 } elsif ($line =~ m/^(args):\s*(.*\S)\s*$/) {
2275 $conf->{$key} = $value;
2276 } elsif ($line =~ m/^delete:\s*(.*\S)\s*$/) {
2278 if ($section eq 'pending') {
2279 $conf->{delete} = $value; # we parse this later
2281 warn "vm $vmid - propertry 'delete' is only allowed in [PENDING]\n";
2283 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(\S+)\s*$/) {
2286 eval { $value = check_type
($key, $value); };
2288 warn "vm $vmid - unable to parse value of '$key' - $@";
2290 $key = 'ide2' if $key eq 'cdrom';
2291 my $fmt = $confdesc->{$key}->{format
};
2292 if ($fmt && $fmt =~ /^pve-qm-(?:ide|scsi|virtio|sata)$/) {
2293 my $v = parse_drive
($key, $value);
2294 if (my $volid = filename_to_volume_id
($vmid, $v->{file
}, $v->{media
})) {
2295 $v->{file
} = $volid;
2296 $value = print_drive
($vmid, $v);
2298 warn "vm $vmid - unable to parse value of '$key'\n";
2303 $conf->{$key} = $value;
2308 if (defined($descr)) {
2310 $conf->{description
} = $descr;
2312 delete $res->{snapstate
}; # just to be sure
2317 sub write_vm_config
{
2318 my ($filename, $conf) = @_;
2320 delete $conf->{snapstate
}; # just to be sure
2322 if ($conf->{cdrom
}) {
2323 die "option ide2 conflicts with cdrom\n" if $conf->{ide2
};
2324 $conf->{ide2
} = $conf->{cdrom
};
2325 delete $conf->{cdrom
};
2328 # we do not use 'smp' any longer
2329 if ($conf->{sockets
}) {
2330 delete $conf->{smp
};
2331 } elsif ($conf->{smp
}) {
2332 $conf->{sockets
} = $conf->{smp
};
2333 delete $conf->{cores
};
2334 delete $conf->{smp
};
2337 my $used_volids = {};
2339 my $cleanup_config = sub {
2340 my ($cref, $pending, $snapname) = @_;
2342 foreach my $key (keys %$cref) {
2343 next if $key eq 'digest' || $key eq 'description' || $key eq 'snapshots' ||
2344 $key eq 'snapstate' || $key eq 'pending';
2345 my $value = $cref->{$key};
2346 if ($key eq 'delete') {
2347 die "propertry 'delete' is only allowed in [PENDING]\n"
2349 # fixme: check syntax?
2352 eval { $value = check_type
($key, $value); };
2353 die "unable to parse value of '$key' - $@" if $@;
2355 $cref->{$key} = $value;
2357 if (!$snapname && is_valid_drivename
($key)) {
2358 my $drive = parse_drive
($key, $value);
2359 $used_volids->{$drive->{file
}} = 1 if $drive && $drive->{file
};
2364 &$cleanup_config($conf);
2366 &$cleanup_config($conf->{pending
}, 1);
2368 foreach my $snapname (keys %{$conf->{snapshots
}}) {
2369 die "internal error" if $snapname eq 'pending';
2370 &$cleanup_config($conf->{snapshots
}->{$snapname}, undef, $snapname);
2373 # remove 'unusedX' settings if we re-add a volume
2374 foreach my $key (keys %$conf) {
2375 my $value = $conf->{$key};
2376 if ($key =~ m/^unused/ && $used_volids->{$value}) {
2377 delete $conf->{$key};
2381 my $generate_raw_config = sub {
2382 my ($conf, $pending) = @_;
2386 # add description as comment to top of file
2387 if (defined(my $descr = $conf->{description
})) {
2389 foreach my $cl (split(/\n/, $descr)) {
2390 $raw .= '#' . PVE
::Tools
::encode_text
($cl) . "\n";
2393 $raw .= "#\n" if $pending;
2397 foreach my $key (sort keys %$conf) {
2398 next if $key eq 'digest' || $key eq 'description' || $key eq 'pending' || $key eq 'snapshots';
2399 $raw .= "$key: $conf->{$key}\n";
2404 my $raw = &$generate_raw_config($conf);
2406 if (scalar(keys %{$conf->{pending
}})){
2407 $raw .= "\n[PENDING]\n";
2408 $raw .= &$generate_raw_config($conf->{pending
}, 1);
2411 foreach my $snapname (sort keys %{$conf->{snapshots
}}) {
2412 $raw .= "\n[$snapname]\n";
2413 $raw .= &$generate_raw_config($conf->{snapshots
}->{$snapname});
2423 # we use static defaults from our JSON schema configuration
2424 foreach my $key (keys %$confdesc) {
2425 if (defined(my $default = $confdesc->{$key}->{default})) {
2426 $res->{$key} = $default;
2430 my $conf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
2431 $res->{keyboard
} = $conf->{keyboard
} if $conf->{keyboard
};
2437 my $vmlist = PVE
::Cluster
::get_vmlist
();
2439 return $res if !$vmlist || !$vmlist->{ids
};
2440 my $ids = $vmlist->{ids
};
2442 foreach my $vmid (keys %$ids) {
2443 my $d = $ids->{$vmid};
2444 next if !$d->{node
} || $d->{node
} ne $nodename;
2445 next if !$d->{type
} || $d->{type
} ne 'qemu';
2446 $res->{$vmid}->{exists} = 1;
2451 # test if VM uses local resources (to prevent migration)
2452 sub check_local_resources
{
2453 my ($conf, $noerr) = @_;
2457 $loc_res = 1 if $conf->{hostusb
}; # old syntax
2458 $loc_res = 1 if $conf->{hostpci
}; # old syntax
2460 foreach my $k (keys %$conf) {
2461 next if $k =~ m/^usb/ && ($conf->{$k} eq 'spice');
2462 # sockets are safe: they will recreated be on the target side post-migrate
2463 next if $k =~ m/^serial/ && ($conf->{$k} eq 'socket');
2464 $loc_res = 1 if $k =~ m/^(usb|hostpci|serial|parallel)\d+$/;
2467 die "VM uses local resources\n" if $loc_res && !$noerr;
2472 # check if used storages are available on all nodes (use by migrate)
2473 sub check_storage_availability
{
2474 my ($storecfg, $conf, $node) = @_;
2476 foreach_drive
($conf, sub {
2477 my ($ds, $drive) = @_;
2479 my $volid = $drive->{file
};
2482 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2485 # check if storage is available on both nodes
2486 my $scfg = PVE
::Storage
::storage_check_node
($storecfg, $sid);
2487 PVE
::Storage
::storage_check_node
($storecfg, $sid, $node);
2491 # list nodes where all VM images are available (used by has_feature API)
2493 my ($conf, $storecfg) = @_;
2495 my $nodelist = PVE
::Cluster
::get_nodelist
();
2496 my $nodehash = { map { $_ => 1 } @$nodelist };
2497 my $nodename = PVE
::INotify
::nodename
();
2499 foreach_drive
($conf, sub {
2500 my ($ds, $drive) = @_;
2502 my $volid = $drive->{file
};
2505 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
2507 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
2508 if ($scfg->{disable
}) {
2510 } elsif (my $avail = $scfg->{nodes
}) {
2511 foreach my $node (keys %$nodehash) {
2512 delete $nodehash->{$node} if !$avail->{$node};
2514 } elsif (!$scfg->{shared
}) {
2515 foreach my $node (keys %$nodehash) {
2516 delete $nodehash->{$node} if $node ne $nodename
2526 my ($pidfile, $pid) = @_;
2528 my $fh = IO
::File-
>new("/proc/$pid/cmdline", "r");
2532 return undef if !$line;
2533 my @param = split(/\0/, $line);
2535 my $cmd = $param[0];
2536 return if !$cmd || ($cmd !~ m
|kvm
$| && $cmd !~ m
|qemu-system-x86_64
$|);
2538 for (my $i = 0; $i < scalar (@param); $i++) {
2541 if (($p eq '-pidfile') || ($p eq '--pidfile')) {
2542 my $p = $param[$i+1];
2543 return 1 if $p && ($p eq $pidfile);
2552 my ($vmid, $nocheck, $node) = @_;
2554 my $filename = PVE
::QemuConfig-
>config_file($vmid, $node);
2556 die "unable to find configuration file for VM $vmid - no such machine\n"
2557 if !$nocheck && ! -f
$filename;
2559 my $pidfile = pidfile_name
($vmid);
2561 if (my $fd = IO
::File-
>new("<$pidfile")) {
2566 my $mtime = $st->mtime;
2567 if ($mtime > time()) {
2568 warn "file '$filename' modified in future\n";
2571 if ($line =~ m/^(\d+)$/) {
2573 if (check_cmdline
($pidfile, $pid)) {
2574 if (my $pinfo = PVE
::ProcFSTools
::check_process_running
($pid)) {
2586 my $vzlist = config_list
();
2588 my $fd = IO
::Dir-
>new($var_run_tmpdir) || return $vzlist;
2590 while (defined(my $de = $fd->read)) {
2591 next if $de !~ m/^(\d+)\.pid$/;
2593 next if !defined($vzlist->{$vmid});
2594 if (my $pid = check_running
($vmid)) {
2595 $vzlist->{$vmid}->{pid
} = $pid;
2603 my ($storecfg, $conf) = @_;
2605 my $bootdisk = $conf->{bootdisk
};
2606 return undef if !$bootdisk;
2607 return undef if !is_valid_drivename
($bootdisk);
2609 return undef if !$conf->{$bootdisk};
2611 my $drive = parse_drive
($bootdisk, $conf->{$bootdisk});
2612 return undef if !defined($drive);
2614 return undef if drive_is_cdrom
($drive);
2616 my $volid = $drive->{file
};
2617 return undef if !$volid;
2619 return $drive->{size
};
2622 my $last_proc_pid_stat;
2624 # get VM status information
2625 # This must be fast and should not block ($full == false)
2626 # We only query KVM using QMP if $full == true (this can be slow)
2628 my ($opt_vmid, $full) = @_;
2632 my $storecfg = PVE
::Storage
::config
();
2634 my $list = vzlist
();
2635 my $defaults = load_defaults
();
2637 my ($uptime) = PVE
::ProcFSTools
::read_proc_uptime
(1);
2639 my $cpucount = $cpuinfo->{cpus
} || 1;
2641 foreach my $vmid (keys %$list) {
2642 next if $opt_vmid && ($vmid ne $opt_vmid);
2644 my $cfspath = PVE
::QemuConfig-
>cfs_config_path($vmid);
2645 my $conf = PVE
::Cluster
::cfs_read_file
($cfspath) || {};
2648 $d->{pid
} = $list->{$vmid}->{pid
};
2650 # fixme: better status?
2651 $d->{status
} = $list->{$vmid}->{pid
} ?
'running' : 'stopped';
2653 my $size = disksize
($storecfg, $conf);
2654 if (defined($size)) {
2655 $d->{disk
} = 0; # no info available
2656 $d->{maxdisk
} = $size;
2662 $d->{cpus
} = ($conf->{sockets
} || $defaults->{sockets
})
2663 * ($conf->{cores
} || $defaults->{cores
});
2664 $d->{cpus
} = $cpucount if $d->{cpus
} > $cpucount;
2665 $d->{cpus
} = $conf->{vcpus
} if $conf->{vcpus
};
2667 $d->{name
} = $conf->{name
} || "VM $vmid";
2668 $d->{maxmem
} = $conf->{memory
} ?
$conf->{memory
}*(1024*1024)
2669 : $defaults->{memory
}*(1024*1024);
2671 if ($conf->{balloon
}) {
2672 $d->{balloon_min
} = $conf->{balloon
}*(1024*1024);
2673 $d->{shares
} = defined($conf->{shares
}) ?
$conf->{shares
}
2674 : $defaults->{shares
};
2685 $d->{diskwrite
} = 0;
2687 $d->{template
} = PVE
::QemuConfig-
>is_template($conf);
2689 $d->{serial
} = 1 if conf_has_serial
($conf);
2694 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
2695 foreach my $dev (keys %$netdev) {
2696 next if $dev !~ m/^tap([1-9]\d*)i/;
2698 my $d = $res->{$vmid};
2701 $d->{netout
} += $netdev->{$dev}->{receive
};
2702 $d->{netin
} += $netdev->{$dev}->{transmit
};
2705 $d->{nics
}->{$dev}->{netout
} = $netdev->{$dev}->{receive
};
2706 $d->{nics
}->{$dev}->{netin
} = $netdev->{$dev}->{transmit
};
2711 my $ctime = gettimeofday
;
2713 foreach my $vmid (keys %$list) {
2715 my $d = $res->{$vmid};
2716 my $pid = $d->{pid
};
2719 my $pstat = PVE
::ProcFSTools
::read_proc_pid_stat
($pid);
2720 next if !$pstat; # not running
2722 my $used = $pstat->{utime} + $pstat->{stime
};
2724 $d->{uptime
} = int(($uptime - $pstat->{starttime
})/$cpuinfo->{user_hz
});
2726 if ($pstat->{vsize
}) {
2727 $d->{mem
} = int(($pstat->{rss
}/$pstat->{vsize
})*$d->{maxmem
});
2730 my $old = $last_proc_pid_stat->{$pid};
2732 $last_proc_pid_stat->{$pid} = {
2740 my $dtime = ($ctime - $old->{time}) * $cpucount * $cpuinfo->{user_hz
};
2742 if ($dtime > 1000) {
2743 my $dutime = $used - $old->{used
};
2745 $d->{cpu
} = (($dutime/$dtime)* $cpucount) / $d->{cpus
};
2746 $last_proc_pid_stat->{$pid} = {
2752 $d->{cpu
} = $old->{cpu
};
2756 return $res if !$full;
2758 my $qmpclient = PVE
::QMPClient-
>new();
2760 my $ballooncb = sub {
2761 my ($vmid, $resp) = @_;
2763 my $info = $resp->{'return'};
2764 return if !$info->{max_mem
};
2766 my $d = $res->{$vmid};
2768 # use memory assigned to VM
2769 $d->{maxmem
} = $info->{max_mem
};
2770 $d->{balloon
} = $info->{actual
};
2772 if (defined($info->{total_mem
}) && defined($info->{free_mem
})) {
2773 $d->{mem
} = $info->{total_mem
} - $info->{free_mem
};
2774 $d->{freemem
} = $info->{free_mem
};
2777 $d->{ballooninfo
} = $info;
2780 my $blockstatscb = sub {
2781 my ($vmid, $resp) = @_;
2782 my $data = $resp->{'return'} || [];
2783 my $totalrdbytes = 0;
2784 my $totalwrbytes = 0;
2786 for my $blockstat (@$data) {
2787 $totalrdbytes = $totalrdbytes + $blockstat->{stats
}->{rd_bytes
};
2788 $totalwrbytes = $totalwrbytes + $blockstat->{stats
}->{wr_bytes
};
2790 $blockstat->{device
} =~ s/drive-//;
2791 $res->{$vmid}->{blockstat
}->{$blockstat->{device
}} = $blockstat->{stats
};
2793 $res->{$vmid}->{diskread
} = $totalrdbytes;
2794 $res->{$vmid}->{diskwrite
} = $totalwrbytes;
2797 my $statuscb = sub {
2798 my ($vmid, $resp) = @_;
2800 $qmpclient->queue_cmd($vmid, $blockstatscb, 'query-blockstats');
2801 # this fails if ballon driver is not loaded, so this must be
2802 # the last commnand (following command are aborted if this fails).
2803 $qmpclient->queue_cmd($vmid, $ballooncb, 'query-balloon');
2805 my $status = 'unknown';
2806 if (!defined($status = $resp->{'return'}->{status
})) {
2807 warn "unable to get VM status\n";
2811 $res->{$vmid}->{qmpstatus
} = $resp->{'return'}->{status
};
2814 foreach my $vmid (keys %$list) {
2815 next if $opt_vmid && ($vmid ne $opt_vmid);
2816 next if !$res->{$vmid}->{pid
}; # not running
2817 $qmpclient->queue_cmd($vmid, $statuscb, 'query-status');
2820 $qmpclient->queue_execute(undef, 2);
2822 foreach my $vmid (keys %$list) {
2823 next if $opt_vmid && ($vmid ne $opt_vmid);
2824 $res->{$vmid}->{qmpstatus
} = $res->{$vmid}->{status
} if !$res->{$vmid}->{qmpstatus
};
2831 my ($conf, $func, @param) = @_;
2833 foreach my $ds (valid_drive_names
()) {
2834 next if !defined($conf->{$ds});
2836 my $drive = parse_drive
($ds, $conf->{$ds});
2839 &$func($ds, $drive, @param);
2844 my ($conf, $func, @param) = @_;
2848 my $test_volid = sub {
2849 my ($volid, $is_cdrom, $replicate, $shared, $snapname) = @_;
2853 $volhash->{$volid}->{cdrom
} //= 1;
2854 $volhash->{$volid}->{cdrom
} = 0 if !$is_cdrom;
2856 $volhash->{$volid}->{replicate
} //= 0;
2857 $volhash->{$volid}->{replicate
} = 1 if $replicate;
2859 $volhash->{$volid}->{shared
} //= 0;
2860 $volhash->{$volid}->{shared
} = 1 if $shared;
2862 $volhash->{$volid}->{referenced_in_config
} //= 0;
2863 $volhash->{$volid}->{referenced_in_config
} = 1 if !defined($snapname);
2865 $volhash->{$volid}->{referenced_in_snapshot
}->{$snapname} = 1
2866 if defined($snapname);
2869 foreach_drive
($conf, sub {
2870 my ($ds, $drive) = @_;
2871 $test_volid->($drive->{file
}, drive_is_cdrom
($drive), $drive->{replicate
} // 1, $drive->{shared
}, undef);
2874 foreach my $snapname (keys %{$conf->{snapshots
}}) {
2875 my $snap = $conf->{snapshots
}->{$snapname};
2876 $test_volid->($snap->{vmstate
}, 0, 1, $snapname);
2877 foreach_drive
($snap, sub {
2878 my ($ds, $drive) = @_;
2879 $test_volid->($drive->{file
}, drive_is_cdrom
($drive), $drive->{replicate
} // 1, $drive->{shared
}, $snapname);
2883 foreach my $volid (keys %$volhash) {
2884 &$func($volid, $volhash->{$volid}, @param);
2888 sub conf_has_serial
{
2891 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
2892 if ($conf->{"serial$i"}) {
2900 sub vga_conf_has_spice
{
2903 return 0 if !$vga || $vga !~ m/^qxl([234])?$/;
2908 sub config_to_command
{
2909 my ($storecfg, $vmid, $conf, $defaults, $forcemachine) = @_;
2912 my $globalFlags = [];
2913 my $machineFlags = [];
2919 my $kvmver = kvm_user_version
();
2920 my $vernum = 0; # unknown
2921 my $ostype = $conf->{ostype
};
2922 my $winversion = windows_version
($ostype);
2923 my $kvm = $conf->{kvm
} // 1;
2925 die "KVM virtualisation configured, but not available. Either disable in VM configuration or enable in BIOS.\n" if (!$cpuinfo->{hvm
} && $kvm);
2927 if ($kvmver =~ m/^(\d+)\.(\d+)$/) {
2928 $vernum = $1*1000000+$2*1000;
2929 } elsif ($kvmver =~ m/^(\d+)\.(\d+)\.(\d+)$/) {
2930 $vernum = $1*1000000+$2*1000+$3;
2933 die "detected old qemu-kvm binary ($kvmver)\n" if $vernum < 15000;
2935 my $have_ovz = -f
'/proc/vz/vestat';
2937 my $q35 = machine_type_is_q35
($conf);
2938 my $hotplug_features = parse_hotplug_features
(defined($conf->{hotplug
}) ?
$conf->{hotplug
} : '1');
2939 my $machine_type = $forcemachine || $conf->{machine
};
2940 my $use_old_bios_files = undef;
2941 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files
($machine_type);
2943 my $cpuunits = defined($conf->{cpuunits
}) ?
2944 $conf->{cpuunits
} : $defaults->{cpuunits
};
2946 push @$cmd, '/usr/bin/kvm';
2948 push @$cmd, '-id', $vmid;
2952 my $qmpsocket = qmp_socket
($vmid);
2953 push @$cmd, '-chardev', "socket,id=qmp,path=$qmpsocket,server,nowait";
2954 push @$cmd, '-mon', "chardev=qmp,mode=control";
2957 push @$cmd, '-pidfile' , pidfile_name
($vmid);
2959 push @$cmd, '-daemonize';
2961 if ($conf->{smbios1
}) {
2962 push @$cmd, '-smbios', "type=1,$conf->{smbios1}";
2965 if ($conf->{bios
} && $conf->{bios
} eq 'ovmf') {
2966 die "uefi base image not found\n" if ! -f
$OVMF_CODE;
2970 if (my $efidisk = $conf->{efidisk0
}) {
2971 my $d = PVE
::JSONSchema
::parse_property_string
($efidisk_fmt, $efidisk);
2972 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($d->{file
}, 1);
2973 $format = $d->{format
};
2975 $path = PVE
::Storage
::path
($storecfg, $d->{file
});
2976 if (!defined($format)) {
2977 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
2978 $format = qemu_img_format
($scfg, $volname);
2982 die "efidisk format must be specified\n"
2983 if !defined($format);
2986 warn "no efidisk configured! Using temporary efivars disk.\n";
2987 $path = "/tmp/$vmid-ovmf.fd";
2988 PVE
::Tools
::file_copy
($OVMF_VARS, $path, -s
$OVMF_VARS);
2992 push @$cmd, '-drive', "if=pflash,unit=0,format=raw,readonly,file=$OVMF_CODE";
2993 push @$cmd, '-drive', "if=pflash,unit=1,format=$format,id=drive-efidisk0,file=$path";
2997 # add usb controllers
2998 my @usbcontrollers = PVE
::QemuServer
::USB
::get_usb_controllers
($conf, $bridges, $q35, $usbdesc->{format
}, $MAX_USB_DEVICES);
2999 push @$devices, @usbcontrollers if @usbcontrollers;
3000 my $vga = $conf->{vga
};
3002 my $qxlnum = vga_conf_has_spice
($vga);
3003 $vga = 'qxl' if $qxlnum;
3006 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 9)) {
3007 $vga = (!$winversion || $winversion >= 6) ?
'std' : 'cirrus';
3009 $vga = ($winversion >= 6) ?
'std' : 'cirrus';
3013 # enable absolute mouse coordinates (needed by vnc)
3015 if (defined($conf->{tablet
})) {
3016 $tablet = $conf->{tablet
};
3018 $tablet = $defaults->{tablet
};
3019 $tablet = 0 if $qxlnum; # disable for spice because it is not needed
3020 $tablet = 0 if $vga =~ m/^serial\d+$/; # disable if we use serial terminal (no vga card)
3023 push @$devices, '-device', print_tabletdevice_full
($conf) if $tablet;
3026 my $gpu_passthrough;
3029 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
3030 my $d = parse_hostpci
($conf->{"hostpci$i"});
3033 my $pcie = $d->{pcie
};
3035 die "q35 machine model is not enabled" if !$q35;
3036 $pciaddr = print_pcie_addr
("hostpci$i");
3038 $pciaddr = print_pci_addr
("hostpci$i", $bridges);
3041 my $rombar = defined($d->{rombar
}) && !$d->{rombar
} ?
',rombar=0' : '';
3042 my $romfile = $d->{romfile
};
3045 if ($d->{'x-vga'}) {
3046 $xvga = ',x-vga=on';
3049 $gpu_passthrough = 1;
3051 if ($conf->{bios
} && $conf->{bios
} eq 'ovmf') {
3055 my $pcidevices = $d->{pciid
};
3056 my $multifunction = 1 if @$pcidevices > 1;
3059 foreach my $pcidevice (@$pcidevices) {
3061 my $id = "hostpci$i";
3062 $id .= ".$j" if $multifunction;
3063 my $addr = $pciaddr;
3064 $addr .= ".$j" if $multifunction;
3065 my $devicestr = "vfio-pci,host=$pcidevice->{id}.$pcidevice->{function},id=$id$addr";
3068 $devicestr .= "$rombar$xvga";
3069 $devicestr .= ",multifunction=on" if $multifunction;
3070 $devicestr .= ",romfile=/usr/share/kvm/$romfile" if $romfile;
3073 push @$devices, '-device', $devicestr;
3079 my @usbdevices = PVE
::QemuServer
::USB
::get_usb_devices
($conf, $usbdesc->{format
}, $MAX_USB_DEVICES);
3080 push @$devices, @usbdevices if @usbdevices;
3082 for (my $i = 0; $i < $MAX_SERIAL_PORTS; $i++) {
3083 if (my $path = $conf->{"serial$i"}) {
3084 if ($path eq 'socket') {
3085 my $socket = "/var/run/qemu-server/${vmid}.serial$i";
3086 push @$devices, '-chardev', "socket,id=serial$i,path=$socket,server,nowait";
3087 push @$devices, '-device', "isa-serial,chardev=serial$i";
3089 die "no such serial device\n" if ! -c
$path;
3090 push @$devices, '-chardev', "tty,id=serial$i,path=$path";
3091 push @$devices, '-device', "isa-serial,chardev=serial$i";
3097 for (my $i = 0; $i < $MAX_PARALLEL_PORTS; $i++) {
3098 if (my $path = $conf->{"parallel$i"}) {
3099 die "no such parallel device\n" if ! -c
$path;
3100 my $devtype = $path =~ m!^/dev/usb/lp! ?
'tty' : 'parport';
3101 push @$devices, '-chardev', "$devtype,id=parallel$i,path=$path";
3102 push @$devices, '-device', "isa-parallel,chardev=parallel$i";
3106 my $vmname = $conf->{name
} || "vm$vmid";
3108 push @$cmd, '-name', $vmname;
3111 $sockets = $conf->{smp
} if $conf->{smp
}; # old style - no longer iused
3112 $sockets = $conf->{sockets
} if $conf->{sockets
};
3114 my $cores = $conf->{cores
} || 1;
3116 my $maxcpus = $sockets * $cores;
3118 my $vcpus = $conf->{vcpus
} ?
$conf->{vcpus
} : $maxcpus;
3120 my $allowed_vcpus = $cpuinfo->{cpus
};
3122 die "MAX $allowed_vcpus vcpus allowed per VM on this node\n"
3123 if ($allowed_vcpus < $maxcpus);
3125 if($hotplug_features->{cpu
} && qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 7)) {
3127 push @$cmd, '-smp', "1,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3128 for (my $i = 2; $i <= $vcpus; $i++) {
3129 my $cpustr = print_cpu_device
($conf,$i);
3130 push @$cmd, '-device', $cpustr;
3135 push @$cmd, '-smp', "$vcpus,sockets=$sockets,cores=$cores,maxcpus=$maxcpus";
3137 push @$cmd, '-nodefaults';
3139 my $bootorder = $conf->{boot
} || $confdesc->{boot
}->{default};
3141 my $bootindex_hash = {};
3143 foreach my $o (split(//, $bootorder)) {
3144 $bootindex_hash->{$o} = $i*100;
3148 push @$cmd, '-boot', "menu=on,strict=on,reboot-timeout=1000,splash=/usr/share/qemu-server/bootsplash.jpg";
3150 push @$cmd, '-no-acpi' if defined($conf->{acpi
}) && $conf->{acpi
} == 0;
3152 push @$cmd, '-no-reboot' if defined($conf->{reboot
}) && $conf->{reboot
} == 0;
3154 push @$cmd, '-vga', $vga if $vga && $vga !~ m/^serial\d+$/; # for kvm 77 and later
3156 if ($vga && $vga !~ m/^serial\d+$/ && $vga ne 'none'){
3157 my $socket = vnc_socket
($vmid);
3158 push @$cmd, '-vnc', "unix:$socket,x509,password";
3160 push @$cmd, '-nographic';
3164 my $tdf = defined($conf->{tdf
}) ?
$conf->{tdf
} : $defaults->{tdf
};
3166 my $useLocaltime = $conf->{localtime};
3168 if ($winversion >= 5) { # windows
3169 $useLocaltime = 1 if !defined($conf->{localtime});
3171 # use time drift fix when acpi is enabled
3172 if (!(defined($conf->{acpi
}) && $conf->{acpi
} == 0)) {
3173 $tdf = 1 if !defined($conf->{tdf
});
3177 if ($winversion >= 6) {
3178 push @$globalFlags, 'kvm-pit.lost_tick_policy=discard';
3179 push @$cmd, '-no-hpet';
3182 push @$rtcFlags, 'driftfix=slew' if $tdf;
3185 push @$machineFlags, 'accel=tcg';
3188 if ($machine_type) {
3189 push @$machineFlags, "type=${machine_type}";
3192 if ($conf->{startdate
}) {
3193 push @$rtcFlags, "base=$conf->{startdate}";
3194 } elsif ($useLocaltime) {
3195 push @$rtcFlags, 'base=localtime';
3198 my $cpu = $kvm ?
"kvm64" : "qemu64";
3199 if (my $cputype = $conf->{cpu
}) {
3200 my $cpuconf = PVE
::JSONSchema
::parse_property_string
($cpu_fmt, $cputype)
3201 or die "Cannot parse cpu description: $cputype\n";
3202 $cpu = $cpuconf->{cputype
};
3203 $kvm_off = 1 if $cpuconf->{hidden
};
3205 if (defined(my $flags = $cpuconf->{flags
})) {
3206 push @$cpuFlags, split(";", $flags);
3210 push @$cpuFlags , '+lahf_lm' if $cpu eq 'kvm64';
3212 push @$cpuFlags , '-x2apic'
3213 if $conf->{ostype
} && $conf->{ostype
} eq 'solaris';
3215 push @$cpuFlags, '+sep' if $cpu eq 'kvm64' || $cpu eq 'kvm32';
3217 push @$cpuFlags, '-rdtscp' if $cpu =~ m/^Opteron/;
3219 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
3221 push @$cpuFlags , '+kvm_pv_unhalt' if $kvm;
3222 push @$cpuFlags , '+kvm_pv_eoi' if $kvm;
3225 add_hyperv_enlightenments
($cpuFlags, $winversion, $machine_type, $kvmver, $conf->{bios
}, $gpu_passthrough) if $kvm;
3227 push @$cpuFlags, 'enforce' if $cpu ne 'host' && $kvm;
3229 push @$cpuFlags, 'kvm=off' if $kvm_off;
3231 my $cpu_vendor = $cpu_vendor_list->{$cpu} ||
3232 die "internal error"; # should not happen
3234 push @$cpuFlags, "vendor=${cpu_vendor}"
3235 if $cpu_vendor ne 'default';
3237 $cpu .= "," . join(',', @$cpuFlags) if scalar(@$cpuFlags);
3239 push @$cmd, '-cpu', $cpu;
3241 PVE
::QemuServer
::Memory
::config
($conf, $vmid, $sockets, $cores, $defaults, $hotplug_features, $cmd);
3243 push @$cmd, '-S' if $conf->{freeze
};
3245 # set keyboard layout
3246 my $kb = $conf->{keyboard
} || $defaults->{keyboard
};
3247 push @$cmd, '-k', $kb if $kb;
3250 #my $soundhw = $conf->{soundhw} || $defaults->{soundhw};
3251 #push @$cmd, '-soundhw', 'es1370';
3252 #push @$cmd, '-soundhw', $soundhw if $soundhw;
3254 if($conf->{agent
}) {
3255 my $qgasocket = qmp_socket
($vmid, 1);
3256 my $pciaddr = print_pci_addr
("qga0", $bridges);
3257 push @$devices, '-chardev', "socket,path=$qgasocket,server,nowait,id=qga0";
3258 push @$devices, '-device', "virtio-serial,id=qga0$pciaddr";
3259 push @$devices, '-device', 'virtserialport,chardev=qga0,name=org.qemu.guest_agent.0';
3267 for(my $i = 1; $i < $qxlnum; $i++){
3268 my $pciaddr = print_pci_addr
("vga$i", $bridges);
3269 push @$cmd, '-device', "qxl,id=vga$i,ram_size=67108864,vram_size=33554432$pciaddr";
3272 # assume other OS works like Linux
3273 push @$cmd, '-global', 'qxl-vga.ram_size=134217728';
3274 push @$cmd, '-global', 'qxl-vga.vram_size=67108864';
3278 my $pciaddr = print_pci_addr
("spice", $bridges);
3280 my $nodename = PVE
::INotify
::nodename
();
3281 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
3282 my @nodeaddrs = PVE
::Tools
::getaddrinfo_all
('localhost', family
=> $pfamily);
3283 die "failed to get an ip address of type $pfamily for 'localhost'\n" if !@nodeaddrs;
3284 my $localhost = PVE
::Network
::addr_to_ip
($nodeaddrs[0]->{addr
});
3285 $spice_port = PVE
::Tools
::next_spice_port
($pfamily, $localhost);
3287 push @$devices, '-spice', "tls-port=${spice_port},addr=$localhost,tls-ciphers=HIGH,seamless-migration=on";
3289 push @$devices, '-device', "virtio-serial,id=spice$pciaddr";
3290 push @$devices, '-chardev', "spicevmc,id=vdagent,name=vdagent";
3291 push @$devices, '-device', "virtserialport,chardev=vdagent,name=com.redhat.spice.0";
3294 # enable balloon by default, unless explicitly disabled
3295 if (!defined($conf->{balloon
}) || $conf->{balloon
}) {
3296 $pciaddr = print_pci_addr
("balloon0", $bridges);
3297 push @$devices, '-device', "virtio-balloon-pci,id=balloon0$pciaddr";
3300 if ($conf->{watchdog
}) {
3301 my $wdopts = parse_watchdog
($conf->{watchdog
});
3302 $pciaddr = print_pci_addr
("watchdog", $bridges);
3303 my $watchdog = $wdopts->{model
} || 'i6300esb';
3304 push @$devices, '-device', "$watchdog$pciaddr";
3305 push @$devices, '-watchdog-action', $wdopts->{action
} if $wdopts->{action
};
3309 my $scsicontroller = {};
3310 my $ahcicontroller = {};
3311 my $scsihw = defined($conf->{scsihw
}) ?
$conf->{scsihw
} : $defaults->{scsihw
};
3313 # Add iscsi initiator name if available
3314 if (my $initiator = get_initiator_name
()) {
3315 push @$devices, '-iscsi', "initiator-name=$initiator";
3318 foreach_drive
($conf, sub {
3319 my ($ds, $drive) = @_;
3321 if (PVE
::Storage
::parse_volume_id
($drive->{file
}, 1)) {
3322 push @$vollist, $drive->{file
};
3325 # ignore efidisk here, already added in bios/fw handling code above
3326 return if $drive->{interface
} eq 'efidisk';
3328 $use_virtio = 1 if $ds =~ m/^virtio/;
3330 if (drive_is_cdrom
($drive)) {
3331 if ($bootindex_hash->{d
}) {
3332 $drive->{bootindex
} = $bootindex_hash->{d
};
3333 $bootindex_hash->{d
} += 1;
3336 if ($bootindex_hash->{c
}) {
3337 $drive->{bootindex
} = $bootindex_hash->{c
} if $conf->{bootdisk
} && ($conf->{bootdisk
} eq $ds);
3338 $bootindex_hash->{c
} += 1;
3342 if($drive->{interface
} eq 'virtio'){
3343 push @$cmd, '-object', "iothread,id=iothread-$ds" if $drive->{iothread
};
3346 if ($drive->{interface
} eq 'scsi') {
3348 my ($maxdev, $controller, $controller_prefix) = scsihw_infos
($conf, $drive);
3350 $pciaddr = print_pci_addr
("$controller_prefix$controller", $bridges);
3351 my $scsihw_type = $scsihw =~ m/^virtio-scsi-single/ ?
"virtio-scsi-pci" : $scsihw;
3354 if($conf->{scsihw
} && $conf->{scsihw
} eq "virtio-scsi-single" && $drive->{iothread
}){
3355 $iothread .= ",iothread=iothread-$controller_prefix$controller";
3356 push @$cmd, '-object', "iothread,id=iothread-$controller_prefix$controller";
3357 } elsif ($drive->{iothread
}) {
3358 warn "iothread is only valid with virtio disk or virtio-scsi-single controller, ignoring\n";
3362 if($conf->{scsihw
} && $conf->{scsihw
} eq "virtio-scsi-single" && $drive->{queues
}){
3363 $queues = ",num_queues=$drive->{queues}";
3366 push @$devices, '-device', "$scsihw_type,id=$controller_prefix$controller$pciaddr$iothread$queues" if !$scsicontroller->{$controller};
3367 $scsicontroller->{$controller}=1;
3370 if ($drive->{interface
} eq 'sata') {
3371 my $controller = int($drive->{index} / $MAX_SATA_DISKS);
3372 $pciaddr = print_pci_addr
("ahci$controller", $bridges);
3373 push @$devices, '-device', "ahci,id=ahci$controller,multifunction=on$pciaddr" if !$ahcicontroller->{$controller};
3374 $ahcicontroller->{$controller}=1;
3377 my $drive_cmd = print_drive_full
($storecfg, $vmid, $drive);
3378 push @$devices, '-drive',$drive_cmd;
3379 push @$devices, '-device', print_drivedevice_full
($storecfg, $conf, $vmid, $drive, $bridges);
3382 for (my $i = 0; $i < $MAX_NETS; $i++) {
3383 next if !$conf->{"net$i"};
3384 my $d = parse_net
($conf->{"net$i"});
3387 $use_virtio = 1 if $d->{model
} eq 'virtio';
3389 if ($bootindex_hash->{n
}) {
3390 $d->{bootindex
} = $bootindex_hash->{n
};
3391 $bootindex_hash->{n
} += 1;
3394 my $netdevfull = print_netdev_full
($vmid,$conf,$d,"net$i");
3395 push @$devices, '-netdev', $netdevfull;
3397 my $netdevicefull = print_netdevice_full
($vmid, $conf, $d, "net$i", $bridges, $use_old_bios_files);
3398 push @$devices, '-device', $netdevicefull;
3403 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
3408 $bridges->{3} = 1 if $scsihw =~ m/^virtio-scsi-single/;
3410 while (my ($k, $v) = each %$bridges) {
3411 $pciaddr = print_pci_addr
("pci.$k");
3412 unshift @$devices, '-device', "pci-bridge,id=pci.$k,chassis_nr=$k$pciaddr" if $k > 0;
3417 if ($conf->{args
}) {
3418 my $aa = PVE
::Tools
::split_args
($conf->{args
});
3422 push @$cmd, @$devices;
3423 push @$cmd, '-rtc', join(',', @$rtcFlags)
3424 if scalar(@$rtcFlags);
3425 push @$cmd, '-machine', join(',', @$machineFlags)
3426 if scalar(@$machineFlags);
3427 push @$cmd, '-global', join(',', @$globalFlags)
3428 if scalar(@$globalFlags);
3430 return wantarray ?
($cmd, $vollist, $spice_port) : $cmd;
3435 return "${var_run_tmpdir}/$vmid.vnc";
3441 my $res = vm_mon_cmd
($vmid, 'query-spice');
3443 return $res->{'tls-port'} || $res->{'port'} || die "no spice port\n";
3447 my ($vmid, $qga) = @_;
3448 my $sockettype = $qga ?
'qga' : 'qmp';
3449 return "${var_run_tmpdir}/$vmid.$sockettype";
3454 return "${var_run_tmpdir}/$vmid.pid";
3457 sub vm_devices_list
{
3460 my $res = vm_mon_cmd
($vmid, 'query-pci');
3462 foreach my $pcibus (@$res) {
3463 foreach my $device (@{$pcibus->{devices
}}) {
3464 next if !$device->{'qdev_id'};
3465 if ($device->{'pci_bridge'}) {
3466 $devices->{$device->{'qdev_id'}} = 1;
3467 foreach my $bridge_device (@{$device->{'pci_bridge'}->{devices
}}) {
3468 next if !$bridge_device->{'qdev_id'};
3469 $devices->{$bridge_device->{'qdev_id'}} = 1;
3470 $devices->{$device->{'qdev_id'}}++;
3473 $devices->{$device->{'qdev_id'}} = 1;
3478 my $resblock = vm_mon_cmd
($vmid, 'query-block');
3479 foreach my $block (@$resblock) {
3480 if($block->{device
} =~ m/^drive-(\S+)/){
3485 my $resmice = vm_mon_cmd
($vmid, 'query-mice');
3486 foreach my $mice (@$resmice) {
3487 if ($mice->{name
} eq 'QEMU HID Tablet') {
3488 $devices->{tablet
} = 1;
3493 # for usb devices there is no query-usb
3494 # but we can iterate over the entries in
3495 # qom-list path=/machine/peripheral
3496 my $resperipheral = vm_mon_cmd
($vmid, 'qom-list', path
=> '/machine/peripheral');
3497 foreach my $per (@$resperipheral) {
3498 if ($per->{name
} =~ m/^usb\d+$/) {
3499 $devices->{$per->{name
}} = 1;
3507 my ($storecfg, $conf, $vmid, $deviceid, $device) = @_;
3509 my $q35 = machine_type_is_q35
($conf);
3511 my $devices_list = vm_devices_list
($vmid);
3512 return 1 if defined($devices_list->{$deviceid});
3514 qemu_add_pci_bridge
($storecfg, $conf, $vmid, $deviceid); # add PCI bridge if we need it for the device
3516 if ($deviceid eq 'tablet') {
3518 qemu_deviceadd
($vmid, print_tabletdevice_full
($conf));
3520 } elsif ($deviceid =~ m/^usb(\d+)$/) {
3522 die "usb hotplug currently not reliable\n";
3523 # since we can't reliably hot unplug all added usb devices
3524 # and usb passthrough disables live migration
3525 # we disable usb hotplugging for now
3526 qemu_deviceadd
($vmid, PVE
::QemuServer
::USB
::print_usbdevice_full
($conf, $deviceid, $device));
3528 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
3530 qemu_iothread_add
($vmid, $deviceid, $device);
3532 qemu_driveadd
($storecfg, $vmid, $device);
3533 my $devicefull = print_drivedevice_full
($storecfg, $conf, $vmid, $device);
3535 qemu_deviceadd
($vmid, $devicefull);
3536 eval { qemu_deviceaddverify
($vmid, $deviceid); };
3538 eval { qemu_drivedel
($vmid, $deviceid); };
3543 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3546 my $scsihw = defined($conf->{scsihw
}) ?
$conf->{scsihw
} : "lsi";
3547 my $pciaddr = print_pci_addr
($deviceid);
3548 my $scsihw_type = $scsihw eq 'virtio-scsi-single' ?
"virtio-scsi-pci" : $scsihw;
3550 my $devicefull = "$scsihw_type,id=$deviceid$pciaddr";
3552 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{iothread
}) {
3553 qemu_iothread_add
($vmid, $deviceid, $device);
3554 $devicefull .= ",iothread=iothread-$deviceid";
3557 if($deviceid =~ m/^virtioscsi(\d+)$/ && $device->{queues
}) {
3558 $devicefull .= ",num_queues=$device->{queues}";
3561 qemu_deviceadd
($vmid, $devicefull);
3562 qemu_deviceaddverify
($vmid, $deviceid);
3564 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
3566 qemu_findorcreatescsihw
($storecfg,$conf, $vmid, $device);
3567 qemu_driveadd
($storecfg, $vmid, $device);
3569 my $devicefull = print_drivedevice_full
($storecfg, $conf, $vmid, $device);
3570 eval { qemu_deviceadd
($vmid, $devicefull); };
3572 eval { qemu_drivedel
($vmid, $deviceid); };
3577 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
3579 return undef if !qemu_netdevadd
($vmid, $conf, $device, $deviceid);
3581 my $machine_type = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
3582 my $use_old_bios_files = undef;
3583 ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files
($machine_type);
3585 my $netdevicefull = print_netdevice_full
($vmid, $conf, $device, $deviceid, undef, $use_old_bios_files);
3586 qemu_deviceadd
($vmid, $netdevicefull);
3587 eval { qemu_deviceaddverify
($vmid, $deviceid); };
3589 eval { qemu_netdevdel
($vmid, $deviceid); };
3594 } elsif (!$q35 && $deviceid =~ m/^(pci\.)(\d+)$/) {
3597 my $pciaddr = print_pci_addr
($deviceid);
3598 my $devicefull = "pci-bridge,id=pci.$bridgeid,chassis_nr=$bridgeid$pciaddr";
3600 qemu_deviceadd
($vmid, $devicefull);
3601 qemu_deviceaddverify
($vmid, $deviceid);
3604 die "can't hotplug device '$deviceid'\n";
3610 # fixme: this should raise exceptions on error!
3611 sub vm_deviceunplug
{
3612 my ($vmid, $conf, $deviceid) = @_;
3614 my $devices_list = vm_devices_list
($vmid);
3615 return 1 if !defined($devices_list->{$deviceid});
3617 die "can't unplug bootdisk" if $conf->{bootdisk
} && $conf->{bootdisk
} eq $deviceid;
3619 if ($deviceid eq 'tablet') {
3621 qemu_devicedel
($vmid, $deviceid);
3623 } elsif ($deviceid =~ m/^usb\d+$/) {
3625 die "usb hotplug currently not reliable\n";
3626 # when unplugging usb devices this way,
3627 # there may be remaining usb controllers/hubs
3628 # so we disable it for now
3629 qemu_devicedel
($vmid, $deviceid);
3630 qemu_devicedelverify
($vmid, $deviceid);
3632 } elsif ($deviceid =~ m/^(virtio)(\d+)$/) {
3634 qemu_devicedel
($vmid, $deviceid);
3635 qemu_devicedelverify
($vmid, $deviceid);
3636 qemu_drivedel
($vmid, $deviceid);
3637 qemu_iothread_del
($conf, $vmid, $deviceid);
3639 } elsif ($deviceid =~ m/^(virtioscsi|scsihw)(\d+)$/) {
3641 qemu_devicedel
($vmid, $deviceid);
3642 qemu_devicedelverify
($vmid, $deviceid);
3643 qemu_iothread_del
($conf, $vmid, $deviceid);
3645 } elsif ($deviceid =~ m/^(scsi)(\d+)$/) {
3647 #qemu 2.3 segfault on drive_del with virtioscsi + iothread
3648 my $device = parse_drive
($deviceid, $conf->{$deviceid});
3649 die "virtioscsi with iothread is not hot-unplugglable currently" if $device->{iothread
};
3651 qemu_devicedel
($vmid, $deviceid);
3652 qemu_drivedel
($vmid, $deviceid);
3653 qemu_deletescsihw
($conf, $vmid, $deviceid);
3655 } elsif ($deviceid =~ m/^(net)(\d+)$/) {
3657 qemu_devicedel
($vmid, $deviceid);
3658 qemu_devicedelverify
($vmid, $deviceid);
3659 qemu_netdevdel
($vmid, $deviceid);
3662 die "can't unplug device '$deviceid'\n";
3668 sub qemu_deviceadd
{
3669 my ($vmid, $devicefull) = @_;
3671 $devicefull = "driver=".$devicefull;
3672 my %options = split(/[=,]/, $devicefull);
3674 vm_mon_cmd
($vmid, "device_add" , %options);
3677 sub qemu_devicedel
{
3678 my ($vmid, $deviceid) = @_;
3680 my $ret = vm_mon_cmd
($vmid, "device_del", id
=> $deviceid);
3683 sub qemu_iothread_add
{
3684 my($vmid, $deviceid, $device) = @_;
3686 if ($device->{iothread
}) {
3687 my $iothreads = vm_iothreads_list
($vmid);
3688 qemu_objectadd
($vmid, "iothread-$deviceid", "iothread") if !$iothreads->{"iothread-$deviceid"};
3692 sub qemu_iothread_del
{
3693 my($conf, $vmid, $deviceid) = @_;
3695 my $device = parse_drive
($deviceid, $conf->{$deviceid});
3696 if ($device->{iothread
}) {
3697 my $iothreads = vm_iothreads_list
($vmid);
3698 qemu_objectdel
($vmid, "iothread-$deviceid") if $iothreads->{"iothread-$deviceid"};
3702 sub qemu_objectadd
{
3703 my($vmid, $objectid, $qomtype) = @_;
3705 vm_mon_cmd
($vmid, "object-add", id
=> $objectid, "qom-type" => $qomtype);
3710 sub qemu_objectdel
{
3711 my($vmid, $objectid) = @_;
3713 vm_mon_cmd
($vmid, "object-del", id
=> $objectid);
3719 my ($storecfg, $vmid, $device) = @_;
3721 my $drive = print_drive_full
($storecfg, $vmid, $device);
3722 $drive =~ s/\\/\\\\/g;
3723 my $ret = vm_human_monitor_command
($vmid, "drive_add auto \"$drive\"");
3725 # If the command succeeds qemu prints: "OK
"
3726 return 1 if $ret =~ m/OK/s;
3728 die "adding drive failed
: $ret\n";
3732 my($vmid, $deviceid) = @_;
3734 my $ret = vm_human_monitor_command($vmid, "drive_del drive-
$deviceid");
3737 return 1 if $ret eq "";
3739 # NB: device not found errors mean the drive was auto-deleted and we ignore the error
3740 return 1 if $ret =~ m/Device \'.*?\' not found/s;
3742 die "deleting drive
$deviceid failed
: $ret\n";
3745 sub qemu_deviceaddverify {
3746 my ($vmid, $deviceid) = @_;
3748 for (my $i = 0; $i <= 5; $i++) {
3749 my $devices_list = vm_devices_list($vmid);
3750 return 1 if defined($devices_list->{$deviceid});
3754 die "error on hotplug device
'$deviceid'\n";
3758 sub qemu_devicedelverify {
3759 my ($vmid, $deviceid) = @_;
3761 # need to verify that the device is correctly removed as device_del
3762 # is async and empty return is not reliable
3764 for (my $i = 0; $i <= 5; $i++) {
3765 my $devices_list = vm_devices_list($vmid);
3766 return 1 if !defined($devices_list->{$deviceid});
3770 die "error on hot-unplugging device
'$deviceid'\n";
3773 sub qemu_findorcreatescsihw {
3774 my ($storecfg, $conf, $vmid, $device) = @_;
3776 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
3778 my $scsihwid="$controller_prefix$controller";
3779 my $devices_list = vm_devices_list($vmid);
3781 if(!defined($devices_list->{$scsihwid})) {
3782 vm_deviceplug($storecfg, $conf, $vmid, $scsihwid, $device);
3788 sub qemu_deletescsihw {
3789 my ($conf, $vmid, $opt) = @_;
3791 my $device = parse_drive($opt, $conf->{$opt});
3793 if ($conf->{scsihw} && ($conf->{scsihw} eq 'virtio-scsi-single')) {
3794 vm_deviceunplug($vmid, $conf, "virtioscsi
$device->{index}");
3798 my ($maxdev, $controller, $controller_prefix) = scsihw_infos($conf, $device);
3800 my $devices_list = vm_devices_list($vmid);
3801 foreach my $opt (keys %{$devices_list}) {
3802 if (PVE::QemuServer::is_valid_drivename($opt)) {
3803 my $drive = PVE::QemuServer::parse_drive($opt, $conf->{$opt});
3804 if($drive->{interface} eq 'scsi' && $drive->{index} < (($maxdev-1)*($controller+1))) {
3810 my $scsihwid="scsihw
$controller";
3812 vm_deviceunplug($vmid, $conf, $scsihwid);
3817 sub qemu_add_pci_bridge {
3818 my ($storecfg, $conf, $vmid, $device) = @_;
3824 print_pci_addr($device, $bridges);
3826 while (my ($k, $v) = each %$bridges) {
3829 return 1 if !defined($bridgeid) || $bridgeid < 1;
3831 my $bridge = "pci
.$bridgeid";
3832 my $devices_list = vm_devices_list($vmid);
3834 if (!defined($devices_list->{$bridge})) {
3835 vm_deviceplug($storecfg, $conf, $vmid, $bridge);
3841 sub qemu_set_link_status {
3842 my ($vmid, $device, $up) = @_;
3844 vm_mon_cmd($vmid, "set_link
", name => $device,
3845 up => $up ? JSON::true : JSON::false);
3848 sub qemu_netdevadd {
3849 my ($vmid, $conf, $device, $deviceid) = @_;
3851 my $netdev = print_netdev_full($vmid, $conf, $device, $deviceid, 1);
3852 my %options = split(/[=,]/, $netdev);
3854 vm_mon_cmd($vmid, "netdev_add
", %options);
3858 sub qemu_netdevdel {
3859 my ($vmid, $deviceid) = @_;
3861 vm_mon_cmd($vmid, "netdev_del
", id => $deviceid);
3864 sub qemu_usb_hotplug {
3865 my ($storecfg, $conf, $vmid, $deviceid, $device) = @_;
3869 # remove the old one first
3870 vm_deviceunplug($vmid, $conf, $deviceid);
3872 # check if xhci controller is necessary and available
3873 if ($device->{usb3}) {
3875 my $devicelist = vm_devices_list($vmid);
3877 if (!$devicelist->{xhci}) {
3878 my $pciaddr = print_pci_addr("xhci
");
3879 qemu_deviceadd($vmid, "nec-usb-xhci
,id
=xhci
$pciaddr");
3882 my $d = parse_usb_device($device->{host});
3883 $d->{usb3} = $device->{usb3};
3886 vm_deviceplug($storecfg, $conf, $vmid, $deviceid, $d);
3889 sub qemu_cpu_hotplug {
3890 my ($vmid, $conf, $vcpus) = @_;
3892 my $machine_type = PVE::QemuServer::get_current_qemu_machine($vmid);
3895 $sockets = $conf->{smp} if $conf->{smp}; # old style - no longer iused
3896 $sockets = $conf->{sockets} if $conf->{sockets};
3897 my $cores = $conf->{cores} || 1;
3898 my $maxcpus = $sockets * $cores;
3900 $vcpus = $maxcpus if !$vcpus;
3902 die "you can
't add more vcpus than maxcpus\n"
3903 if $vcpus > $maxcpus;
3905 my $currentvcpus = $conf->{vcpus} || $maxcpus;
3907 if ($vcpus < $currentvcpus) {
3909 if (qemu_machine_feature_enabled ($machine_type, undef, 2, 7)) {
3911 for (my $i = $currentvcpus; $i > $vcpus; $i--) {
3912 qemu_devicedel($vmid, "cpu$i");
3914 my $currentrunningvcpus = undef;
3916 $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3917 last if scalar(@{$currentrunningvcpus}) == $i-1;
3918 raise_param_exc({ vcpus => "error unplugging cpu$i" }) if $retry > 5;
3922 #update conf after each succesfull cpu unplug
3923 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
3924 PVE::QemuConfig->write_config($vmid, $conf);
3927 die "cpu hot-unplugging requires qemu version 2.7 or higher\n";
3933 my $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3934 die "vcpus in running vm does not match its configuration\n"
3935 if scalar(@{$currentrunningvcpus}) != $currentvcpus;
3937 if (qemu_machine_feature_enabled ($machine_type, undef, 2, 7)) {
3939 for (my $i = $currentvcpus+1; $i <= $vcpus; $i++) {
3940 my $cpustr = print_cpu_device($conf, $i);
3941 qemu_deviceadd($vmid, $cpustr);
3944 my $currentrunningvcpus = undef;
3946 $currentrunningvcpus = vm_mon_cmd($vmid, "query-cpus");
3947 last if scalar(@{$currentrunningvcpus}) == $i;
3948 raise_param_exc({ vcpus => "error hotplugging cpu$i" }) if $retry > 10;
3952 #update conf after each succesfull cpu hotplug
3953 $conf->{vcpus} = scalar(@{$currentrunningvcpus});
3954 PVE::QemuConfig->write_config($vmid, $conf);
3958 for (my $i = $currentvcpus; $i < $vcpus; $i++) {
3959 vm_mon_cmd($vmid, "cpu-add", id => int($i));
3964 sub qemu_block_set_io_throttle {
3965 my ($vmid, $deviceid,
3966 $bps, $bps_rd, $bps_wr, $iops, $iops_rd, $iops_wr,
3967 $bps_max, $bps_rd_max, $bps_wr_max, $iops_max, $iops_rd_max, $iops_wr_max,
3968 $bps_max_length, $bps_rd_max_length, $bps_wr_max_length,
3969 $iops_max_length, $iops_rd_max_length, $iops_wr_max_length) = @_;
3971 return if !check_running($vmid) ;
3973 vm_mon_cmd($vmid, "block_set_io_throttle", device => $deviceid,
3975 bps_rd => int($bps_rd),
3976 bps_wr => int($bps_wr),
3978 iops_rd => int($iops_rd),
3979 iops_wr => int($iops_wr),
3980 bps_max => int($bps_max),
3981 bps_rd_max => int($bps_rd_max),
3982 bps_wr_max => int($bps_wr_max),
3983 iops_max => int($iops_max),
3984 iops_rd_max => int($iops_rd_max),
3985 iops_wr_max => int($iops_wr_max),
3986 bps_max_length => int($bps_max_length),
3987 bps_rd_max_length => int($bps_rd_max_length),
3988 bps_wr_max_length => int($bps_wr_max_length),
3989 iops_max_length => int($iops_max_length),
3990 iops_rd_max_length => int($iops_rd_max_length),
3991 iops_wr_max_length => int($iops_wr_max_length),
3996 # old code, only used to shutdown old VM after update
3998 my ($fh, $timeout) = @_;
4000 my $sel = new IO::Select;
4007 while (scalar (@ready = $sel->can_read($timeout))) {
4009 if ($count = $fh->sysread($buf, 8192)) {
4010 if ($buf =~ /^(.*)\(qemu\) $/s) {
4017 if (!defined($count)) {
4024 die "monitor read timeout\n" if !scalar(@ready);
4029 # old code, only used to shutdown old VM after update
4030 sub vm_monitor_command {
4031 my ($vmid, $cmdstr, $nocheck) = @_;
4036 die "VM $vmid not running\n" if !check_running($vmid, $nocheck);
4038 my $sname = "${var_run_tmpdir}/$vmid.mon";
4040 my $sock = IO::Socket::UNIX->new( Peer => $sname ) ||
4041 die "unable to connect to VM $vmid socket - $!\n";
4045 # hack: migrate sometime blocks the monitor (when migrate_downtime
4047 if ($cmdstr =~ m/^(info\s+migrate|migrate\s)/) {
4048 $timeout = 60*60; # 1 hour
4052 my $data = __read_avail($sock, $timeout);
4054 if ($data !~ m/^QEMU\s+(\S+)\s+monitor\s/) {
4055 die "got unexpected qemu monitor banner\n";
4058 my $sel = new IO::Select;
4061 if (!scalar(my @ready = $sel->can_write($timeout))) {
4062 die "monitor write error - timeout";
4065 my $fullcmd = "$cmdstr\r";
4067 # syslog('info
', "VM $vmid monitor command: $cmdstr");
4070 if (!($b = $sock->syswrite($fullcmd)) || ($b != length($fullcmd))) {
4071 die "monitor write error - $!";
4074 return if ($cmdstr eq 'q
') || ($cmdstr eq 'quit
');
4078 if ($cmdstr =~ m/^(info\s+migrate|migrate\s)/) {
4079 $timeout = 60*60; # 1 hour
4080 } elsif ($cmdstr =~ m/^(eject|change)/) {
4081 $timeout = 60; # note: cdrom mount command is slow
4083 if ($res = __read_avail($sock, $timeout)) {
4085 my @lines = split("\r?\n", $res);
4087 shift @lines if $lines[0] !~ m/^unknown command/; # skip echo
4089 $res = join("\n", @lines);
4097 syslog("err", "VM $vmid monitor command failed - $err");
4104 sub qemu_block_resize {
4105 my ($vmid, $deviceid, $storecfg, $volid, $size) = @_;
4107 my $running = check_running($vmid);
4109 $size = 0 if !PVE::Storage::volume_resize($storecfg, $volid, $size, $running);
4111 return if !$running;
4113 vm_mon_cmd($vmid, "block_resize", device => $deviceid, size => int($size));
4117 sub qemu_volume_snapshot {
4118 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4120 my $running = check_running($vmid);
4122 if ($running && do_snapshots_with_qemu($storecfg, $volid)){
4123 vm_mon_cmd($vmid, "snapshot-drive", device => $deviceid, name => $snap);
4125 PVE::Storage::volume_snapshot($storecfg, $volid, $snap);
4129 sub qemu_volume_snapshot_delete {
4130 my ($vmid, $deviceid, $storecfg, $volid, $snap) = @_;
4132 my $running = check_running($vmid);
4134 if ($running && do_snapshots_with_qemu($storecfg, $volid)){
4135 vm_mon_cmd($vmid, "delete-drive-snapshot", device => $deviceid, name => $snap);
4137 PVE::Storage::volume_snapshot_delete($storecfg, $volid, $snap, $running);
4141 sub set_migration_caps {
4147 "auto-converge" => 1,
4149 "x-rdma-pin-all" => 0,
4154 my $supported_capabilities = vm_mon_cmd_nocheck($vmid, "query-migrate-capabilities");
4156 for my $supported_capability (@$supported_capabilities) {
4158 capability => $supported_capability->{capability},
4159 state => $enabled_cap->{$supported_capability->{capability}} ? JSON::true : JSON::false,
4163 vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => $cap_ref);
4166 my $fast_plug_option = {
4174 'vmstatestorage
' => 1,
4177 # hotplug changes in [PENDING]
4178 # $selection hash can be used to only apply specified options, for
4179 # example: { cores => 1 } (only apply changed 'cores
')
4180 # $errors ref is used to return error messages
4181 sub vmconfig_hotplug_pending {
4182 my ($vmid, $conf, $storecfg, $selection, $errors) = @_;
4184 my $defaults = load_defaults();
4186 # commit values which do not have any impact on running VM first
4187 # Note: those option cannot raise errors, we we do not care about
4188 # $selection and always apply them.
4190 my $add_error = sub {
4191 my ($opt, $msg) = @_;
4192 $errors->{$opt} = "hotplug problem - $msg";
4196 foreach my $opt (keys %{$conf->{pending}}) { # add/change
4197 if ($fast_plug_option->{$opt}) {
4198 $conf->{$opt} = $conf->{pending}->{$opt};
4199 delete $conf->{pending}->{$opt};
4205 PVE::QemuConfig->write_config($vmid, $conf);
4206 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4209 my $hotplug_features = parse_hotplug_features(defined($conf->{hotplug}) ? $conf->{hotplug} : '1');
4211 my $pending_delete_hash = split_flagged_list($conf->{pending}->{delete});
4212 while (my ($opt, $force) = each %$pending_delete_hash) {
4213 next if $selection && !$selection->{$opt};
4215 if ($opt eq 'hotplug
') {
4216 die "skip\n" if ($conf->{hotplug} =~ /memory/);
4217 } elsif ($opt eq 'tablet
') {
4218 die "skip\n" if !$hotplug_features->{usb};
4219 if ($defaults->{tablet}) {
4220 vm_deviceplug($storecfg, $conf, $vmid, $opt);
4222 vm_deviceunplug($vmid, $conf, $opt);
4224 } elsif ($opt =~ m/^usb\d+/) {
4226 # since we cannot reliably hot unplug usb devices
4227 # we are disabling it
4228 die "skip\n" if !$hotplug_features->{usb} || $conf->{$opt} =~ m/spice/i;
4229 vm_deviceunplug($vmid, $conf, $opt);
4230 } elsif ($opt eq 'vcpus
') {
4231 die "skip\n" if !$hotplug_features->{cpu};
4232 qemu_cpu_hotplug($vmid, $conf, undef);
4233 } elsif ($opt eq 'balloon
') {
4234 # enable balloon device is not hotpluggable
4235 die "skip\n" if !defined($conf->{balloon}) || $conf->{balloon};
4236 } elsif ($fast_plug_option->{$opt}) {
4238 } elsif ($opt =~ m/^net(\d+)$/) {
4239 die "skip\n" if !$hotplug_features->{network};
4240 vm_deviceunplug($vmid, $conf, $opt);
4241 } elsif (is_valid_drivename($opt)) {
4242 die "skip\n" if !$hotplug_features->{disk} || $opt =~ m/(ide|sata)(\d+)/;
4243 vm_deviceunplug($vmid, $conf, $opt);
4244 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4245 } elsif ($opt =~ m/^memory$/) {
4246 die "skip\n" if !$hotplug_features->{memory};
4247 PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt);
4248 } elsif ($opt eq 'cpuunits
') {
4249 cgroups_write("cpu", $vmid, "cpu.shares", $defaults->{cpuunits});
4250 } elsif ($opt eq 'cpulimit
') {
4251 cgroups_write("cpu", $vmid, "cpu.cfs_quota_us", -1);
4257 &$add_error($opt, $err) if $err ne "skip\n";
4259 # save new config if hotplug was successful
4260 delete $conf->{$opt};
4261 vmconfig_undelete_pending_option($conf, $opt);
4262 PVE::QemuConfig->write_config($vmid, $conf);
4263 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4267 foreach my $opt (keys %{$conf->{pending}}) {
4268 next if $selection && !$selection->{$opt};
4269 my $value = $conf->{pending}->{$opt};
4271 if ($opt eq 'hotplug
') {
4272 die "skip\n" if ($value =~ /memory/) || ($value !~ /memory/ && $conf->{hotplug} =~ /memory/);
4273 } elsif ($opt eq 'tablet
') {
4274 die "skip\n" if !$hotplug_features->{usb};
4276 vm_deviceplug($storecfg, $conf, $vmid, $opt);
4277 } elsif ($value == 0) {
4278 vm_deviceunplug($vmid, $conf, $opt);
4280 } elsif ($opt =~ m/^usb\d+$/) {
4282 # since we cannot reliably hot unplug usb devices
4283 # we are disabling it
4284 die "skip\n" if !$hotplug_features->{usb} || $value =~ m/spice/i;
4285 my $d = eval { PVE::JSONSchema::parse_property_string($usbdesc->{format}, $value) };
4286 die "skip\n" if !$d;
4287 qemu_usb_hotplug($storecfg, $conf, $vmid, $opt, $d);
4288 } elsif ($opt eq 'vcpus
') {
4289 die "skip\n" if !$hotplug_features->{cpu};
4290 qemu_cpu_hotplug($vmid, $conf, $value);
4291 } elsif ($opt eq 'balloon
') {
4292 # enable/disable balloning device is not hotpluggable
4293 my $old_balloon_enabled = !!(!defined($conf->{balloon}) || $conf->{balloon});
4294 my $new_balloon_enabled = !!(!defined($conf->{pending}->{balloon}) || $conf->{pending}->{balloon});
4295 die "skip\n" if $old_balloon_enabled != $new_balloon_enabled;
4297 # allow manual ballooning if shares is set to zero
4298 if ((defined($conf->{shares}) && ($conf->{shares} == 0))) {
4299 my $balloon = $conf->{pending}->{balloon} || $conf->{memory} || $defaults->{memory};
4300 vm_mon_cmd($vmid, "balloon", value => $balloon*1024*1024);
4302 } elsif ($opt =~ m/^net(\d+)$/) {
4303 # some changes can be done without hotplug
4304 vmconfig_update_net($storecfg, $conf, $hotplug_features->{network},
4305 $vmid, $opt, $value);
4306 } elsif (is_valid_drivename($opt)) {
4307 # some changes can be done without hotplug
4308 vmconfig_update_disk($storecfg, $conf, $hotplug_features->{disk},
4309 $vmid, $opt, $value, 1);
4310 } elsif ($opt =~ m/^memory$/) { #dimms
4311 die "skip\n" if !$hotplug_features->{memory};
4312 $value = PVE::QemuServer::Memory::qemu_memory_hotplug($vmid, $conf, $defaults, $opt, $value);
4313 } elsif ($opt eq 'cpuunits
') {
4314 cgroups_write("cpu", $vmid, "cpu.shares", $conf->{pending}->{$opt});
4315 } elsif ($opt eq 'cpulimit
') {
4316 my $cpulimit = $conf->{pending}->{$opt} == 0 ? -1 : int($conf->{pending}->{$opt} * 100000);
4317 cgroups_write("cpu", $vmid, "cpu.cfs_quota_us", $cpulimit);
4319 die "skip\n"; # skip non-hot-pluggable options
4323 &$add_error($opt, $err) if $err ne "skip\n";
4325 # save new config if hotplug was successful
4326 $conf->{$opt} = $value;
4327 delete $conf->{pending}->{$opt};
4328 PVE::QemuConfig->write_config($vmid, $conf);
4329 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4334 sub try_deallocate_drive {
4335 my ($storecfg, $vmid, $conf, $key, $drive, $rpcenv, $authuser, $force) = @_;
4337 if (($force || $key =~ /^unused/) && !drive_is_cdrom($drive, 1)) {
4338 my $volid = $drive->{file};
4339 if (vm_is_volid_owner($storecfg, $vmid, $volid)) {
4340 my $sid = PVE::Storage::parse_volume_id($volid);
4341 $rpcenv->check($authuser, "/storage/$sid", ['Datastore
.AllocateSpace
']);
4343 # check if the disk is really unused
4344 die "unable to delete '$volid' - volume is still in use (snapshot?)\n"
4345 if is_volume_in_use($storecfg, $conf, $key, $volid);
4346 PVE::Storage::vdisk_free($storecfg, $volid);
4349 # If vm is not owner of this disk remove from config
4357 sub vmconfig_delete_or_detach_drive {
4358 my ($vmid, $storecfg, $conf, $opt, $force) = @_;
4360 my $drive = parse_drive($opt, $conf->{$opt});
4362 my $rpcenv = PVE::RPCEnvironment::get();
4363 my $authuser = $rpcenv->get_user();
4366 $rpcenv->check_vm_perm($authuser, $vmid, undef, ['VM
.Config
.Disk
']);
4367 try_deallocate_drive($storecfg, $vmid, $conf, $opt, $drive, $rpcenv, $authuser, $force);
4369 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $drive);
4373 sub vmconfig_apply_pending {
4374 my ($vmid, $conf, $storecfg) = @_;
4378 my $pending_delete_hash = split_flagged_list($conf->{pending}->{delete});
4379 while (my ($opt, $force) = each %$pending_delete_hash) {
4380 die "internal error" if $opt =~ m/^unused/;
4381 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4382 if (!defined($conf->{$opt})) {
4383 vmconfig_undelete_pending_option($conf, $opt);
4384 PVE::QemuConfig->write_config($vmid, $conf);
4385 } elsif (is_valid_drivename($opt)) {
4386 vmconfig_delete_or_detach_drive($vmid, $storecfg, $conf, $opt, $force);
4387 vmconfig_undelete_pending_option($conf, $opt);
4388 delete $conf->{$opt};
4389 PVE::QemuConfig->write_config($vmid, $conf);
4391 vmconfig_undelete_pending_option($conf, $opt);
4392 delete $conf->{$opt};
4393 PVE::QemuConfig->write_config($vmid, $conf);
4397 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4399 foreach my $opt (keys %{$conf->{pending}}) { # add/change
4400 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4402 if (defined($conf->{$opt}) && ($conf->{$opt} eq $conf->{pending}->{$opt})) {
4403 # skip if nothing changed
4404 } elsif (is_valid_drivename($opt)) {
4405 vmconfig_register_unused_drive($storecfg, $vmid, $conf, parse_drive($opt, $conf->{$opt}))
4406 if defined($conf->{$opt});
4407 $conf->{$opt} = $conf->{pending}->{$opt};
4409 $conf->{$opt} = $conf->{pending}->{$opt};
4412 delete $conf->{pending}->{$opt};
4413 PVE::QemuConfig->write_config($vmid, $conf);
4417 my $safe_num_ne = sub {
4420 return 0 if !defined($a) && !defined($b);
4421 return 1 if !defined($a);
4422 return 1 if !defined($b);
4427 my $safe_string_ne = sub {
4430 return 0 if !defined($a) && !defined($b);
4431 return 1 if !defined($a);
4432 return 1 if !defined($b);
4437 sub vmconfig_update_net {
4438 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value) = @_;
4440 my $newnet = parse_net($value);
4442 if ($conf->{$opt}) {
4443 my $oldnet = parse_net($conf->{$opt});
4445 if (&$safe_string_ne($oldnet->{model}, $newnet->{model}) ||
4446 &$safe_string_ne($oldnet->{macaddr}, $newnet->{macaddr}) ||
4447 &$safe_num_ne($oldnet->{queues}, $newnet->{queues}) ||
4448 !($newnet->{bridge} && $oldnet->{bridge})) { # bridge/nat mode change
4450 # for non online change, we try to hot-unplug
4451 die "skip\n" if !$hotplug;
4452 vm_deviceunplug($vmid, $conf, $opt);
4455 die "internal error" if $opt !~ m/net(\d+)/;
4456 my $iface = "tap${vmid}i$1";
4458 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
4459 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
4460 &$safe_string_ne($oldnet->{trunks}, $newnet->{trunks}) ||
4461 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
4462 PVE::Network::tap_unplug($iface);
4463 PVE::Network::tap_plug($iface, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
4464 } elsif (&$safe_num_ne($oldnet->{rate}, $newnet->{rate})) {
4465 # Rate can be applied on its own but any change above needs to
4466 # include the rate in tap_plug since OVS resets everything.
4467 PVE::Network::tap_rate_limit($iface, $newnet->{rate});
4470 if (&$safe_string_ne($oldnet->{link_down}, $newnet->{link_down})) {
4471 qemu_set_link_status($vmid, $opt, !$newnet->{link_down});
4479 vm_deviceplug($storecfg, $conf, $vmid, $opt, $newnet);
4485 sub vmconfig_update_disk {
4486 my ($storecfg, $conf, $hotplug, $vmid, $opt, $value, $force) = @_;
4488 # fixme: do we need force?
4490 my $drive = parse_drive($opt, $value);
4492 if ($conf->{$opt}) {
4494 if (my $old_drive = parse_drive($opt, $conf->{$opt})) {
4496 my $media = $drive->{media} || 'disk
';
4497 my $oldmedia = $old_drive->{media} || 'disk
';
4498 die "unable to change media type\n" if $media ne $oldmedia;
4500 if (!drive_is_cdrom($old_drive)) {
4502 if ($drive->{file} ne $old_drive->{file}) {
4504 die "skip\n" if !$hotplug;
4506 # unplug and register as unused
4507 vm_deviceunplug($vmid, $conf, $opt);
4508 vmconfig_register_unused_drive($storecfg, $vmid, $conf, $old_drive)
4511 # update existing disk
4513 # skip non hotpluggable value
4514 if (&$safe_string_ne($drive->{discard}, $old_drive->{discard}) ||
4515 &$safe_string_ne($drive->{iothread}, $old_drive->{iothread}) ||
4516 &$safe_string_ne($drive->{queues}, $old_drive->{queues}) ||
4517 &$safe_string_ne($drive->{cache}, $old_drive->{cache})) {
4522 if (&$safe_num_ne($drive->{mbps}, $old_drive->{mbps}) ||
4523 &$safe_num_ne($drive->{mbps_rd}, $old_drive->{mbps_rd}) ||
4524 &$safe_num_ne($drive->{mbps_wr}, $old_drive->{mbps_wr}) ||
4525 &$safe_num_ne($drive->{iops}, $old_drive->{iops}) ||
4526 &$safe_num_ne($drive->{iops_rd}, $old_drive->{iops_rd}) ||
4527 &$safe_num_ne($drive->{iops_wr}, $old_drive->{iops_wr}) ||
4528 &$safe_num_ne($drive->{mbps_max}, $old_drive->{mbps_max}) ||
4529 &$safe_num_ne($drive->{mbps_rd_max}, $old_drive->{mbps_rd_max}) ||
4530 &$safe_num_ne($drive->{mbps_wr_max}, $old_drive->{mbps_wr_max}) ||
4531 &$safe_num_ne($drive->{iops_max}, $old_drive->{iops_max}) ||
4532 &$safe_num_ne($drive->{iops_rd_max}, $old_drive->{iops_rd_max}) ||
4533 &$safe_num_ne($drive->{iops_wr_max}, $old_drive->{iops_wr_max}) ||
4534 &$safe_num_ne($drive->{bps_max_length}, $old_drive->{bps_max_length}) ||
4535 &$safe_num_ne($drive->{bps_rd_max_length}, $old_drive->{bps_rd_max_length}) ||
4536 &$safe_num_ne($drive->{bps_wr_max_length}, $old_drive->{bps_wr_max_length}) ||
4537 &$safe_num_ne($drive->{iops_max_length}, $old_drive->{iops_max_length}) ||
4538 &$safe_num_ne($drive->{iops_rd_max_length}, $old_drive->{iops_rd_max_length}) ||
4539 &$safe_num_ne($drive->{iops_wr_max_length}, $old_drive->{iops_wr_max_length})) {
4541 qemu_block_set_io_throttle($vmid,"drive-$opt",
4542 ($drive->{mbps} || 0)*1024*1024,
4543 ($drive->{mbps_rd} || 0)*1024*1024,
4544 ($drive->{mbps_wr} || 0)*1024*1024,
4545 $drive->{iops} || 0,
4546 $drive->{iops_rd} || 0,
4547 $drive->{iops_wr} || 0,
4548 ($drive->{mbps_max} || 0)*1024*1024,
4549 ($drive->{mbps_rd_max} || 0)*1024*1024,
4550 ($drive->{mbps_wr_max} || 0)*1024*1024,
4551 $drive->{iops_max} || 0,
4552 $drive->{iops_rd_max} || 0,
4553 $drive->{iops_wr_max} || 0,
4554 $drive->{bps_max_length} || 1,
4555 $drive->{bps_rd_max_length} || 1,
4556 $drive->{bps_wr_max_length} || 1,
4557 $drive->{iops_max_length} || 1,
4558 $drive->{iops_rd_max_length} || 1,
4559 $drive->{iops_wr_max_length} || 1);
4568 if ($drive->{file} eq 'none
') {
4569 vm_mon_cmd($vmid, "eject",force => JSON::true,device => "drive-$opt");
4571 my $path = get_iso_path($storecfg, $vmid, $drive->{file});
4572 vm_mon_cmd($vmid, "eject", force => JSON::true,device => "drive-$opt"); # force eject if locked
4573 vm_mon_cmd($vmid, "change", device => "drive-$opt",target => "$path") if $path;
4581 die "skip\n" if !$hotplug || $opt =~ m/(ide|sata)(\d+)/;
4583 PVE::Storage::activate_volumes($storecfg, [$drive->{file}]) if $drive->{file} !~ m|^/dev/.+|;
4584 vm_deviceplug($storecfg, $conf, $vmid, $opt, $drive);
4588 my ($storecfg, $vmid, $statefile, $skiplock, $migratedfrom, $paused,
4589 $forcemachine, $spice_ticket, $migration_network, $migration_type, $targetstorage) = @_;
4591 PVE::QemuConfig->lock_config($vmid, sub {
4592 my $conf = PVE::QemuConfig->load_config($vmid, $migratedfrom);
4594 die "you can't start a vm
if it
's a template\n" if PVE::QemuConfig->is_template($conf);
4596 PVE::QemuConfig->check_lock($conf) if !$skiplock;
4598 die "VM $vmid already running\n" if check_running($vmid, undef, $migratedfrom);
4600 if (!$statefile && scalar(keys %{$conf->{pending}})) {
4601 vmconfig_apply_pending($vmid, $conf, $storecfg);
4602 $conf = PVE::QemuConfig->load_config($vmid); # update/reload
4605 my $defaults = load_defaults();
4607 # set environment variable useful inside network script
4608 $ENV{PVE_MIGRATED_FROM} = $migratedfrom if $migratedfrom;
4610 my $local_volumes = {};
4612 if ($targetstorage) {
4613 foreach_drive($conf, sub {
4614 my ($ds, $drive) = @_;
4616 return if drive_is_cdrom($drive);
4618 my $volid = $drive->{file};
4622 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
4624 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
4625 return if $scfg->{shared};
4626 $local_volumes->{$ds} = [$volid, $storeid, $volname];
4631 foreach my $opt (sort keys %$local_volumes) {
4633 my ($volid, $storeid, $volname) = @{$local_volumes->{$opt}};
4634 my $drive = parse_drive($opt, $conf->{$opt});
4636 #if remote storage is specified, use default format
4637 if ($targetstorage && $targetstorage ne "1") {
4638 $storeid = $targetstorage;
4639 my ($defFormat, $validFormats) = PVE::Storage::storage_default_format($storecfg, $storeid);
4640 $format = $defFormat;
4642 #else we use same format than original
4643 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
4644 $format = qemu_img_format($scfg, $volid);
4647 my $newvolid = PVE::Storage::vdisk_alloc($storecfg, $storeid, $vmid, $format, undef, ($drive->{size}/1024));
4648 my $newdrive = $drive;
4649 $newdrive->{format} = $format;
4650 $newdrive->{file} = $newvolid;
4651 my $drivestr = PVE::QemuServer::print_drive($vmid, $newdrive);
4652 $local_volumes->{$opt} = $drivestr;
4653 #pass drive to conf for command line
4654 $conf->{$opt} = $drivestr;
4658 my ($cmd, $vollist, $spice_port) = config_to_command($storecfg, $vmid, $conf, $defaults, $forcemachine);
4660 my $migrate_port = 0;
4663 if ($statefile eq 'tcp
') {
4664 my $localip = "localhost";
4665 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter
.cfg
');
4666 my $nodename = PVE::INotify::nodename();
4668 if (!defined($migration_type)) {
4669 if (defined($datacenterconf->{migration}->{type})) {
4670 $migration_type = $datacenterconf->{migration}->{type};
4672 $migration_type = 'secure
';
4676 if ($migration_type eq 'insecure
') {
4677 my $migrate_network_addr = PVE::Cluster::get_local_migration_ip($migration_network);
4678 if ($migrate_network_addr) {
4679 $localip = $migrate_network_addr;
4681 $localip = PVE::Cluster::remote_node_ip($nodename, 1);
4684 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
4687 my $pfamily = PVE::Tools::get_host_address_family($nodename);
4688 $migrate_port = PVE::Tools::next_migrate_port($pfamily);
4689 $migrate_uri = "tcp:${localip}:${migrate_port}";
4690 push @$cmd, '-incoming
', $migrate_uri;
4693 } elsif ($statefile eq 'unix
') {
4694 # should be default for secure migrations as a ssh TCP forward
4695 # tunnel is not deterministic reliable ready and fails regurarly
4696 # to set up in time, so use UNIX socket forwards
4697 my $socket_addr = "/run/qemu-server/$vmid.migrate";
4698 unlink $socket_addr;
4700 $migrate_uri = "unix:$socket_addr";
4702 push @$cmd, '-incoming
', $migrate_uri;
4706 push @$cmd, '-loadstate
', $statefile;
4713 for (my $i = 0; $i < $MAX_HOSTPCI_DEVICES; $i++) {
4714 my $d = parse_hostpci($conf->{"hostpci$i"});
4716 my $pcidevices = $d->{pciid};
4717 foreach my $pcidevice (@$pcidevices) {
4718 my $pciid = $pcidevice->{id}.".".$pcidevice->{function};
4720 my $info = pci_device_info("0000:$pciid");
4721 die "IOMMU not present\n" if !check_iommu_support();
4722 die "no pci device info for device '$pciid'\n" if !$info;
4723 die "can't unbind
/bind pci group to vfio
'$pciid'\n" if !pci_dev_group_bind_to_vfio($pciid);
4724 die "can
't reset pci device '$pciid'\n" if $info->{has_fl_reset} and !pci_dev_reset($info);
4728 PVE::Storage::activate_volumes($storecfg, $vollist);
4730 if (!check_running($vmid, 1) && -d "/sys/fs/cgroup/systemd/qemu.slice/$vmid.scope") {
4732 push @$cmd, '/bin/systemctl
', 'stop
', "$vmid.scope";
4733 eval { run_command($cmd); };
4736 my $cpuunits = defined($conf->{cpuunits}) ? $conf->{cpuunits}
4737 : $defaults->{cpuunits};
4739 my $start_timeout = $conf->{hugepages} ? 300 : 30;
4740 my %run_params = (timeout => $statefile ? undef : $start_timeout, umask => 0077);
4743 Slice => 'qemu
.slice
',
4745 CPUShares => $cpuunits
4748 if (my $cpulimit = $conf->{cpulimit}) {
4749 $properties{CPUQuota} = int($cpulimit * 100);
4751 $properties{timeout} = 10 if $statefile; # setting up the scope shoul be quick
4753 if ($conf->{hugepages}) {
4756 my $hugepages_topology = PVE::QemuServer::Memory::hugepages_topology($conf);
4757 my $hugepages_host_topology = PVE::QemuServer::Memory::hugepages_host_topology();
4759 PVE::QemuServer::Memory::hugepages_mount();
4760 PVE::QemuServer::Memory::hugepages_allocate($hugepages_topology, $hugepages_host_topology);
4763 PVE::Tools::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %properties);
4764 run_command($cmd, %run_params);
4768 PVE::QemuServer::Memory::hugepages_reset($hugepages_host_topology);
4772 PVE::QemuServer::Memory::hugepages_pre_deallocate($hugepages_topology);
4774 eval { PVE::QemuServer::Memory::hugepages_update_locked($code); };
4778 PVE::Tools::enter_systemd_scope($vmid, "Proxmox VE VM $vmid", %properties);
4779 run_command($cmd, %run_params);
4784 # deactivate volumes if start fails
4785 eval { PVE::Storage::deactivate_volumes($storecfg, $vollist); };
4786 die "start failed: $err";
4789 print "migration listens on $migrate_uri\n" if $migrate_uri;
4791 if ($statefile && $statefile ne 'tcp
' && $statefile ne 'unix
') {
4792 eval { vm_mon_cmd_nocheck($vmid, "cont"); };
4796 #start nbd server for storage migration
4797 if ($targetstorage) {
4798 my $nodename = PVE::INotify::nodename();
4799 my $migrate_network_addr = PVE::Cluster::get_local_migration_ip($migration_network);
4800 my $localip = $migrate_network_addr ? $migrate_network_addr : PVE::Cluster::remote_node_ip($nodename, 1);
4801 my $pfamily = PVE::Tools::get_host_address_family($nodename);
4802 $migrate_port = PVE::Tools::next_migrate_port($pfamily);
4804 vm_mon_cmd_nocheck($vmid, "nbd-server-start", addr => { type => 'inet
', data => { host => "${localip}", port => "${migrate_port}" } } );
4806 $localip = "[$localip]" if Net::IP::ip_is_ipv6($localip);
4808 foreach my $opt (sort keys %$local_volumes) {
4809 my $volid = $local_volumes->{$opt};
4810 vm_mon_cmd_nocheck($vmid, "nbd-server-add", device => "drive-$opt", writable => JSON::true );
4811 my $migrate_storage_uri = "nbd:${localip}:${migrate_port}:exportname=drive-$opt";
4812 print "storage migration listens on $migrate_storage_uri volume:$volid\n";
4816 if ($migratedfrom) {
4818 set_migration_caps($vmid);
4823 print "spice listens on port $spice_port\n";
4824 if ($spice_ticket) {
4825 vm_mon_cmd_nocheck($vmid, "set_password", protocol => 'spice
', password => $spice_ticket);
4826 vm_mon_cmd_nocheck($vmid, "expire_password", protocol => 'spice
', time => "+30");
4831 if (!$statefile && (!defined($conf->{balloon}) || $conf->{balloon})) {
4832 vm_mon_cmd_nocheck($vmid, "balloon", value => $conf->{balloon}*1024*1024)
4833 if $conf->{balloon};
4836 foreach my $opt (keys %$conf) {
4837 next if $opt !~ m/^net\d+$/;
4838 my $nicconf = parse_net($conf->{$opt});
4839 qemu_set_link_status($vmid, $opt, 0) if $nicconf->{link_down};
4843 vm_mon_cmd_nocheck($vmid, 'qom-set
',
4844 path => "machine/peripheral/balloon0",
4845 property => "guest-stats-polling-interval",
4846 value => 2) if (!defined($conf->{balloon}) || $conf->{balloon});
4852 my ($vmid, $execute, %params) = @_;
4854 my $cmd = { execute => $execute, arguments => \%params };
4855 vm_qmp_command($vmid, $cmd);
4858 sub vm_mon_cmd_nocheck {
4859 my ($vmid, $execute, %params) = @_;
4861 my $cmd = { execute => $execute, arguments => \%params };
4862 vm_qmp_command($vmid, $cmd, 1);
4865 sub vm_qmp_command {
4866 my ($vmid, $cmd, $nocheck) = @_;
4871 if ($cmd->{arguments} && $cmd->{arguments}->{timeout}) {
4872 $timeout = $cmd->{arguments}->{timeout};
4873 delete $cmd->{arguments}->{timeout};
4877 die "VM $vmid not running\n" if !check_running($vmid, $nocheck);
4878 my $sname = qmp_socket($vmid);
4879 if (-e $sname) { # test if VM is reasonambe new and supports qmp/qga
4880 my $qmpclient = PVE::QMPClient->new();
4882 $res = $qmpclient->cmd($vmid, $cmd, $timeout);
4883 } elsif (-e "${var_run_tmpdir}/$vmid.mon") {
4884 die "can't execute complex command on old monitor
- stop
/start your vm to fix the problem
\n"
4885 if scalar(%{$cmd->{arguments}});
4886 vm_monitor_command($vmid, $cmd->{execute}, $nocheck);
4888 die "unable to
open monitor
socket\n";
4892 syslog("err
", "VM
$vmid qmp command failed
- $err");
4899 sub vm_human_monitor_command {
4900 my ($vmid, $cmdline) = @_;
4905 execute => 'human-monitor-command',
4906 arguments => { 'command-line' => $cmdline},
4909 return vm_qmp_command($vmid, $cmd);
4912 sub vm_commandline {
4913 my ($storecfg, $vmid) = @_;
4915 my $conf = PVE::QemuConfig->load_config($vmid);
4917 my $defaults = load_defaults();
4919 my $cmd = config_to_command($storecfg, $vmid, $conf, $defaults);
4921 return PVE::Tools::cmd2string($cmd);
4925 my ($vmid, $skiplock) = @_;
4927 PVE::QemuConfig->lock_config($vmid, sub {
4929 my $conf = PVE::QemuConfig->load_config($vmid);
4931 PVE::QemuConfig->check_lock($conf) if !$skiplock;
4933 vm_mon_cmd($vmid, "system_reset
");
4937 sub get_vm_volumes {
4941 foreach_volid($conf, sub {
4942 my ($volid, $attr) = @_;
4944 return if $volid =~ m|^/|;
4946 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
4949 push @$vollist, $volid;
4955 sub vm_stop_cleanup {
4956 my ($storecfg, $vmid, $conf, $keepActive, $apply_pending_changes) = @_;
4961 my $vollist = get_vm_volumes($conf);
4962 PVE::Storage::deactivate_volumes($storecfg, $vollist);
4965 foreach my $ext (qw(mon qmp pid vnc qga)) {
4966 unlink "/var/run/qemu-server/${vmid}.$ext";
4969 vmconfig_apply_pending
($vmid, $conf, $storecfg) if $apply_pending_changes;
4971 warn $@ if $@; # avoid errors - just warn
4974 # Note: use $nockeck to skip tests if VM configuration file exists.
4975 # We need that when migration VMs to other nodes (files already moved)
4976 # Note: we set $keepActive in vzdump stop mode - volumes need to stay active
4978 my ($storecfg, $vmid, $skiplock, $nocheck, $timeout, $shutdown, $force, $keepActive, $migratedfrom) = @_;
4980 $force = 1 if !defined($force) && !$shutdown;
4983 my $pid = check_running
($vmid, $nocheck, $migratedfrom);
4984 kill 15, $pid if $pid;
4985 my $conf = PVE
::QemuConfig-
>load_config($vmid, $migratedfrom);
4986 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 0);
4990 PVE
::QemuConfig-
>lock_config($vmid, sub {
4992 my $pid = check_running
($vmid, $nocheck);
4997 $conf = PVE
::QemuConfig-
>load_config($vmid);
4998 PVE
::QemuConfig-
>check_lock($conf) if !$skiplock;
4999 if (!defined($timeout) && $shutdown && $conf->{startup
}) {
5000 my $opts = PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
});
5001 $timeout = $opts->{down
} if $opts->{down
};
5005 $timeout = 60 if !defined($timeout);
5009 if (defined($conf) && $conf->{agent
}) {
5010 vm_qmp_command
($vmid, { execute
=> "guest-shutdown" }, $nocheck);
5012 vm_qmp_command
($vmid, { execute
=> "system_powerdown" }, $nocheck);
5015 vm_qmp_command
($vmid, { execute
=> "quit" }, $nocheck);
5022 while (($count < $timeout) && check_running
($vmid, $nocheck)) {
5027 if ($count >= $timeout) {
5029 warn "VM still running - terminating now with SIGTERM\n";
5032 die "VM quit/powerdown failed - got timeout\n";
5035 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
5040 warn "VM quit/powerdown failed - terminating now with SIGTERM\n";
5043 die "VM quit/powerdown failed\n";
5051 while (($count < $timeout) && check_running
($vmid, $nocheck)) {
5056 if ($count >= $timeout) {
5057 warn "VM still running - terminating now with SIGKILL\n";
5062 vm_stop_cleanup
($storecfg, $vmid, $conf, $keepActive, 1) if $conf;
5067 my ($vmid, $skiplock) = @_;
5069 PVE
::QemuConfig-
>lock_config($vmid, sub {
5071 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5073 PVE
::QemuConfig-
>check_lock($conf)
5074 if !($skiplock || PVE
::QemuConfig-
>has_lock($conf, 'backup'));
5076 vm_mon_cmd
($vmid, "stop");
5081 my ($vmid, $skiplock, $nocheck) = @_;
5083 PVE
::QemuConfig-
>lock_config($vmid, sub {
5087 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5089 PVE
::QemuConfig-
>check_lock($conf)
5090 if !($skiplock || PVE
::QemuConfig-
>has_lock($conf, 'backup'));
5092 vm_mon_cmd
($vmid, "cont");
5095 vm_mon_cmd_nocheck
($vmid, "cont");
5101 my ($vmid, $skiplock, $key) = @_;
5103 PVE
::QemuConfig-
>lock_config($vmid, sub {
5105 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5107 # there is no qmp command, so we use the human monitor command
5108 vm_human_monitor_command
($vmid, "sendkey $key");
5113 my ($storecfg, $vmid, $skiplock) = @_;
5115 PVE
::QemuConfig-
>lock_config($vmid, sub {
5117 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5119 if (!check_running
($vmid)) {
5120 destroy_vm
($storecfg, $vmid, undef, $skiplock);
5122 die "VM $vmid is running - destroy failed\n";
5130 my ($filename, $buf) = @_;
5132 my $fh = IO
::File-
>new($filename, "w");
5133 return undef if !$fh;
5135 my $res = print $fh $buf;
5142 sub pci_device_info
{
5147 return undef if $name !~ m/^([a-f0-9]{4}):([a-f0-9]{2}):([a-f0-9]{2})\.([a-f0-9])$/;
5148 my ($domain, $bus, $slot, $func) = ($1, $2, $3, $4);
5150 my $irq = file_read_firstline
("$pcisysfs/devices/$name/irq");
5151 return undef if !defined($irq) || $irq !~ m/^\d+$/;
5153 my $vendor = file_read_firstline
("$pcisysfs/devices/$name/vendor");
5154 return undef if !defined($vendor) || $vendor !~ s/^0x//;
5156 my $product = file_read_firstline
("$pcisysfs/devices/$name/device");
5157 return undef if !defined($product) || $product !~ s/^0x//;
5162 product
=> $product,
5168 has_fl_reset
=> -f
"$pcisysfs/devices/$name/reset" || 0,
5177 my $name = $dev->{name
};
5179 my $fn = "$pcisysfs/devices/$name/reset";
5181 return file_write
($fn, "1");
5184 sub pci_dev_bind_to_vfio
{
5187 my $name = $dev->{name
};
5189 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
5191 if (!-d
$vfio_basedir) {
5192 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
5194 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
5196 my $testdir = "$vfio_basedir/$name";
5197 return 1 if -d
$testdir;
5199 my $data = "$dev->{vendor} $dev->{product}";
5200 return undef if !file_write
("$vfio_basedir/new_id", $data);
5202 my $fn = "$pcisysfs/devices/$name/driver/unbind";
5203 if (!file_write
($fn, $name)) {
5204 return undef if -f
$fn;
5207 $fn = "$vfio_basedir/bind";
5208 if (! -d
$testdir) {
5209 return undef if !file_write
($fn, $name);
5215 sub pci_dev_group_bind_to_vfio
{
5218 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
5220 if (!-d
$vfio_basedir) {
5221 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
5223 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
5225 # get IOMMU group devices
5226 opendir(my $D, "$pcisysfs/devices/0000:$pciid/iommu_group/devices/") || die "Cannot open iommu_group: $!\n";
5227 my @devs = grep /^0000:/, readdir($D);
5230 foreach my $pciid (@devs) {
5231 $pciid =~ m/^([:\.\da-f]+)$/ or die "PCI ID $pciid not valid!\n";
5233 # pci bridges, switches or root ports are not supported
5234 # they have a pci_bus subdirectory so skip them
5235 next if (-e
"$pcisysfs/devices/$pciid/pci_bus");
5237 my $info = pci_device_info
($1);
5238 pci_dev_bind_to_vfio
($info) || die "Cannot bind $pciid to vfio\n";
5244 # vzdump restore implementaion
5246 sub tar_archive_read_firstfile
{
5247 my $archive = shift;
5249 die "ERROR: file '$archive' does not exist\n" if ! -f
$archive;
5251 # try to detect archive type first
5252 my $pid = open (my $fh, '-|', 'tar', 'tf', $archive) ||
5253 die "unable to open file '$archive'\n";
5254 my $firstfile = <$fh>;
5258 die "ERROR: archive contaions no data\n" if !$firstfile;
5264 sub tar_restore_cleanup
{
5265 my ($storecfg, $statfile) = @_;
5267 print STDERR
"starting cleanup\n";
5269 if (my $fd = IO
::File-
>new($statfile, "r")) {
5270 while (defined(my $line = <$fd>)) {
5271 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
5274 if ($volid =~ m
|^/|) {
5275 unlink $volid || die 'unlink failed\n';
5277 PVE
::Storage
::vdisk_free
($storecfg, $volid);
5279 print STDERR
"temporary volume '$volid' sucessfuly removed\n";
5281 print STDERR
"unable to cleanup '$volid' - $@" if $@;
5283 print STDERR
"unable to parse line in statfile - $line";
5290 sub restore_archive
{
5291 my ($archive, $vmid, $user, $opts) = @_;
5293 my $format = $opts->{format
};
5296 if ($archive =~ m/\.tgz$/ || $archive =~ m/\.tar\.gz$/) {
5297 $format = 'tar' if !$format;
5299 } elsif ($archive =~ m/\.tar$/) {
5300 $format = 'tar' if !$format;
5301 } elsif ($archive =~ m/.tar.lzo$/) {
5302 $format = 'tar' if !$format;
5304 } elsif ($archive =~ m/\.vma$/) {
5305 $format = 'vma' if !$format;
5306 } elsif ($archive =~ m/\.vma\.gz$/) {
5307 $format = 'vma' if !$format;
5309 } elsif ($archive =~ m/\.vma\.lzo$/) {
5310 $format = 'vma' if !$format;
5313 $format = 'vma' if !$format; # default
5316 # try to detect archive format
5317 if ($format eq 'tar') {
5318 return restore_tar_archive
($archive, $vmid, $user, $opts);
5320 return restore_vma_archive
($archive, $vmid, $user, $opts, $comp);
5324 sub restore_update_config_line
{
5325 my ($outfd, $cookie, $vmid, $map, $line, $unique) = @_;
5327 return if $line =~ m/^\#qmdump\#/;
5328 return if $line =~ m/^\#vzdump\#/;
5329 return if $line =~ m/^lock:/;
5330 return if $line =~ m/^unused\d+:/;
5331 return if $line =~ m/^parent:/;
5332 return if $line =~ m/^template:/; # restored VM is never a template
5334 my $dc = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
5335 if (($line =~ m/^(vlan(\d+)):\s*(\S+)\s*$/)) {
5336 # try to convert old 1.X settings
5337 my ($id, $ind, $ethcfg) = ($1, $2, $3);
5338 foreach my $devconfig (PVE
::Tools
::split_list
($ethcfg)) {
5339 my ($model, $macaddr) = split(/\=/, $devconfig);
5340 $macaddr = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
}) if !$macaddr || $unique;
5343 bridge
=> "vmbr$ind",
5344 macaddr
=> $macaddr,
5346 my $netstr = print_net
($net);
5348 print $outfd "net$cookie->{netcount}: $netstr\n";
5349 $cookie->{netcount
}++;
5351 } elsif (($line =~ m/^(net\d+):\s*(\S+)\s*$/) && $unique) {
5352 my ($id, $netstr) = ($1, $2);
5353 my $net = parse_net
($netstr);
5354 $net->{macaddr
} = PVE
::Tools
::random_ether_addr
($dc->{mac_prefix
}) if $net->{macaddr
};
5355 $netstr = print_net
($net);
5356 print $outfd "$id: $netstr\n";
5357 } elsif ($line =~ m/^((ide|scsi|virtio|sata|efidisk)\d+):\s*(\S+)\s*$/) {
5360 my $di = parse_drive
($virtdev, $value);
5361 if (defined($di->{backup
}) && !$di->{backup
}) {
5362 print $outfd "#$line";
5363 } elsif ($map->{$virtdev}) {
5364 delete $di->{format
}; # format can change on restore
5365 $di->{file
} = $map->{$virtdev};
5366 $value = print_drive
($vmid, $di);
5367 print $outfd "$virtdev: $value\n";
5371 } elsif (($line =~ m/^(smbios1: )(.*)/) && $unique) {
5372 my ($uuid, $uuid_str);
5373 UUID
::generate
($uuid);
5374 UUID
::unparse
($uuid, $uuid_str);
5375 my $smbios1 = parse_smbios1
($2);
5376 $smbios1->{uuid
} = $uuid_str;
5377 print $outfd $1.print_smbios1
($smbios1)."\n";
5384 my ($cfg, $vmid) = @_;
5386 my $info = PVE
::Storage
::vdisk_list
($cfg, undef, $vmid);
5388 my $volid_hash = {};
5389 foreach my $storeid (keys %$info) {
5390 foreach my $item (@{$info->{$storeid}}) {
5391 next if !($item->{volid
} && $item->{size
});
5392 $item->{path
} = PVE
::Storage
::path
($cfg, $item->{volid
});
5393 $volid_hash->{$item->{volid
}} = $item;
5400 sub is_volume_in_use
{
5401 my ($storecfg, $conf, $skip_drive, $volid) = @_;
5403 my $path = PVE
::Storage
::path
($storecfg, $volid);
5405 my $scan_config = sub {
5406 my ($cref, $snapname) = @_;
5408 foreach my $key (keys %$cref) {
5409 my $value = $cref->{$key};
5410 if (is_valid_drivename
($key)) {
5411 next if $skip_drive && $key eq $skip_drive;
5412 my $drive = parse_drive
($key, $value);
5413 next if !$drive || !$drive->{file
} || drive_is_cdrom
($drive);
5414 return 1 if $volid eq $drive->{file
};
5415 if ($drive->{file
} =~ m!^/!) {
5416 return 1 if $drive->{file
} eq $path;
5418 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
}, 1);
5420 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid, 1);
5422 return 1 if $path eq PVE
::Storage
::path
($storecfg, $drive->{file
}, $snapname);
5430 return 1 if &$scan_config($conf);
5434 foreach my $snapname (keys %{$conf->{snapshots
}}) {
5435 return 1 if &$scan_config($conf->{snapshots
}->{$snapname}, $snapname);
5441 sub update_disksize
{
5442 my ($vmid, $conf, $volid_hash) = @_;
5446 # used and unused disks
5447 my $referenced = {};
5449 # Note: it is allowed to define multiple storages with same path (alias), so
5450 # we need to check both 'volid' and real 'path' (two different volid can point
5451 # to the same path).
5453 my $referencedpath = {};
5456 foreach my $opt (keys %$conf) {
5457 if (is_valid_drivename
($opt)) {
5458 my $drive = parse_drive
($opt, $conf->{$opt});
5459 my $volid = $drive->{file
};
5462 $referenced->{$volid} = 1;
5463 if ($volid_hash->{$volid} &&
5464 (my $path = $volid_hash->{$volid}->{path
})) {
5465 $referencedpath->{$path} = 1;
5468 next if drive_is_cdrom
($drive);
5469 next if !$volid_hash->{$volid};
5471 $drive->{size
} = $volid_hash->{$volid}->{size
};
5472 my $new = print_drive
($vmid, $drive);
5473 if ($new ne $conf->{$opt}) {
5475 $conf->{$opt} = $new;
5480 # remove 'unusedX' entry if volume is used
5481 foreach my $opt (keys %$conf) {
5482 next if $opt !~ m/^unused\d+$/;
5483 my $volid = $conf->{$opt};
5484 my $path = $volid_hash->{$volid}->{path
} if $volid_hash->{$volid};
5485 if ($referenced->{$volid} || ($path && $referencedpath->{$path})) {
5487 delete $conf->{$opt};
5490 $referenced->{$volid} = 1;
5491 $referencedpath->{$path} = 1 if $path;
5494 foreach my $volid (sort keys %$volid_hash) {
5495 next if $volid =~ m/vm-$vmid-state-/;
5496 next if $referenced->{$volid};
5497 my $path = $volid_hash->{$volid}->{path
};
5498 next if !$path; # just to be sure
5499 next if $referencedpath->{$path};
5501 PVE
::QemuConfig-
>add_unused_volume($conf, $volid);
5502 $referencedpath->{$path} = 1; # avoid to add more than once (aliases)
5509 my ($vmid, $nolock) = @_;
5511 my $cfg = PVE
::Storage
::config
();
5513 my $volid_hash = scan_volids
($cfg, $vmid);
5515 my $updatefn = sub {
5518 my $conf = PVE
::QemuConfig-
>load_config($vmid);
5520 PVE
::QemuConfig-
>check_lock($conf);
5523 foreach my $volid (keys %$volid_hash) {
5524 my $info = $volid_hash->{$volid};
5525 $vm_volids->{$volid} = $info if $info->{vmid
} && $info->{vmid
} == $vmid;
5528 my $changes = update_disksize
($vmid, $conf, $vm_volids);
5530 PVE
::QemuConfig-
>write_config($vmid, $conf) if $changes;
5533 if (defined($vmid)) {
5537 PVE
::QemuConfig-
>lock_config($vmid, $updatefn, $vmid);
5540 my $vmlist = config_list
();
5541 foreach my $vmid (keys %$vmlist) {
5545 PVE
::QemuConfig-
>lock_config($vmid, $updatefn, $vmid);
5551 sub restore_vma_archive
{
5552 my ($archive, $vmid, $user, $opts, $comp) = @_;
5554 my $input = $archive eq '-' ?
"<&STDIN" : undef;
5555 my $readfrom = $archive;
5560 my $qarchive = PVE
::Tools
::shellquote
($archive);
5561 if ($comp eq 'gzip') {
5562 $uncomp = "zcat $qarchive|";
5563 } elsif ($comp eq 'lzop') {
5564 $uncomp = "lzop -d -c $qarchive|";
5566 die "unknown compression method '$comp'\n";
5571 my $tmpdir = "/var/tmp/vzdumptmp$$";
5574 # disable interrupts (always do cleanups)
5578 local $SIG{HUP
} = sub { warn "got interrupt - ignored\n"; };
5580 my $mapfifo = "/var/tmp/vzdumptmp$$.fifo";
5581 POSIX
::mkfifo
($mapfifo, 0600);
5584 my $openfifo = sub {
5585 open($fifofh, '>', $mapfifo) || die $!;
5588 my $cmd = "${uncomp}vma extract -v -r $mapfifo $readfrom $tmpdir";
5595 my $rpcenv = PVE
::RPCEnvironment
::get
();
5597 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
5598 my $tmpfn = "$conffile.$$.tmp";
5600 # Note: $oldconf is undef if VM does not exists
5601 my $cfs_path = PVE
::QemuConfig-
>cfs_config_path($vmid);
5602 my $oldconf = PVE
::Cluster
::cfs_read_file
($cfs_path);
5604 my $print_devmap = sub {
5605 my $virtdev_hash = {};
5607 my $cfgfn = "$tmpdir/qemu-server.conf";
5609 # we can read the config - that is already extracted
5610 my $fh = IO
::File-
>new($cfgfn, "r") ||
5611 "unable to read qemu-server.conf - $!\n";
5613 my $fwcfgfn = "$tmpdir/qemu-server.fw";
5615 my $pve_firewall_dir = '/etc/pve/firewall';
5616 mkdir $pve_firewall_dir; # make sure the dir exists
5617 PVE
::Tools
::file_copy
($fwcfgfn, "${pve_firewall_dir}/$vmid.fw");
5620 while (defined(my $line = <$fh>)) {
5621 if ($line =~ m/^\#qmdump\#map:(\S+):(\S+):(\S*):(\S*):$/) {
5622 my ($virtdev, $devname, $storeid, $format) = ($1, $2, $3, $4);
5623 die "archive does not contain data for drive '$virtdev'\n"
5624 if !$devinfo->{$devname};
5625 if (defined($opts->{storage
})) {
5626 $storeid = $opts->{storage
} || 'local';
5627 } elsif (!$storeid) {
5630 $format = 'raw' if !$format;
5631 $devinfo->{$devname}->{devname
} = $devname;
5632 $devinfo->{$devname}->{virtdev
} = $virtdev;
5633 $devinfo->{$devname}->{format
} = $format;
5634 $devinfo->{$devname}->{storeid
} = $storeid;
5636 # check permission on storage
5637 my $pool = $opts->{pool
}; # todo: do we need that?
5638 if ($user ne 'root@pam') {
5639 $rpcenv->check($user, "/storage/$storeid", ['Datastore.AllocateSpace']);
5642 $virtdev_hash->{$virtdev} = $devinfo->{$devname};
5646 foreach my $devname (keys %$devinfo) {
5647 die "found no device mapping information for device '$devname'\n"
5648 if !$devinfo->{$devname}->{virtdev
};
5651 my $cfg = PVE
::Storage
::config
();
5653 # create empty/temp config
5655 PVE
::Tools
::file_set_contents
($conffile, "memory: 128\n");
5656 foreach_drive
($oldconf, sub {
5657 my ($ds, $drive) = @_;
5659 return if drive_is_cdrom
($drive);
5661 my $volid = $drive->{file
};
5663 return if !$volid || $volid =~ m
|^/|;
5665 my ($path, $owner) = PVE
::Storage
::path
($cfg, $volid);
5666 return if !$path || !$owner || ($owner != $vmid);
5668 # Note: only delete disk we want to restore
5669 # other volumes will become unused
5670 if ($virtdev_hash->{$ds}) {
5671 eval { PVE
::Storage
::vdisk_free
($cfg, $volid); };
5678 # delete vmstate files
5679 # since after the restore we have no snapshots anymore
5680 foreach my $snapname (keys %{$oldconf->{snapshots
}}) {
5681 my $snap = $oldconf->{snapshots
}->{$snapname};
5682 if ($snap->{vmstate
}) {
5683 eval { PVE
::Storage
::vdisk_free
($cfg, $snap->{vmstate
}); };
5692 foreach my $virtdev (sort keys %$virtdev_hash) {
5693 my $d = $virtdev_hash->{$virtdev};
5694 my $alloc_size = int(($d->{size
} + 1024 - 1)/1024);
5695 my $scfg = PVE
::Storage
::storage_config
($cfg, $d->{storeid
});
5697 # test if requested format is supported
5698 my ($defFormat, $validFormats) = PVE
::Storage
::storage_default_format
($cfg, $d->{storeid
});
5699 my $supported = grep { $_ eq $d->{format
} } @$validFormats;
5700 $d->{format
} = $defFormat if !$supported;
5702 my $volid = PVE
::Storage
::vdisk_alloc
($cfg, $d->{storeid
}, $vmid,
5703 $d->{format
}, undef, $alloc_size);
5704 print STDERR
"new volume ID is '$volid'\n";
5705 $d->{volid
} = $volid;
5706 my $path = PVE
::Storage
::path
($cfg, $volid);
5708 PVE
::Storage
::activate_volumes
($cfg,[$volid]);
5710 my $write_zeros = 1;
5711 if (PVE
::Storage
::volume_has_feature
($cfg, 'sparseinit', $volid)) {
5715 print $fifofh "format=$d->{format}:${write_zeros}:$d->{devname}=$path\n";
5717 print "map '$d->{devname}' to '$path' (write zeros = ${write_zeros})\n";
5718 $map->{$virtdev} = $volid;
5721 $fh->seek(0, 0) || die "seek failed - $!\n";
5723 my $outfd = new IO
::File
($tmpfn, "w") ||
5724 die "unable to write config for VM $vmid\n";
5726 my $cookie = { netcount
=> 0 };
5727 while (defined(my $line = <$fh>)) {
5728 restore_update_config_line
($outfd, $cookie, $vmid, $map, $line, $opts->{unique
});
5741 local $SIG{PIPE
} = sub { die "interrupted by signal\n"; };
5742 local $SIG{ALRM
} = sub { die "got timeout\n"; };
5744 $oldtimeout = alarm($timeout);
5751 if ($line =~ m/^DEV:\sdev_id=(\d+)\ssize:\s(\d+)\sdevname:\s(\S+)$/) {
5752 my ($dev_id, $size, $devname) = ($1, $2, $3);
5753 $devinfo->{$devname} = { size
=> $size, dev_id
=> $dev_id };
5754 } elsif ($line =~ m/^CTIME: /) {
5755 # we correctly received the vma config, so we can disable
5756 # the timeout now for disk allocation (set to 10 minutes, so
5757 # that we always timeout if something goes wrong)
5760 print $fifofh "done\n";
5761 my $tmp = $oldtimeout || 0;
5762 $oldtimeout = undef;
5768 print "restore vma archive: $cmd\n";
5769 run_command
($cmd, input
=> $input, outfunc
=> $parser, afterfork
=> $openfifo);
5773 alarm($oldtimeout) if $oldtimeout;
5776 foreach my $devname (keys %$devinfo) {
5777 my $volid = $devinfo->{$devname}->{volid
};
5778 push @$vollist, $volid if $volid;
5781 my $cfg = PVE
::Storage
::config
();
5782 PVE
::Storage
::deactivate_volumes
($cfg, $vollist);
5790 foreach my $devname (keys %$devinfo) {
5791 my $volid = $devinfo->{$devname}->{volid
};
5794 if ($volid =~ m
|^/|) {
5795 unlink $volid || die 'unlink failed\n';
5797 PVE
::Storage
::vdisk_free
($cfg, $volid);
5799 print STDERR
"temporary volume '$volid' sucessfuly removed\n";
5801 print STDERR
"unable to cleanup '$volid' - $@" if $@;
5808 rename($tmpfn, $conffile) ||
5809 die "unable to commit configuration file '$conffile'\n";
5811 PVE
::Cluster
::cfs_update
(); # make sure we read new file
5813 eval { rescan
($vmid, 1); };
5817 sub restore_tar_archive
{
5818 my ($archive, $vmid, $user, $opts) = @_;
5820 if ($archive ne '-') {
5821 my $firstfile = tar_archive_read_firstfile
($archive);
5822 die "ERROR: file '$archive' dos not lock like a QemuServer vzdump backup\n"
5823 if $firstfile ne 'qemu-server.conf';
5826 my $storecfg = PVE
::Storage
::config
();
5828 # destroy existing data - keep empty config
5829 my $vmcfgfn = PVE
::QemuConfig-
>config_file($vmid);
5830 destroy_vm
($storecfg, $vmid, 1) if -f
$vmcfgfn;
5832 my $tocmd = "/usr/lib/qemu-server/qmextract";
5834 $tocmd .= " --storage " . PVE
::Tools
::shellquote
($opts->{storage
}) if $opts->{storage
};
5835 $tocmd .= " --pool " . PVE
::Tools
::shellquote
($opts->{pool
}) if $opts->{pool
};
5836 $tocmd .= ' --prealloc' if $opts->{prealloc
};
5837 $tocmd .= ' --info' if $opts->{info
};
5839 # tar option "xf" does not autodetect compression when read from STDIN,
5840 # so we pipe to zcat
5841 my $cmd = "zcat -f|tar xf " . PVE
::Tools
::shellquote
($archive) . " " .
5842 PVE
::Tools
::shellquote
("--to-command=$tocmd");
5844 my $tmpdir = "/var/tmp/vzdumptmp$$";
5847 local $ENV{VZDUMP_TMPDIR
} = $tmpdir;
5848 local $ENV{VZDUMP_VMID
} = $vmid;
5849 local $ENV{VZDUMP_USER
} = $user;
5851 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
5852 my $tmpfn = "$conffile.$$.tmp";
5854 # disable interrupts (always do cleanups)
5858 local $SIG{HUP
} = sub { print STDERR
"got interrupt - ignored\n"; };
5866 local $SIG{PIPE
} = sub { die "interrupted by signal\n"; };
5868 if ($archive eq '-') {
5869 print "extracting archive from STDIN\n";
5870 run_command
($cmd, input
=> "<&STDIN");
5872 print "extracting archive '$archive'\n";
5876 return if $opts->{info
};
5880 my $statfile = "$tmpdir/qmrestore.stat";
5881 if (my $fd = IO
::File-
>new($statfile, "r")) {
5882 while (defined (my $line = <$fd>)) {
5883 if ($line =~ m/vzdump:([^\s:]*):(\S+)$/) {
5884 $map->{$1} = $2 if $1;
5886 print STDERR
"unable to parse line in statfile - $line\n";
5892 my $confsrc = "$tmpdir/qemu-server.conf";
5894 my $srcfd = new IO
::File
($confsrc, "r") ||
5895 die "unable to open file '$confsrc'\n";
5897 my $outfd = new IO
::File
($tmpfn, "w") ||
5898 die "unable to write config for VM $vmid\n";
5900 my $cookie = { netcount
=> 0 };
5901 while (defined (my $line = <$srcfd>)) {
5902 restore_update_config_line
($outfd, $cookie, $vmid, $map, $line, $opts->{unique
});
5914 tar_restore_cleanup
($storecfg, "$tmpdir/qmrestore.stat") if !$opts->{info
};
5921 rename $tmpfn, $conffile ||
5922 die "unable to commit configuration file '$conffile'\n";
5924 PVE
::Cluster
::cfs_update
(); # make sure we read new file
5926 eval { rescan
($vmid, 1); };
5930 sub foreach_storage_used_by_vm
{
5931 my ($conf, $func) = @_;
5935 foreach_drive
($conf, sub {
5936 my ($ds, $drive) = @_;
5937 return if drive_is_cdrom
($drive);
5939 my $volid = $drive->{file
};
5941 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
5942 $sidhash->{$sid} = $sid if $sid;
5945 foreach my $sid (sort keys %$sidhash) {
5950 sub do_snapshots_with_qemu
{
5951 my ($storecfg, $volid) = @_;
5953 my $storage_name = PVE
::Storage
::parse_volume_id
($volid);
5955 if ($qemu_snap_storage->{$storecfg->{ids
}->{$storage_name}->{type
}}
5956 && !$storecfg->{ids
}->{$storage_name}->{krbd
}){
5960 if ($volid =~ m/\.(qcow2|qed)$/){
5967 sub qga_check_running
{
5970 eval { vm_mon_cmd
($vmid, "guest-ping", timeout
=> 3); };
5972 warn "Qemu Guest Agent is not running - $@";
5978 sub template_create
{
5979 my ($vmid, $conf, $disk) = @_;
5981 my $storecfg = PVE
::Storage
::config
();
5983 foreach_drive
($conf, sub {
5984 my ($ds, $drive) = @_;
5986 return if drive_is_cdrom
($drive);
5987 return if $disk && $ds ne $disk;
5989 my $volid = $drive->{file
};
5990 return if !PVE
::Storage
::volume_has_feature
($storecfg, 'template', $volid);
5992 my $voliddst = PVE
::Storage
::vdisk_create_base
($storecfg, $volid);
5993 $drive->{file
} = $voliddst;
5994 $conf->{$ds} = print_drive
($vmid, $drive);
5995 PVE
::QemuConfig-
>write_config($vmid, $conf);
5999 sub qemu_img_convert
{
6000 my ($src_volid, $dst_volid, $size, $snapname, $is_zero_initialized) = @_;
6002 my $storecfg = PVE
::Storage
::config
();
6003 my ($src_storeid, $src_volname) = PVE
::Storage
::parse_volume_id
($src_volid, 1);
6004 my ($dst_storeid, $dst_volname) = PVE
::Storage
::parse_volume_id
($dst_volid, 1);
6006 if ($src_storeid && $dst_storeid) {
6008 PVE
::Storage
::activate_volumes
($storecfg, [$src_volid], $snapname);
6010 my $src_scfg = PVE
::Storage
::storage_config
($storecfg, $src_storeid);
6011 my $dst_scfg = PVE
::Storage
::storage_config
($storecfg, $dst_storeid);
6013 my $src_format = qemu_img_format
($src_scfg, $src_volname);
6014 my $dst_format = qemu_img_format
($dst_scfg, $dst_volname);
6016 my $src_path = PVE
::Storage
::path
($storecfg, $src_volid, $snapname);
6017 my $dst_path = PVE
::Storage
::path
($storecfg, $dst_volid);
6020 push @$cmd, '/usr/bin/qemu-img', 'convert', '-p', '-n';
6021 push @$cmd, '-s', $snapname if($snapname && $src_format eq "qcow2");
6022 push @$cmd, '-f', $src_format, '-O', $dst_format, $src_path;
6023 if ($is_zero_initialized) {
6024 push @$cmd, "zeroinit:$dst_path";
6026 push @$cmd, $dst_path;
6031 if($line =~ m/\((\S+)\/100\
%\)/){
6033 my $transferred = int($size * $percent / 100);
6034 my $remaining = $size - $transferred;
6036 print "transferred: $transferred bytes remaining: $remaining bytes total: $size bytes progression: $percent %\n";
6041 eval { run_command
($cmd, timeout
=> undef, outfunc
=> $parser); };
6043 die "copy failed: $err" if $err;
6047 sub qemu_img_format
{
6048 my ($scfg, $volname) = @_;
6050 if ($scfg->{path
} && $volname =~ m/\.(raw|cow|qcow|qcow2|qed|vmdk|cloop)$/) {
6057 sub qemu_drive_mirror
{
6058 my ($vmid, $drive, $dst_volid, $vmiddst, $is_zero_initialized, $jobs, $skipcomplete, $qga) = @_;
6060 $jobs = {} if !$jobs;
6064 $jobs->{"drive-$drive"} = {};
6066 if ($dst_volid =~ /^nbd:/) {
6067 $qemu_target = $dst_volid;
6070 my $storecfg = PVE
::Storage
::config
();
6071 my ($dst_storeid, $dst_volname) = PVE
::Storage
::parse_volume_id
($dst_volid);
6073 my $dst_scfg = PVE
::Storage
::storage_config
($storecfg, $dst_storeid);
6075 $format = qemu_img_format
($dst_scfg, $dst_volname);
6077 my $dst_path = PVE
::Storage
::path
($storecfg, $dst_volid);
6079 $qemu_target = $is_zero_initialized ?
"zeroinit:$dst_path" : $dst_path;
6082 my $opts = { timeout
=> 10, device
=> "drive-$drive", mode
=> "existing", sync
=> "full", target
=> $qemu_target };
6083 $opts->{format
} = $format if $format;
6085 print "drive mirror is starting for drive-$drive\n";
6087 eval { vm_mon_cmd
($vmid, "drive-mirror", %$opts); }; #if a job already run for this device,it's throw an error
6090 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs) };
6091 die "mirroring error: $err";
6094 qemu_drive_mirror_monitor
($vmid, $vmiddst, $jobs, $skipcomplete, $qga);
6097 sub qemu_drive_mirror_monitor
{
6098 my ($vmid, $vmiddst, $jobs, $skipcomplete, $qga) = @_;
6101 my $err_complete = 0;
6104 die "storage migration timed out\n" if $err_complete > 300;
6106 my $stats = vm_mon_cmd
($vmid, "query-block-jobs");
6108 my $running_mirror_jobs = {};
6109 foreach my $stat (@$stats) {
6110 next if $stat->{type
} ne 'mirror';
6111 $running_mirror_jobs->{$stat->{device
}} = $stat;
6114 my $readycounter = 0;
6116 foreach my $job (keys %$jobs) {
6118 if(defined($jobs->{$job}->{complete
}) && !defined($running_mirror_jobs->{$job})) {
6119 print "$job : finished\n";
6120 delete $jobs->{$job};
6124 die "$job: mirroring has been cancelled\n" if !defined($running_mirror_jobs->{$job});
6126 my $busy = $running_mirror_jobs->{$job}->{busy
};
6127 my $ready = $running_mirror_jobs->{$job}->{ready
};
6128 if (my $total = $running_mirror_jobs->{$job}->{len
}) {
6129 my $transferred = $running_mirror_jobs->{$job}->{offset
} || 0;
6130 my $remaining = $total - $transferred;
6131 my $percent = sprintf "%.2f", ($transferred * 100 / $total);
6133 print "$job: transferred: $transferred bytes remaining: $remaining bytes total: $total bytes progression: $percent % busy: $busy ready: $ready \n";
6136 $readycounter++ if $running_mirror_jobs->{$job}->{ready
};
6139 last if scalar(keys %$jobs) == 0;
6141 if ($readycounter == scalar(keys %$jobs)) {
6142 print "all mirroring jobs are ready \n";
6143 last if $skipcomplete; #do the complete later
6145 if ($vmiddst && $vmiddst != $vmid) {
6146 my $agent_running = $qga && qga_check_running
($vmid);
6147 if ($agent_running) {
6148 print "freeze filesystem\n";
6149 eval { PVE
::QemuServer
::vm_mon_cmd
($vmid, "guest-fsfreeze-freeze"); };
6151 print "suspend vm\n";
6152 eval { PVE
::QemuServer
::vm_suspend
($vmid, 1); };
6155 # if we clone a disk for a new target vm, we don't switch the disk
6156 PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs);
6158 if ($agent_running) {
6159 print "unfreeze filesystem\n";
6160 eval { PVE
::QemuServer
::vm_mon_cmd
($vmid, "guest-fsfreeze-thaw"); };
6162 print "resume vm\n";
6163 eval { PVE
::QemuServer
::vm_resume
($vmid, 1, 1); };
6169 foreach my $job (keys %$jobs) {
6170 # try to switch the disk if source and destination are on the same guest
6171 print "$job: Completing block job...\n";
6173 eval { vm_mon_cmd
($vmid, "block-job-complete", device
=> $job) };
6174 if ($@ =~ m/cannot be completed/) {
6175 print "$job: Block job cannot be completed, try again.\n";
6178 print "$job: Completed successfully.\n";
6179 $jobs->{$job}->{complete
} = 1;
6190 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $jobs) };
6191 die "mirroring error: $err";
6196 sub qemu_blockjobs_cancel
{
6197 my ($vmid, $jobs) = @_;
6199 foreach my $job (keys %$jobs) {
6200 print "$job: Cancelling block job\n";
6201 eval { vm_mon_cmd
($vmid, "block-job-cancel", device
=> $job); };
6202 $jobs->{$job}->{cancel
} = 1;
6206 my $stats = vm_mon_cmd
($vmid, "query-block-jobs");
6208 my $running_jobs = {};
6209 foreach my $stat (@$stats) {
6210 $running_jobs->{$stat->{device
}} = $stat;
6213 foreach my $job (keys %$jobs) {
6215 if (defined($jobs->{$job}->{cancel
}) && !defined($running_jobs->{$job})) {
6216 print "$job: Done.\n";
6217 delete $jobs->{$job};
6221 last if scalar(keys %$jobs) == 0;
6228 my ($storecfg, $vmid, $running, $drivename, $drive, $snapname,
6229 $newvmid, $storage, $format, $full, $newvollist, $jobs, $skipcomplete, $qga) = @_;
6234 print "create linked clone of drive $drivename ($drive->{file})\n";
6235 $newvolid = PVE
::Storage
::vdisk_clone
($storecfg, $drive->{file
}, $newvmid, $snapname);
6236 push @$newvollist, $newvolid;
6239 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
6240 $storeid = $storage if $storage;
6242 my $dst_format = resolve_dst_disk_format
($storecfg, $storeid, $volname, $format);
6243 my ($size) = PVE
::Storage
::volume_size_info
($storecfg, $drive->{file
}, 3);
6245 print "create full clone of drive $drivename ($drive->{file})\n";
6246 $newvolid = PVE
::Storage
::vdisk_alloc
($storecfg, $storeid, $newvmid, $dst_format, undef, ($size/1024));
6247 push @$newvollist, $newvolid;
6249 PVE
::Storage
::activate_volumes
($storecfg, [$newvolid]);
6251 my $sparseinit = PVE
::Storage
::volume_has_feature
($storecfg, 'sparseinit', $newvolid);
6252 if (!$running || $snapname) {
6253 qemu_img_convert
($drive->{file
}, $newvolid, $size, $snapname, $sparseinit);
6256 my $kvmver = get_running_qemu_version
($vmid);
6257 if (!qemu_machine_feature_enabled
(undef, $kvmver, 2, 7)) {
6258 die "drive-mirror with iothread requires qemu version 2.7 or higher\n"
6259 if $drive->{iothread
};
6262 qemu_drive_mirror
($vmid, $drivename, $newvolid, $newvmid, $sparseinit, $jobs, $skipcomplete, $qga);
6266 my ($size) = PVE
::Storage
::volume_size_info
($storecfg, $newvolid, 3);
6269 $disk->{format
} = undef;
6270 $disk->{file
} = $newvolid;
6271 $disk->{size
} = $size;
6276 # this only works if VM is running
6277 sub get_current_qemu_machine
{
6280 my $cmd = { execute
=> 'query-machines', arguments
=> {} };
6281 my $res = vm_qmp_command
($vmid, $cmd);
6283 my ($current, $default);
6284 foreach my $e (@$res) {
6285 $default = $e->{name
} if $e->{'is-default'};
6286 $current = $e->{name
} if $e->{'is-current'};
6289 # fallback to the default machine if current is not supported by qemu
6290 return $current || $default || 'pc';
6293 sub get_running_qemu_version
{
6295 my $cmd = { execute
=> 'query-version', arguments
=> {} };
6296 my $res = vm_qmp_command
($vmid, $cmd);
6297 return "$res->{qemu}->{major}.$res->{qemu}->{minor}";
6300 sub qemu_machine_feature_enabled
{
6301 my ($machine, $kvmver, $version_major, $version_minor) = @_;
6306 if ($machine && $machine =~ m/^(pc(-i440fx|-q35)?-(\d+)\.(\d+))/) {
6308 $current_major = $3;
6309 $current_minor = $4;
6311 } elsif ($kvmver =~ m/^(\d+)\.(\d+)/) {
6313 $current_major = $1;
6314 $current_minor = $2;
6317 return 1 if $current_major >= $version_major && $current_minor >= $version_minor;
6322 sub qemu_machine_pxe
{
6323 my ($vmid, $conf, $machine) = @_;
6325 $machine = PVE
::QemuServer
::get_current_qemu_machine
($vmid) if !$machine;
6327 foreach my $opt (keys %$conf) {
6328 next if $opt !~ m/^net(\d+)$/;
6329 my $net = PVE
::QemuServer
::parse_net
($conf->{$opt});
6331 my $romfile = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'qom-get', path
=> $opt, property
=> 'romfile');
6332 return $machine.".pxe" if $romfile =~ m/pxe/;
6339 sub qemu_use_old_bios_files
{
6340 my ($machine_type) = @_;
6342 return if !$machine_type;
6344 my $use_old_bios_files = undef;
6346 if ($machine_type =~ m/^(\S+)\.pxe$/) {
6348 $use_old_bios_files = 1;
6350 my $kvmver = kvm_user_version
();
6351 # Note: kvm version < 2.4 use non-efi pxe files, and have problems when we
6352 # load new efi bios files on migration. So this hack is required to allow
6353 # live migration from qemu-2.2 to qemu-2.4, which is sometimes used when
6354 # updrading from proxmox-ve-3.X to proxmox-ve 4.0
6355 $use_old_bios_files = !qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 4);
6358 return ($use_old_bios_files, $machine_type);
6361 sub create_efidisk
{
6362 my ($storecfg, $storeid, $vmid, $fmt) = @_;
6364 die "EFI vars default image not found\n" if ! -f
$OVMF_VARS;
6366 my $vars_size = PVE
::Tools
::convert_size
(-s
$OVMF_VARS, 'b' => 'kb');
6367 my $volid = PVE
::Storage
::vdisk_alloc
($storecfg, $storeid, $vmid, $fmt, undef, $vars_size);
6368 PVE
::Storage
::activate_volumes
($storecfg, [$volid]);
6370 my $path = PVE
::Storage
::path
($storecfg, $volid);
6372 run_command
(['/usr/bin/qemu-img', 'convert', '-n', '-f', 'raw', '-O', $fmt, $OVMF_VARS, $path]);
6374 die "Copying EFI vars image failed: $@" if $@;
6376 return ($volid, $vars_size);
6383 dir_glob_foreach
("$pcisysfs/devices", '[a-f0-9]{4}:([a-f0-9]{2}:[a-f0-9]{2})\.([0-9])', sub {
6384 my (undef, $id, $function) = @_;
6385 my $res = { id
=> $id, function
=> $function};
6386 push @{$devices->{$id}}, $res;
6389 # Entries should be sorted by functions.
6390 foreach my $id (keys %$devices) {
6391 my $dev = $devices->{$id};
6392 $devices->{$id} = [ sort { $a->{function
} <=> $b->{function
} } @$dev ];
6398 sub vm_iothreads_list
{
6401 my $res = vm_mon_cmd
($vmid, 'query-iothreads');
6404 foreach my $iothread (@$res) {
6405 $iothreads->{ $iothread->{id
} } = $iothread->{"thread-id"};
6412 my ($conf, $drive) = @_;
6416 if (!$conf->{scsihw
} || ($conf->{scsihw
} =~ m/^lsi/)) {
6418 } elsif ($conf->{scsihw
} && ($conf->{scsihw
} eq 'virtio-scsi-single')) {
6424 my $controller = int($drive->{index} / $maxdev);
6425 my $controller_prefix = ($conf->{scsihw
} && $conf->{scsihw
} eq 'virtio-scsi-single') ?
"virtioscsi" : "scsihw";
6427 return ($maxdev, $controller, $controller_prefix);
6430 sub add_hyperv_enlightenments
{
6431 my ($cpuFlags, $winversion, $machine_type, $kvmver, $bios, $gpu_passthrough) = @_;
6433 return if $winversion < 6;
6434 return if $bios && $bios eq 'ovmf' && $winversion < 8;
6436 push @$cpuFlags , 'hv_vendor_id=proxmox' if $gpu_passthrough;
6438 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 3)) {
6439 push @$cpuFlags , 'hv_spinlocks=0x1fff';
6440 push @$cpuFlags , 'hv_vapic';
6441 push @$cpuFlags , 'hv_time';
6443 push @$cpuFlags , 'hv_spinlocks=0xffff';
6446 if (qemu_machine_feature_enabled
($machine_type, $kvmver, 2, 6)) {
6447 push @$cpuFlags , 'hv_reset';
6448 push @$cpuFlags , 'hv_vpindex';
6449 push @$cpuFlags , 'hv_runtime';
6452 if ($winversion >= 7) {
6453 push @$cpuFlags , 'hv_relaxed';
6457 sub windows_version
{
6460 return 0 if !$ostype;
6464 if($ostype eq 'wxp' || $ostype eq 'w2k3' || $ostype eq 'w2k') {
6466 } elsif($ostype eq 'w2k8' || $ostype eq 'wvista') {
6468 } elsif ($ostype =~ m/^win(\d+)$/) {
6475 sub resolve_dst_disk_format
{
6476 my ($storecfg, $storeid, $src_volname, $format) = @_;
6477 my ($defFormat, $validFormats) = PVE
::Storage
::storage_default_format
($storecfg, $storeid);
6480 # if no target format is specified, use the source disk format as hint
6482 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
6483 $format = qemu_img_format
($scfg, $src_volname);
6489 # test if requested format is supported - else use default
6490 my $supported = grep { $_ eq $format } @$validFormats;
6491 $format = $defFormat if !$supported;
6495 sub resolve_first_disk
{
6497 my @disks = PVE
::QemuServer
::valid_drive_names
();
6499 foreach my $ds (reverse @disks) {
6500 next if !$conf->{$ds};
6501 my $disk = PVE
::QemuServer
::parse_drive
($ds, $conf->{$ds});
6502 next if PVE
::QemuServer
::drive_is_cdrom
($disk);
6508 sub generate_smbios1_uuid
{
6509 my ($uuid, $uuid_str);
6510 UUID
::generate
($uuid);
6511 UUID
::unparse
($uuid, $uuid_str);
6512 return "uuid=$uuid_str";
6515 # bash completion helper
6517 sub complete_backup_archives
{
6518 my ($cmdname, $pname, $cvalue) = @_;
6520 my $cfg = PVE
::Storage
::config
();
6524 if ($cvalue =~ m/^([^:]+):/) {
6528 my $data = PVE
::Storage
::template_list
($cfg, $storeid, 'backup');
6531 foreach my $id (keys %$data) {
6532 foreach my $item (@{$data->{$id}}) {
6533 next if $item->{format
} !~ m/^vma\.(gz|lzo)$/;
6534 push @$res, $item->{volid
} if defined($item->{volid
});
6541 my $complete_vmid_full = sub {
6544 my $idlist = vmstatus
();
6548 foreach my $id (keys %$idlist) {
6549 my $d = $idlist->{$id};
6550 if (defined($running)) {
6551 next if $d->{template
};
6552 next if $running && $d->{status
} ne 'running';
6553 next if !$running && $d->{status
} eq 'running';
6562 return &$complete_vmid_full();
6565 sub complete_vmid_stopped
{
6566 return &$complete_vmid_full(0);
6569 sub complete_vmid_running
{
6570 return &$complete_vmid_full(1);
6573 sub complete_storage
{
6575 my $cfg = PVE
::Storage
::config
();
6576 my $ids = $cfg->{ids
};
6579 foreach my $sid (keys %$ids) {
6580 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, undef, 1);
6581 next if !$ids->{$sid}->{content
}->{images
};
6591 vm_mon_cmd
($vmid, 'nbd-server-stop');