1 package PVE
::QemuMigrate
;
8 use POSIX
qw( WNOHANG );
9 use Time
::HiRes
qw( usleep );
11 use PVE
::Format
qw(render_bytes);
13 use PVE
::GuestHelpers
qw(safe_boolean_ne safe_string_ne);
15 use PVE
::RPCEnvironment
;
17 use PVE
::ReplicationConfig
;
18 use PVE
::ReplicationState
;
23 use PVE
::QemuServer
::CPUConfig
;
24 use PVE
::QemuServer
::Drive
;
25 use PVE
::QemuServer
::Helpers
qw(min_version);
26 use PVE
::QemuServer
::Machine
;
27 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
30 use PVE
::AbstractMigrate
;
31 use base
qw(PVE::AbstractMigrate);
33 sub fork_command_pipe
{
34 my ($self, $cmd) = @_;
36 my $reader = IO
::File-
>new();
37 my $writer = IO
::File-
>new();
43 eval { $cpid = open2
($reader, $writer, @$cmd); };
48 if ($orig_pid != $$) {
49 $self->log('err', "can't fork command pipe\n");
56 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
59 sub finish_command_pipe
{
60 my ($self, $cmdpipe, $timeout) = @_;
62 my $cpid = $cmdpipe->{pid
};
63 return if !defined($cpid);
65 my $writer = $cmdpipe->{writer
};
66 my $reader = $cmdpipe->{reader
};
71 my $collect_child_process = sub {
72 my $res = waitpid($cpid, WNOHANG
);
73 if (defined($res) && ($res == $cpid)) {
74 delete $cmdpipe->{cpid
};
82 for (my $i = 0; $i < $timeout; $i++) {
83 return if &$collect_child_process();
88 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
92 for (my $i = 0; $i < 10; $i++) {
93 return if &$collect_child_process();
97 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
101 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
102 if !&$collect_child_process();
106 my ($self, $tunnel, $timeout) = @_;
108 $timeout = 60 if !defined($timeout);
110 my $reader = $tunnel->{reader
};
114 PVE
::Tools
::run_with_timeout
($timeout, sub { $output = <$reader>; });
116 die "reading from tunnel failed: $@\n" if $@;
124 my ($self, $tunnel, $timeout, $command) = @_;
126 $timeout = 60 if !defined($timeout);
128 my $writer = $tunnel->{writer
};
131 PVE
::Tools
::run_with_timeout
($timeout, sub {
132 print $writer "$command\n";
136 die "writing to tunnel failed: $@\n" if $@;
138 if ($tunnel->{version
} && $tunnel->{version
} >= 1) {
139 my $res = eval { $self->read_tunnel($tunnel, 10); };
140 die "no reply to command '$command': $@\n" if $@;
145 die "tunnel replied '$res' to command '$command'\n";
151 my ($self, $ssh_forward_info) = @_;
153 my @localtunnelinfo = ();
154 foreach my $addr (@$ssh_forward_info) {
155 push @localtunnelinfo, '-L', $addr;
158 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
160 my $tunnel = $self->fork_command_pipe($cmd);
163 my $helo = $self->read_tunnel($tunnel, 60);
164 die "no reply\n" if !$helo;
165 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
166 die "got strange reply from mtunnel ('$helo')\n"
167 if $helo !~ m/^tunnel online$/;
172 my $ver = $self->read_tunnel($tunnel, 10);
173 if ($ver =~ /^ver (\d+)$/) {
174 $tunnel->{version
} = $1;
175 $self->log('info', "ssh tunnel $ver\n");
177 $err = "received invalid tunnel version string '$ver'\n" if !$err;
182 $self->finish_command_pipe($tunnel);
183 die "can't open migration tunnel - $err";
189 my ($self, $tunnel) = @_;
191 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
194 $self->finish_command_pipe($tunnel, 30);
196 if (my $unix_sockets = $tunnel->{unix_sockets
}) {
197 # ssh does not clean up on local host
198 my $cmd = ['rm', '-f', @$unix_sockets];
199 PVE
::Tools
::run_command
($cmd);
201 # .. and just to be sure check on remote side
202 unshift @{$cmd}, @{$self->{rem_ssh
}};
203 PVE
::Tools
::run_command
($cmd);
209 sub start_remote_tunnel
{
210 my ($self, $raddr, $rport, $ruri, $unix_socket_info) = @_;
212 my $nodename = PVE
::INotify
::nodename
();
213 my $migration_type = $self->{opts
}->{migration_type
};
215 if ($migration_type eq 'secure') {
217 if ($ruri =~ /^unix:/) {
218 my $ssh_forward_info = ["$raddr:$raddr"];
219 $unix_socket_info->{$raddr} = 1;
221 my $unix_sockets = [ keys %$unix_socket_info ];
222 for my $sock (@$unix_sockets) {
223 push @$ssh_forward_info, "$sock:$sock";
227 $self->{tunnel
} = $self->fork_tunnel($ssh_forward_info);
229 my $unix_socket_try = 0; # wait for the socket to become ready
230 while ($unix_socket_try <= 100) {
233 foreach my $sock (@$unix_sockets) {
239 if ($available == @$unix_sockets) {
245 if ($unix_socket_try > 100) {
247 $self->finish_tunnel($self->{tunnel
});
248 die "Timeout, migration socket $ruri did not get ready";
250 $self->{tunnel
}->{unix_sockets
} = $unix_sockets if (@$unix_sockets);
252 } elsif ($ruri =~ /^tcp:/) {
253 my $ssh_forward_info = [];
254 if ($raddr eq "localhost") {
255 # for backwards compatibility with older qemu-server versions
256 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
257 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
258 push @$ssh_forward_info, "$lport:localhost:$rport";
261 $self->{tunnel
} = $self->fork_tunnel($ssh_forward_info);
264 die "unsupported protocol in migration URI: $ruri\n";
267 #fork tunnel for insecure migration, to send faster commands like resume
268 $self->{tunnel
} = $self->fork_tunnel();
273 my ($self, $vmid, $code, @param) = @_;
275 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
279 my ($self, $vmid) = @_;
281 my $online = $self->{opts
}->{online
};
283 my $storecfg = $self->{storecfg
} = PVE
::Storage
::config
();
286 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
288 my $repl_conf = PVE
::ReplicationConfig-
>new();
289 $self->{replication_jobcfg
} = $repl_conf->find_local_replication_job($vmid, $self->{node
});
290 $self->{is_replicated
} = $repl_conf->check_for_existing_jobs($vmid, 1);
292 if ($self->{replication_jobcfg
} && defined($self->{replication_jobcfg
}->{remove_job
})) {
293 die "refusing to migrate replicated VM whose replication job is marked for removal\n";
296 PVE
::QemuConfig-
>check_lock($conf);
299 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
300 die "can't migrate running VM without --online\n" if !$online;
303 if ($self->{is_replicated
} && !$self->{replication_jobcfg
}) {
304 if ($self->{opts
}->{force
}) {
305 $self->log('warn', "WARNING: Node '$self->{node}' is not a replication target. Existing " .
306 "replication jobs will fail after migration!\n");
308 die "Cannot live-migrate replicated VM to node '$self->{node}' - not a replication " .
309 "target. Use 'force' to override.\n";
313 $self->{forcemachine
} = PVE
::QemuServer
::Machine
::qemu_machine_pxe
($vmid, $conf);
315 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
316 # Since the parameter itself contains no reference to a custom model,
317 # this makes migration independent of changes to "cpu-models.conf".
319 my $cpuconf = PVE
::JSONSchema
::parse_property_string
('pve-cpu-conf', $conf->{cpu
});
320 if ($cpuconf && PVE
::QemuServer
::CPUConfig
::is_custom_model
($cpuconf->{cputype
})) {
321 $self->{forcecpu
} = PVE
::QemuServer
::CPUConfig
::get_cpu_from_running_vm
($pid);
326 my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1);
327 if (scalar @$loc_res) {
328 if ($self->{running
} || !$self->{opts
}->{force
}) {
329 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
331 $self->log('info', "migrating VM which uses local devices");
335 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
336 foreach my $volid (@$vollist) {
337 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
339 # check if storage is available on both nodes
340 my $scfg = PVE
::Storage
::storage_check_enabled
($storecfg, $sid);
343 if ($scfg->{shared
}) {
346 $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $sid);
349 my $target_scfg = PVE
::Storage
::storage_check_enabled
(
354 my ($vtype) = PVE
::Storage
::parse_volname
($storecfg, $volid);
356 die "$volid: content type '$vtype' is not available on storage '$targetsid'\n"
357 if !$target_scfg->{content
}->{$vtype};
359 if ($scfg->{shared
}) {
360 # PVE::Storage::activate_storage checks this for non-shared storages
361 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
362 warn "Used shared storage '$sid' is not online on source node!\n"
363 if !$plugin->check_connection($sid, $scfg);
367 # test ssh connection
368 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
369 eval { $self->cmd_quiet($cmd); };
370 die "Can't connect to destination address using public key\n" if $@;
375 sub scan_local_volumes
{
376 my ($self, $vmid) = @_;
378 my $conf = $self->{vmconf
};
380 # local volumes which have been copied
381 # and their old_id => new_id pairs
382 $self->{volume_map
} = {};
383 $self->{local_volumes
} = {};
385 my $storecfg = $self->{storecfg
};
388 # found local volumes and their origin
389 my $local_volumes = $self->{local_volumes
};
390 my $local_volumes_errors = {};
391 my $other_errors = [];
394 my $log_error = sub {
395 my ($msg, $volid) = @_;
397 if (defined($volid)) {
398 $local_volumes_errors->{$volid} = $msg;
400 push @$other_errors, $msg;
405 my @sids = PVE
::Storage
::storage_ids
($storecfg);
406 foreach my $storeid (@sids) {
407 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
408 next if $scfg->{shared
};
409 next if !PVE
::Storage
::storage_check_enabled
($storecfg, $storeid, undef, 1);
411 # get list from PVE::Storage (for unused volumes)
412 my $dl = PVE
::Storage
::vdisk_list
($storecfg, $storeid, $vmid, undef, 'images');
414 next if @{$dl->{$storeid}} == 0;
416 my $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $storeid);
417 # check if storage is available on target node
418 my $target_scfg = PVE
::Storage
::storage_check_enabled
(
424 die "content type 'images' is not available on storage '$targetsid'\n"
425 if !$target_scfg->{content
}->{images
};
427 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
(
429 [$targetsid, $storeid],
430 $self->{opts
}->{bwlimit
},
433 PVE
::Storage
::foreach_volid
($dl, sub {
434 my ($volid, $sid, $volinfo) = @_;
436 $local_volumes->{$volid}->{ref} = 'storage';
437 $local_volumes->{$volid}->{size
} = $volinfo->{size
};
438 $local_volumes->{$volid}->{targetsid
} = $targetsid;
439 $local_volumes->{$volid}->{bwlimit
} = $bwlimit;
441 # If with_snapshots is not set for storage migrate, it tries to use
442 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
443 # back to qcow2 is currently not possible.
444 $local_volumes->{$volid}->{snapshots
} = ($volinfo->{format
} =~ /^(?:qcow2|vmdk)$/);
445 $local_volumes->{$volid}->{format
} = $volinfo->{format
};
449 my $replicatable_volumes = !$self->{replication_jobcfg
} ?
{}
450 : PVE
::QemuConfig-
>get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
451 foreach my $volid (keys %{$replicatable_volumes}) {
452 $local_volumes->{$volid}->{replicated
} = 1;
455 my $test_volid = sub {
456 my ($volid, $attr) = @_;
458 if ($volid =~ m
|^/|) {
459 return if $attr->{shared
};
460 $local_volumes->{$volid}->{ref} = 'config';
461 die "local file/device\n";
464 my $snaprefs = $attr->{referenced_in_snapshot
};
466 if ($attr->{cdrom
}) {
467 if ($volid eq 'cdrom') {
468 my $msg = "can't migrate local cdrom drive";
469 if (defined($snaprefs) && !$attr->{referenced_in_config
}) {
470 my $snapnames = join(', ', sort keys %$snaprefs);
471 $msg .= " (referenced in snapshot - $snapnames)";
473 &$log_error("$msg\n");
476 return if $volid eq 'none';
479 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
481 # check if storage is available on both nodes
482 my $scfg = PVE
::Storage
::storage_check_enabled
($storecfg, $sid);
485 if ($scfg->{shared
}) {
488 $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $sid);
491 PVE
::Storage
::storage_check_enabled
($storecfg, $targetsid, $self->{node
});
493 return if $scfg->{shared
};
495 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
496 $local_volumes->{$volid}->{ref} = 'storage' if $attr->{is_unused
};
498 $local_volumes->{$volid}->{is_vmstate
} = $attr->{is_vmstate
} ?
1 : 0;
500 $local_volumes->{$volid}->{drivename
} = $attr->{drivename
}
501 if $attr->{drivename
};
503 if ($attr->{cdrom
}) {
504 if ($volid =~ /vm-\d+-cloudinit/) {
505 $local_volumes->{$volid}->{ref} = 'generated';
508 die "local cdrom image\n";
511 my ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid);
513 die "owned by other VM (owner = VM $owner)\n"
514 if !$owner || ($owner != $vmid);
516 return if $attr->{is_vmstate
};
518 if (defined($snaprefs)) {
519 $local_volumes->{$volid}->{snapshots
} = 1;
521 # we cannot migrate shapshots on local storage
522 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
524 die "online storage migration not possible if snapshot exists\n" if $self->{running
};
525 if (!($scfg->{type
} eq 'zfspool'
526 || ($scfg->{type
} eq 'btrfs' && $local_volumes->{$volid}->{format
} eq 'raw')
527 || $local_volumes->{$volid}->{format
} eq 'qcow2'
529 die "non-migratable snapshot exists\n";
533 die "referenced by linked clone(s)\n"
534 if PVE
::Storage
::volume_is_base_and_used
($storecfg, $volid);
537 PVE
::QemuServer
::foreach_volid
($conf, sub {
538 my ($volid, $attr) = @_;
539 eval { $test_volid->($volid, $attr); };
541 &$log_error($err, $volid);
545 foreach my $vol (sort keys %$local_volumes) {
546 my $type = $replicatable_volumes->{$vol} ?
'local, replicated' : 'local';
547 my $ref = $local_volumes->{$vol}->{ref};
548 if ($ref eq 'storage') {
549 $self->log('info', "found $type disk '$vol' (via storage)\n");
550 } elsif ($ref eq 'config') {
551 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
552 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
553 $self->log('info', "found $type disk '$vol' (in current VM config)\n");
554 } elsif ($ref eq 'snapshot') {
555 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
556 } elsif ($ref eq 'generated') {
557 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
559 $self->log('info', "found $type disk '$vol'\n");
563 foreach my $vol (sort keys %$local_volumes_errors) {
564 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
566 foreach my $err (@$other_errors) {
567 $self->log('warn', "$err");
571 die "can't migrate VM - check log\n";
574 # additional checks for local storage
575 foreach my $volid (keys %$local_volumes) {
576 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
577 my $scfg = PVE
::Storage
::storage_config
($storecfg, $sid);
579 my $migratable = $scfg->{type
} =~ /^(?:dir|btrfs|zfspool|lvmthin|lvm)$/;
581 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
584 # image is a linked clone on local storage, se we can't migrate.
585 if (my $basename = (PVE
::Storage
::parse_volname
($storecfg, $volid))[3]) {
586 die "can't migrate '$volid' as it's a clone of '$basename'";
590 foreach my $volid (sort keys %$local_volumes) {
591 my $ref = $local_volumes->{$volid}->{ref};
592 if ($self->{running
} && $ref eq 'config') {
593 $local_volumes->{$volid}->{migration_mode
} = 'online';
594 } elsif ($self->{running
} && $ref eq 'generated') {
595 # offline migrate the cloud-init ISO and don't regenerate on VM start
596 $local_volumes->{$volid}->{migration_mode
} = 'offline';
598 $local_volumes->{$volid}->{migration_mode
} = 'offline';
602 die "Problem found while scanning volumes - $@" if $@;
605 sub handle_replication
{
606 my ($self, $vmid) = @_;
608 my $conf = $self->{vmconf
};
609 my $local_volumes = $self->{local_volumes
};
611 return if !$self->{replication_jobcfg
};
612 if ($self->{running
}) {
614 my $version = PVE
::QemuServer
::kvm_user_version
();
615 if (!min_version
($version, 4, 2)) {
616 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
619 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
620 foreach my $volid (@live_replicatable_volumes) {
621 my $drive = $local_volumes->{$volid}->{drivename
};
622 die "internal error - no drive for '$volid'\n" if !defined($drive);
624 my $bitmap = "repl_$drive";
626 # start tracking before replication to get full delta + a few duplicates
627 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
628 mon_cmd
($vmid, 'block-dirty-bitmap-add', node
=> "drive-$drive", name
=> $bitmap);
630 # other info comes from target node in phase 2
631 $self->{target_drive
}->{$drive}->{bitmap
} = $bitmap;
634 $self->log('info', "replicating disk images");
636 my $start_time = time();
637 my $logfunc = sub { $self->log('info', shift) };
638 my $actual_replicated_volumes = PVE
::Replication
::run_replication
(
639 'PVE::QemuConfig', $self->{replication_jobcfg
}, $start_time, $start_time, $logfunc);
642 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
643 foreach my $volid (@replicated_volumes) {
644 die "expected volume '$volid' to get replicated, but it wasn't\n"
645 if !$actual_replicated_volumes->{$volid};
649 sub config_update_local_disksizes
{
652 my $conf = $self->{vmconf
};
653 my $local_volumes = $self->{local_volumes
};
655 PVE
::QemuConfig-
>foreach_volume($conf, sub {
656 my ($key, $drive) = @_;
657 return if $key eq 'efidisk0'; # skip efidisk, will be handled later
659 my $volid = $drive->{file
};
660 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
662 my ($updated, $msg) = PVE
::QemuServer
::Drive
::update_disksize
($drive, $local_volumes->{$volid}->{size
});
663 if (defined($updated)) {
664 $conf->{$key} = PVE
::QemuServer
::print_drive
($updated);
665 $self->log('info', "drive '$key': $msg");
669 # we want to set the efidisk size in the config to the size of the
670 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
671 if (defined($conf->{efidisk0
})) {
672 PVE
::QemuServer
::update_efidisk_size
($conf);
676 sub filter_local_volumes
{
677 my ($self, $migration_mode, $replicated) = @_;
679 my $volumes = $self->{local_volumes
};
682 foreach my $volid (sort keys %{$volumes}) {
683 next if defined($migration_mode) && safe_string_ne
($volumes->{$volid}->{migration_mode
}, $migration_mode);
684 next if defined($replicated) && safe_boolean_ne
($volumes->{$volid}->{replicated
}, $replicated);
685 push @filtered_volids, $volid;
688 return @filtered_volids;
691 sub sync_offline_local_volumes
{
694 my $local_volumes = $self->{local_volumes
};
695 my @volids = $self->filter_local_volumes('offline', 0);
697 my $storecfg = $self->{storecfg
};
698 my $opts = $self->{opts
};
700 $self->log('info', "copying local disk images") if scalar(@volids);
702 foreach my $volid (@volids) {
703 my $targetsid = $local_volumes->{$volid}->{targetsid
};
704 my $bwlimit = $local_volumes->{$volid}->{bwlimit
};
705 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
707 my $storage_migrate_opts = {
708 'ratelimit_bps' => $bwlimit,
709 'insecure' => $opts->{migration_type
} eq 'insecure',
710 'with_snapshots' => $local_volumes->{$volid}->{snapshots
},
711 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate
},
714 my $logfunc = sub { $self->log('info', $_[0]); };
715 my $new_volid = eval {
716 PVE
::Storage
::storage_migrate
($storecfg, $volid, $self->{ssh_info
},
717 $targetsid, $storage_migrate_opts, $logfunc);
720 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
723 $self->{volume_map
}->{$volid} = $new_volid;
724 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
726 eval { PVE
::Storage
::deactivate_volumes
($storecfg, [$volid]); };
728 $self->log('warn', $err);
733 sub cleanup_remotedisks
{
736 my $local_volumes = $self->{local_volumes
};
738 foreach my $volid (values %{$self->{volume_map
}}) {
739 # don't clean up replicated disks!
740 next if $local_volumes->{$volid}->{replicated
};
742 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
744 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
746 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
748 $self->log('err', $err);
754 sub cleanup_bitmaps
{
756 foreach my $drive (keys %{$self->{target_drive
}}) {
757 my $bitmap = $self->{target_drive
}->{$drive}->{bitmap
};
759 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
760 mon_cmd
($self->{vmid
}, 'block-dirty-bitmap-remove', node
=> "drive-$drive", name
=> $bitmap);
765 my ($self, $vmid) = @_;
767 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
769 my $conf = $self->{vmconf
};
771 # set migrate lock in config file
772 $conf->{lock} = 'migrate';
773 PVE
::QemuConfig-
>write_config($vmid, $conf);
775 $self->scan_local_volumes($vmid);
777 # fix disk sizes to match their actual size and write changes,
778 # so that the target allocates the correct volumes
779 $self->config_update_local_disksizes();
780 PVE
::QemuConfig-
>write_config($vmid, $conf);
782 $self->handle_replication($vmid);
784 $self->sync_offline_local_volumes();
788 my ($self, $vmid, $err) = @_;
790 $self->log('info', "aborting phase 1 - cleanup resources");
792 my $conf = $self->{vmconf
};
793 delete $conf->{lock};
794 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
796 $self->log('err', $err);
799 eval { $self->cleanup_remotedisks() };
801 $self->log('err', $err);
804 eval { $self->cleanup_bitmaps() };
806 $self->log('err', $err);
811 my ($self, $vmid) = @_;
813 my $conf = $self->{vmconf
};
814 my $local_volumes = $self->{local_volumes
};
815 my @online_local_volumes = $self->filter_local_volumes('online');
817 $self->{storage_migration
} = 1 if scalar(@online_local_volumes);
819 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
823 my $ruri; # the whole migration dst. URI (protocol:address[:port])
824 my $nodename = PVE
::INotify
::nodename
();
826 ## start on remote node
827 my $cmd = [@{$self->{rem_ssh
}}];
830 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
831 my $res = mon_cmd
($vmid, 'query-spice');
832 $spice_ticket = $res->{ticket
};
835 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
837 my $migration_type = $self->{opts
}->{migration_type
};
839 push @$cmd, '--migration_type', $migration_type;
841 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
842 if $self->{opts
}->{migration_network
};
844 if ($migration_type eq 'insecure') {
845 push @$cmd, '--stateuri', 'tcp';
847 push @$cmd, '--stateuri', 'unix';
850 if ($self->{forcemachine
}) {
851 push @$cmd, '--machine', $self->{forcemachine
};
854 if ($self->{forcecpu
}) {
855 push @$cmd, '--force-cpu', $self->{forcecpu
};
858 if ($self->{storage_migration
}) {
859 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
863 my $unix_socket_info = {};
864 # version > 0 for unix socket support
865 my $nbd_protocol_version = 1;
866 my $input = "nbd_protocol_version: $nbd_protocol_version\n";
867 $input .= "spice_ticket: $spice_ticket\n" if $spice_ticket;
869 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
870 foreach my $volid (@online_replicated_volumes) {
871 $input .= "replicated_volume: $volid\n";
874 my $handle_storage_migration_listens = sub {
875 my ($drive_key, $drivestr, $nbd_uri) = @_;
877 $self->{stopnbd
} = 1;
878 $self->{target_drive
}->{$drive_key}->{drivestr
} = $drivestr;
879 $self->{target_drive
}->{$drive_key}->{nbd_uri
} = $nbd_uri;
881 my $source_drive = PVE
::QemuServer
::parse_drive
($drive_key, $conf->{$drive_key});
882 my $target_drive = PVE
::QemuServer
::parse_drive
($drive_key, $drivestr);
883 my $source_volid = $source_drive->{file
};
884 my $target_volid = $target_drive->{file
};
886 $self->{volume_map
}->{$source_volid} = $target_volid;
887 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
890 my $target_replicated_volumes = {};
892 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
893 # instead we pipe it through STDIN
894 my $exitcode = PVE
::Tools
::run_command
($cmd, input
=> $input, outfunc
=> sub {
897 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
900 $ruri = "tcp:$raddr:$rport";
902 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
904 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
905 $ruri = "unix:$raddr";
907 elsif ($line =~ m/^migration listens on port (\d+)$/) {
908 $raddr = "localhost";
910 $ruri = "tcp:$raddr:$rport";
912 elsif ($line =~ m/^spice listens on port (\d+)$/) {
913 $spice_port = int($1);
915 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
917 my $nbd_uri = "nbd:$1:$2:exportname=$3";
918 my $targetdrive = $3;
919 $targetdrive =~ s/drive-//g;
921 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
922 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
924 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
925 my $nbd_unix_addr = $1;
926 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
927 my $targetdrive = $3;
928 $targetdrive =~ s/drive-//g;
930 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
931 $unix_socket_info->{$nbd_unix_addr} = 1;
932 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
935 $target_replicated_volumes->{$volid} = $drive;
936 } elsif ($line =~ m/^QEMU: (.*)$/) {
937 $self->log('info', "[$self->{node}] $1\n");
941 $self->log('info', "[$self->{node}] $line");
944 die "remote command failed with exit code $exitcode\n" if $exitcode;
946 die "unable to detect remote migration address\n" if !$raddr;
948 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
949 die "number of replicated disks on source and target node do not match - target node too old?\n"
952 $self->log('info', "start remote tunnel");
953 $self->start_remote_tunnel($raddr, $rport, $ruri, $unix_socket_info);
955 if ($self->{storage_migration
}) {
956 $self->{storage_migration_jobs
} = {};
957 $self->log('info', "starting storage migration");
959 die "The number of local disks does not match between the source and the destination.\n"
960 if (scalar(keys %{$self->{target_drive
}}) != scalar(@online_local_volumes));
961 foreach my $drive (keys %{$self->{target_drive
}}){
962 my $target = $self->{target_drive
}->{$drive};
963 my $nbd_uri = $target->{nbd_uri
};
965 my $source_drive = PVE
::QemuServer
::parse_drive
($drive, $conf->{$drive});
966 my $source_volid = $source_drive->{file
};
968 my $bwlimit = $local_volumes->{$source_volid}->{bwlimit
};
969 my $bitmap = $target->{bitmap
};
971 $self->log('info', "$drive: start migration to $nbd_uri");
972 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 'skip', undef, $bwlimit, $bitmap);
976 $self->log('info', "starting online/live migration on $ruri");
977 $self->{livemigration
} = 1;
980 my $defaults = PVE
::QemuServer
::load_defaults
();
982 $self->log('info', "set migration capabilities");
983 eval { PVE
::QemuServer
::set_migration_caps
($vmid) };
986 my $qemu_migrate_params = {};
988 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
989 # migrate_speed parameter in qm.conf - take the lower of the two.
990 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migration', undef, $self->{opts
}->{bwlimit
}) // 0;
991 my $migrate_speed = $conf->{migrate_speed
} // 0;
992 $migrate_speed *= 1024; # migrate_speed is in MB/s, bwlimit in KB/s
994 if ($bwlimit && $migrate_speed) {
995 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
997 $migrate_speed ||= $bwlimit;
999 $migrate_speed ||= ($defaults->{migrate_speed
} || 0) * 1024;
1001 if ($migrate_speed) {
1002 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
1003 $self->log('info', "migration speed limit: ". render_bytes
($migrate_speed, 1) ."/s");
1005 # always set migrate speed as QEMU default to 128 MiBps == 1 Gbps, use 16 GiBps == 128 Gbps
1006 $migrate_speed = (16 << 30);
1008 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
1010 my $migrate_downtime = $defaults->{migrate_downtime
};
1011 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
1012 # migrate-set-parameters expects limit in ms
1013 $migrate_downtime *= 1000;
1014 $self->log('info', "migration downtime limit: $migrate_downtime ms");
1015 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
1017 # set cachesize to 10% of the total memory
1018 my $memory = $conf->{memory
} || $defaults->{memory
};
1019 my $cachesize = int($memory * 1048576 / 10);
1020 $cachesize = round_powerof2
($cachesize);
1022 $self->log('info', "migration cachesize: " . render_bytes
($cachesize, 1));
1023 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
1025 $self->log('info', "set migration parameters");
1027 mon_cmd
($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
1029 $self->log('info', "migrate-set-parameters error: $@") if $@;
1031 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
1032 my $rpcenv = PVE
::RPCEnvironment
::get
();
1033 my $authuser = $rpcenv->get_user();
1035 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
1037 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
1038 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
1040 $self->log('info', "spice client_migrate_info");
1043 mon_cmd
($vmid, "client_migrate_info", protocol
=> 'spice',
1044 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
1045 'cert-subject' => $subject);
1047 $self->log('info', "client_migrate_info error: $@") if $@;
1053 $self->log('info', "start migrate command to $ruri");
1055 mon_cmd
($vmid, "migrate", uri
=> $ruri);
1058 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
1060 my $last_mem_transferred = 0;
1061 my $usleep = 1000000;
1064 my $lastrem = undef;
1065 my $downtimecounter = 0;
1068 my $avglstat = $last_mem_transferred ?
$last_mem_transferred / $i : 0;
1072 my $stat = eval { mon_cmd
($vmid, "query-migrate") };
1075 warn "query migrate failed: $err\n";
1076 $self->log('info', "query migrate failed: $err");
1077 if ($err_count <= 5) {
1081 die "too many query migrate failures - aborting\n";
1084 my $status = $stat->{status
};
1085 if (defined($status) && $status =~ m/^(setup)$/im) {
1090 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1092 die "unable to parse migration status '$status' - aborting\n";
1097 my $memstat = $stat->{ram
};
1099 if ($status eq 'completed') {
1100 my $delay = time() - $start;
1102 my $total = $memstat->{total
} || 0;
1103 my $avg_speed = render_bytes
($total / $delay, 1);
1104 my $downtime = $stat->{downtime
} || 0;
1105 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1109 if ($status eq 'failed' || $status eq 'cancelled') {
1110 $self->log('info', "migration status error: $status");
1114 if ($status ne 'active') {
1115 $self->log('info', "migration status: $status");
1119 if ($memstat->{transferred
} ne $last_mem_transferred) {
1120 my $trans = $memstat->{transferred
} || 0;
1121 my $rem = $memstat->{remaining
} || 0;
1122 my $total = $memstat->{total
} || 0;
1123 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1124 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
1126 # reduce sleep if remainig memory is lower than the average transfer speed
1127 $usleep = 100_000 if $avglstat && $rem < $avglstat;
1129 # also reduce loggin if we poll more frequent
1130 my $should_log = $usleep > 100_000 ?
1 : ($i % 10) == 0;
1132 my $total_h = render_bytes
($total, 1);
1133 my $transferred_h = render_bytes
($trans, 1);
1134 my $speed_h = render_bytes
($speed, 1);
1136 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1138 if ($dirty_rate > $speed) {
1139 my $dirty_rate_h = render_bytes
($dirty_rate, 1);
1140 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1143 $self->log('info', "migration $status, $progress") if $should_log;
1145 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1146 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1147 if ($xbzrlebytes || $xbzrlepages) {
1148 my $bytes_h = render_bytes
($xbzrlebytes, 1);
1150 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1152 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1153 if $xbzrle->{'cache-miss-rate'};
1155 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow
};
1157 $self->log('info', "xbzrle: $msg") if $should_log;
1160 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
1165 if ($downtimecounter > 5) {
1166 $downtimecounter = 0;
1167 $migrate_downtime *= 2;
1168 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1170 # migrate-set-parameters does not touch values not
1171 # specified, so this only changes downtime-limit
1172 mon_cmd
($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1174 $self->log('info', "migrate-set-parameters error: $@") if $@;
1178 $last_mem_transferred = $memstat->{transferred
};
1181 if ($self->{storage_migration
}) {
1182 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1183 # to avoid it trying to re-establish it. We are in blockjob ready state,
1184 # thus, this command changes to it to blockjob complete (see qapi docs)
1185 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}, 'cancel'); };
1187 die "Failed to complete storage migration: $err\n";
1192 sub phase2_cleanup
{
1193 my ($self, $vmid, $err) = @_;
1195 return if !$self->{errors
};
1196 $self->{phase2errors
} = 1;
1198 $self->log('info', "aborting phase 2 - cleanup resources");
1200 $self->log('info', "migrate_cancel");
1202 mon_cmd
($vmid, "migrate_cancel");
1204 $self->log('info', "migrate_cancel error: $@") if $@;
1206 my $conf = $self->{vmconf
};
1207 delete $conf->{lock};
1208 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
1210 $self->log('err', $err);
1213 # cleanup ressources on target host
1214 if ($self->{storage_migration
}) {
1215 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
1217 $self->log('err', $err);
1221 eval { $self->cleanup_bitmaps() };
1223 $self->log('err', $err);
1226 my $nodename = PVE
::INotify
::nodename
();
1228 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1229 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1231 $self->log('err', $err);
1232 $self->{errors
} = 1;
1235 # cleanup after stopping, otherwise disks might be in-use by target VM!
1236 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
1238 $self->log('err', $err);
1242 if ($self->{tunnel
}) {
1243 eval { finish_tunnel
($self, $self->{tunnel
}); };
1245 $self->log('err', $err);
1246 $self->{errors
} = 1;
1252 my ($self, $vmid) = @_;
1257 sub phase3_cleanup
{
1258 my ($self, $vmid, $err) = @_;
1260 my $conf = $self->{vmconf
};
1261 return if $self->{phase2errors
};
1263 my $tunnel = $self->{tunnel
};
1265 if ($self->{volume_map
}) {
1266 my $target_drives = $self->{target_drive
};
1268 # FIXME: for NBD storage migration we now only update the volid, and
1269 # not the full drivestr from the target node. Workaround that until we
1270 # got some real rescan, to avoid things like wrong format in the drive
1271 delete $conf->{$_} for keys %$target_drives;
1272 PVE
::QemuConfig-
>update_volume_ids($conf, $self->{volume_map
});
1274 for my $drive (keys %$target_drives) {
1275 $conf->{$drive} = $target_drives->{$drive}->{drivestr
};
1277 PVE
::QemuConfig-
>write_config($vmid, $conf);
1280 # transfer replication state before move config
1281 $self->transfer_replication_state() if $self->{is_replicated
};
1282 PVE
::QemuConfig-
>move_config_to_node($vmid, $self->{node
});
1283 $self->switch_replication_job_target() if $self->{is_replicated
};
1285 if ($self->{livemigration
}) {
1286 if ($self->{stopnbd
}) {
1287 $self->log('info', "stopping NBD storage migration server on target.");
1288 # stop nbd server on remote vm - requirement for resume since 2.9
1289 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
1291 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1293 $self->log('err', $err);
1294 $self->{errors
} = 1;
1298 # config moved and nbd server stopped - now we can resume vm on target
1299 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
1301 $self->write_tunnel($tunnel, 30, "resume $vmid");
1304 $self->log('err', $err);
1305 $self->{errors
} = 1;
1308 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1311 $self->log('err', $line);
1313 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1315 $self->log('err', $err);
1316 $self->{errors
} = 1;
1320 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
1321 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1322 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1326 # close tunnel on successful migration, on error phase2_cleanup closed it
1328 eval { finish_tunnel
($self, $tunnel); };
1330 $self->log('err', $err);
1331 $self->{errors
} = 1;
1337 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1338 $self->log('info', "Waiting for spice server migration");
1340 my $res = mon_cmd
($vmid, 'query-spice');
1341 last if int($res->{'migrated'}) == 1;
1342 last if $timer > 50;
1349 # always stop local VM
1350 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1352 $self->log('err', "stopping vm failed - $err");
1353 $self->{errors
} = 1;
1356 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1358 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1359 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1362 $self->log('err', $err);
1363 $self->{errors
} = 1;
1366 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
1368 # destroy local copies
1369 foreach my $volid (@not_replicated_volumes) {
1370 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1372 $self->log('err', "removing local copy of '$volid' failed - $err");
1373 $self->{errors
} = 1;
1374 last if $err =~ /^interrupted by signal$/;
1378 # clear migrate lock
1379 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1380 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1384 my ($self, $vmid) = @_;
1389 sub round_powerof2
{
1390 return 1 if $_[0] < 2;
1391 return 2 << int(log($_[0]-1)/log(2));