]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
migrate: add remote migration handling
[qemu-server.git] / PVE / QemuMigrate.pm
1 package PVE::QemuMigrate;
2
3 use strict;
4 use warnings;
5
6 use IO::File;
7 use IPC::Open2;
8 use Time::HiRes qw( usleep );
9
10 use PVE::Cluster;
11 use PVE::Format qw(render_bytes);
12 use PVE::GuestHelpers qw(safe_boolean_ne safe_string_ne);
13 use PVE::INotify;
14 use PVE::RPCEnvironment;
15 use PVE::Replication;
16 use PVE::ReplicationConfig;
17 use PVE::ReplicationState;
18 use PVE::Storage;
19 use PVE::StorageTunnel;
20 use PVE::Tools;
21 use PVE::Tunnel;
22
23 use PVE::QemuConfig;
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;
30
31 use PVE::AbstractMigrate;
32 use base qw(PVE::AbstractMigrate);
33
34 # compared against remote end's minimum version
35 our $WS_TUNNEL_VERSION = 2;
36
37 sub fork_tunnel {
38 my ($self, $ssh_forward_info) = @_;
39
40 my $cmd = ['/usr/sbin/qm', 'mtunnel'];
41 my $log = sub {
42 my ($level, $msg) = @_;
43 $self->log($level, $msg);
44 };
45
46 return PVE::Tunnel::fork_ssh_tunnel($self->{rem_ssh}, $cmd, $ssh_forward_info, $log);
47 }
48
49 sub fork_websocket_tunnel {
50 my ($self, $storages, $bridges) = @_;
51
52 my $remote = $self->{opts}->{remote};
53 my $conn = $remote->{conn};
54
55 my $log = sub {
56 my ($level, $msg) = @_;
57 $self->log($level, $msg);
58 };
59
60 my $websocket_url = "https://$conn->{host}:$conn->{port}/api2/json/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnelwebsocket";
61 my $url = "/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnel";
62
63 my $tunnel_params = {
64 url => $websocket_url,
65 };
66
67 my $storage_list = join(',', keys %$storages);
68 my $bridge_list = join(',', keys %$bridges);
69
70 my $req_params = {
71 storages => $storage_list,
72 bridges => $bridge_list,
73 };
74
75 return PVE::Tunnel::fork_websocket_tunnel($conn, $url, $req_params, $tunnel_params, $log);
76 }
77
78 # tunnel_info:
79 # proto: unix (secure) or tcp (insecure/legacy compat)
80 # addr: IP or UNIX socket path
81 # port: optional TCP port
82 # unix_sockets: additional UNIX socket paths to forward
83 sub start_remote_tunnel {
84 my ($self, $tunnel_info) = @_;
85
86 my $nodename = PVE::INotify::nodename();
87 my $migration_type = $self->{opts}->{migration_type};
88
89 if ($migration_type eq 'secure') {
90
91 if ($tunnel_info->{proto} eq 'unix') {
92 my $ssh_forward_info = [];
93
94 my $unix_sockets = [ keys %{$tunnel_info->{unix_sockets}} ];
95 push @$unix_sockets, $tunnel_info->{addr};
96 for my $sock (@$unix_sockets) {
97 push @$ssh_forward_info, "$sock:$sock";
98 unlink $sock;
99 }
100
101 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
102
103 my $unix_socket_try = 0; # wait for the socket to become ready
104 while ($unix_socket_try <= 100) {
105 $unix_socket_try++;
106 my $available = 0;
107 foreach my $sock (@$unix_sockets) {
108 if (-S $sock) {
109 $available++;
110 }
111 }
112
113 if ($available == @$unix_sockets) {
114 last;
115 }
116
117 usleep(50000);
118 }
119 if ($unix_socket_try > 100) {
120 $self->{errors} = 1;
121 PVE::Tunnel::finish_tunnel($self->{tunnel});
122 die "Timeout, migration socket $tunnel_info->{addr} did not get ready";
123 }
124 $self->{tunnel}->{unix_sockets} = $unix_sockets if (@$unix_sockets);
125
126 } elsif ($tunnel_info->{proto} eq 'tcp') {
127 my $ssh_forward_info = [];
128 if ($tunnel_info->{addr} eq "localhost") {
129 # for backwards compatibility with older qemu-server versions
130 my $pfamily = PVE::Tools::get_host_address_family($nodename);
131 my $lport = PVE::Tools::next_migrate_port($pfamily);
132 push @$ssh_forward_info, "$lport:localhost:$tunnel_info->{port}";
133 }
134
135 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
136
137 } else {
138 die "unsupported protocol in migration URI: $tunnel_info->{proto}\n";
139 }
140 } else {
141 #fork tunnel for insecure migration, to send faster commands like resume
142 $self->{tunnel} = $self->fork_tunnel();
143 }
144 }
145
146 sub lock_vm {
147 my ($self, $vmid, $code, @param) = @_;
148
149 return PVE::QemuConfig->lock_config($vmid, $code, @param);
150 }
151
152 sub prepare {
153 my ($self, $vmid) = @_;
154
155 my $online = $self->{opts}->{online};
156
157 my $storecfg = $self->{storecfg} = PVE::Storage::config();
158
159 # test if VM exists
160 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
161
162 my $version = PVE::QemuServer::Helpers::get_node_pvecfg_version($self->{node});
163 my $cloudinit_config = $conf->{cloudinit};
164
165 if (
166 PVE::QemuConfig->has_cloudinit($conf) && defined($cloudinit_config)
167 && scalar(keys %$cloudinit_config) > 0
168 && !PVE::QemuServer::Helpers::pvecfg_min_version($version, 7, 2, 13)
169 ) {
170 die "target node is too old (manager <= 7.2-13) and doesn't support new cloudinit section\n";
171 }
172
173 my $repl_conf = PVE::ReplicationConfig->new();
174 $self->{replication_jobcfg} = $repl_conf->find_local_replication_job($vmid, $self->{node});
175 $self->{is_replicated} = $repl_conf->check_for_existing_jobs($vmid, 1);
176
177 if ($self->{replication_jobcfg} && defined($self->{replication_jobcfg}->{remove_job})) {
178 die "refusing to migrate replicated VM whose replication job is marked for removal\n";
179 }
180
181 PVE::QemuConfig->check_lock($conf);
182
183 my $running = 0;
184 if (my $pid = PVE::QemuServer::check_running($vmid)) {
185 die "can't migrate running VM without --online\n" if !$online;
186 $running = $pid;
187
188 if ($self->{is_replicated} && !$self->{replication_jobcfg}) {
189 if ($self->{opts}->{force}) {
190 $self->log('warn', "WARNING: Node '$self->{node}' is not a replication target. Existing " .
191 "replication jobs will fail after migration!\n");
192 } else {
193 die "Cannot live-migrate replicated VM to node '$self->{node}' - not a replication " .
194 "target. Use 'force' to override.\n";
195 }
196 }
197
198 $self->{forcemachine} = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
199
200 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
201 # Since the parameter itself contains no reference to a custom model,
202 # this makes migration independent of changes to "cpu-models.conf".
203 if ($conf->{cpu}) {
204 my $cpuconf = PVE::JSONSchema::parse_property_string('pve-cpu-conf', $conf->{cpu});
205 if ($cpuconf && PVE::QemuServer::CPUConfig::is_custom_model($cpuconf->{cputype})) {
206 $self->{forcecpu} = PVE::QemuServer::CPUConfig::get_cpu_from_running_vm($pid);
207 }
208 }
209
210 $self->{vm_was_paused} = 1 if PVE::QemuServer::vm_is_paused($vmid);
211 }
212
213 my $loc_res = PVE::QemuServer::check_local_resources($conf, 1);
214 if (scalar @$loc_res) {
215 if ($self->{running} || !$self->{opts}->{force}) {
216 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
217 } else {
218 $self->log('info', "migrating VM which uses local devices");
219 }
220 }
221
222 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
223
224 my $storages = {};
225 foreach my $volid (@$vollist) {
226 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
227
228 # check if storage is available on source node
229 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
230
231 my $targetsid = $sid;
232 # NOTE: local ignores shared mappings, remote maps them
233 if (!$scfg->{shared} || $self->{opts}->{remote}) {
234 $targetsid = PVE::JSONSchema::map_id($self->{opts}->{storagemap}, $sid);
235 }
236
237 $storages->{$targetsid} = 1;
238
239 if (!$self->{opts}->{remote}) {
240 # check if storage is available on target node
241 my $target_scfg = PVE::Storage::storage_check_enabled(
242 $storecfg,
243 $targetsid,
244 $self->{node},
245 );
246 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
247
248 die "$volid: content type '$vtype' is not available on storage '$targetsid'\n"
249 if !$target_scfg->{content}->{$vtype};
250 }
251
252 if ($scfg->{shared}) {
253 # PVE::Storage::activate_storage checks this for non-shared storages
254 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
255 warn "Used shared storage '$sid' is not online on source node!\n"
256 if !$plugin->check_connection($sid, $scfg);
257 }
258 }
259
260 if ($self->{opts}->{remote}) {
261 # test & establish websocket connection
262 my $bridges = map_bridges($conf, $self->{opts}->{bridgemap}, 1);
263 my $tunnel = $self->fork_websocket_tunnel($storages, $bridges);
264 my $min_version = $tunnel->{version} - $tunnel->{age};
265 $self->log('info', "local WS tunnel version: $WS_TUNNEL_VERSION");
266 $self->log('info', "remote WS tunnel version: $tunnel->{version}");
267 $self->log('info', "minimum required WS tunnel version: $min_version");
268 die "Remote tunnel endpoint not compatible, upgrade required\n"
269 if $WS_TUNNEL_VERSION < $min_version;
270 die "Remote tunnel endpoint too old, upgrade required\n"
271 if $WS_TUNNEL_VERSION > $tunnel->{version};
272
273 print "websocket tunnel started\n";
274 $self->{tunnel} = $tunnel;
275 } else {
276 # test ssh connection
277 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
278 eval { $self->cmd_quiet($cmd); };
279 die "Can't connect to destination address using public key\n" if $@;
280 }
281
282 return $running;
283 }
284
285 sub scan_local_volumes {
286 my ($self, $vmid) = @_;
287
288 my $conf = $self->{vmconf};
289
290 # local volumes which have been copied
291 # and their old_id => new_id pairs
292 $self->{volume_map} = {};
293 $self->{local_volumes} = {};
294
295 my $storecfg = $self->{storecfg};
296 eval {
297
298 # found local volumes and their origin
299 my $local_volumes = $self->{local_volumes};
300 my $local_volumes_errors = {};
301 my $other_errors = [];
302 my $abort = 0;
303
304 my $log_error = sub {
305 my ($msg, $volid) = @_;
306
307 if (defined($volid)) {
308 $local_volumes_errors->{$volid} = $msg;
309 } else {
310 push @$other_errors, $msg;
311 }
312 $abort = 1;
313 };
314
315 my @sids = PVE::Storage::storage_ids($storecfg);
316 foreach my $storeid (@sids) {
317 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
318 next if $scfg->{shared} && !$self->{opts}->{remote};
319 next if !PVE::Storage::storage_check_enabled($storecfg, $storeid, undef, 1);
320
321 # get list from PVE::Storage (for unused volumes)
322 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, $vmid, undef, 'images');
323
324 next if @{$dl->{$storeid}} == 0;
325
326 my $targetsid = PVE::JSONSchema::map_id($self->{opts}->{storagemap}, $storeid);
327 if (!$self->{opts}->{remote}) {
328 # check if storage is available on target node
329 my $target_scfg = PVE::Storage::storage_check_enabled(
330 $storecfg,
331 $targetsid,
332 $self->{node},
333 );
334
335 die "content type 'images' is not available on storage '$targetsid'\n"
336 if !$target_scfg->{content}->{images};
337
338 }
339
340 my $bwlimit = $self->get_bwlimit($storeid, $targetsid);
341
342 PVE::Storage::foreach_volid($dl, sub {
343 my ($volid, $sid, $volinfo) = @_;
344
345 $local_volumes->{$volid}->{ref} = 'storage';
346 $local_volumes->{$volid}->{size} = $volinfo->{size};
347 $local_volumes->{$volid}->{targetsid} = $targetsid;
348 $local_volumes->{$volid}->{bwlimit} = $bwlimit;
349
350 # If with_snapshots is not set for storage migrate, it tries to use
351 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
352 # back to qcow2 is currently not possible.
353 $local_volumes->{$volid}->{snapshots} = ($volinfo->{format} =~ /^(?:qcow2|vmdk)$/);
354 $local_volumes->{$volid}->{format} = $volinfo->{format};
355 });
356 }
357
358 my $replicatable_volumes = !$self->{replication_jobcfg} ? {}
359 : PVE::QemuConfig->get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
360 foreach my $volid (keys %{$replicatable_volumes}) {
361 $local_volumes->{$volid}->{replicated} = 1;
362 }
363
364 my $test_volid = sub {
365 my ($volid, $attr) = @_;
366
367 if ($volid =~ m|^/|) {
368 return if $attr->{shared};
369 $local_volumes->{$volid}->{ref} = 'config';
370 die "local file/device\n";
371 }
372
373 my $snaprefs = $attr->{referenced_in_snapshot};
374
375 if ($attr->{cdrom}) {
376 if ($volid eq 'cdrom') {
377 my $msg = "can't migrate local cdrom drive";
378 if (defined($snaprefs) && !$attr->{referenced_in_config}) {
379 my $snapnames = join(', ', sort keys %$snaprefs);
380 $msg .= " (referenced in snapshot - $snapnames)";
381 }
382 &$log_error("$msg\n");
383 return;
384 }
385 return if $volid eq 'none';
386 }
387
388 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
389
390 # check if storage is available on both nodes
391 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
392
393 my $targetsid = $sid;
394 # NOTE: local ignores shared mappings, remote maps them
395 if (!$scfg->{shared} || $self->{opts}->{remote}) {
396 $targetsid = PVE::JSONSchema::map_id($self->{opts}->{storagemap}, $sid);
397 }
398
399 # check target storage on target node if intra-cluster migration
400 if (!$self->{opts}->{remote}) {
401 PVE::Storage::storage_check_enabled($storecfg, $targetsid, $self->{node});
402
403 return if $scfg->{shared};
404 }
405
406 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config} ? 'config' : 'snapshot';
407 $local_volumes->{$volid}->{ref} = 'storage' if $attr->{is_unused};
408 $local_volumes->{$volid}->{ref} = 'generated' if $attr->{is_tpmstate};
409
410 $local_volumes->{$volid}->{is_vmstate} = $attr->{is_vmstate} ? 1 : 0;
411
412 $local_volumes->{$volid}->{drivename} = $attr->{drivename}
413 if $attr->{drivename};
414
415 if ($attr->{cdrom}) {
416 if ($volid =~ /vm-\d+-cloudinit/) {
417 $local_volumes->{$volid}->{ref} = 'generated';
418 return;
419 }
420 die "local cdrom image\n";
421 }
422
423 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
424
425 die "owned by other VM (owner = VM $owner)\n"
426 if !$owner || ($owner != $vmid);
427
428 return if $attr->{is_vmstate};
429
430 if (defined($snaprefs)) {
431 $local_volumes->{$volid}->{snapshots} = 1;
432
433 # we cannot migrate shapshots on local storage
434 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
435
436 die "online storage migration not possible if snapshot exists\n" if $self->{running};
437 die "remote migration with snapshots not supported yet\n" if $self->{opts}->{remote};
438
439 if (!($scfg->{type} eq 'zfspool'
440 || ($scfg->{type} eq 'btrfs' && $local_volumes->{$volid}->{format} eq 'raw')
441 || $local_volumes->{$volid}->{format} eq 'qcow2'
442 )) {
443 die "non-migratable snapshot exists\n";
444 }
445 }
446
447 die "referenced by linked clone(s)\n"
448 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
449 };
450
451 PVE::QemuServer::foreach_volid($conf, sub {
452 my ($volid, $attr) = @_;
453 eval { $test_volid->($volid, $attr); };
454 if (my $err = $@) {
455 &$log_error($err, $volid);
456 }
457 });
458
459 foreach my $vol (sort keys %$local_volumes) {
460 my $type = $replicatable_volumes->{$vol} ? 'local, replicated' : 'local';
461 my $ref = $local_volumes->{$vol}->{ref};
462 if ($ref eq 'storage') {
463 $self->log('info', "found $type disk '$vol' (via storage)\n");
464 } elsif ($ref eq 'config') {
465 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
466 if $self->{running} && !$self->{opts}->{"with-local-disks"};
467 $self->log('info', "found $type disk '$vol' (in current VM config)\n");
468 } elsif ($ref eq 'snapshot') {
469 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
470 } elsif ($ref eq 'generated') {
471 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
472 } else {
473 $self->log('info', "found $type disk '$vol'\n");
474 }
475 }
476
477 foreach my $vol (sort keys %$local_volumes_errors) {
478 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
479 }
480 foreach my $err (@$other_errors) {
481 $self->log('warn', "$err");
482 }
483
484 if ($abort) {
485 die "can't migrate VM - check log\n";
486 }
487
488 # additional checks for local storage
489 foreach my $volid (keys %$local_volumes) {
490 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
491 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
492
493 my $migratable = $scfg->{type} =~ /^(?:dir|btrfs|zfspool|lvmthin|lvm)$/;
494
495 # TODO: what is this even here for?
496 $migratable = 1 if $self->{opts}->{remote};
497
498 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
499 if !$migratable;
500
501 # image is a linked clone on local storage, se we can't migrate.
502 if (my $basename = (PVE::Storage::parse_volname($storecfg, $volid))[3]) {
503 die "can't migrate '$volid' as it's a clone of '$basename'";
504 }
505 }
506
507 foreach my $volid (sort keys %$local_volumes) {
508 my $ref = $local_volumes->{$volid}->{ref};
509 if ($self->{running} && $ref eq 'config') {
510 $local_volumes->{$volid}->{migration_mode} = 'online';
511 } elsif ($self->{running} && $ref eq 'generated') {
512 # offline migrate the cloud-init ISO and don't regenerate on VM start
513 #
514 # tpmstate will also be offline migrated first, and in case of
515 # live migration then updated by QEMU/swtpm if necessary
516 $local_volumes->{$volid}->{migration_mode} = 'offline';
517 } else {
518 $local_volumes->{$volid}->{migration_mode} = 'offline';
519 }
520 }
521 };
522 die "Problem found while scanning volumes - $@" if $@;
523 }
524
525 sub handle_replication {
526 my ($self, $vmid) = @_;
527
528 my $conf = $self->{vmconf};
529 my $local_volumes = $self->{local_volumes};
530
531 return if !$self->{replication_jobcfg};
532
533 die "can't migrate VM with replicated volumes to remote cluster/node\n"
534 if $self->{opts}->{remote};
535
536 if ($self->{running}) {
537
538 my $version = PVE::QemuServer::kvm_user_version();
539 if (!min_version($version, 4, 2)) {
540 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
541 }
542
543 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
544 foreach my $volid (@live_replicatable_volumes) {
545 my $drive = $local_volumes->{$volid}->{drivename};
546 die "internal error - no drive for '$volid'\n" if !defined($drive);
547
548 my $bitmap = "repl_$drive";
549
550 # start tracking before replication to get full delta + a few duplicates
551 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
552 mon_cmd($vmid, 'block-dirty-bitmap-add', node => "drive-$drive", name => $bitmap);
553
554 # other info comes from target node in phase 2
555 $self->{target_drive}->{$drive}->{bitmap} = $bitmap;
556 }
557 }
558 $self->log('info', "replicating disk images");
559
560 my $start_time = time();
561 my $logfunc = sub { $self->log('info', shift) };
562 my $actual_replicated_volumes = PVE::Replication::run_replication(
563 'PVE::QemuConfig', $self->{replication_jobcfg}, $start_time, $start_time, $logfunc);
564
565 # extra safety check
566 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
567 foreach my $volid (@replicated_volumes) {
568 die "expected volume '$volid' to get replicated, but it wasn't\n"
569 if !$actual_replicated_volumes->{$volid};
570 }
571 }
572
573 sub config_update_local_disksizes {
574 my ($self) = @_;
575
576 my $conf = $self->{vmconf};
577 my $local_volumes = $self->{local_volumes};
578
579 PVE::QemuConfig->foreach_volume($conf, sub {
580 my ($key, $drive) = @_;
581 # skip special disks, will be handled later
582 return if $key eq 'efidisk0';
583 return if $key eq 'tpmstate0';
584
585 my $volid = $drive->{file};
586 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
587
588 my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $local_volumes->{$volid}->{size});
589 if (defined($updated)) {
590 $conf->{$key} = PVE::QemuServer::print_drive($updated);
591 $self->log('info', "drive '$key': $msg");
592 }
593 });
594
595 # we want to set the efidisk size in the config to the size of the
596 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
597 if (defined($conf->{efidisk0})) {
598 PVE::QemuServer::update_efidisk_size($conf);
599 }
600
601 # TPM state might have an irregular filesize, to avoid problems on transfer
602 # we always assume the static size of 4M to allocate on the target
603 if (defined($conf->{tpmstate0})) {
604 PVE::QemuServer::update_tpmstate_size($conf);
605 }
606 }
607
608 sub filter_local_volumes {
609 my ($self, $migration_mode, $replicated) = @_;
610
611 my $volumes = $self->{local_volumes};
612 my @filtered_volids;
613
614 foreach my $volid (sort keys %{$volumes}) {
615 next if defined($migration_mode) && safe_string_ne($volumes->{$volid}->{migration_mode}, $migration_mode);
616 next if defined($replicated) && safe_boolean_ne($volumes->{$volid}->{replicated}, $replicated);
617 push @filtered_volids, $volid;
618 }
619
620 return @filtered_volids;
621 }
622
623 sub sync_offline_local_volumes {
624 my ($self) = @_;
625
626 my $local_volumes = $self->{local_volumes};
627 my @volids = $self->filter_local_volumes('offline', 0);
628
629 my $storecfg = $self->{storecfg};
630 my $opts = $self->{opts};
631
632 $self->log('info', "copying local disk images") if scalar(@volids);
633
634 foreach my $volid (@volids) {
635 my $new_volid;
636
637 my $opts = $self->{opts};
638 if ($opts->{remote}) {
639 my $log = sub {
640 my ($level, $msg) = @_;
641 $self->log($level, $msg);
642 };
643
644 $new_volid = PVE::StorageTunnel::storage_migrate(
645 $self->{tunnel},
646 $storecfg,
647 $volid,
648 $self->{vmid},
649 $opts->{remote}->{vmid},
650 $local_volumes->{$volid},
651 $log,
652 );
653 } else {
654 my $targetsid = $local_volumes->{$volid}->{targetsid};
655
656 my $bwlimit = $local_volumes->{$volid}->{bwlimit};
657 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
658
659 my $storage_migrate_opts = {
660 'ratelimit_bps' => $bwlimit,
661 'insecure' => $opts->{migration_type} eq 'insecure',
662 'with_snapshots' => $local_volumes->{$volid}->{snapshots},
663 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate},
664 };
665
666 my $logfunc = sub { $self->log('info', $_[0]); };
667 $new_volid = eval {
668 PVE::Storage::storage_migrate(
669 $storecfg,
670 $volid,
671 $self->{ssh_info},
672 $targetsid,
673 $storage_migrate_opts,
674 $logfunc,
675 );
676 };
677 if (my $err = $@) {
678 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
679 }
680 }
681
682 $self->{volume_map}->{$volid} = $new_volid;
683 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
684
685 eval { PVE::Storage::deactivate_volumes($storecfg, [$volid]); };
686 if (my $err = $@) {
687 $self->log('warn', $err);
688 }
689 }
690 }
691
692 sub cleanup_remotedisks {
693 my ($self) = @_;
694
695 if ($self->{opts}->{remote}) {
696 PVE::Tunnel::finish_tunnel($self->{tunnel}, 1);
697 delete $self->{tunnel};
698 return;
699 }
700
701 my $local_volumes = $self->{local_volumes};
702
703 foreach my $volid (values %{$self->{volume_map}}) {
704 # don't clean up replicated disks!
705 next if $local_volumes->{$volid}->{replicated};
706
707 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
708
709 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
710
711 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
712 if (my $err = $@) {
713 $self->log('err', $err);
714 $self->{errors} = 1;
715 }
716 }
717 }
718
719 sub cleanup_bitmaps {
720 my ($self) = @_;
721 foreach my $drive (keys %{$self->{target_drive}}) {
722 my $bitmap = $self->{target_drive}->{$drive}->{bitmap};
723 next if !$bitmap;
724 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
725 mon_cmd($self->{vmid}, 'block-dirty-bitmap-remove', node => "drive-$drive", name => $bitmap);
726 }
727 }
728
729 sub phase1 {
730 my ($self, $vmid) = @_;
731
732 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
733
734 my $conf = $self->{vmconf};
735
736 # set migrate lock in config file
737 $conf->{lock} = 'migrate';
738 PVE::QemuConfig->write_config($vmid, $conf);
739
740 $self->scan_local_volumes($vmid);
741
742 # fix disk sizes to match their actual size and write changes,
743 # so that the target allocates the correct volumes
744 $self->config_update_local_disksizes();
745 PVE::QemuConfig->write_config($vmid, $conf);
746
747 $self->handle_replication($vmid);
748
749 $self->sync_offline_local_volumes();
750 $self->phase1_remote($vmid) if $self->{opts}->{remote};
751 };
752
753 sub map_bridges {
754 my ($conf, $map, $scan_only) = @_;
755
756 my $bridges = {};
757
758 foreach my $opt (keys %$conf) {
759 next if $opt !~ m/^net\d+$/;
760
761 next if !$conf->{$opt};
762 my $d = PVE::QemuServer::parse_net($conf->{$opt});
763 next if !$d || !$d->{bridge};
764
765 my $target_bridge = PVE::JSONSchema::map_id($map, $d->{bridge});
766 $bridges->{$target_bridge}->{$opt} = $d->{bridge};
767
768 next if $scan_only;
769
770 $d->{bridge} = $target_bridge;
771 $conf->{$opt} = PVE::QemuServer::print_net($d);
772 }
773
774 return $bridges;
775 }
776
777 sub phase1_remote {
778 my ($self, $vmid) = @_;
779
780 my $remote_conf = PVE::QemuConfig->load_config($vmid);
781 PVE::QemuConfig->update_volume_ids($remote_conf, $self->{volume_map});
782
783 my $bridges = map_bridges($remote_conf, $self->{opts}->{bridgemap});
784 for my $target (keys $bridges->%*) {
785 for my $nic (keys $bridges->{$target}->%*) {
786 $self->log('info', "mapped: $nic from $bridges->{$target}->{$nic} to $target");
787 }
788 }
789
790 my @online_local_volumes = $self->filter_local_volumes('online');
791
792 my $storage_map = $self->{opts}->{storagemap};
793 $self->{nbd} = {};
794 PVE::QemuConfig->foreach_volume($remote_conf, sub {
795 my ($ds, $drive) = @_;
796
797 # TODO eject CDROM?
798 return if PVE::QemuServer::drive_is_cdrom($drive);
799
800 my $volid = $drive->{file};
801 return if !$volid;
802
803 return if !grep { $_ eq $volid} @online_local_volumes;
804
805 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
806 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
807 my $source_format = PVE::QemuServer::qemu_img_format($scfg, $volname);
808
809 # set by target cluster
810 my $oldvolid = delete $drive->{file};
811 delete $drive->{format};
812
813 my $targetsid = PVE::JSONSchema::map_id($storage_map, $storeid);
814
815 my $params = {
816 format => $source_format,
817 storage => $targetsid,
818 drive => $drive,
819 };
820
821 $self->log('info', "Allocating volume for drive '$ds' on remote storage '$targetsid'..");
822 my $res = PVE::Tunnel::write_tunnel($self->{tunnel}, 600, 'disk', $params);
823
824 $self->log('info', "volume '$oldvolid' is '$res->{volid}' on the target\n");
825 $remote_conf->{$ds} = $res->{drivestr};
826 $self->{nbd}->{$ds} = $res;
827 });
828
829 my $conf_str = PVE::QemuServer::write_vm_config("remote", $remote_conf);
830
831 # TODO expose in PVE::Firewall?
832 my $vm_fw_conf_path = "/etc/pve/firewall/$vmid.fw";
833 my $fw_conf_str;
834 $fw_conf_str = PVE::Tools::file_get_contents($vm_fw_conf_path)
835 if -e $vm_fw_conf_path;
836 my $params = {
837 conf => $conf_str,
838 'firewall-config' => $fw_conf_str,
839 };
840
841 PVE::Tunnel::write_tunnel($self->{tunnel}, 10, 'config', $params);
842 }
843
844 sub phase1_cleanup {
845 my ($self, $vmid, $err) = @_;
846
847 $self->log('info', "aborting phase 1 - cleanup resources");
848
849 my $conf = $self->{vmconf};
850 delete $conf->{lock};
851 eval { PVE::QemuConfig->write_config($vmid, $conf) };
852 if (my $err = $@) {
853 $self->log('err', $err);
854 }
855
856 eval { $self->cleanup_remotedisks() };
857 if (my $err = $@) {
858 $self->log('err', $err);
859 }
860
861 eval { $self->cleanup_bitmaps() };
862 if (my $err =$@) {
863 $self->log('err', $err);
864 }
865 }
866
867 sub phase2_start_local_cluster {
868 my ($self, $vmid, $params) = @_;
869
870 my $conf = $self->{vmconf};
871 my $local_volumes = $self->{local_volumes};
872 my @online_local_volumes = $self->filter_local_volumes('online');
873
874 my $start = $params->{start_params};
875 my $migrate = $params->{migrate_opts};
876
877 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
878
879 my $tunnel_info = {};
880
881 ## start on remote node
882 my $cmd = [@{$self->{rem_ssh}}];
883
884 push @$cmd, 'qm', 'start', $vmid;
885
886 if ($start->{skiplock}) {
887 push @$cmd, '--skiplock';
888 }
889
890 push @$cmd, '--migratedfrom', $migrate->{migratedfrom};
891
892 push @$cmd, '--migration_type', $migrate->{type};
893
894 push @$cmd, '--migration_network', $migrate->{network}
895 if $migrate->{network};
896
897 push @$cmd, '--stateuri', $start->{statefile};
898
899 if ($start->{forcemachine}) {
900 push @$cmd, '--machine', $start->{forcemachine};
901 }
902
903 if ($start->{forcecpu}) {
904 push @$cmd, '--force-cpu', $start->{forcecpu};
905 }
906
907 if ($self->{storage_migration}) {
908 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
909 }
910
911 my $spice_port;
912 my $input = "nbd_protocol_version: $migrate->{nbd_proto_version}\n";
913
914 my @offline_local_volumes = $self->filter_local_volumes('offline');
915 for my $volid (@offline_local_volumes) {
916 my $drivename = $local_volumes->{$volid}->{drivename};
917 next if !$drivename || !$conf->{$drivename};
918
919 my $new_volid = $self->{volume_map}->{$volid};
920 next if !$new_volid || $volid eq $new_volid;
921
922 # FIXME PVE 8.x only use offline_volume variant once all targets can handle it
923 if ($drivename eq 'tpmstate0') {
924 $input .= "$drivename: $new_volid\n"
925 } else {
926 $input .= "offline_volume: $drivename: $new_volid\n"
927 }
928 }
929
930 $input .= "spice_ticket: $migrate->{spice_ticket}\n" if $migrate->{spice_ticket};
931
932 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
933 foreach my $volid (@online_replicated_volumes) {
934 $input .= "replicated_volume: $volid\n";
935 }
936
937 my $handle_storage_migration_listens = sub {
938 my ($drive_key, $drivestr, $nbd_uri) = @_;
939
940 $self->{stopnbd} = 1;
941 $self->{target_drive}->{$drive_key}->{drivestr} = $drivestr;
942 $self->{target_drive}->{$drive_key}->{nbd_uri} = $nbd_uri;
943
944 my $source_drive = PVE::QemuServer::parse_drive($drive_key, $conf->{$drive_key});
945 my $target_drive = PVE::QemuServer::parse_drive($drive_key, $drivestr);
946 my $source_volid = $source_drive->{file};
947 my $target_volid = $target_drive->{file};
948
949 $self->{volume_map}->{$source_volid} = $target_volid;
950 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
951 };
952
953 my $target_replicated_volumes = {};
954
955 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
956 # instead we pipe it through STDIN
957 my $exitcode = PVE::Tools::run_command($cmd, input => $input, outfunc => sub {
958 my $line = shift;
959
960 if ($line =~ m/^migration listens on (tcp):(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
961 $tunnel_info->{addr} = $2;
962 $tunnel_info->{port} = int($3);
963 $tunnel_info->{proto} = $1;
964 }
965 elsif ($line =~ m!^migration listens on (unix):(/run/qemu-server/(\d+)\.migrate)$!) {
966 $tunnel_info->{addr} = $2;
967 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $3;
968 $tunnel_info->{proto} = $1;
969 }
970 elsif ($line =~ m/^migration listens on port (\d+)$/) {
971 $tunnel_info->{addr} = "localhost";
972 $tunnel_info->{port} = int($1);
973 $tunnel_info->{proto} = "tcp";
974 }
975 elsif ($line =~ m/^spice listens on port (\d+)$/) {
976 $spice_port = int($1);
977 }
978 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
979 my $drivestr = $4;
980 my $nbd_uri = "nbd:$1:$2:exportname=$3";
981 my $targetdrive = $3;
982 $targetdrive =~ s/drive-//g;
983
984 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
985 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
986 my $drivestr = $4;
987 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
988 my $nbd_unix_addr = $1;
989 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
990 my $targetdrive = $3;
991 $targetdrive =~ s/drive-//g;
992
993 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
994 $tunnel_info->{unix_sockets}->{$nbd_unix_addr} = 1;
995 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
996 my $drive = $1;
997 my $volid = $2;
998 $target_replicated_volumes->{$volid} = $drive;
999 } elsif ($line =~ m/^QEMU: (.*)$/) {
1000 $self->log('info', "[$self->{node}] $1\n");
1001 }
1002 }, errfunc => sub {
1003 my $line = shift;
1004 $self->log('info', "[$self->{node}] $line");
1005 }, noerr => 1);
1006
1007 die "remote command failed with exit code $exitcode\n" if $exitcode;
1008
1009 die "unable to detect remote migration address\n" if !$tunnel_info->{addr} || !$tunnel_info->{proto};
1010
1011 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
1012 die "number of replicated disks on source and target node do not match - target node too old?\n"
1013 }
1014
1015 return ($tunnel_info, $spice_port);
1016 }
1017
1018 sub phase2_start_remote_cluster {
1019 my ($self, $vmid, $params) = @_;
1020
1021 die "insecure migration to remote cluster not implemented\n"
1022 if $params->{migrate_opts}->{type} ne 'websocket';
1023
1024 my $remote_vmid = $self->{opts}->{remote}->{vmid};
1025
1026 # like regular start but with some overhead accounted for
1027 my $timeout = PVE::QemuServer::Helpers::config_aware_timeout($self->{vmconf}) + 10;
1028
1029 my $res = PVE::Tunnel::write_tunnel($self->{tunnel}, $timeout, "start", $params);
1030
1031 foreach my $drive (keys %{$res->{drives}}) {
1032 $self->{stopnbd} = 1;
1033 $self->{target_drive}->{$drive}->{drivestr} = $res->{drives}->{$drive}->{drivestr};
1034 my $nbd_uri = $res->{drives}->{$drive}->{nbd_uri};
1035 die "unexpected NBD uri for '$drive': $nbd_uri\n"
1036 if $nbd_uri !~ s!/run/qemu-server/$remote_vmid\_!/run/qemu-server/$vmid\_!;
1037
1038 $self->{target_drive}->{$drive}->{nbd_uri} = $nbd_uri;
1039 }
1040
1041 return ($res->{migrate}, $res->{spice_port});
1042 }
1043
1044 sub phase2 {
1045 my ($self, $vmid) = @_;
1046
1047 my $conf = $self->{vmconf};
1048 my $local_volumes = $self->{local_volumes};
1049
1050 # version > 0 for unix socket support
1051 my $nbd_protocol_version = 1;
1052
1053 my $spice_ticket;
1054 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
1055 my $res = mon_cmd($vmid, 'query-spice');
1056 $spice_ticket = $res->{ticket};
1057 }
1058
1059 my $migration_type = $self->{opts}->{migration_type};
1060 my $state_uri = $migration_type eq 'insecure' ? 'tcp' : 'unix';
1061
1062 my $params = {
1063 start_params => {
1064 statefile => $state_uri,
1065 forcemachine => $self->{forcemachine},
1066 forcecpu => $self->{forcecpu},
1067 skiplock => 1,
1068 },
1069 migrate_opts => {
1070 spice_ticket => $spice_ticket,
1071 type => $migration_type,
1072 network => $self->{opts}->{migration_network},
1073 storagemap => $self->{opts}->{storagemap},
1074 migratedfrom => PVE::INotify::nodename(),
1075 nbd_proto_version => $nbd_protocol_version,
1076 nbd => $self->{nbd},
1077 },
1078 };
1079
1080 my ($tunnel_info, $spice_port);
1081
1082 my @online_local_volumes = $self->filter_local_volumes('online');
1083 $self->{storage_migration} = 1 if scalar(@online_local_volumes);
1084
1085 if (my $remote = $self->{opts}->{remote}) {
1086 my $remote_vmid = $remote->{vmid};
1087 $params->{migrate_opts}->{remote_node} = $self->{node};
1088 ($tunnel_info, $spice_port) = $self->phase2_start_remote_cluster($vmid, $params);
1089 die "only UNIX sockets are supported for remote migration\n"
1090 if $tunnel_info->{proto} ne 'unix';
1091
1092 my $remote_socket = $tunnel_info->{addr};
1093 my $local_socket = $remote_socket;
1094 $local_socket =~ s/$remote_vmid/$vmid/g;
1095 $tunnel_info->{addr} = $local_socket;
1096
1097 $self->log('info', "Setting up tunnel for '$local_socket'");
1098 PVE::Tunnel::forward_unix_socket($self->{tunnel}, $local_socket, $remote_socket);
1099
1100 foreach my $remote_socket (@{$tunnel_info->{unix_sockets}}) {
1101 my $local_socket = $remote_socket;
1102 $local_socket =~ s/$remote_vmid/$vmid/g;
1103 next if $self->{tunnel}->{forwarded}->{$local_socket};
1104 $self->log('info', "Setting up tunnel for '$local_socket'");
1105 PVE::Tunnel::forward_unix_socket($self->{tunnel}, $local_socket, $remote_socket);
1106 }
1107 } else {
1108 ($tunnel_info, $spice_port) = $self->phase2_start_local_cluster($vmid, $params);
1109
1110 $self->log('info', "start remote tunnel");
1111 $self->start_remote_tunnel($tunnel_info);
1112 }
1113
1114 my $migrate_uri = "$tunnel_info->{proto}:$tunnel_info->{addr}";
1115 $migrate_uri .= ":$tunnel_info->{port}"
1116 if defined($tunnel_info->{port});
1117
1118 if ($self->{storage_migration}) {
1119 $self->{storage_migration_jobs} = {};
1120 $self->log('info', "starting storage migration");
1121
1122 die "The number of local disks does not match between the source and the destination.\n"
1123 if (scalar(keys %{$self->{target_drive}}) != scalar(@online_local_volumes));
1124 foreach my $drive (keys %{$self->{target_drive}}){
1125 my $target = $self->{target_drive}->{$drive};
1126 my $nbd_uri = $target->{nbd_uri};
1127
1128 my $source_drive = PVE::QemuServer::parse_drive($drive, $conf->{$drive});
1129 my $source_volid = $source_drive->{file};
1130
1131 my $bwlimit = $self->{local_volumes}->{$source_volid}->{bwlimit};
1132 my $bitmap = $target->{bitmap};
1133
1134 $self->log('info', "$drive: start migration to $nbd_uri");
1135 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 'skip', undef, $bwlimit, $bitmap);
1136 }
1137 }
1138
1139 $self->log('info', "starting online/live migration on $migrate_uri");
1140 $self->{livemigration} = 1;
1141
1142 # load_defaults
1143 my $defaults = PVE::QemuServer::load_defaults();
1144
1145 $self->log('info', "set migration capabilities");
1146 eval { PVE::QemuServer::set_migration_caps($vmid) };
1147 warn $@ if $@;
1148
1149 my $qemu_migrate_params = {};
1150
1151 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
1152 # migrate_speed parameter in qm.conf - take the lower of the two.
1153 my $bwlimit = $self->get_bwlimit();
1154
1155 my $migrate_speed = $conf->{migrate_speed} // 0;
1156 $migrate_speed *= 1024; # migrate_speed is in MB/s, bwlimit in KB/s
1157
1158 if ($bwlimit && $migrate_speed) {
1159 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
1160 } else {
1161 $migrate_speed ||= $bwlimit;
1162 }
1163 $migrate_speed ||= ($defaults->{migrate_speed} || 0) * 1024;
1164
1165 if ($migrate_speed) {
1166 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
1167 $self->log('info', "migration speed limit: ". render_bytes($migrate_speed, 1) ."/s");
1168 } else {
1169 # always set migrate speed as QEMU default to 128 MiBps == 1 Gbps, use 16 GiBps == 128 Gbps
1170 $migrate_speed = (16 << 30);
1171 }
1172 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
1173
1174 my $migrate_downtime = $defaults->{migrate_downtime};
1175 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
1176 # migrate-set-parameters expects limit in ms
1177 $migrate_downtime *= 1000;
1178 $self->log('info', "migration downtime limit: $migrate_downtime ms");
1179 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
1180
1181 # set cachesize to 10% of the total memory
1182 my $memory = $conf->{memory} || $defaults->{memory};
1183 my $cachesize = int($memory * 1048576 / 10);
1184 $cachesize = round_powerof2($cachesize);
1185
1186 $self->log('info', "migration cachesize: " . render_bytes($cachesize, 1));
1187 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
1188
1189 $self->log('info', "set migration parameters");
1190 eval {
1191 mon_cmd($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
1192 };
1193 $self->log('info', "migrate-set-parameters error: $@") if $@;
1194
1195 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && !$self->{opts}->{remote}) {
1196 my $rpcenv = PVE::RPCEnvironment::get();
1197 my $authuser = $rpcenv->get_user();
1198
1199 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
1200
1201 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
1202 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
1203
1204 $self->log('info', "spice client_migrate_info");
1205
1206 eval {
1207 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
1208 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
1209 'cert-subject' => $subject);
1210 };
1211 $self->log('info', "client_migrate_info error: $@") if $@;
1212
1213 }
1214
1215 my $start = time();
1216
1217 $self->log('info', "start migrate command to $migrate_uri");
1218 eval {
1219 mon_cmd($vmid, "migrate", uri => $migrate_uri);
1220 };
1221 my $merr = $@;
1222 $self->log('info', "migrate uri => $migrate_uri failed: $merr") if $merr;
1223
1224 my $last_mem_transferred = 0;
1225 my $usleep = 1000000;
1226 my $i = 0;
1227 my $err_count = 0;
1228 my $lastrem = undef;
1229 my $downtimecounter = 0;
1230 while (1) {
1231 $i++;
1232 my $avglstat = $last_mem_transferred ? $last_mem_transferred / $i : 0;
1233
1234 usleep($usleep);
1235
1236 my $stat = eval { mon_cmd($vmid, "query-migrate") };
1237 if (my $err = $@) {
1238 $err_count++;
1239 warn "query migrate failed: $err\n";
1240 $self->log('info', "query migrate failed: $err");
1241 if ($err_count <= 5) {
1242 usleep(1_000_000);
1243 next;
1244 }
1245 die "too many query migrate failures - aborting\n";
1246 }
1247
1248 my $status = $stat->{status};
1249 if (defined($status) && $status =~ m/^(setup)$/im) {
1250 sleep(1);
1251 next;
1252 }
1253
1254 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1255 die $merr if $merr;
1256 die "unable to parse migration status '$status' - aborting\n";
1257 }
1258 $merr = undef;
1259 $err_count = 0;
1260
1261 my $memstat = $stat->{ram};
1262
1263 if ($status eq 'completed') {
1264 my $delay = time() - $start;
1265 if ($delay > 0) {
1266 my $total = $memstat->{total} || 0;
1267 my $avg_speed = render_bytes($total / $delay, 1);
1268 my $downtime = $stat->{downtime} || 0;
1269 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1270 }
1271 }
1272
1273 if ($status eq 'failed' || $status eq 'cancelled') {
1274 $self->log('info', "migration status error: $status");
1275 die "aborting\n"
1276 }
1277
1278 if ($status ne 'active') {
1279 $self->log('info', "migration status: $status");
1280 last;
1281 }
1282
1283 if ($memstat->{transferred} ne $last_mem_transferred) {
1284 my $trans = $memstat->{transferred} || 0;
1285 my $rem = $memstat->{remaining} || 0;
1286 my $total = $memstat->{total} || 0;
1287 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1288 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
1289
1290 # reduce sleep if remainig memory is lower than the average transfer speed
1291 $usleep = 100_000 if $avglstat && $rem < $avglstat;
1292
1293 # also reduce loggin if we poll more frequent
1294 my $should_log = $usleep > 100_000 ? 1 : ($i % 10) == 0;
1295
1296 my $total_h = render_bytes($total, 1);
1297 my $transferred_h = render_bytes($trans, 1);
1298 my $speed_h = render_bytes($speed, 1);
1299
1300 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1301
1302 if ($dirty_rate > $speed) {
1303 my $dirty_rate_h = render_bytes($dirty_rate, 1);
1304 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1305 }
1306
1307 $self->log('info', "migration $status, $progress") if $should_log;
1308
1309 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1310 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1311 if ($xbzrlebytes || $xbzrlepages) {
1312 my $bytes_h = render_bytes($xbzrlebytes, 1);
1313
1314 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1315
1316 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1317 if $xbzrle->{'cache-miss-rate'};
1318
1319 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow};
1320
1321 $self->log('info', "xbzrle: $msg") if $should_log;
1322 }
1323
1324 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
1325 $downtimecounter++;
1326 }
1327 $lastrem = $rem;
1328
1329 if ($downtimecounter > 5) {
1330 $downtimecounter = 0;
1331 $migrate_downtime *= 2;
1332 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1333 eval {
1334 # migrate-set-parameters does not touch values not
1335 # specified, so this only changes downtime-limit
1336 mon_cmd($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1337 };
1338 $self->log('info', "migrate-set-parameters error: $@") if $@;
1339 }
1340 }
1341
1342 $last_mem_transferred = $memstat->{transferred};
1343 }
1344
1345 if ($self->{storage_migration}) {
1346 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1347 # to avoid it trying to re-establish it. We are in blockjob ready state,
1348 # thus, this command changes to it to blockjob complete (see qapi docs)
1349 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}, 'cancel'); };
1350 if (my $err = $@) {
1351 die "Failed to complete storage migration: $err\n";
1352 }
1353 }
1354 }
1355
1356 sub phase2_cleanup {
1357 my ($self, $vmid, $err) = @_;
1358
1359 return if !$self->{errors};
1360 $self->{phase2errors} = 1;
1361
1362 $self->log('info', "aborting phase 2 - cleanup resources");
1363
1364 $self->log('info', "migrate_cancel");
1365 eval {
1366 mon_cmd($vmid, "migrate_cancel");
1367 };
1368 $self->log('info', "migrate_cancel error: $@") if $@;
1369
1370 my $vm_status = eval {
1371 mon_cmd($vmid, 'query-status')->{status} or die "no 'status' in result\n";
1372 };
1373 $self->log('err', "query-status error: $@") if $@;
1374
1375 # Can end up in POSTMIGRATE state if failure occurred after convergence. Try going back to
1376 # original state. Unfortunately, direct transition from POSTMIGRATE to PAUSED is not possible.
1377 if ($vm_status && $vm_status eq 'postmigrate') {
1378 if (!$self->{vm_was_paused}) {
1379 eval { mon_cmd($vmid, 'cont'); };
1380 $self->log('err', "resuming VM failed: $@") if $@;
1381 } else {
1382 $self->log('err', "VM was paused, but ended in postmigrate state");
1383 }
1384 }
1385
1386 my $conf = $self->{vmconf};
1387 delete $conf->{lock};
1388 eval { PVE::QemuConfig->write_config($vmid, $conf) };
1389 if (my $err = $@) {
1390 $self->log('err', $err);
1391 }
1392
1393 # cleanup ressources on target host
1394 if ($self->{storage_migration}) {
1395 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1396 if (my $err = $@) {
1397 $self->log('err', $err);
1398 }
1399 }
1400
1401 eval { $self->cleanup_bitmaps() };
1402 if (my $err =$@) {
1403 $self->log('err', $err);
1404 }
1405
1406 my $nodename = PVE::INotify::nodename();
1407
1408 if ($self->{tunnel} && $self->{tunnel}->{version} >= 2) {
1409 PVE::Tunnel::write_tunnel($self->{tunnel}, 10, 'stop');
1410 } else {
1411 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1412 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1413 if (my $err = $@) {
1414 $self->log('err', $err);
1415 $self->{errors} = 1;
1416 }
1417 }
1418
1419 # cleanup after stopping, otherwise disks might be in-use by target VM!
1420 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1421 if (my $err = $@) {
1422 $self->log('err', $err);
1423 }
1424
1425
1426 if ($self->{tunnel}) {
1427 eval { PVE::Tunnel::finish_tunnel($self->{tunnel}); };
1428 if (my $err = $@) {
1429 $self->log('err', $err);
1430 $self->{errors} = 1;
1431 }
1432 }
1433 }
1434
1435 sub phase3 {
1436 my ($self, $vmid) = @_;
1437
1438 return;
1439 }
1440
1441 sub phase3_cleanup {
1442 my ($self, $vmid, $err) = @_;
1443
1444 my $conf = $self->{vmconf};
1445 return if $self->{phase2errors};
1446
1447 my $tunnel = $self->{tunnel};
1448
1449 if ($self->{volume_map} && !$self->{opts}->{remote}) {
1450 my $target_drives = $self->{target_drive};
1451
1452 # FIXME: for NBD storage migration we now only update the volid, and
1453 # not the full drivestr from the target node. Workaround that until we
1454 # got some real rescan, to avoid things like wrong format in the drive
1455 delete $conf->{$_} for keys %$target_drives;
1456 PVE::QemuConfig->update_volume_ids($conf, $self->{volume_map});
1457
1458 for my $drive (keys %$target_drives) {
1459 $conf->{$drive} = $target_drives->{$drive}->{drivestr};
1460 }
1461 PVE::QemuConfig->write_config($vmid, $conf);
1462 }
1463
1464 # transfer replication state before move config
1465 if (!$self->{opts}->{remote}) {
1466 $self->transfer_replication_state() if $self->{is_replicated};
1467 PVE::QemuConfig->move_config_to_node($vmid, $self->{node});
1468 $self->switch_replication_job_target() if $self->{is_replicated};
1469 }
1470
1471 if ($self->{livemigration}) {
1472 if ($self->{stopnbd}) {
1473 $self->log('info', "stopping NBD storage migration server on target.");
1474 # stop nbd server on remote vm - requirement for resume since 2.9
1475 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 2) {
1476 PVE::Tunnel::write_tunnel($tunnel, 30, 'nbdstop');
1477 } else {
1478 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
1479
1480 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1481 if (my $err = $@) {
1482 $self->log('err', $err);
1483 $self->{errors} = 1;
1484 }
1485 }
1486 }
1487
1488 # deletes local FDB entries if learning is disabled, they'll be re-added on target on resume
1489 PVE::QemuServer::del_nets_bridge_fdb($conf, $vmid);
1490
1491 if (!$self->{vm_was_paused}) {
1492 # config moved and nbd server stopped - now we can resume vm on target
1493 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1494 my $cmd = $tunnel->{version} == 1 ? "resume $vmid" : "resume";
1495 eval {
1496 PVE::Tunnel::write_tunnel($tunnel, 30, $cmd);
1497 };
1498 if (my $err = $@) {
1499 $self->log('err', $err);
1500 $self->{errors} = 1;
1501 }
1502 } else {
1503 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1504 my $logf = sub {
1505 my $line = shift;
1506 $self->log('err', $line);
1507 };
1508 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1509 if (my $err = $@) {
1510 $self->log('err', $err);
1511 $self->{errors} = 1;
1512 }
1513 }
1514 }
1515
1516 if (
1517 $self->{storage_migration}
1518 && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks}
1519 && $self->{running}
1520 ) {
1521 if (!$self->{vm_was_paused}) {
1522 $self->log('info', "issuing guest fstrim");
1523 if ($self->{opts}->{remote}) {
1524 PVE::Tunnel::write_tunnel($self->{tunnel}, 600, 'fstrim');
1525 } else {
1526 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1527 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1528 if (my $err = $@) {
1529 $self->log('err', "fstrim failed - $err");
1530 $self->{errors} = 1;
1531 }
1532 }
1533 } else {
1534 $self->log('info', "skipping guest fstrim, because VM is paused");
1535 }
1536 }
1537 }
1538
1539 # close tunnel on successful migration, on error phase2_cleanup closed it
1540 if ($tunnel && $tunnel->{version} == 1) {
1541 eval { PVE::Tunnel::finish_tunnel($tunnel); };
1542 if (my $err = $@) {
1543 $self->log('err', $err);
1544 $self->{errors} = 1;
1545 }
1546 $tunnel = undef;
1547 delete $self->{tunnel};
1548 }
1549
1550 eval {
1551 my $timer = 0;
1552 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1553 $self->log('info', "Waiting for spice server migration");
1554 while (1) {
1555 my $res = mon_cmd($vmid, 'query-spice');
1556 last if int($res->{'migrated'}) == 1;
1557 last if $timer > 50;
1558 $timer ++;
1559 usleep(200000);
1560 }
1561 }
1562 };
1563
1564 # always stop local VM
1565 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1566 if (my $err = $@) {
1567 $self->log('err', "stopping vm failed - $err");
1568 $self->{errors} = 1;
1569 }
1570
1571 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1572 eval {
1573 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1574 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1575 };
1576 if (my $err = $@) {
1577 $self->log('err', $err);
1578 $self->{errors} = 1;
1579 }
1580
1581 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
1582
1583 # destroy local copies
1584 foreach my $volid (@not_replicated_volumes) {
1585 # remote is cleaned up below
1586 next if $self->{opts}->{remote};
1587
1588 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1589 if (my $err = $@) {
1590 $self->log('err', "removing local copy of '$volid' failed - $err");
1591 $self->{errors} = 1;
1592 last if $err =~ /^interrupted by signal$/;
1593 }
1594 }
1595
1596 # clear migrate lock
1597 if ($tunnel && $tunnel->{version} >= 2) {
1598 PVE::Tunnel::write_tunnel($tunnel, 10, "unlock");
1599
1600 PVE::Tunnel::finish_tunnel($tunnel);
1601 } else {
1602 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1603 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1604 }
1605
1606 if ($self->{opts}->{remote} && $self->{opts}->{delete}) {
1607 eval { PVE::QemuServer::destroy_vm($self->{storecfg}, $vmid, 1, undef, 0) };
1608 warn "Failed to remove source VM - $@\n" if $@;
1609 }
1610 }
1611
1612 sub final_cleanup {
1613 my ($self, $vmid) = @_;
1614
1615 # nothing to do
1616 }
1617
1618 sub round_powerof2 {
1619 return 1 if $_[0] < 2;
1620 return 2 << int(log($_[0]-1)/log(2));
1621 }
1622
1623 1;