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 $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);
337 foreach my $volid (@$vollist) {
338 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
340 # check if storage is available on both nodes
341 my $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $sid);
343 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
344 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
346 if ($scfg->{shared
}) {
347 # PVE::Storage::activate_storage checks this for non-shared storages
348 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
349 warn "Used shared storage '$sid' is not online on source node!\n"
350 if !$plugin->check_connection($sid, $scfg);
354 # test ssh connection
355 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
356 eval { $self->cmd_quiet($cmd); };
357 die "Can't connect to destination address using public key\n" if $@;
362 sub scan_local_volumes
{
363 my ($self, $vmid) = @_;
365 my $conf = $self->{vmconf
};
367 # local volumes which have been copied
368 # and their old_id => new_id pairs
369 $self->{volume_map
} = {};
370 $self->{local_volumes
} = {};
372 my $storecfg = $self->{storecfg
};
375 # found local volumes and their origin
376 my $local_volumes = $self->{local_volumes
};
377 my $local_volumes_errors = {};
378 my $other_errors = [];
381 my $log_error = sub {
382 my ($msg, $volid) = @_;
384 if (defined($volid)) {
385 $local_volumes_errors->{$volid} = $msg;
387 push @$other_errors, $msg;
392 my @sids = PVE
::Storage
::storage_ids
($storecfg);
393 foreach my $storeid (@sids) {
394 my $scfg = PVE
::Storage
::storage_config
($storecfg, $storeid);
395 next if $scfg->{shared
};
396 next if !PVE
::Storage
::storage_check_enabled
($storecfg, $storeid, undef, 1);
398 # get list from PVE::Storage (for unused volumes)
399 my $dl = PVE
::Storage
::vdisk_list
($storecfg, $storeid, $vmid);
401 next if @{$dl->{$storeid}} == 0;
403 my $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $storeid);
404 # check if storage is available on target node
405 PVE
::Storage
::storage_check_node
($storecfg, $targetsid, $self->{node
});
407 # grandfather in existing mismatches
408 if ($targetsid ne $storeid) {
409 my $target_scfg = PVE
::Storage
::storage_config
($storecfg, $targetsid);
410 die "content type 'images' is not available on storage '$targetsid'\n"
411 if !$target_scfg->{content
}->{images
};
414 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
(
416 [$targetsid, $storeid],
417 $self->{opts
}->{bwlimit
},
420 PVE
::Storage
::foreach_volid
($dl, sub {
421 my ($volid, $sid, $volinfo) = @_;
423 $local_volumes->{$volid}->{ref} = 'storage';
424 $local_volumes->{$volid}->{size
} = $volinfo->{size
};
425 $local_volumes->{$volid}->{targetsid
} = $targetsid;
426 $local_volumes->{$volid}->{bwlimit
} = $bwlimit;
428 # If with_snapshots is not set for storage migrate, it tries to use
429 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
430 # back to qcow2 is currently not possible.
431 $local_volumes->{$volid}->{snapshots
} = ($volinfo->{format
} =~ /^(?:qcow2|vmdk)$/);
432 $local_volumes->{$volid}->{format
} = $volinfo->{format
};
436 my $replicatable_volumes = !$self->{replication_jobcfg
} ?
{}
437 : PVE
::QemuConfig-
>get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
438 foreach my $volid (keys %{$replicatable_volumes}) {
439 $local_volumes->{$volid}->{replicated
} = 1;
442 my $test_volid = sub {
443 my ($volid, $attr) = @_;
445 if ($volid =~ m
|^/|) {
446 return if $attr->{shared
};
447 $local_volumes->{$volid}->{ref} = 'config';
448 die "local file/device\n";
451 my $snaprefs = $attr->{referenced_in_snapshot
};
453 if ($attr->{cdrom
}) {
454 if ($volid eq 'cdrom') {
455 my $msg = "can't migrate local cdrom drive";
456 if (defined($snaprefs) && !$attr->{referenced_in_config
}) {
457 my $snapnames = join(', ', sort keys %$snaprefs);
458 $msg .= " (referenced in snapshot - $snapnames)";
460 &$log_error("$msg\n");
463 return if $volid eq 'none';
466 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
468 my $targetsid = PVE
::QemuServer
::map_storage
($self->{opts
}->{storagemap
}, $sid);
469 # check if storage is available on both nodes
470 my $scfg = PVE
::Storage
::storage_check_node
($storecfg, $sid);
471 PVE
::Storage
::storage_check_node
($storecfg, $targetsid, $self->{node
});
473 return if $scfg->{shared
};
475 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
476 $local_volumes->{$volid}->{ref} = 'storage' if $attr->{is_unused
};
478 $local_volumes->{$volid}->{is_vmstate
} = $attr->{is_vmstate
} ?
1 : 0;
480 $local_volumes->{$volid}->{drivename
} = $attr->{drivename
}
481 if $attr->{drivename
};
483 if ($attr->{cdrom
}) {
484 if ($volid =~ /vm-\d+-cloudinit/) {
485 $local_volumes->{$volid}->{ref} = 'generated';
488 die "local cdrom image\n";
491 my ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid);
493 die "owned by other VM (owner = VM $owner)\n"
494 if !$owner || ($owner != $vmid);
496 return if $attr->{is_vmstate
};
498 if (defined($snaprefs)) {
499 $local_volumes->{$volid}->{snapshots
} = 1;
501 # we cannot migrate shapshots on local storage
502 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
504 die "online storage migration not possible if snapshot exists\n" if $self->{running
};
505 if (!($scfg->{type
} eq 'zfspool' || $local_volumes->{$volid}->{format
} eq 'qcow2')) {
506 die "non-migratable snapshot exists\n";
510 die "referenced by linked clone(s)\n"
511 if PVE
::Storage
::volume_is_base_and_used
($storecfg, $volid);
514 PVE
::QemuServer
::foreach_volid
($conf, sub {
515 my ($volid, $attr) = @_;
516 eval { $test_volid->($volid, $attr); };
518 &$log_error($err, $volid);
522 foreach my $vol (sort keys %$local_volumes) {
523 my $type = $replicatable_volumes->{$vol} ?
'local, replicated' : 'local';
524 my $ref = $local_volumes->{$vol}->{ref};
525 if ($ref eq 'storage') {
526 $self->log('info', "found $type disk '$vol' (via storage)\n");
527 } elsif ($ref eq 'config') {
528 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
529 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
530 $self->log('info', "found $type disk '$vol' (in current VM config)\n");
531 } elsif ($ref eq 'snapshot') {
532 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
533 } elsif ($ref eq 'generated') {
534 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
536 $self->log('info', "found $type disk '$vol'\n");
540 foreach my $vol (sort keys %$local_volumes_errors) {
541 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
543 foreach my $err (@$other_errors) {
544 $self->log('warn', "$err");
548 die "can't migrate VM - check log\n";
551 # additional checks for local storage
552 foreach my $volid (keys %$local_volumes) {
553 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
554 my $scfg = PVE
::Storage
::storage_config
($storecfg, $sid);
556 my $migratable = $scfg->{type
} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
558 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
561 # image is a linked clone on local storage, se we can't migrate.
562 if (my $basename = (PVE
::Storage
::parse_volname
($storecfg, $volid))[3]) {
563 die "can't migrate '$volid' as it's a clone of '$basename'";
567 foreach my $volid (sort keys %$local_volumes) {
568 my $ref = $local_volumes->{$volid}->{ref};
569 if ($self->{running
} && $ref eq 'config') {
570 $local_volumes->{$volid}->{migration_mode
} = 'online';
571 } elsif ($self->{running
} && $ref eq 'generated') {
572 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n";
574 $local_volumes->{$volid}->{migration_mode
} = 'offline';
578 die "Problem found while scanning volumes - $@" if $@;
581 sub handle_replication
{
582 my ($self, $vmid) = @_;
584 my $conf = $self->{vmconf
};
585 my $local_volumes = $self->{local_volumes
};
587 return if !$self->{replication_jobcfg
};
588 if ($self->{running
}) {
590 my $version = PVE
::QemuServer
::kvm_user_version
();
591 if (!min_version
($version, 4, 2)) {
592 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
595 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
596 foreach my $volid (@live_replicatable_volumes) {
597 my $drive = $local_volumes->{$volid}->{drivename
};
598 die "internal error - no drive for '$volid'\n" if !defined($drive);
600 my $bitmap = "repl_$drive";
602 # start tracking before replication to get full delta + a few duplicates
603 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
604 mon_cmd
($vmid, 'block-dirty-bitmap-add', node
=> "drive-$drive", name
=> $bitmap);
606 # other info comes from target node in phase 2
607 $self->{target_drive
}->{$drive}->{bitmap
} = $bitmap;
610 $self->log('info', "replicating disk images");
612 my $start_time = time();
613 my $logfunc = sub { $self->log('info', shift) };
614 my $actual_replicated_volumes = PVE
::Replication
::run_replication
(
615 'PVE::QemuConfig', $self->{replication_jobcfg
}, $start_time, $start_time, $logfunc);
618 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
619 foreach my $volid (@replicated_volumes) {
620 die "expected volume '$volid' to get replicated, but it wasn't\n"
621 if !$actual_replicated_volumes->{$volid};
625 sub config_update_local_disksizes
{
628 my $conf = $self->{vmconf
};
629 my $local_volumes = $self->{local_volumes
};
631 PVE
::QemuConfig-
>foreach_volume($conf, sub {
632 my ($key, $drive) = @_;
633 return if $key eq 'efidisk0'; # skip efidisk, will be handled later
635 my $volid = $drive->{file
};
636 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
638 my ($updated, $msg) = PVE
::QemuServer
::Drive
::update_disksize
($drive, $local_volumes->{$volid}->{size
});
639 if (defined($updated)) {
640 $conf->{$key} = PVE
::QemuServer
::print_drive
($updated);
641 $self->log('info', "drive '$key': $msg");
645 # we want to set the efidisk size in the config to the size of the
646 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
647 if (defined($conf->{efidisk0
})) {
648 PVE
::QemuServer
::update_efidisk_size
($conf);
652 sub filter_local_volumes
{
653 my ($self, $migration_mode, $replicated) = @_;
655 my $volumes = $self->{local_volumes
};
658 foreach my $volid (sort keys %{$volumes}) {
659 next if defined($migration_mode) && safe_string_ne
($volumes->{$volid}->{migration_mode
}, $migration_mode);
660 next if defined($replicated) && safe_boolean_ne
($volumes->{$volid}->{replicated
}, $replicated);
661 push @filtered_volids, $volid;
664 return @filtered_volids;
667 sub sync_offline_local_volumes
{
670 my $local_volumes = $self->{local_volumes
};
671 my @volids = $self->filter_local_volumes('offline', 0);
673 my $storecfg = $self->{storecfg
};
674 my $opts = $self->{opts
};
676 $self->log('info', "copying local disk images") if scalar(@volids);
678 foreach my $volid (@volids) {
679 my $targetsid = $local_volumes->{$volid}->{targetsid
};
680 my $bwlimit = $local_volumes->{$volid}->{bwlimit
};
681 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
683 my $storage_migrate_opts = {
684 'ratelimit_bps' => $bwlimit,
685 'insecure' => $opts->{migration_type
} eq 'insecure',
686 'with_snapshots' => $local_volumes->{$volid}->{snapshots
},
687 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate
},
690 my $logfunc = sub { $self->log('info', $_[0]); };
691 my $new_volid = eval {
692 PVE
::Storage
::storage_migrate
($storecfg, $volid, $self->{ssh_info
},
693 $targetsid, $storage_migrate_opts, $logfunc);
696 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
699 $self->{volume_map
}->{$volid} = $new_volid;
700 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
702 eval { PVE
::Storage
::deactivate_volumes
($storecfg, [$volid]); };
704 $self->log('warn', $err);
709 sub cleanup_remotedisks
{
712 my $local_volumes = $self->{local_volumes
};
714 foreach my $volid (values %{$self->{volume_map
}}) {
715 # don't clean up replicated disks!
716 next if $local_volumes->{$volid}->{replicated
};
718 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
720 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
722 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
724 $self->log('err', $err);
730 sub cleanup_bitmaps
{
732 foreach my $drive (keys %{$self->{target_drive
}}) {
733 my $bitmap = $self->{target_drive
}->{$drive}->{bitmap
};
735 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
736 mon_cmd
($self->{vmid
}, 'block-dirty-bitmap-remove', node
=> "drive-$drive", name
=> $bitmap);
741 my ($self, $vmid) = @_;
743 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
745 my $conf = $self->{vmconf
};
747 # set migrate lock in config file
748 $conf->{lock} = 'migrate';
749 PVE
::QemuConfig-
>write_config($vmid, $conf);
751 $self->scan_local_volumes($vmid);
753 # fix disk sizes to match their actual size and write changes,
754 # so that the target allocates the correct volumes
755 $self->config_update_local_disksizes();
756 PVE
::QemuConfig-
>write_config($vmid, $conf);
758 $self->handle_replication($vmid);
760 $self->sync_offline_local_volumes();
764 my ($self, $vmid, $err) = @_;
766 $self->log('info', "aborting phase 1 - cleanup resources");
768 my $conf = $self->{vmconf
};
769 delete $conf->{lock};
770 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
772 $self->log('err', $err);
775 eval { $self->cleanup_remotedisks() };
777 $self->log('err', $err);
780 eval { $self->cleanup_bitmaps() };
782 $self->log('err', $err);
787 my ($self, $vmid) = @_;
789 my $conf = $self->{vmconf
};
790 my $local_volumes = $self->{local_volumes
};
791 my @online_local_volumes = $self->filter_local_volumes('online');
793 $self->{storage_migration
} = 1 if scalar(@online_local_volumes);
795 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
799 my $ruri; # the whole migration dst. URI (protocol:address[:port])
800 my $nodename = PVE
::INotify
::nodename
();
802 ## start on remote node
803 my $cmd = [@{$self->{rem_ssh
}}];
806 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
807 my $res = mon_cmd
($vmid, 'query-spice');
808 $spice_ticket = $res->{ticket
};
811 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
813 my $migration_type = $self->{opts
}->{migration_type
};
815 push @$cmd, '--migration_type', $migration_type;
817 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
818 if $self->{opts
}->{migration_network
};
820 if ($migration_type eq 'insecure') {
821 push @$cmd, '--stateuri', 'tcp';
823 push @$cmd, '--stateuri', 'unix';
826 if ($self->{forcemachine
}) {
827 push @$cmd, '--machine', $self->{forcemachine
};
830 if ($self->{forcecpu
}) {
831 push @$cmd, '--force-cpu', $self->{forcecpu
};
834 if ($self->{storage_migration
}) {
835 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
839 my $unix_socket_info = {};
840 # version > 0 for unix socket support
841 my $nbd_protocol_version = 1;
842 my $input = "nbd_protocol_version: $nbd_protocol_version\n";
843 $input .= "spice_ticket: $spice_ticket\n" if $spice_ticket;
845 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
846 foreach my $volid (@online_replicated_volumes) {
847 $input .= "replicated_volume: $volid\n";
850 my $handle_storage_migration_listens = sub {
851 my ($drive_key, $drivestr, $nbd_uri) = @_;
853 $self->{stopnbd
} = 1;
854 $self->{target_drive
}->{$drive_key}->{drivestr
} = $drivestr;
855 $self->{target_drive
}->{$drive_key}->{nbd_uri
} = $nbd_uri;
857 my $source_drive = PVE
::QemuServer
::parse_drive
($drive_key, $conf->{$drive_key});
858 my $target_drive = PVE
::QemuServer
::parse_drive
($drive_key, $drivestr);
859 my $source_volid = $source_drive->{file
};
860 my $target_volid = $target_drive->{file
};
862 $self->{volume_map
}->{$source_volid} = $target_volid;
863 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
866 my $target_replicated_volumes = {};
868 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
869 # instead we pipe it through STDIN
870 my $exitcode = PVE
::Tools
::run_command
($cmd, input
=> $input, outfunc
=> sub {
873 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
876 $ruri = "tcp:$raddr:$rport";
878 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
880 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
881 $ruri = "unix:$raddr";
883 elsif ($line =~ m/^migration listens on port (\d+)$/) {
884 $raddr = "localhost";
886 $ruri = "tcp:$raddr:$rport";
888 elsif ($line =~ m/^spice listens on port (\d+)$/) {
889 $spice_port = int($1);
891 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
893 my $nbd_uri = "nbd:$1:$2:exportname=$3";
894 my $targetdrive = $3;
895 $targetdrive =~ s/drive-//g;
897 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
898 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
900 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
901 my $nbd_unix_addr = $1;
902 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
903 my $targetdrive = $3;
904 $targetdrive =~ s/drive-//g;
906 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
907 $unix_socket_info->{$nbd_unix_addr} = 1;
908 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
911 $target_replicated_volumes->{$volid} = $drive;
912 } elsif ($line =~ m/^QEMU: (.*)$/) {
913 $self->log('info', "[$self->{node}] $1\n");
917 $self->log('info', "[$self->{node}] $line");
920 die "remote command failed with exit code $exitcode\n" if $exitcode;
922 die "unable to detect remote migration address\n" if !$raddr;
924 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
925 die "number of replicated disks on source and target node do not match - target node too old?\n"
928 $self->log('info', "start remote tunnel");
929 $self->start_remote_tunnel($raddr, $rport, $ruri, $unix_socket_info);
931 if ($self->{storage_migration
}) {
932 $self->{storage_migration_jobs
} = {};
933 $self->log('info', "starting storage migration");
935 die "The number of local disks does not match between the source and the destination.\n"
936 if (scalar(keys %{$self->{target_drive
}}) != scalar(@online_local_volumes));
937 foreach my $drive (keys %{$self->{target_drive
}}){
938 my $target = $self->{target_drive
}->{$drive};
939 my $nbd_uri = $target->{nbd_uri
};
941 my $source_drive = PVE
::QemuServer
::parse_drive
($drive, $conf->{$drive});
942 my $source_volid = $source_drive->{file
};
944 my $bwlimit = $local_volumes->{$source_volid}->{bwlimit
};
945 my $bitmap = $target->{bitmap
};
947 $self->log('info', "$drive: start migration to $nbd_uri");
948 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 'skip', undef, $bwlimit, $bitmap);
952 $self->log('info', "starting online/live migration on $ruri");
953 $self->{livemigration
} = 1;
956 my $defaults = PVE
::QemuServer
::load_defaults
();
958 $self->log('info', "set migration capabilities");
959 eval { PVE
::QemuServer
::set_migration_caps
($vmid) };
962 my $qemu_migrate_params = {};
964 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
965 # migrate_speed parameter in qm.conf - take the lower of the two.
966 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migration', undef, $self->{opts
}->{bwlimit
}) // 0;
967 my $migrate_speed = $conf->{migrate_speed
} // 0;
968 $migrate_speed *= 1024; # migrate_speed is in MB/s, bwlimit in KB/s
970 if ($bwlimit && $migrate_speed) {
971 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
973 $migrate_speed ||= $bwlimit;
975 $migrate_speed ||= ($defaults->{migrate_speed
} || 0) * 1024;
977 if ($migrate_speed) {
978 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
979 $self->log('info', "migration speed limit: ". render_bytes
($migrate_speed, 1) ."/s");
981 # always set migrate speed as QEMU default to 128 MiBps == 1 Gbps, use 16 GiBps == 128 Gbps
982 $migrate_speed = (16 << 30);
984 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
986 my $migrate_downtime = $defaults->{migrate_downtime
};
987 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
988 # migrate-set-parameters expects limit in ms
989 $migrate_downtime *= 1000;
990 $self->log('info', "migration downtime limit: $migrate_downtime ms");
991 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
993 # set cachesize to 10% of the total memory
994 my $memory = $conf->{memory
} || $defaults->{memory
};
995 my $cachesize = int($memory * 1048576 / 10);
996 $cachesize = round_powerof2
($cachesize);
998 $self->log('info', "migration cachesize: " . render_bytes
($cachesize, 1));
999 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
1001 $self->log('info', "set migration parameters");
1003 mon_cmd
($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
1005 $self->log('info', "migrate-set-parameters error: $@") if $@;
1007 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
1008 my $rpcenv = PVE
::RPCEnvironment
::get
();
1009 my $authuser = $rpcenv->get_user();
1011 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
1013 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
1014 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
1016 $self->log('info', "spice client_migrate_info");
1019 mon_cmd
($vmid, "client_migrate_info", protocol
=> 'spice',
1020 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
1021 'cert-subject' => $subject);
1023 $self->log('info', "client_migrate_info error: $@") if $@;
1029 $self->log('info', "start migrate command to $ruri");
1031 mon_cmd
($vmid, "migrate", uri
=> $ruri);
1034 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
1036 my $last_mem_transferred = 0;
1037 my $usleep = 1000000;
1040 my $lastrem = undef;
1041 my $downtimecounter = 0;
1044 my $avglstat = $last_mem_transferred ?
$last_mem_transferred / $i : 0;
1048 my $stat = eval { mon_cmd
($vmid, "query-migrate") };
1051 warn "query migrate failed: $err\n";
1052 $self->log('info', "query migrate failed: $err");
1053 if ($err_count <= 5) {
1057 die "too many query migrate failures - aborting\n";
1060 my $status = $stat->{status
};
1061 if (defined($status) && $status =~ m/^(setup)$/im) {
1066 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1068 die "unable to parse migration status '$status' - aborting\n";
1073 my $memstat = $stat->{ram
};
1075 if ($status eq 'completed') {
1076 my $delay = time() - $start;
1078 my $total = $memstat->{total
} || 0;
1079 my $avg_speed = render_bytes
($total / $delay, 1);
1080 my $downtime = $stat->{downtime
} || 0;
1081 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1085 if ($status eq 'failed' || $status eq 'cancelled') {
1086 $self->log('info', "migration status error: $status");
1090 if ($status ne 'active') {
1091 $self->log('info', "migration status: $status");
1095 if ($memstat->{transferred
} ne $last_mem_transferred) {
1096 my $trans = $memstat->{transferred
} || 0;
1097 my $rem = $memstat->{remaining
} || 0;
1098 my $total = $memstat->{total
} || 0;
1099 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1100 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
1102 # reduce sleep if remainig memory is lower than the average transfer speed
1103 $usleep = 100_000 if $avglstat && $rem < $avglstat;
1105 # also reduce loggin if we poll more frequent
1106 my $should_log = $usleep > 100_000 ?
1 : ($i % 10) == 0;
1108 my $total_h = render_bytes
($total, 1);
1109 my $transferred_h = render_bytes
($trans, 1);
1110 my $speed_h = render_bytes
($speed, 1);
1112 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1114 if ($dirty_rate > $speed) {
1115 my $dirty_rate_h = render_bytes
($dirty_rate, 1);
1116 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1119 $self->log('info', "migration $status, $progress") if $should_log;
1121 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1122 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1123 if ($xbzrlebytes || $xbzrlepages) {
1124 my $bytes_h = render_bytes
($xbzrlebytes, 1);
1126 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1128 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1129 if $xbzrle->{'cache-miss-rate'};
1131 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow
};
1133 $self->log('info', "xbzrle: $msg") if $should_log;
1136 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
1141 if ($downtimecounter > 5) {
1142 $downtimecounter = 0;
1143 $migrate_downtime *= 2;
1144 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1146 # migrate-set-parameters does not touch values not
1147 # specified, so this only changes downtime-limit
1148 mon_cmd
($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1150 $self->log('info', "migrate-set-parameters error: $@") if $@;
1154 $last_mem_transferred = $memstat->{transferred
};
1157 if ($self->{storage_migration
}) {
1158 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1159 # to avoid it trying to re-establish it. We are in blockjob ready state,
1160 # thus, this command changes to it to blockjob complete (see qapi docs)
1161 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}, 'cancel'); };
1163 die "Failed to complete storage migration: $err\n";
1168 sub phase2_cleanup
{
1169 my ($self, $vmid, $err) = @_;
1171 return if !$self->{errors
};
1172 $self->{phase2errors
} = 1;
1174 $self->log('info', "aborting phase 2 - cleanup resources");
1176 $self->log('info', "migrate_cancel");
1178 mon_cmd
($vmid, "migrate_cancel");
1180 $self->log('info', "migrate_cancel error: $@") if $@;
1182 my $conf = $self->{vmconf
};
1183 delete $conf->{lock};
1184 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
1186 $self->log('err', $err);
1189 # cleanup ressources on target host
1190 if ($self->{storage_migration
}) {
1191 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
1193 $self->log('err', $err);
1197 eval { $self->cleanup_bitmaps() };
1199 $self->log('err', $err);
1202 my $nodename = PVE
::INotify
::nodename
();
1204 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1205 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1207 $self->log('err', $err);
1208 $self->{errors
} = 1;
1211 # cleanup after stopping, otherwise disks might be in-use by target VM!
1212 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
1214 $self->log('err', $err);
1218 if ($self->{tunnel
}) {
1219 eval { finish_tunnel
($self, $self->{tunnel
}); };
1221 $self->log('err', $err);
1222 $self->{errors
} = 1;
1228 my ($self, $vmid) = @_;
1233 sub phase3_cleanup
{
1234 my ($self, $vmid, $err) = @_;
1236 my $conf = $self->{vmconf
};
1237 return if $self->{phase2errors
};
1239 my $tunnel = $self->{tunnel
};
1241 if ($self->{volume_map
}) {
1242 my $target_drives = $self->{target_drive
};
1244 # FIXME: for NBD storage migration we now only update the volid, and
1245 # not the full drivestr from the target node. Workaround that until we
1246 # got some real rescan, to avoid things like wrong format in the drive
1247 delete $conf->{$_} for keys %$target_drives;
1248 PVE
::QemuConfig-
>update_volume_ids($conf, $self->{volume_map
});
1250 for my $drive (keys %$target_drives) {
1251 $conf->{$drive} = $target_drives->{$drive}->{drivestr
};
1253 PVE
::QemuConfig-
>write_config($vmid, $conf);
1256 # transfer replication state before move config
1257 $self->transfer_replication_state() if $self->{is_replicated
};
1258 PVE
::QemuConfig-
>move_config_to_node($vmid, $self->{node
});
1259 $self->switch_replication_job_target() if $self->{is_replicated
};
1261 if ($self->{livemigration
}) {
1262 if ($self->{stopnbd
}) {
1263 $self->log('info', "stopping NBD storage migration server on target.");
1264 # stop nbd server on remote vm - requirement for resume since 2.9
1265 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
1267 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1269 $self->log('err', $err);
1270 $self->{errors
} = 1;
1274 # config moved and nbd server stopped - now we can resume vm on target
1275 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
1277 $self->write_tunnel($tunnel, 30, "resume $vmid");
1280 $self->log('err', $err);
1281 $self->{errors
} = 1;
1284 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1287 $self->log('err', $line);
1289 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1291 $self->log('err', $err);
1292 $self->{errors
} = 1;
1296 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
1297 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1298 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1302 # close tunnel on successful migration, on error phase2_cleanup closed it
1304 eval { finish_tunnel
($self, $tunnel); };
1306 $self->log('err', $err);
1307 $self->{errors
} = 1;
1313 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1314 $self->log('info', "Waiting for spice server migration");
1316 my $res = mon_cmd
($vmid, 'query-spice');
1317 last if int($res->{'migrated'}) == 1;
1318 last if $timer > 50;
1325 # always stop local VM
1326 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1328 $self->log('err', "stopping vm failed - $err");
1329 $self->{errors
} = 1;
1332 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1334 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1335 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1338 $self->log('err', $err);
1339 $self->{errors
} = 1;
1342 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
1344 # destroy local copies
1345 foreach my $volid (@not_replicated_volumes) {
1346 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1348 $self->log('err', "removing local copy of '$volid' failed - $err");
1349 $self->{errors
} = 1;
1350 last if $err =~ /^interrupted by signal$/;
1354 # clear migrate lock
1355 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1356 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1360 my ($self, $vmid) = @_;
1365 sub round_powerof2
{
1366 return 1 if $_[0] < 2;
1367 return 2 << int(log($_[0]-1)/log(2));