1 package PVE
::QemuMigrate
;
8 use Time
::HiRes
qw( usleep );
11 use PVE
::Format
qw(render_bytes);
12 use PVE
::GuestHelpers
qw(safe_boolean_ne safe_string_ne);
14 use PVE
::RPCEnvironment
;
16 use PVE
::ReplicationConfig
;
17 use PVE
::ReplicationState
;
19 use PVE
::StorageTunnel
;
24 use PVE
::QemuServer
::CPUConfig
;
25 use PVE
::QemuServer
::Drive
;
26 use PVE
::QemuServer
::Helpers
qw(min_version);
27 use PVE
::QemuServer
::Machine
;
28 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
29 use PVE
::QemuServer
::Memory
qw(get_current_memory);
32 use PVE
::AbstractMigrate
;
33 use base
qw(PVE::AbstractMigrate);
35 # compared against remote end's minimum version
36 our $WS_TUNNEL_VERSION = 2;
39 my ($self, $ssh_forward_info) = @_;
41 my $cmd = ['/usr/sbin/qm', 'mtunnel'];
43 my ($level, $msg) = @_;
44 $self->log($level, $msg);
47 return PVE
::Tunnel
::fork_ssh_tunnel
($self->{rem_ssh
}, $cmd, $ssh_forward_info, $log);
50 sub fork_websocket_tunnel
{
51 my ($self, $storages, $bridges) = @_;
53 my $remote = $self->{opts
}->{remote
};
54 my $conn = $remote->{conn
};
57 my ($level, $msg) = @_;
58 $self->log($level, $msg);
61 my $websocket_url = "https://$conn->{host}:$conn->{port}/api2/json/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnelwebsocket";
62 my $url = "/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnel";
65 url
=> $websocket_url,
68 my $storage_list = join(',', keys %$storages);
69 my $bridge_list = join(',', keys %$bridges);
72 storages
=> $storage_list,
73 bridges
=> $bridge_list,
76 return PVE
::Tunnel
::fork_websocket_tunnel
($conn, $url, $req_params, $tunnel_params, $log);
80 # proto: unix (secure) or tcp (insecure/legacy compat)
81 # addr: IP or UNIX socket path
82 # port: optional TCP port
83 # unix_sockets: additional UNIX socket paths to forward
84 sub start_remote_tunnel
{
85 my ($self, $tunnel_info) = @_;
87 my $nodename = PVE
::INotify
::nodename
();
88 my $migration_type = $self->{opts
}->{migration_type
};
90 if ($migration_type eq 'secure') {
92 if ($tunnel_info->{proto
} eq 'unix') {
93 my $ssh_forward_info = [];
95 my $unix_sockets = [ keys %{$tunnel_info->{unix_sockets
}} ];
96 push @$unix_sockets, $tunnel_info->{addr
};
97 for my $sock (@$unix_sockets) {
98 push @$ssh_forward_info, "$sock:$sock";
102 $self->{tunnel
} = $self->fork_tunnel($ssh_forward_info);
104 my $unix_socket_try = 0; # wait for the socket to become ready
105 while ($unix_socket_try <= 100) {
108 foreach my $sock (@$unix_sockets) {
114 if ($available == @$unix_sockets) {
120 if ($unix_socket_try > 100) {
122 PVE
::Tunnel
::finish_tunnel
($self->{tunnel
});
123 die "Timeout, migration socket $tunnel_info->{addr} did not get ready";
125 $self->{tunnel
}->{unix_sockets
} = $unix_sockets if (@$unix_sockets);
127 } elsif ($tunnel_info->{proto
} eq 'tcp') {
128 my $ssh_forward_info = [];
129 if ($tunnel_info->{addr
} eq "localhost") {
130 # for backwards compatibility with older qemu-server versions
131 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
132 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
133 push @$ssh_forward_info, "$lport:localhost:$tunnel_info->{port}";
136 $self->{tunnel
} = $self->fork_tunnel($ssh_forward_info);
139 die "unsupported protocol in migration URI: $tunnel_info->{proto}\n";
142 #fork tunnel for insecure migration, to send faster commands like resume
143 $self->{tunnel
} = $self->fork_tunnel();
148 my ($self, $vmid, $code, @param) = @_;
150 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
153 sub target_storage_check_available
{
154 my ($self, $storecfg, $targetsid, $volid) = @_;
156 if (!$self->{opts
}->{remote
}) {
157 # check if storage is available on target node
158 my $target_scfg = PVE
::Storage
::storage_check_enabled
(
163 my ($vtype) = PVE
::Storage
::parse_volname
($storecfg, $volid);
164 die "$volid: content type '$vtype' is not available on storage '$targetsid'\n"
165 if !$target_scfg->{content
}->{$vtype};
170 my ($self, $vmid) = @_;
172 my $online = $self->{opts
}->{online
};
174 my $storecfg = $self->{storecfg
} = PVE
::Storage
::config
();
177 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
179 my $version = PVE
::QemuServer
::Helpers
::get_node_pvecfg_version
($self->{node
});
180 my $cloudinit_config = $conf->{cloudinit
};
183 PVE
::QemuConfig-
>has_cloudinit($conf) && defined($cloudinit_config)
184 && scalar(keys %$cloudinit_config) > 0
185 && !PVE
::QemuServer
::Helpers
::pvecfg_min_version
($version, 7, 2, 13)
187 die "target node is too old (manager <= 7.2-13) and doesn't support new cloudinit section\n";
190 my $repl_conf = PVE
::ReplicationConfig-
>new();
191 $self->{replication_jobcfg
} = $repl_conf->find_local_replication_job($vmid, $self->{node
});
192 $self->{is_replicated
} = $repl_conf->check_for_existing_jobs($vmid, 1);
194 if ($self->{replication_jobcfg
} && defined($self->{replication_jobcfg
}->{remove_job
})) {
195 die "refusing to migrate replicated VM whose replication job is marked for removal\n";
198 PVE
::QemuConfig-
>check_lock($conf);
201 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
202 die "can't migrate running VM without --online\n" if !$online;
205 if ($self->{is_replicated
} && !$self->{replication_jobcfg
}) {
206 if ($self->{opts
}->{force
}) {
207 $self->log('warn', "WARNING: Node '$self->{node}' is not a replication target. Existing " .
208 "replication jobs will fail after migration!\n");
210 die "Cannot live-migrate replicated VM to node '$self->{node}' - not a replication " .
211 "target. Use 'force' to override.\n";
215 $self->{forcemachine
} = PVE
::QemuServer
::Machine
::qemu_machine_pxe
($vmid, $conf);
217 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
218 # Since the parameter itself contains no reference to a custom model,
219 # this makes migration independent of changes to "cpu-models.conf".
221 my $cpuconf = PVE
::JSONSchema
::parse_property_string
('pve-cpu-conf', $conf->{cpu
});
222 if ($cpuconf && PVE
::QemuServer
::CPUConfig
::is_custom_model
($cpuconf->{cputype
})) {
223 $self->{forcecpu
} = PVE
::QemuServer
::CPUConfig
::get_cpu_from_running_vm
($pid);
227 # Do not treat a suspended VM as paused, as it might wake up
228 # during migration and remain paused after migration finishes.
229 $self->{vm_was_paused
} = 1 if PVE
::QemuServer
::vm_is_paused
($vmid, 0);
232 my ($loc_res, $mapped_res, $missing_mappings_by_node) = PVE
::QemuServer
::check_local_resources
($conf, 1);
233 my $blocking_resources = [];
234 for my $res ($loc_res->@*) {
235 if (!grep($res, $mapped_res->@*)) {
236 push $blocking_resources->@*, $res;
239 if (scalar($blocking_resources->@*)) {
240 if ($self->{running
} || !$self->{opts
}->{force
}) {
241 die "can't migrate VM which uses local devices: " . join(", ", $blocking_resources->@*) . "\n";
243 $self->log('info', "migrating VM which uses local devices");
247 if (scalar($mapped_res->@*)) {
248 my $missing_mappings = $missing_mappings_by_node->{$self->{node
}};
250 die "can't migrate running VM which uses mapped devices: " . join(", ", $mapped_res->@*) . "\n";
251 } elsif (scalar($missing_mappings->@*)) {
252 die "can't migrate to '$self->{node}': missing mapped devices " . join(", ", $missing_mappings->@*) . "\n";
254 $self->log('info', "migrating VM which uses mapped local devices");
258 my $vga = PVE
::QemuServer
::parse_vga
($conf->{vga
});
259 if ($running && $vga->{'clipboard'} && $vga->{'clipboard'} eq 'vnc') {
260 die "VMs with 'clipboard' set to 'vnc' are not live migratable!\n";
263 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
266 foreach my $volid (@$vollist) {
267 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
269 # check if storage is available on source node
270 my $scfg = PVE
::Storage
::storage_check_enabled
($storecfg, $sid);
272 my $targetsid = $sid;
273 # NOTE: local ignores shared mappings, remote maps them
274 if (!$scfg->{shared
} || $self->{opts
}->{remote
}) {
275 $targetsid = PVE
::JSONSchema
::map_id
($self->{opts
}->{storagemap
}, $sid);
278 $storages->{$targetsid} = 1;
280 $self->target_storage_check_available($storecfg, $targetsid, $volid);
282 if ($scfg->{shared
}) {
283 # PVE::Storage::activate_storage checks this for non-shared storages
284 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
285 warn "Used shared storage '$sid' is not online on source node!\n"
286 if !$plugin->check_connection($sid, $scfg);
290 if ($self->{opts
}->{remote
}) {
291 # test & establish websocket connection
292 my $bridges = map_bridges
($conf, $self->{opts
}->{bridgemap
}, 1);
293 my $tunnel = $self->fork_websocket_tunnel($storages, $bridges);
294 my $min_version = $tunnel->{version
} - $tunnel->{age
};
295 $self->log('info', "local WS tunnel version: $WS_TUNNEL_VERSION");
296 $self->log('info', "remote WS tunnel version: $tunnel->{version}");
297 $self->log('info', "minimum required WS tunnel version: $min_version");
298 die "Remote tunnel endpoint not compatible, upgrade required\n"
299 if $WS_TUNNEL_VERSION < $min_version;
300 die "Remote tunnel endpoint too old, upgrade required\n"
301 if $WS_TUNNEL_VERSION > $tunnel->{version
};
303 print "websocket tunnel started\n";
304 $self->{tunnel
} = $tunnel;
306 # test ssh connection
307 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
308 eval { $self->cmd_quiet($cmd); };
309 die "Can't connect to destination address using public key\n" if $@;
315 sub scan_local_volumes
{
316 my ($self, $vmid) = @_;
318 my $conf = $self->{vmconf
};
320 # local volumes which have been copied
321 # and their old_id => new_id pairs
322 $self->{volume_map
} = {};
323 $self->{local_volumes
} = {};
325 my $storecfg = $self->{storecfg
};
327 # found local volumes and their origin
328 my $local_volumes = $self->{local_volumes
};
329 my $local_volumes_errors = {};
330 my $other_errors = [];
332 my $path_to_volid = {};
334 my $log_error = sub {
335 my ($msg, $volid) = @_;
337 if (defined($volid)) {
338 $local_volumes_errors->{$volid} = $msg;
340 push @$other_errors, $msg;
345 my $replicatable_volumes = !$self->{replication_jobcfg
} ?
{}
346 : PVE
::QemuConfig-
>get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
347 foreach my $volid (keys %{$replicatable_volumes}) {
348 $local_volumes->{$volid}->{replicated
} = 1;
351 my $test_volid = sub {
352 my ($volid, $attr) = @_;
354 if ($volid =~ m
|^/|) {
355 return if $attr->{shared
};
356 $local_volumes->{$volid}->{ref} = 'config';
357 die "local file/device\n";
360 my $snaprefs = $attr->{referenced_in_snapshot
};
362 if ($attr->{cdrom
}) {
363 if ($volid eq 'cdrom') {
364 my $msg = "can't migrate local cdrom drive";
365 if (defined($snaprefs) && !$attr->{is_attached
}) {
366 my $snapnames = join(', ', sort keys %$snaprefs);
367 $msg .= " (referenced in snapshot - $snapnames)";
369 &$log_error("$msg\n");
372 return if $volid eq 'none';
375 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
377 # check if storage is available on both nodes
378 my $scfg = PVE
::Storage
::storage_check_enabled
($storecfg, $sid);
380 my $targetsid = $sid;
381 # NOTE: local ignores shared mappings, remote maps them
382 if (!$scfg->{shared
} || $self->{opts
}->{remote
}) {
383 $targetsid = PVE
::JSONSchema
::map_id
($self->{opts
}->{storagemap
}, $sid);
386 $self->target_storage_check_available($storecfg, $targetsid, $volid);
387 return if $scfg->{shared
} && !$self->{opts
}->{remote
};
389 $local_volumes->{$volid}->{ref} = 'pending' if $attr->{referenced_in_pending
};
390 $local_volumes->{$volid}->{ref} = 'snapshot' if $attr->{referenced_in_snapshot
};
391 $local_volumes->{$volid}->{ref} = 'unused' if $attr->{is_unused
};
392 $local_volumes->{$volid}->{ref} = 'attached' if $attr->{is_attached
};
393 $local_volumes->{$volid}->{ref} = 'generated' if $attr->{is_tpmstate
};
395 $local_volumes->{$volid}->{bwlimit
} = $self->get_bwlimit($sid, $targetsid);
396 $local_volumes->{$volid}->{targetsid
} = $targetsid;
398 $local_volumes->{$volid}->@{qw(size format)} = PVE
::Storage
::volume_size_info
($storecfg, $volid);
400 $local_volumes->{$volid}->{is_vmstate
} = $attr->{is_vmstate
} ?
1 : 0;
402 $local_volumes->{$volid}->{drivename
} = $attr->{drivename
}
403 if $attr->{drivename
};
405 # If with_snapshots is not set for storage migrate, it tries to use
406 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
407 # back to qcow2 is currently not possible.
408 $local_volumes->{$volid}->{snapshots
} = ($local_volumes->{$volid}->{format
} =~ /^(?:qcow2|vmdk)$/);
410 if ($attr->{cdrom
}) {
411 if ($volid =~ /vm-\d+-cloudinit/) {
412 $local_volumes->{$volid}->{ref} = 'generated';
415 die "local cdrom image\n";
418 my ($path, $owner) = PVE
::Storage
::path
($storecfg, $volid);
420 die "owned by other VM (owner = VM $owner)\n"
421 if !$owner || ($owner != $vmid);
423 $path_to_volid->{$path}->{$volid} = 1;
425 return if $attr->{is_vmstate
};
427 if (defined($snaprefs)) {
428 $local_volumes->{$volid}->{snapshots
} = 1;
430 # we cannot migrate shapshots on local storage
431 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
433 die "online storage migration not possible if non-replicated snapshot exists\n"
434 if $self->{running
} && !$local_volumes->{$volid}->{replicated
};
436 die "remote migration with snapshots not supported yet\n" if $self->{opts
}->{remote
};
438 if (!($scfg->{type
} eq 'zfspool'
439 || ($scfg->{type
} eq 'btrfs' && $local_volumes->{$volid}->{format
} eq 'raw')
440 || $local_volumes->{$volid}->{format
} eq 'qcow2'
442 die "non-migratable snapshot exists\n";
446 die "referenced by linked clone(s)\n"
447 if PVE
::Storage
::volume_is_base_and_used
($storecfg, $volid);
450 PVE
::QemuServer
::foreach_volid
($conf, sub {
451 my ($volid, $attr) = @_;
452 eval { $test_volid->($volid, $attr); };
454 &$log_error($err, $volid);
458 for my $path (keys %$path_to_volid) {
459 my @volids = keys $path_to_volid->{$path}->%*;
460 die "detected not supported aliased volumes: '" . join("', '", @volids) . "'\n"
461 if (scalar(@volids) > 1);
464 foreach my $vol (sort keys %$local_volumes) {
465 my $type = $replicatable_volumes->{$vol} ?
'local, replicated' : 'local';
466 my $ref = $local_volumes->{$vol}->{ref};
467 if ($ref eq 'attached') {
468 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
469 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
470 $self->log('info', "found $type disk '$vol' (attached)\n");
471 } elsif ($ref eq 'unused') {
472 $self->log('info', "found $type disk '$vol' (unused)\n");
473 } elsif ($ref eq 'snapshot') {
474 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
475 } elsif ($ref eq 'pending') {
476 $self->log('info', "found $type disk '$vol' (pending change)\n");
477 } elsif ($ref eq 'generated') {
478 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
480 $self->log('info', "found $type disk '$vol'\n");
484 foreach my $vol (sort keys %$local_volumes_errors) {
485 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
487 foreach my $err (@$other_errors) {
488 $self->log('warn', "$err");
492 die "can't migrate VM - check log\n";
495 # additional checks for local storage
496 foreach my $volid (keys %$local_volumes) {
497 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
498 my $scfg = PVE
::Storage
::storage_config
($storecfg, $sid);
500 my $migratable = $scfg->{type
} =~ /^(?:dir|btrfs|zfspool|lvmthin|lvm)$/;
502 # TODO: what is this even here for?
503 $migratable = 1 if $self->{opts
}->{remote
};
505 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
508 # image is a linked clone on local storage, se we can't migrate.
509 if (my $basename = (PVE
::Storage
::parse_volname
($storecfg, $volid))[3]) {
510 die "can't migrate '$volid' as it's a clone of '$basename'";
514 foreach my $volid (sort keys %$local_volumes) {
515 my $ref = $local_volumes->{$volid}->{ref};
516 if ($self->{running
} && $ref eq 'attached') {
517 $local_volumes->{$volid}->{migration_mode
} = 'online';
518 } elsif ($self->{running
} && $ref eq 'generated') {
519 # offline migrate the cloud-init ISO and don't regenerate on VM start
521 # tpmstate will also be offline migrated first, and in case of
522 # live migration then updated by QEMU/swtpm if necessary
523 $local_volumes->{$volid}->{migration_mode
} = 'offline';
525 $local_volumes->{$volid}->{migration_mode
} = 'offline';
529 die "Problem found while scanning volumes - $@" if $@;
532 sub handle_replication
{
533 my ($self, $vmid) = @_;
535 my $conf = $self->{vmconf
};
536 my $local_volumes = $self->{local_volumes
};
538 return if !$self->{replication_jobcfg
};
540 die "can't migrate VM with replicated volumes to remote cluster/node\n"
541 if $self->{opts
}->{remote
};
543 if ($self->{running
}) {
545 my $version = PVE
::QemuServer
::kvm_user_version
();
546 if (!min_version
($version, 4, 2)) {
547 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
550 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
551 foreach my $volid (@live_replicatable_volumes) {
552 my $drive = $local_volumes->{$volid}->{drivename
};
553 die "internal error - no drive for '$volid'\n" if !defined($drive);
555 my $bitmap = "repl_$drive";
557 # start tracking before replication to get full delta + a few duplicates
558 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
559 mon_cmd
($vmid, 'block-dirty-bitmap-add', node
=> "drive-$drive", name
=> $bitmap);
561 # other info comes from target node in phase 2
562 $self->{target_drive
}->{$drive}->{bitmap
} = $bitmap;
565 $self->log('info', "replicating disk images");
567 my $start_time = time();
568 my $logfunc = sub { $self->log('info', shift) };
569 my $actual_replicated_volumes = PVE
::Replication
::run_replication
(
570 'PVE::QemuConfig', $self->{replication_jobcfg
}, $start_time, $start_time, $logfunc);
573 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
574 foreach my $volid (@replicated_volumes) {
575 die "expected volume '$volid' to get replicated, but it wasn't\n"
576 if !$actual_replicated_volumes->{$volid};
580 sub config_update_local_disksizes
{
583 my $conf = $self->{vmconf
};
584 my $local_volumes = $self->{local_volumes
};
586 PVE
::QemuConfig-
>foreach_volume($conf, sub {
587 my ($key, $drive) = @_;
588 # skip special disks, will be handled later
589 return if $key eq 'efidisk0';
590 return if $key eq 'tpmstate0';
592 my $volid = $drive->{file
};
593 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
595 my ($updated, $msg) = PVE
::QemuServer
::Drive
::update_disksize
($drive, $local_volumes->{$volid}->{size
});
596 if (defined($updated)) {
597 $conf->{$key} = PVE
::QemuServer
::print_drive
($updated);
598 $self->log('info', "drive '$key': $msg");
602 # we want to set the efidisk size in the config to the size of the
603 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
604 if (defined($conf->{efidisk0
})) {
605 PVE
::QemuServer
::update_efidisk_size
($conf);
608 # TPM state might have an irregular filesize, to avoid problems on transfer
609 # we always assume the static size of 4M to allocate on the target
610 if (defined($conf->{tpmstate0
})) {
611 PVE
::QemuServer
::update_tpmstate_size
($conf);
615 sub filter_local_volumes
{
616 my ($self, $migration_mode, $replicated) = @_;
618 my $volumes = $self->{local_volumes
};
621 foreach my $volid (sort keys %{$volumes}) {
622 next if defined($migration_mode) && safe_string_ne
($volumes->{$volid}->{migration_mode
}, $migration_mode);
623 next if defined($replicated) && safe_boolean_ne
($volumes->{$volid}->{replicated
}, $replicated);
624 push @filtered_volids, $volid;
627 return @filtered_volids;
630 sub sync_offline_local_volumes
{
633 my $local_volumes = $self->{local_volumes
};
634 my @volids = $self->filter_local_volumes('offline', 0);
636 my $storecfg = $self->{storecfg
};
637 my $opts = $self->{opts
};
639 $self->log('info', "copying local disk images") if scalar(@volids);
641 foreach my $volid (@volids) {
644 my $opts = $self->{opts
};
645 if ($opts->{remote
}) {
647 my ($level, $msg) = @_;
648 $self->log($level, $msg);
651 $new_volid = PVE
::StorageTunnel
::storage_migrate
(
656 $opts->{remote
}->{vmid
},
657 $local_volumes->{$volid},
661 my $targetsid = $local_volumes->{$volid}->{targetsid
};
663 my $bwlimit = $local_volumes->{$volid}->{bwlimit
};
664 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
666 my $storage_migrate_opts = {
667 'ratelimit_bps' => $bwlimit,
668 'insecure' => $opts->{migration_type
} eq 'insecure',
669 'with_snapshots' => $local_volumes->{$volid}->{snapshots
},
670 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate
},
673 my $logfunc = sub { $self->log('info', $_[0]); };
675 PVE
::Storage
::storage_migrate
(
680 $storage_migrate_opts,
685 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
689 $self->{volume_map
}->{$volid} = $new_volid;
690 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
692 eval { PVE
::Storage
::deactivate_volumes
($storecfg, [$volid]); };
694 $self->log('warn', $err);
699 sub cleanup_remotedisks
{
702 if ($self->{opts
}->{remote
}) {
703 PVE
::Tunnel
::finish_tunnel
($self->{tunnel
}, 1);
704 delete $self->{tunnel
};
708 my $local_volumes = $self->{local_volumes
};
710 foreach my $volid (values %{$self->{volume_map
}}) {
711 # don't clean up replicated disks!
712 next if $local_volumes->{$volid}->{replicated
};
714 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
716 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
718 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
720 $self->log('err', $err);
726 sub cleanup_bitmaps
{
728 foreach my $drive (keys %{$self->{target_drive
}}) {
729 my $bitmap = $self->{target_drive
}->{$drive}->{bitmap
};
731 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
732 mon_cmd
($self->{vmid
}, 'block-dirty-bitmap-remove', node
=> "drive-$drive", name
=> $bitmap);
737 my ($self, $vmid) = @_;
739 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
741 my $conf = $self->{vmconf
};
743 # set migrate lock in config file
744 $conf->{lock} = 'migrate';
745 PVE
::QemuConfig-
>write_config($vmid, $conf);
747 $self->scan_local_volumes($vmid);
749 # fix disk sizes to match their actual size and write changes,
750 # so that the target allocates the correct volumes
751 $self->config_update_local_disksizes();
752 PVE
::QemuConfig-
>write_config($vmid, $conf);
754 $self->handle_replication($vmid);
756 $self->sync_offline_local_volumes();
757 $self->phase1_remote($vmid) if $self->{opts
}->{remote
};
761 my ($conf, $map, $scan_only) = @_;
765 foreach my $opt (keys %$conf) {
766 next if $opt !~ m/^net\d+$/;
768 next if !$conf->{$opt};
769 my $d = PVE
::QemuServer
::parse_net
($conf->{$opt});
770 next if !$d || !$d->{bridge
};
772 my $target_bridge = PVE
::JSONSchema
::map_id
($map, $d->{bridge
});
773 $bridges->{$target_bridge}->{$opt} = $d->{bridge
};
777 $d->{bridge
} = $target_bridge;
778 $conf->{$opt} = PVE
::QemuServer
::print_net
($d);
785 my ($self, $vmid) = @_;
787 my $remote_conf = PVE
::QemuConfig-
>load_config($vmid);
788 PVE
::QemuConfig-
>update_volume_ids($remote_conf, $self->{volume_map
});
790 my $bridges = map_bridges
($remote_conf, $self->{opts
}->{bridgemap
});
791 for my $target (keys $bridges->%*) {
792 for my $nic (keys $bridges->{$target}->%*) {
793 $self->log('info', "mapped: $nic from $bridges->{$target}->{$nic} to $target");
797 my @online_local_volumes = $self->filter_local_volumes('online');
799 my $storage_map = $self->{opts
}->{storagemap
};
801 PVE
::QemuConfig-
>foreach_volume($remote_conf, sub {
802 my ($ds, $drive) = @_;
805 return if PVE
::QemuServer
::drive_is_cdrom
($drive);
807 my $volid = $drive->{file
};
810 return if !grep { $_ eq $volid} @online_local_volumes;
812 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
813 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
814 my $source_format = PVE
::QemuServer
::qemu_img_format
($scfg, $volname);
816 # set by target cluster
817 my $oldvolid = delete $drive->{file
};
818 delete $drive->{format
};
820 my $targetsid = PVE
::JSONSchema
::map_id
($storage_map, $storeid);
823 format
=> $source_format,
824 storage
=> $targetsid,
828 $self->log('info', "Allocating volume for drive '$ds' on remote storage '$targetsid'..");
829 my $res = PVE
::Tunnel
::write_tunnel
($self->{tunnel
}, 600, 'disk', $params);
831 $self->log('info', "volume '$oldvolid' is '$res->{volid}' on the target\n");
832 $remote_conf->{$ds} = $res->{drivestr
};
833 $self->{nbd
}->{$ds} = $res;
836 my $conf_str = PVE
::QemuServer
::write_vm_config
("remote", $remote_conf);
838 # TODO expose in PVE::Firewall?
839 my $vm_fw_conf_path = "/etc/pve/firewall/$vmid.fw";
841 $fw_conf_str = PVE
::Tools
::file_get_contents
($vm_fw_conf_path)
842 if -e
$vm_fw_conf_path;
845 'firewall-config' => $fw_conf_str,
848 PVE
::Tunnel
::write_tunnel
($self->{tunnel
}, 10, 'config', $params);
852 my ($self, $vmid, $err) = @_;
854 $self->log('info', "aborting phase 1 - cleanup resources");
856 my $conf = $self->{vmconf
};
857 delete $conf->{lock};
858 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
860 $self->log('err', $err);
863 eval { $self->cleanup_remotedisks() };
865 $self->log('err', $err);
868 eval { $self->cleanup_bitmaps() };
870 $self->log('err', $err);
874 sub phase2_start_local_cluster
{
875 my ($self, $vmid, $params) = @_;
877 my $conf = $self->{vmconf
};
878 my $local_volumes = $self->{local_volumes
};
879 my @online_local_volumes = $self->filter_local_volumes('online');
881 my $start = $params->{start_params
};
882 my $migrate = $params->{migrate_opts
};
884 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
886 my $tunnel_info = {};
888 ## start on remote node
889 my $cmd = [@{$self->{rem_ssh
}}];
891 push @$cmd, 'qm', 'start', $vmid;
893 if ($start->{skiplock
}) {
894 push @$cmd, '--skiplock';
897 push @$cmd, '--migratedfrom', $migrate->{migratedfrom
};
899 push @$cmd, '--migration_type', $migrate->{type
};
901 push @$cmd, '--migration_network', $migrate->{network
}
902 if $migrate->{network
};
904 push @$cmd, '--stateuri', $start->{statefile
};
906 if ($start->{forcemachine
}) {
907 push @$cmd, '--machine', $start->{forcemachine
};
910 if ($start->{forcecpu
}) {
911 push @$cmd, '--force-cpu', $start->{forcecpu
};
914 if ($self->{storage_migration
}) {
915 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
919 my $input = "nbd_protocol_version: $migrate->{nbd_proto_version}\n";
921 my @offline_local_volumes = $self->filter_local_volumes('offline');
922 for my $volid (@offline_local_volumes) {
923 my $drivename = $local_volumes->{$volid}->{drivename
};
924 next if !$drivename || !$conf->{$drivename};
926 my $new_volid = $self->{volume_map
}->{$volid};
927 next if !$new_volid || $volid eq $new_volid;
929 # FIXME PVE 8.x only use offline_volume variant once all targets can handle it
930 if ($drivename eq 'tpmstate0') {
931 $input .= "$drivename: $new_volid\n"
933 $input .= "offline_volume: $drivename: $new_volid\n"
937 $input .= "spice_ticket: $migrate->{spice_ticket}\n" if $migrate->{spice_ticket
};
939 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
940 foreach my $volid (@online_replicated_volumes) {
941 $input .= "replicated_volume: $volid\n";
944 my $handle_storage_migration_listens = sub {
945 my ($drive_key, $drivestr, $nbd_uri) = @_;
947 $self->{stopnbd
} = 1;
948 $self->{target_drive
}->{$drive_key}->{drivestr
} = $drivestr;
949 $self->{target_drive
}->{$drive_key}->{nbd_uri
} = $nbd_uri;
951 my $source_drive = PVE
::QemuServer
::parse_drive
($drive_key, $conf->{$drive_key});
952 my $target_drive = PVE
::QemuServer
::parse_drive
($drive_key, $drivestr);
953 my $source_volid = $source_drive->{file
};
954 my $target_volid = $target_drive->{file
};
956 $self->{volume_map
}->{$source_volid} = $target_volid;
957 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
960 my $target_replicated_volumes = {};
962 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
963 # instead we pipe it through STDIN
964 my $exitcode = PVE
::Tools
::run_command
($cmd, input
=> $input, outfunc
=> sub {
967 if ($line =~ m/^migration listens on (tcp):(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
968 $tunnel_info->{addr
} = $2;
969 $tunnel_info->{port
} = int($3);
970 $tunnel_info->{proto
} = $1;
972 elsif ($line =~ m!^migration listens on (unix):(/run/qemu-server/(\d+)\.migrate)$!) {
973 $tunnel_info->{addr
} = $2;
974 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $3;
975 $tunnel_info->{proto
} = $1;
977 elsif ($line =~ m/^migration listens on port (\d+)$/) {
978 $tunnel_info->{addr
} = "localhost";
979 $tunnel_info->{port
} = int($1);
980 $tunnel_info->{proto
} = "tcp";
982 elsif ($line =~ m/^spice listens on port (\d+)$/) {
983 $spice_port = int($1);
985 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
987 my $nbd_uri = "nbd:$1:$2:exportname=$3";
988 my $targetdrive = $3;
989 $targetdrive =~ s/drive-//g;
991 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
992 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
994 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
995 my $nbd_unix_addr = $1;
996 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
997 my $targetdrive = $3;
998 $targetdrive =~ s/drive-//g;
1000 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
1001 $tunnel_info->{unix_sockets
}->{$nbd_unix_addr} = 1;
1002 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
1005 $target_replicated_volumes->{$volid} = $drive;
1006 } elsif ($line =~ m/^QEMU: (.*)$/) {
1007 $self->log('info', "[$self->{node}] $1\n");
1011 $self->log('info', "[$self->{node}] $line");
1014 die "remote command failed with exit code $exitcode\n" if $exitcode;
1016 die "unable to detect remote migration address\n" if !$tunnel_info->{addr
} || !$tunnel_info->{proto
};
1018 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
1019 die "number of replicated disks on source and target node do not match - target node too old?\n"
1022 return ($tunnel_info, $spice_port);
1025 sub phase2_start_remote_cluster
{
1026 my ($self, $vmid, $params) = @_;
1028 die "insecure migration to remote cluster not implemented\n"
1029 if $params->{migrate_opts
}->{type
} ne 'websocket';
1031 my $remote_vmid = $self->{opts
}->{remote
}->{vmid
};
1033 # like regular start but with some overhead accounted for
1034 my $memory = get_current_memory
($self->{vmconf
}->{memory
});
1035 my $timeout = PVE
::QemuServer
::Helpers
::config_aware_timeout
($self->{vmconf
}, $memory) + 10;
1037 my $res = PVE
::Tunnel
::write_tunnel
($self->{tunnel
}, $timeout, "start", $params);
1039 foreach my $drive (keys %{$res->{drives
}}) {
1040 $self->{stopnbd
} = 1;
1041 $self->{target_drive
}->{$drive}->{drivestr
} = $res->{drives
}->{$drive}->{drivestr
};
1042 my $nbd_uri = $res->{drives
}->{$drive}->{nbd_uri
};
1043 die "unexpected NBD uri for '$drive': $nbd_uri\n"
1044 if $nbd_uri !~ s!/run/qemu-server/$remote_vmid\_!/run/qemu-server/$vmid\_!;
1046 $self->{target_drive
}->{$drive}->{nbd_uri
} = $nbd_uri;
1049 return ($res->{migrate
}, $res->{spice_port
});
1053 my ($self, $vmid) = @_;
1055 my $conf = $self->{vmconf
};
1056 my $local_volumes = $self->{local_volumes
};
1058 # version > 0 for unix socket support
1059 my $nbd_protocol_version = 1;
1062 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
1063 my $res = mon_cmd
($vmid, 'query-spice');
1064 $spice_ticket = $res->{ticket
};
1067 my $migration_type = $self->{opts
}->{migration_type
};
1068 my $state_uri = $migration_type eq 'insecure' ?
'tcp' : 'unix';
1072 statefile
=> $state_uri,
1073 forcemachine
=> $self->{forcemachine
},
1074 forcecpu
=> $self->{forcecpu
},
1078 spice_ticket
=> $spice_ticket,
1079 type
=> $migration_type,
1080 network
=> $self->{opts
}->{migration_network
},
1081 storagemap
=> $self->{opts
}->{storagemap
},
1082 migratedfrom
=> PVE
::INotify
::nodename
(),
1083 nbd_proto_version
=> $nbd_protocol_version,
1084 nbd
=> $self->{nbd
},
1088 my ($tunnel_info, $spice_port);
1090 my @online_local_volumes = $self->filter_local_volumes('online');
1091 $self->{storage_migration
} = 1 if scalar(@online_local_volumes);
1093 if (my $remote = $self->{opts
}->{remote
}) {
1094 my $remote_vmid = $remote->{vmid
};
1095 $params->{migrate_opts
}->{remote_node
} = $self->{node
};
1096 ($tunnel_info, $spice_port) = $self->phase2_start_remote_cluster($vmid, $params);
1097 die "only UNIX sockets are supported for remote migration\n"
1098 if $tunnel_info->{proto
} ne 'unix';
1100 my $remote_socket = $tunnel_info->{addr
};
1101 my $local_socket = $remote_socket;
1102 $local_socket =~ s/$remote_vmid/$vmid/g;
1103 $tunnel_info->{addr
} = $local_socket;
1105 $self->log('info', "Setting up tunnel for '$local_socket'");
1106 PVE
::Tunnel
::forward_unix_socket
($self->{tunnel
}, $local_socket, $remote_socket);
1108 foreach my $remote_socket (@{$tunnel_info->{unix_sockets
}}) {
1109 my $local_socket = $remote_socket;
1110 $local_socket =~ s/$remote_vmid/$vmid/g;
1111 next if $self->{tunnel
}->{forwarded
}->{$local_socket};
1112 $self->log('info', "Setting up tunnel for '$local_socket'");
1113 PVE
::Tunnel
::forward_unix_socket
($self->{tunnel
}, $local_socket, $remote_socket);
1116 ($tunnel_info, $spice_port) = $self->phase2_start_local_cluster($vmid, $params);
1118 $self->log('info', "start remote tunnel");
1119 $self->start_remote_tunnel($tunnel_info);
1122 my $migrate_uri = "$tunnel_info->{proto}:$tunnel_info->{addr}";
1123 $migrate_uri .= ":$tunnel_info->{port}"
1124 if defined($tunnel_info->{port
});
1126 if ($self->{storage_migration
}) {
1127 $self->{storage_migration_jobs
} = {};
1128 $self->log('info', "starting storage migration");
1130 die "The number of local disks does not match between the source and the destination.\n"
1131 if (scalar(keys %{$self->{target_drive
}}) != scalar(@online_local_volumes));
1132 foreach my $drive (keys %{$self->{target_drive
}}){
1133 my $target = $self->{target_drive
}->{$drive};
1134 my $nbd_uri = $target->{nbd_uri
};
1136 my $source_drive = PVE
::QemuServer
::parse_drive
($drive, $conf->{$drive});
1137 my $source_volid = $source_drive->{file
};
1139 my $bwlimit = $self->{local_volumes
}->{$source_volid}->{bwlimit
};
1140 my $bitmap = $target->{bitmap
};
1142 $self->log('info', "$drive: start migration to $nbd_uri");
1143 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 'skip', undef, $bwlimit, $bitmap);
1147 $self->log('info', "starting online/live migration on $migrate_uri");
1148 $self->{livemigration
} = 1;
1151 my $defaults = PVE
::QemuServer
::load_defaults
();
1153 $self->log('info', "set migration capabilities");
1154 eval { PVE
::QemuServer
::set_migration_caps
($vmid) };
1157 my $qemu_migrate_params = {};
1159 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
1160 # migrate_speed parameter in qm.conf - take the lower of the two.
1161 my $bwlimit = $self->get_bwlimit();
1163 my $migrate_speed = $conf->{migrate_speed
} // 0;
1164 $migrate_speed *= 1024; # migrate_speed is in MB/s, bwlimit in KB/s
1166 if ($bwlimit && $migrate_speed) {
1167 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
1169 $migrate_speed ||= $bwlimit;
1171 $migrate_speed ||= ($defaults->{migrate_speed
} || 0) * 1024;
1173 if ($migrate_speed) {
1174 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
1175 $self->log('info', "migration speed limit: ". render_bytes
($migrate_speed, 1) ."/s");
1177 # always set migrate speed as QEMU default to 128 MiBps == 1 Gbps, use 16 GiBps == 128 Gbps
1178 $migrate_speed = (16 << 30);
1180 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
1182 my $migrate_downtime = $defaults->{migrate_downtime
};
1183 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
1184 # migrate-set-parameters expects limit in ms
1185 $migrate_downtime *= 1000;
1186 $self->log('info', "migration downtime limit: $migrate_downtime ms");
1187 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
1189 # set cachesize to 10% of the total memory
1190 my $memory = get_current_memory
($conf->{memory
});
1191 my $cachesize = int($memory * 1048576 / 10);
1192 $cachesize = round_powerof2
($cachesize);
1194 $self->log('info', "migration cachesize: " . render_bytes
($cachesize, 1));
1195 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
1197 $self->log('info', "set migration parameters");
1199 mon_cmd
($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
1201 $self->log('info', "migrate-set-parameters error: $@") if $@;
1203 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && !$self->{opts
}->{remote
}) {
1204 my $rpcenv = PVE
::RPCEnvironment
::get
();
1205 my $authuser = $rpcenv->get_user();
1207 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
1209 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
1210 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
1212 $self->log('info', "spice client_migrate_info");
1215 mon_cmd
($vmid, "client_migrate_info", protocol
=> 'spice',
1216 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
1217 'cert-subject' => $subject);
1219 $self->log('info', "client_migrate_info error: $@") if $@;
1225 $self->log('info', "start migrate command to $migrate_uri");
1227 mon_cmd
($vmid, "migrate", uri
=> $migrate_uri);
1230 $self->log('info', "migrate uri => $migrate_uri failed: $merr") if $merr;
1232 my $last_mem_transferred = 0;
1233 my $usleep = 1000000;
1236 my $lastrem = undef;
1237 my $downtimecounter = 0;
1240 my $avglstat = $last_mem_transferred ?
$last_mem_transferred / $i : 0;
1244 my $stat = eval { mon_cmd
($vmid, "query-migrate") };
1247 warn "query migrate failed: $err\n";
1248 $self->log('info', "query migrate failed: $err");
1249 if ($err_count <= 5) {
1253 die "too many query migrate failures - aborting\n";
1256 my $status = $stat->{status
};
1257 if (defined($status) && $status =~ m/^(setup)$/im) {
1262 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1264 die "unable to parse migration status '$status' - aborting\n";
1269 my $memstat = $stat->{ram
};
1271 if ($status eq 'completed') {
1272 my $delay = time() - $start;
1274 my $total = $memstat->{total
} || 0;
1275 my $avg_speed = render_bytes
($total / $delay, 1);
1276 my $downtime = $stat->{downtime
} || 0;
1277 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1281 if ($status eq 'failed' || $status eq 'cancelled') {
1282 my $message = $stat->{'error-desc'} ?
"$status - $stat->{'error-desc'}" : $status;
1283 $self->log('info', "migration status error: $message");
1287 if ($status ne 'active') {
1288 $self->log('info', "migration status: $status");
1292 if ($memstat->{transferred
} ne $last_mem_transferred) {
1293 my $trans = $memstat->{transferred
} || 0;
1294 my $rem = $memstat->{remaining
} || 0;
1295 my $total = $memstat->{total
} || 0;
1296 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1297 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
1299 # reduce sleep if remainig memory is lower than the average transfer speed
1300 $usleep = 100_000 if $avglstat && $rem < $avglstat;
1302 # also reduce loggin if we poll more frequent
1303 my $should_log = $usleep > 100_000 ?
1 : ($i % 10) == 0;
1305 my $total_h = render_bytes
($total, 1);
1306 my $transferred_h = render_bytes
($trans, 1);
1307 my $speed_h = render_bytes
($speed, 1);
1309 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1311 if ($dirty_rate > $speed) {
1312 my $dirty_rate_h = render_bytes
($dirty_rate, 1);
1313 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1316 $self->log('info', "migration $status, $progress") if $should_log;
1318 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1319 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1320 if ($xbzrlebytes || $xbzrlepages) {
1321 my $bytes_h = render_bytes
($xbzrlebytes, 1);
1323 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1325 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1326 if $xbzrle->{'cache-miss-rate'};
1328 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow
};
1330 $self->log('info', "xbzrle: $msg") if $should_log;
1333 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
1338 if ($downtimecounter > 5) {
1339 $downtimecounter = 0;
1340 $migrate_downtime *= 2;
1341 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1343 # migrate-set-parameters does not touch values not
1344 # specified, so this only changes downtime-limit
1345 mon_cmd
($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1347 $self->log('info', "migrate-set-parameters error: $@") if $@;
1351 $last_mem_transferred = $memstat->{transferred
};
1354 if ($self->{storage_migration
}) {
1355 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1356 # to avoid it trying to re-establish it. We are in blockjob ready state,
1357 # thus, this command changes to it to blockjob complete (see qapi docs)
1358 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}, 'cancel'); };
1360 die "Failed to complete storage migration: $err\n";
1365 sub phase2_cleanup
{
1366 my ($self, $vmid, $err) = @_;
1368 return if !$self->{errors
};
1369 $self->{phase2errors
} = 1;
1371 $self->log('info', "aborting phase 2 - cleanup resources");
1373 $self->log('info', "migrate_cancel");
1375 mon_cmd
($vmid, "migrate_cancel");
1377 $self->log('info', "migrate_cancel error: $@") if $@;
1379 my $vm_status = eval {
1380 mon_cmd
($vmid, 'query-status')->{status
} or die "no 'status' in result\n";
1382 $self->log('err', "query-status error: $@") if $@;
1384 # Can end up in POSTMIGRATE state if failure occurred after convergence. Try going back to
1385 # original state. Unfortunately, direct transition from POSTMIGRATE to PAUSED is not possible.
1386 if ($vm_status && $vm_status eq 'postmigrate') {
1387 if (!$self->{vm_was_paused
}) {
1388 eval { mon_cmd
($vmid, 'cont'); };
1389 $self->log('err', "resuming VM failed: $@") if $@;
1391 $self->log('err', "VM was paused, but ended in postmigrate state");
1395 my $conf = $self->{vmconf
};
1396 delete $conf->{lock};
1397 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
1399 $self->log('err', $err);
1402 # cleanup ressources on target host
1403 if ($self->{storage_migration
}) {
1404 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
1406 $self->log('err', $err);
1410 eval { $self->cleanup_bitmaps() };
1412 $self->log('err', $err);
1415 my $nodename = PVE
::INotify
::nodename
();
1417 if ($self->{tunnel
} && $self->{tunnel
}->{version
} >= 2) {
1418 PVE
::Tunnel
::write_tunnel
($self->{tunnel
}, 10, 'stop');
1420 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1421 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1423 $self->log('err', $err);
1424 $self->{errors
} = 1;
1428 # cleanup after stopping, otherwise disks might be in-use by target VM!
1429 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
1431 $self->log('err', $err);
1435 if ($self->{tunnel
}) {
1436 eval { PVE
::Tunnel
::finish_tunnel
($self->{tunnel
}); };
1438 $self->log('err', $err);
1439 $self->{errors
} = 1;
1445 my ($self, $vmid) = @_;
1450 sub phase3_cleanup
{
1451 my ($self, $vmid, $err) = @_;
1453 my $conf = $self->{vmconf
};
1454 return if $self->{phase2errors
};
1456 my $tunnel = $self->{tunnel
};
1458 my $sourcevollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1460 if ($self->{volume_map
} && !$self->{opts
}->{remote
}) {
1461 my $target_drives = $self->{target_drive
};
1463 # FIXME: for NBD storage migration we now only update the volid, and
1464 # not the full drivestr from the target node. Workaround that until we
1465 # got some real rescan, to avoid things like wrong format in the drive
1466 delete $conf->{$_} for keys %$target_drives;
1467 PVE
::QemuConfig-
>update_volume_ids($conf, $self->{volume_map
});
1469 for my $drive (keys %$target_drives) {
1470 $conf->{$drive} = $target_drives->{$drive}->{drivestr
};
1472 PVE
::QemuConfig-
>write_config($vmid, $conf);
1475 # transfer replication state before move config
1476 if (!$self->{opts
}->{remote
}) {
1477 $self->transfer_replication_state() if $self->{is_replicated
};
1478 PVE
::QemuConfig-
>move_config_to_node($vmid, $self->{node
});
1479 $self->switch_replication_job_target() if $self->{is_replicated
};
1482 if ($self->{livemigration
}) {
1483 if ($self->{stopnbd
}) {
1484 $self->log('info', "stopping NBD storage migration server on target.");
1485 # stop nbd server on remote vm - requirement for resume since 2.9
1486 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 2) {
1488 PVE
::Tunnel
::write_tunnel
($tunnel, 30, 'nbdstop');
1491 $self->log('err', $err);
1492 $self->{errors
} = 1;
1495 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
1497 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1499 $self->log('err', $err);
1500 $self->{errors
} = 1;
1505 # deletes local FDB entries if learning is disabled, they'll be re-added on target on resume
1506 PVE
::QemuServer
::del_nets_bridge_fdb
($conf, $vmid);
1508 if (!$self->{vm_was_paused
}) {
1509 # config moved and nbd server stopped - now we can resume vm on target
1510 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
1511 my $cmd = $tunnel->{version
} == 1 ?
"resume $vmid" : "resume";
1513 PVE
::Tunnel
::write_tunnel
($tunnel, 30, $cmd);
1516 $self->log('err', $err);
1517 $self->{errors
} = 1;
1520 # nocheck in case target node hasn't processed the config move/rename yet
1521 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1524 $self->log('err', $line);
1526 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1528 $self->log('err', $err);
1529 $self->{errors
} = 1;
1535 $self->{storage_migration
}
1536 && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
}
1539 if (!$self->{vm_was_paused
}) {
1540 $self->log('info', "issuing guest fstrim");
1541 if ($self->{opts
}->{remote
}) {
1542 PVE
::Tunnel
::write_tunnel
($self->{tunnel
}, 600, 'fstrim');
1544 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1545 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1547 $self->log('err', "fstrim failed - $err");
1548 $self->{errors
} = 1;
1552 $self->log('info', "skipping guest fstrim, because VM is paused");
1557 # close tunnel on successful migration, on error phase2_cleanup closed it
1558 if ($tunnel && $tunnel->{version
} == 1) {
1559 eval { PVE
::Tunnel
::finish_tunnel
($tunnel); };
1561 $self->log('err', $err);
1562 $self->{errors
} = 1;
1565 delete $self->{tunnel
};
1570 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1571 $self->log('info', "Waiting for spice server migration");
1573 my $res = mon_cmd
($vmid, 'query-spice');
1574 last if int($res->{'migrated'}) == 1;
1575 last if $timer > 50;
1582 # always stop local VM with nocheck, since config is moved already
1583 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1585 $self->log('err', "stopping vm failed - $err");
1586 $self->{errors
} = 1;
1589 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1591 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $sourcevollist);
1594 $self->log('err', $err);
1595 $self->{errors
} = 1;
1598 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
1600 # destroy local copies
1601 foreach my $volid (@not_replicated_volumes) {
1602 # remote is cleaned up below
1603 next if $self->{opts
}->{remote
};
1605 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1607 $self->log('err', "removing local copy of '$volid' failed - $err");
1608 $self->{errors
} = 1;
1609 last if $err =~ /^interrupted by signal$/;
1613 # clear migrate lock
1614 if ($tunnel && $tunnel->{version
} >= 2) {
1615 PVE
::Tunnel
::write_tunnel
($tunnel, 10, "unlock");
1617 PVE
::Tunnel
::finish_tunnel
($tunnel);
1619 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1620 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1623 if ($self->{opts
}->{remote
} && $self->{opts
}->{delete}) {
1624 eval { PVE
::QemuServer
::destroy_vm
($self->{storecfg
}, $vmid, 1, undef, 0) };
1625 warn "Failed to remove source VM - $@\n" if $@;
1630 my ($self, $vmid) = @_;
1635 sub round_powerof2
{
1636 return 1 if $_[0] < 2;
1637 return 2 << int(log($_[0]-1)/log(2));