]> git.proxmox.com Git - qemu-server.git/blame - PVE/QemuMigrate.pm
bump version to 6.4-1
[qemu-server.git] / PVE / QemuMigrate.pm
CommitLineData
3ea94c60 1package PVE::QemuMigrate;
1ef75254 2
1e3baf05 3use strict;
3ea94c60 4use warnings;
6d7450cb 5
3ea94c60 6use IO::File;
1e3baf05 7use IPC::Open2;
61b04c6d 8use POSIX qw( WNOHANG );
6d7450cb
TL
9use Time::HiRes qw( usleep );
10
0fca250a 11use PVE::Format qw(render_bytes);
3ea94c60 12use PVE::Cluster;
4b26ffbf 13use PVE::GuestHelpers qw(safe_boolean_ne safe_string_ne);
6d7450cb
TL
14use PVE::INotify;
15use PVE::RPCEnvironment;
16use PVE::Replication;
17use PVE::ReplicationConfig;
18use PVE::ReplicationState;
1e3baf05 19use PVE::Storage;
6d7450cb
TL
20use PVE::Tools;
21
912792e2 22use PVE::QemuConfig;
58c64ad5 23use PVE::QemuServer::CPUConfig;
e0fd2b2f 24use PVE::QemuServer::Drive;
28e6e180 25use PVE::QemuServer::Helpers qw(min_version);
3392d6ca 26use PVE::QemuServer::Machine;
0a13e08e 27use PVE::QemuServer::Monitor qw(mon_cmd);
6d7450cb 28use PVE::QemuServer;
1e3baf05 29
6d7450cb 30use PVE::AbstractMigrate;
16e903f2 31use base qw(PVE::AbstractMigrate);
1e3baf05 32
1ef75254 33sub fork_command_pipe {
46a84fd4 34 my ($self, $cmd) = @_;
19672434 35
1ef75254
DM
36 my $reader = IO::File->new();
37 my $writer = IO::File->new();
38
39 my $orig_pid = $$;
40
41 my $cpid;
42
43 eval { $cpid = open2($reader, $writer, @$cmd); };
44
45 my $err = $@;
46
47 # catch exec errors
48 if ($orig_pid != $$) {
46a84fd4 49 $self->log('err', "can't fork command pipe\n");
19672434
DM
50 POSIX::_exit(1);
51 kill('KILL', $$);
1ef75254
DM
52 }
53
54 die $err if $err;
55
56 return { writer => $writer, reader => $reader, pid => $cpid };
57}
58
19672434 59sub finish_command_pipe {
97439670 60 my ($self, $cmdpipe, $timeout) = @_;
1ef75254 61
61b04c6d
TL
62 my $cpid = $cmdpipe->{pid};
63 return if !defined($cpid);
64
1ef75254
DM
65 my $writer = $cmdpipe->{writer};
66 my $reader = $cmdpipe->{reader};
67
68 $writer->close();
69 $reader->close();
70
61b04c6d
TL
71 my $collect_child_process = sub {
72 my $res = waitpid($cpid, WNOHANG);
73 if (defined($res) && ($res == $cpid)) {
74 delete $cmdpipe->{cpid};
75 return 1;
76 } else {
77 return 0;
78 }
79 };
1ef75254 80
97439670
DM
81 if ($timeout) {
82 for (my $i = 0; $i < $timeout; $i++) {
61b04c6d 83 return if &$collect_child_process();
97439670
DM
84 sleep(1);
85 }
86 }
87
88 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
89 kill(15, $cpid);
1ef75254 90
97439670
DM
91 # wait again
92 for (my $i = 0; $i < 10; $i++) {
61b04c6d 93 return if &$collect_child_process();
97439670
DM
94 sleep(1);
95 }
96
97 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
98 kill 9, $cpid;
99 sleep 1;
61b04c6d
TL
100
101 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
102 if !&$collect_child_process();
1ef75254
DM
103}
104
e0eb1f76
FG
105sub read_tunnel {
106 my ($self, $tunnel, $timeout) = @_;
107
108 $timeout = 60 if !defined($timeout);
109
110 my $reader = $tunnel->{reader};
111
112 my $output;
113 eval {
114 PVE::Tools::run_with_timeout($timeout, sub { $output = <$reader>; });
115 };
116 die "reading from tunnel failed: $@\n" if $@;
117
118 chomp $output;
119
120 return $output;
121}
122
123sub write_tunnel {
124 my ($self, $tunnel, $timeout, $command) = @_;
125
126 $timeout = 60 if !defined($timeout);
127
128 my $writer = $tunnel->{writer};
129
130 eval {
131 PVE::Tools::run_with_timeout($timeout, sub {
132 print $writer "$command\n";
133 $writer->flush();
134 });
135 };
136 die "writing to tunnel failed: $@\n" if $@;
bcb51ae8
FG
137
138 if ($tunnel->{version} && $tunnel->{version} >= 1) {
139 my $res = eval { $self->read_tunnel($tunnel, 10); };
140 die "no reply to command '$command': $@\n" if $@;
141
142 if ($res eq 'OK') {
143 return;
144 } else {
145 die "tunnel replied '$res' to command '$command'\n";
146 }
147 }
e0eb1f76
FG
148}
149
1e3baf05 150sub fork_tunnel {
ae194a5c 151 my ($self, $ssh_forward_info) = @_;
1e3baf05 152
7827de41 153 my @localtunnelinfo = ();
ae194a5c 154 foreach my $addr (@$ssh_forward_info) {
7827de41
ML
155 push @localtunnelinfo, '-L', $addr;
156 }
5bc1e039 157
d7b1b24b 158 my $cmd = [@{$self->{rem_ssh}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
19672434 159
46a84fd4 160 my $tunnel = $self->fork_command_pipe($cmd);
1e3baf05 161
19672434 162 eval {
e0eb1f76 163 my $helo = $self->read_tunnel($tunnel, 60);
1e3baf05 164 die "no reply\n" if !$helo;
1ef75254 165 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
19672434 166 die "got strange reply from mtunnel ('$helo')\n"
1e3baf05
DM
167 if $helo !~ m/^tunnel online$/;
168 };
169 my $err = $@;
170
58cbe639
FG
171 eval {
172 my $ver = $self->read_tunnel($tunnel, 10);
173 if ($ver =~ /^ver (\d+)$/) {
174 $tunnel->{version} = $1;
175 $self->log('info', "ssh tunnel $ver\n");
176 } else {
177 $err = "received invalid tunnel version string '$ver'\n" if !$err;
178 }
179 };
180
1e3baf05 181 if ($err) {
46a84fd4 182 $self->finish_command_pipe($tunnel);
1e3baf05
DM
183 die "can't open migration tunnel - $err";
184 }
185 return $tunnel;
186}
187
19672434 188sub finish_tunnel {
16e903f2 189 my ($self, $tunnel) = @_;
1e3baf05 190
e0eb1f76 191 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
1e3baf05 192 my $err = $@;
19672434 193
97439670 194 $self->finish_command_pipe($tunnel, 30);
19672434 195
ae194a5c 196 if (my $unix_sockets = $tunnel->{unix_sockets}) {
1c9d54bf 197 # ssh does not clean up on local host
ae194a5c 198 my $cmd = ['rm', '-f', @$unix_sockets];
1c9d54bf
TL
199 PVE::Tools::run_command($cmd);
200
201 # .. and just to be sure check on remote side
202 unshift @{$cmd}, @{$self->{rem_ssh}};
203 PVE::Tools::run_command($cmd);
204 }
205
1e3baf05
DM
206 die $err if $err;
207}
208
7d730f95
FE
209sub start_remote_tunnel {
210 my ($self, $raddr, $rport, $ruri, $unix_socket_info) = @_;
211
212 my $nodename = PVE::INotify::nodename();
213 my $migration_type = $self->{opts}->{migration_type};
214
215 if ($migration_type eq 'secure') {
216
217 if ($ruri =~ /^unix:/) {
218 my $ssh_forward_info = ["$raddr:$raddr"];
219 $unix_socket_info->{$raddr} = 1;
220
221 my $unix_sockets = [ keys %$unix_socket_info ];
222 for my $sock (@$unix_sockets) {
223 push @$ssh_forward_info, "$sock:$sock";
224 unlink $sock;
225 }
226
227 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
228
229 my $unix_socket_try = 0; # wait for the socket to become ready
230 while ($unix_socket_try <= 100) {
231 $unix_socket_try++;
232 my $available = 0;
233 foreach my $sock (@$unix_sockets) {
234 if (-S $sock) {
235 $available++;
236 }
237 }
238
239 if ($available == @$unix_sockets) {
240 last;
241 }
242
243 usleep(50000);
244 }
245 if ($unix_socket_try > 100) {
246 $self->{errors} = 1;
247 $self->finish_tunnel($self->{tunnel});
248 die "Timeout, migration socket $ruri did not get ready";
249 }
250 $self->{tunnel}->{unix_sockets} = $unix_sockets if (@$unix_sockets);
251
252 } elsif ($ruri =~ /^tcp:/) {
253 my $ssh_forward_info = [];
254 if ($raddr eq "localhost") {
255 # for backwards compatibility with older qemu-server versions
256 my $pfamily = PVE::Tools::get_host_address_family($nodename);
257 my $lport = PVE::Tools::next_migrate_port($pfamily);
258 push @$ssh_forward_info, "$lport:localhost:$rport";
259 }
260
261 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
262
263 } else {
264 die "unsupported protocol in migration URI: $ruri\n";
265 }
266 } else {
267 #fork tunnel for insecure migration, to send faster commands like resume
268 $self->{tunnel} = $self->fork_tunnel();
269 }
270}
271
16e903f2
DM
272sub lock_vm {
273 my ($self, $vmid, $code, @param) = @_;
f5eb281a 274
ffda963f 275 return PVE::QemuConfig->lock_config($vmid, $code, @param);
16e903f2 276}
ff1a2432 277
16e903f2
DM
278sub prepare {
279 my ($self, $vmid) = @_;
ff1a2432 280
16e903f2 281 my $online = $self->{opts}->{online};
3ea94c60 282
16e903f2 283 $self->{storecfg} = PVE::Storage::config();
3ea94c60 284
e1fc368d 285 # test if VM exists
ffda963f 286 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
3ea94c60 287
c2c96d73
FE
288 my $repl_conf = PVE::ReplicationConfig->new();
289 $self->{replication_jobcfg} = $repl_conf->find_local_replication_job($vmid, $self->{node});
290 $self->{is_replicated} = $repl_conf->check_for_existing_jobs($vmid, 1);
291
19ff3682
FE
292 if ($self->{replication_jobcfg} && defined($self->{replication_jobcfg}->{remove_job})) {
293 die "refusing to migrate replicated VM whose replication job is marked for removal\n";
294 }
295
ffda963f 296 PVE::QemuConfig->check_lock($conf);
3ea94c60 297
16e903f2
DM
298 my $running = 0;
299 if (my $pid = PVE::QemuServer::check_running($vmid)) {
b6adff33 300 die "can't migrate running VM without --online\n" if !$online;
16e903f2 301 $running = $pid;
42dbd2ee 302
c2c96d73 303 if ($self->{is_replicated} && !$self->{replication_jobcfg}) {
68980d66
FE
304 if ($self->{opts}->{force}) {
305 $self->log('warn', "WARNING: Node '$self->{node}' is not a replication target. Existing " .
306 "replication jobs will fail after migration!\n");
307 } else {
308 die "Cannot live-migrate replicated VM to node '$self->{node}' - not a replication " .
309 "target. Use 'force' to override.\n";
310 }
311 }
312
3392d6ca 313 $self->{forcemachine} = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
7bac824e 314
58c64ad5
SR
315 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
316 # Since the parameter itself contains no reference to a custom model,
317 # this makes migration independent of changes to "cpu-models.conf".
318 if ($conf->{cpu}) {
b53ba8d0 319 my $cpuconf = PVE::JSONSchema::parse_property_string('pve-cpu-conf', $conf->{cpu});
58c64ad5
SR
320 if ($cpuconf && PVE::QemuServer::CPUConfig::is_custom_model($cpuconf->{cputype})) {
321 $self->{forcecpu} = PVE::QemuServer::CPUConfig::get_cpu_from_running_vm($pid);
322 }
323 }
3ea94c60 324 }
58c64ad5 325
ca6abacf
TM
326 my $loc_res = PVE::QemuServer::check_local_resources($conf, 1);
327 if (scalar @$loc_res) {
16e903f2 328 if ($self->{running} || !$self->{opts}->{force}) {
ca6abacf 329 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
16e903f2
DM
330 } else {
331 $self->log('info', "migrating VM which uses local devices");
332 }
3ea94c60
DM
333 }
334
ff1a2432 335 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
16e903f2 336
29701766
FG
337 foreach my $volid (@$vollist) {
338 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
339
340 # check if storage is available on both nodes
bf8fc5a3 341 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $sid);
b74cad8a 342
29701766 343 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
b74cad8a 344 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
73f5ee92
FG
345
346 if ($scfg->{shared}) {
347 # PVE::Storage::activate_storage checks this for non-shared storages
348 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
349 warn "Used shared storage '$sid' is not online on source node!\n"
350 if !$plugin->check_connection($sid, $scfg);
73f5ee92 351 }
29701766 352 }
3ea94c60
DM
353
354 # test ssh connection
16e903f2
DM
355 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
356 eval { $self->cmd_quiet($cmd); };
3ea94c60 357 die "Can't connect to destination address using public key\n" if $@;
ff1a2432 358
16e903f2 359 return $running;
3ea94c60
DM
360}
361
d10b78f4 362sub scan_local_volumes {
16e903f2
DM
363 my ($self, $vmid) = @_;
364
16e903f2
DM
365 my $conf = $self->{vmconf};
366
dabf2473 367 # local volumes which have been copied
37666e4c 368 # and their old_id => new_id pairs
37666e4c 369 $self->{volume_map} = {};
d10b78f4 370 $self->{local_volumes} = {};
3ea94c60 371
b10afa31 372 my $storecfg = $self->{storecfg};
3ea94c60
DM
373 eval {
374
dabf2473 375 # found local volumes and their origin
d10b78f4 376 my $local_volumes = $self->{local_volumes};
5bf7f0f1
FG
377 my $local_volumes_errors = {};
378 my $other_errors = [];
379 my $abort = 0;
3ea94c60 380
5bf7f0f1
FG
381 my $log_error = sub {
382 my ($msg, $volid) = @_;
383
384 if (defined($volid)) {
385 $local_volumes_errors->{$volid} = $msg;
386 } else {
387 push @$other_errors, $msg;
388 }
389 $abort = 1;
390 };
391
b10afa31 392 my @sids = PVE::Storage::storage_ids($storecfg);
86638cc2 393 foreach my $storeid (@sids) {
b10afa31 394 my $scfg = PVE::Storage::storage_config($storecfg, $storeid);
86638cc2 395 next if $scfg->{shared};
b10afa31 396 next if !PVE::Storage::storage_check_enabled($storecfg, $storeid, undef, 1);
373ea579 397
86638cc2 398 # get list from PVE::Storage (for unused volumes)
b10afa31 399 my $dl = PVE::Storage::vdisk_list($storecfg, $storeid, $vmid);
89719f98
FG
400
401 next if @{$dl->{$storeid}} == 0;
402
bf8fc5a3 403 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $storeid);
86638cc2 404 # check if storage is available on target node
b10afa31 405 PVE::Storage::storage_check_node($storecfg, $targetsid, $self->{node});
89719f98 406
bf8fc5a3
FG
407 # grandfather in existing mismatches
408 if ($targetsid ne $storeid) {
409 my $target_scfg = PVE::Storage::storage_config($storecfg, $targetsid);
410 die "content type 'images' is not available on storage '$targetsid'\n"
411 if !$target_scfg->{content}->{images};
412 }
413
c3417e3b
FE
414 my $bwlimit = PVE::Storage::get_bandwidth_limit(
415 'migration',
416 [$targetsid, $storeid],
417 $self->{opts}->{bwlimit},
418 );
419
86638cc2 420 PVE::Storage::foreach_volid($dl, sub {
5eca0c36 421 my ($volid, $sid, $volinfo) = @_;
80b2cbd1 422
6f58fce9 423 $local_volumes->{$volid}->{ref} = 'storage';
62a4c963 424 $local_volumes->{$volid}->{size} = $volinfo->{size};
c3417e3b
FE
425 $local_volumes->{$volid}->{targetsid} = $targetsid;
426 $local_volumes->{$volid}->{bwlimit} = $bwlimit;
5eca0c36
FE
427
428 # If with_snapshots is not set for storage migrate, it tries to use
429 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
430 # back to qcow2 is currently not possible.
431 $local_volumes->{$volid}->{snapshots} = ($volinfo->{format} =~ /^(?:qcow2|vmdk)$/);
0ad295f9 432 $local_volumes->{$volid}->{format} = $volinfo->{format};
86638cc2
FG
433 });
434 }
3ea94c60 435
c2c96d73 436 my $replicatable_volumes = !$self->{replication_jobcfg} ? {}
2cd808d3 437 : PVE::QemuConfig->get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
4b26ffbf
FE
438 foreach my $volid (keys %{$replicatable_volumes}) {
439 $local_volumes->{$volid}->{replicated} = 1;
440 }
b9f44d27 441
3629c19d 442 my $test_volid = sub {
aee6abe5 443 my ($volid, $attr) = @_;
3ea94c60 444
5bf7f0f1 445 if ($volid =~ m|^/|) {
ec82e3ee 446 return if $attr->{shared};
6f58fce9 447 $local_volumes->{$volid}->{ref} = 'config';
5bf7f0f1
FG
448 die "local file/device\n";
449 }
3ea94c60 450
aee6abe5
DM
451 my $snaprefs = $attr->{referenced_in_snapshot};
452
453 if ($attr->{cdrom}) {
5bf7f0f1
FG
454 if ($volid eq 'cdrom') {
455 my $msg = "can't migrate local cdrom drive";
5009a8c7 456 if (defined($snaprefs) && !$attr->{referenced_in_config}) {
aee6abe5 457 my $snapnames = join(', ', sort keys %$snaprefs);
5009a8c7 458 $msg .= " (referenced in snapshot - $snapnames)";
aee6abe5 459 }
5bf7f0f1
FG
460 &$log_error("$msg\n");
461 return;
462 }
3ea94c60 463 return if $volid eq 'none';
3ea94c60
DM
464 }
465
466 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
467
bf8fc5a3 468 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $sid);
16e903f2 469 # check if storage is available on both nodes
b10afa31
TL
470 my $scfg = PVE::Storage::storage_check_node($storecfg, $sid);
471 PVE::Storage::storage_check_node($storecfg, $targetsid, $self->{node});
3ea94c60
DM
472
473 return if $scfg->{shared};
474
6f58fce9 475 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config} ? 'config' : 'snapshot';
ae180b8f 476 $local_volumes->{$volid}->{ref} = 'storage' if $attr->{is_unused};
d62fcf74 477
cc1a3820
FE
478 $local_volumes->{$volid}->{is_vmstate} = $attr->{is_vmstate} ? 1 : 0;
479
a6be63ac
FE
480 $local_volumes->{$volid}->{drivename} = $attr->{drivename}
481 if $attr->{drivename};
482
9e93a63f
ML
483 if ($attr->{cdrom}) {
484 if ($volid =~ /vm-\d+-cloudinit/) {
485 $local_volumes->{$volid}->{ref} = 'generated';
486 return;
487 }
488 die "local cdrom image\n";
489 }
3629c19d 490
b10afa31 491 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
3ea94c60 492
5bf7f0f1 493 die "owned by other VM (owner = VM $owner)\n"
b10afa31 494 if !$owner || ($owner != $vmid);
3ea94c60 495
b24f07d4
FE
496 return if $attr->{is_vmstate};
497
aee6abe5 498 if (defined($snaprefs)) {
5eca0c36
FE
499 $local_volumes->{$volid}->{snapshots} = 1;
500
3629c19d
DM
501 # we cannot migrate shapshots on local storage
502 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
503
b74cad8a 504 die "online storage migration not possible if snapshot exists\n" if $self->{running};
0ad295f9 505 if (!($scfg->{type} eq 'zfspool' || $local_volumes->{$volid}->{format} eq 'qcow2')) {
5bf7f0f1 506 die "non-migratable snapshot exists\n";
3629c19d 507 }
3629c19d 508 }
3a7bc9e2
FG
509
510 die "referenced by linked clone(s)\n"
b10afa31 511 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
3629c19d
DM
512 };
513
aee6abe5
DM
514 PVE::QemuServer::foreach_volid($conf, sub {
515 my ($volid, $attr) = @_;
516 eval { $test_volid->($volid, $attr); };
517 if (my $err = $@) {
518 &$log_error($err, $volid);
519 }
520 });
3ea94c60 521
dabf2473 522 foreach my $vol (sort keys %$local_volumes) {
b9f44d27 523 my $type = $replicatable_volumes->{$vol} ? 'local, replicated' : 'local';
6f58fce9
WB
524 my $ref = $local_volumes->{$vol}->{ref};
525 if ($ref eq 'storage') {
b9f44d27 526 $self->log('info', "found $type disk '$vol' (via storage)\n");
6f58fce9 527 } elsif ($ref eq 'config') {
dbc9420b
DM
528 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
529 if $self->{running} && !$self->{opts}->{"with-local-disks"};
b9f44d27 530 $self->log('info', "found $type disk '$vol' (in current VM config)\n");
6f58fce9 531 } elsif ($ref eq 'snapshot') {
b9f44d27 532 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
9e93a63f
ML
533 } elsif ($ref eq 'generated') {
534 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
d62fcf74 535 } else {
b9f44d27 536 $self->log('info', "found $type disk '$vol'\n");
d62fcf74
FG
537 }
538 }
539
5bf7f0f1
FG
540 foreach my $vol (sort keys %$local_volumes_errors) {
541 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
542 }
543 foreach my $err (@$other_errors) {
544 $self->log('warn', "$err");
545 }
546
5bf7f0f1
FG
547 if ($abort) {
548 die "can't migrate VM - check log\n";
549 }
550
c4d2d6c1 551 # additional checks for local storage
dabf2473 552 foreach my $volid (keys %$local_volumes) {
3ea94c60 553 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
b10afa31 554 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
3ea94c60 555
dad06e20 556 my $migratable = $scfg->{type} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
c4d2d6c1 557
37a6dc78 558 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
c4d2d6c1 559 if !$migratable;
d5604092 560
c4d2d6c1 561 # image is a linked clone on local storage, se we can't migrate.
b10afa31 562 if (my $basename = (PVE::Storage::parse_volname($storecfg, $volid))[3]) {
c4d2d6c1 563 die "can't migrate '$volid' as it's a clone of '$basename'";
d5604092 564 }
3ea94c60
DM
565 }
566
eb3acec8 567 foreach my $volid (sort keys %$local_volumes) {
9e93a63f
ML
568 my $ref = $local_volumes->{$volid}->{ref};
569 if ($self->{running} && $ref eq 'config') {
efe0d457 570 $local_volumes->{$volid}->{migration_mode} = 'online';
ad8b9d5e
FE
571 } elsif ($self->{running} && $ref eq 'generated') {
572 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n";
b74cad8a 573 } else {
d10b78f4 574 $local_volumes->{$volid}->{migration_mode} = 'offline';
b74cad8a 575 }
3ea94c60
DM
576 }
577 };
d10b78f4
FE
578 die "Problem found while scanning volumes - $@" if $@;
579}
580
a6be63ac
FE
581sub handle_replication {
582 my ($self, $vmid) = @_;
583
584 my $conf = $self->{vmconf};
585 my $local_volumes = $self->{local_volumes};
586
587 return if !$self->{replication_jobcfg};
588 if ($self->{running}) {
589
590 my $version = PVE::QemuServer::kvm_user_version();
591 if (!min_version($version, 4, 2)) {
592 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
593 }
594
595 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
596 foreach my $volid (@live_replicatable_volumes) {
597 my $drive = $local_volumes->{$volid}->{drivename};
598 die "internal error - no drive for '$volid'\n" if !defined($drive);
599
600 my $bitmap = "repl_$drive";
601
602 # start tracking before replication to get full delta + a few duplicates
603 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
604 mon_cmd($vmid, 'block-dirty-bitmap-add', node => "drive-$drive", name => $bitmap);
605
606 # other info comes from target node in phase 2
607 $self->{target_drive}->{$drive}->{bitmap} = $bitmap;
608 }
609 }
610 $self->log('info', "replicating disk images");
611
612 my $start_time = time();
613 my $logfunc = sub { $self->log('info', shift) };
614 my $actual_replicated_volumes = PVE::Replication::run_replication(
615 'PVE::QemuConfig', $self->{replication_jobcfg}, $start_time, $start_time, $logfunc);
616
617 # extra safety check
618 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
619 foreach my $volid (@replicated_volumes) {
620 die "expected volume '$volid' to get replicated, but it wasn't\n"
621 if !$actual_replicated_volumes->{$volid};
622 }
623}
624
3276a434
FE
625sub config_update_local_disksizes {
626 my ($self) = @_;
627
628 my $conf = $self->{vmconf};
629 my $local_volumes = $self->{local_volumes};
630
631 PVE::QemuConfig->foreach_volume($conf, sub {
632 my ($key, $drive) = @_;
633 return if $key eq 'efidisk0'; # skip efidisk, will be handled later
634
635 my $volid = $drive->{file};
636 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
637
638 my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $local_volumes->{$volid}->{size});
639 if (defined($updated)) {
640 $conf->{$key} = PVE::QemuServer::print_drive($updated);
641 $self->log('info', "drive '$key': $msg");
642 }
643 });
644
645 # we want to set the efidisk size in the config to the size of the
646 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
647 if (defined($conf->{efidisk0})) {
648 PVE::QemuServer::update_efidisk_size($conf);
649 }
650}
651
d10b78f4 652sub filter_local_volumes {
4b26ffbf 653 my ($self, $migration_mode, $replicated) = @_;
d10b78f4
FE
654
655 my $volumes = $self->{local_volumes};
656 my @filtered_volids;
657
658 foreach my $volid (sort keys %{$volumes}) {
659 next if defined($migration_mode) && safe_string_ne($volumes->{$volid}->{migration_mode}, $migration_mode);
4b26ffbf 660 next if defined($replicated) && safe_boolean_ne($volumes->{$volid}->{replicated}, $replicated);
d10b78f4
FE
661 push @filtered_volids, $volid;
662 }
663
664 return @filtered_volids;
665}
666
667sub sync_offline_local_volumes {
668 my ($self) = @_;
669
670 my $local_volumes = $self->{local_volumes};
4b26ffbf 671 my @volids = $self->filter_local_volumes('offline', 0);
d10b78f4
FE
672
673 my $storecfg = $self->{storecfg};
674 my $opts = $self->{opts};
675
676 $self->log('info', "copying local disk images") if scalar(@volids);
677
678 foreach my $volid (@volids) {
c3417e3b
FE
679 my $targetsid = $local_volumes->{$volid}->{targetsid};
680 my $bwlimit = $local_volumes->{$volid}->{bwlimit};
681 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
d10b78f4
FE
682
683 my $storage_migrate_opts = {
684 'ratelimit_bps' => $bwlimit,
685 'insecure' => $opts->{migration_type} eq 'insecure',
686 'with_snapshots' => $local_volumes->{$volid}->{snapshots},
687 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate},
688 };
689
690 my $logfunc = sub { $self->log('info', $_[0]); };
691 my $new_volid = eval {
692 PVE::Storage::storage_migrate($storecfg, $volid, $self->{ssh_info},
693 $targetsid, $storage_migrate_opts, $logfunc);
694 };
695 if (my $err = $@) {
696 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
697 }
698
699 $self->{volume_map}->{$volid} = $new_volid;
700 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
701
702 eval { PVE::Storage::deactivate_volumes($storecfg, [$volid]); };
703 if (my $err = $@) {
704 $self->log('warn', $err);
705 }
706 }
3ea94c60
DM
707}
708
b74cad8a
AD
709sub cleanup_remotedisks {
710 my ($self) = @_;
711
4b26ffbf
FE
712 my $local_volumes = $self->{local_volumes};
713
eb5751ba 714 foreach my $volid (values %{$self->{volume_map}}) {
9b6efe43 715 # don't clean up replicated disks!
4b26ffbf 716 next if $local_volumes->{$volid}->{replicated};
b74cad8a 717
eb5751ba 718 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
b74cad8a
AD
719
720 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
721
722 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
723 if (my $err = $@) {
724 $self->log('err', $err);
725 $self->{errors} = 1;
726 }
727 }
728}
729
9b6efe43
FG
730sub cleanup_bitmaps {
731 my ($self) = @_;
7f5fb49a 732 foreach my $drive (keys %{$self->{target_drive}}) {
9b6efe43
FG
733 my $bitmap = $self->{target_drive}->{$drive}->{bitmap};
734 next if !$bitmap;
735 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
736 mon_cmd($self->{vmid}, 'block-dirty-bitmap-remove', node => "drive-$drive", name => $bitmap);
737 }
738}
739
1e3baf05 740sub phase1 {
16e903f2 741 my ($self, $vmid) = @_;
1e3baf05 742
16e903f2 743 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
1e3baf05 744
16e903f2 745 my $conf = $self->{vmconf};
1e3baf05
DM
746
747 # set migrate lock in config file
1858638f 748 $conf->{lock} = 'migrate';
ffda963f 749 PVE::QemuConfig->write_config($vmid, $conf);
1e3baf05 750
d10b78f4 751 $self->scan_local_volumes($vmid);
3276a434
FE
752
753 # fix disk sizes to match their actual size and write changes,
754 # so that the target allocates the correct volumes
755 $self->config_update_local_disksizes();
68b108ee 756 PVE::QemuConfig->write_config($vmid, $conf);
d10b78f4 757
a6be63ac
FE
758 $self->handle_replication($vmid);
759
d10b78f4 760 $self->sync_offline_local_volumes();
1e3baf05
DM
761};
762
16e903f2
DM
763sub phase1_cleanup {
764 my ($self, $vmid, $err) = @_;
765
766 $self->log('info', "aborting phase 1 - cleanup resources");
767
1858638f
DM
768 my $conf = $self->{vmconf};
769 delete $conf->{lock};
ffda963f 770 eval { PVE::QemuConfig->write_config($vmid, $conf) };
16e903f2
DM
771 if (my $err = $@) {
772 $self->log('err', $err);
773 }
f5eb281a 774
eb5751ba
FE
775 eval { $self->cleanup_remotedisks() };
776 if (my $err = $@) {
777 $self->log('err', $err);
16e903f2 778 }
9b6efe43
FG
779
780 eval { $self->cleanup_bitmaps() };
781 if (my $err =$@) {
782 $self->log('err', $err);
783 }
16e903f2
DM
784}
785
1e3baf05 786sub phase2 {
16e903f2 787 my ($self, $vmid) = @_;
1e3baf05 788
16e903f2 789 my $conf = $self->{vmconf};
c3417e3b 790 my $local_volumes = $self->{local_volumes};
efe0d457
FE
791 my @online_local_volumes = $self->filter_local_volumes('online');
792
793 $self->{storage_migration} = 1 if scalar(@online_local_volumes);
16e903f2 794
46a84fd4 795 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
1e3baf05 796
5bc1e039 797 my $raddr;
1e3baf05 798 my $rport;
1c9d54bf 799 my $ruri; # the whole migration dst. URI (protocol:address[:port])
7e8dcf2c
AD
800 my $nodename = PVE::INotify::nodename();
801
19672434 802 ## start on remote node
95a4b4a9
AD
803 my $cmd = [@{$self->{rem_ssh}}];
804
7c14dcae 805 my $spice_ticket;
86b8228b 806 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
0a13e08e 807 my $res = mon_cmd($vmid, 'query-spice');
7c14dcae 808 $spice_ticket = $res->{ticket};
95a4b4a9
AD
809 }
810
1c9d54bf
TL
811 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
812
f1c2a53a 813 my $migration_type = $self->{opts}->{migration_type};
2de2d6f7
TL
814
815 push @$cmd, '--migration_type', $migration_type;
816
817 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
818 if $self->{opts}->{migration_network};
819
820 if ($migration_type eq 'insecure') {
1c9d54bf
TL
821 push @$cmd, '--stateuri', 'tcp';
822 } else {
823 push @$cmd, '--stateuri', 'unix';
824 }
95a4b4a9 825
42668529
DM
826 if ($self->{forcemachine}) {
827 push @$cmd, '--machine', $self->{forcemachine};
828 }
829
58c64ad5
SR
830 if ($self->{forcecpu}) {
831 push @$cmd, '--force-cpu', $self->{forcecpu};
832 }
833
efe0d457 834 if ($self->{storage_migration}) {
4530494b 835 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
b74cad8a
AD
836 }
837
86b8228b 838 my $spice_port;
ae194a5c 839 my $unix_socket_info = {};
7827de41
ML
840 # version > 0 for unix socket support
841 my $nbd_protocol_version = 1;
ff09c795
ML
842 # TODO change to 'spice_ticket: <ticket>\n' in 7.0
843 my $input = $spice_ticket ? "$spice_ticket\n" : "\n";
844 $input .= "nbd_protocol_version: $nbd_protocol_version\n";
cee620e6 845
4b26ffbf
FE
846 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
847 foreach my $volid (@online_replicated_volumes) {
efe0d457 848 $input .= "replicated_volume: $volid\n";
88126be3
FG
849 }
850
efbbe59d
FE
851 my $handle_storage_migration_listens = sub {
852 my ($drive_key, $drivestr, $nbd_uri) = @_;
853
854 $self->{stopnbd} = 1;
855 $self->{target_drive}->{$drive_key}->{drivestr} = $drivestr;
856 $self->{target_drive}->{$drive_key}->{nbd_uri} = $nbd_uri;
857
858 my $source_drive = PVE::QemuServer::parse_drive($drive_key, $conf->{$drive_key});
859 my $target_drive = PVE::QemuServer::parse_drive($drive_key, $drivestr);
860 my $source_volid = $source_drive->{file};
861 my $target_volid = $target_drive->{file};
862
863 $self->{volume_map}->{$source_volid} = $target_volid;
864 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
865 };
866
88126be3 867 my $target_replicated_volumes = {};
86b8228b 868
7c14dcae
DM
869 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
870 # instead we pipe it through STDIN
7827de41 871 my $exitcode = PVE::Tools::run_command($cmd, input => $input, outfunc => sub {
1e3baf05
DM
872 my $line = shift;
873
407e0b8b 874 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
5bc1e039
SP
875 $raddr = $1;
876 $rport = int($2);
1c9d54bf
TL
877 $ruri = "tcp:$raddr:$rport";
878 }
879 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
880 $raddr = $1;
881 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
882 $ruri = "unix:$raddr";
5bc1e039
SP
883 }
884 elsif ($line =~ m/^migration listens on port (\d+)$/) {
885 $raddr = "localhost";
86b8228b 886 $rport = int($1);
1c9d54bf 887 $ruri = "tcp:$raddr:$rport";
5bc1e039 888 }
f3a483b6 889 elsif ($line =~ m/^spice listens on port (\d+)$/) {
86b8228b 890 $spice_port = int($1);
1e3baf05 891 }
769f187d 892 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
8b02e568 893 my $drivestr = $4;
b74cad8a
AD
894 my $nbd_uri = "nbd:$1:$2:exportname=$3";
895 my $targetdrive = $3;
896 $targetdrive =~ s/drive-//g;
897
efbbe59d 898 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
7827de41
ML
899 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
900 my $drivestr = $4;
901 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
902 my $nbd_unix_addr = $1;
903 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
904 my $targetdrive = $3;
905 $targetdrive =~ s/drive-//g;
b74cad8a 906
efbbe59d 907 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
ae194a5c 908 $unix_socket_info->{$nbd_unix_addr} = 1;
88126be3
FG
909 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
910 my $drive = $1;
911 my $volid = $2;
912 $target_replicated_volumes->{$volid} = $drive;
8bf30c2a
SR
913 } elsif ($line =~ m/^QEMU: (.*)$/) {
914 $self->log('info', "[$self->{node}] $1\n");
b74cad8a 915 }
ab399b7c
AD
916 }, errfunc => sub {
917 my $line = shift;
8bf30c2a 918 $self->log('info', "[$self->{node}] $line");
6e0216d8
SR
919 }, noerr => 1);
920
921 die "remote command failed with exit code $exitcode\n" if $exitcode;
1e3baf05 922
5bc1e039 923 die "unable to detect remote migration address\n" if !$raddr;
1ef75254 924
4b26ffbf 925 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
88126be3
FG
926 die "number of replicated disks on source and target node do not match - target node too old?\n"
927 }
928
d296ed08 929 $self->log('info', "start remote tunnel");
7d730f95 930 $self->start_remote_tunnel($raddr, $rport, $ruri, $unix_socket_info);
d296ed08 931
efe0d457 932 if ($self->{storage_migration}) {
b74cad8a
AD
933 $self->{storage_migration_jobs} = {};
934 $self->log('info', "starting storage migration");
935
bd2d5fe6 936 die "The number of local disks does not match between the source and the destination.\n"
efe0d457 937 if (scalar(keys %{$self->{target_drive}}) != scalar(@online_local_volumes));
b74cad8a 938 foreach my $drive (keys %{$self->{target_drive}}){
d189e590
SI
939 my $target = $self->{target_drive}->{$drive};
940 my $nbd_uri = $target->{nbd_uri};
683ab654 941
1764fa05 942 my $source_drive = PVE::QemuServer::parse_drive($drive, $conf->{$drive});
97ece9dd 943 my $source_volid = $source_drive->{file};
97ece9dd 944
c3417e3b 945 my $bwlimit = $local_volumes->{$source_volid}->{bwlimit};
9b6efe43 946 my $bitmap = $target->{bitmap};
d189e590 947
d108cb1e 948 $self->log('info', "$drive: start migration to $nbd_uri");
9b6efe43 949 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 'skip', undef, $bwlimit, $bitmap);
b74cad8a
AD
950 }
951 }
952
1c9d54bf 953 $self->log('info', "starting online/live migration on $ruri");
5bc1e039 954 $self->{livemigration} = 1;
e18b0b99 955
3beb415b
AD
956 # load_defaults
957 my $defaults = PVE::QemuServer::load_defaults();
958
7de328c6
TL
959 $self->log('info', "set migration capabilities");
960 eval { PVE::QemuServer::set_migration_caps($vmid) };
485449e3
SR
961 warn $@ if $@;
962
963 my $qemu_migrate_params = {};
964
ddd664d7
SI
965 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
966 # migrate_speed parameter in qm.conf - take the lower of the two.
c3417e3b 967 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', undef, $self->{opts}->{bwlimit}) // 0;
2c4ba4c3 968 my $migrate_speed = $conf->{migrate_speed} // 0;
ddd664d7
SI
969 # migrate_speed is in MB/s, bwlimit in KB/s
970 $migrate_speed *= 1024;
971
2c4ba4c3
FE
972 if ($bwlimit && $migrate_speed) {
973 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
974 } else {
975 $migrate_speed ||= $bwlimit;
976 }
a89bd100 977 $migrate_speed ||= ($defaults->{migrate_speed} || 0) * 1024;
ddd664d7 978
a89bd100
TL
979 if ($migrate_speed) {
980 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
0fca250a 981 $self->log('info', "migration speed limit: ". render_bytes($migrate_speed, 1) ."/s");
a89bd100
TL
982 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
983 }
3beb415b
AD
984
985 my $migrate_downtime = $defaults->{migrate_downtime};
986 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
c05f1b33
SR
987 # migrate-set-parameters expects limit in ms
988 $migrate_downtime *= 1000;
989 $self->log('info', "migration downtime limit: $migrate_downtime ms");
990 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
3beb415b 991
171ed95c
EK
992 # set cachesize to 10% of the total memory
993 my $memory = $conf->{memory} || $defaults->{memory};
994 my $cachesize = int($memory * 1048576 / 10);
50d8dd5d
AD
995 $cachesize = round_powerof2($cachesize);
996
0fca250a 997 $self->log('info', "migration cachesize: " . render_bytes($cachesize, 1));
485449e3
SR
998 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
999
1000 $self->log('info', "set migration parameters");
e18b0b99 1001 eval {
485449e3 1002 mon_cmd($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
e18b0b99 1003 };
485449e3 1004 $self->log('info', "migrate-set-parameters error: $@") if $@;
f34d1466 1005
86b8228b 1006 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
95a4b4a9
AD
1007 my $rpcenv = PVE::RPCEnvironment::get();
1008 my $authuser = $rpcenv->get_user();
1009
86b8228b 1010 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
95a4b4a9 1011
86b8228b 1012 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
769f187d 1013 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
95a4b4a9
AD
1014
1015 $self->log('info', "spice client_migrate_info");
1016
1017 eval {
0a13e08e 1018 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
ccab68c2 1019 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
86b8228b 1020 'cert-subject' => $subject);
95a4b4a9
AD
1021 };
1022 $self->log('info', "client_migrate_info error: $@") if $@;
1023
1024 }
1025
9938d24d
FE
1026 my $start = time();
1027
f34d1466 1028 $self->log('info', "start migrate command to $ruri");
5a7835f5 1029 eval {
0a13e08e 1030 mon_cmd($vmid, "migrate", uri => $ruri);
5a7835f5
AD
1031 };
1032 my $merr = $@;
1c9d54bf 1033 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
1e3baf05 1034
e693c491 1035 my $last_mem_transferred = 0;
4305207d 1036 my $usleep = 1000000;
e52bd94c 1037 my $i = 0;
b0b756c1 1038 my $err_count = 0;
865ef132
SP
1039 my $lastrem = undef;
1040 my $downtimecounter = 0;
1e3baf05 1041 while (1) {
e52bd94c 1042 $i++;
e693c491 1043 my $avglstat = $last_mem_transferred ? $last_mem_transferred / $i : 0;
e52bd94c 1044
b0b756c1 1045 usleep($usleep);
6539865a
TL
1046
1047 my $stat = eval { mon_cmd($vmid, "query-migrate") };
b0b756c1
DM
1048 if (my $err = $@) {
1049 $err_count++;
1050 warn "query migrate failed: $err\n";
f34d1466 1051 $self->log('info', "query migrate failed: $err");
b0b756c1 1052 if ($err_count <= 5) {
6539865a 1053 usleep(1_000_000);
b0b756c1
DM
1054 next;
1055 }
1056 die "too many query migrate failures - aborting\n";
1057 }
985a5f48 1058
6539865a
TL
1059 my $status = $stat->{status};
1060 if (defined($status) && $status =~ m/^(setup)$/im) {
1061 sleep(1);
1062 next;
1063 }
f5eb281a 1064
6539865a
TL
1065 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1066 die $merr if $merr;
1067 die "unable to parse migration status '$status' - aborting\n";
1068 }
1069 $merr = undef;
1070 $err_count = 0;
1071
e693c491
TL
1072 my $memstat = $stat->{ram};
1073
6539865a
TL
1074 if ($status eq 'completed') {
1075 my $delay = time() - $start;
1076 if ($delay > 0) {
0fca250a
TL
1077 my $total = $memstat->{total} || 0;
1078 my $avg_speed = render_bytes($total / $delay, 1);
6539865a 1079 my $downtime = $stat->{downtime} || 0;
0fca250a 1080 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1e3baf05 1081 }
6539865a 1082 }
1e3baf05 1083
6539865a
TL
1084 if ($status eq 'failed' || $status eq 'cancelled') {
1085 $self->log('info', "migration status error: $status");
1086 die "aborting\n"
1087 }
a05b47a8 1088
6539865a
TL
1089 if ($status ne 'active') {
1090 $self->log('info', "migration status: $status");
1091 last;
1092 }
2e787b18 1093
e693c491
TL
1094 if ($memstat->{transferred} ne $last_mem_transferred) {
1095 my $trans = $memstat->{transferred} || 0;
1096 my $rem = $memstat->{remaining} || 0;
1097 my $total = $memstat->{total} || 0;
0fca250a
TL
1098 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1099 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
a05b47a8 1100
6539865a
TL
1101 # reduce sleep if remainig memory is lower than the average transfer speed
1102 $usleep = 100_000 if $avglstat && $rem < $avglstat;
865ef132 1103
b68a957b
TL
1104 # also reduce loggin if we poll more frequent
1105 my $should_log = $usleep > 100_000 ? 1 : ($i % 10) == 0;
370b05e7 1106
0fca250a
TL
1107 my $total_h = render_bytes($total, 1);
1108 my $transferred_h = render_bytes($trans, 1);
1109 my $speed_h = render_bytes($speed, 1);
1110
1111 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1112
1113 if ($dirty_rate > $speed) {
1114 my $dirty_rate_h = render_bytes($dirty_rate, 1);
1115 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1116 }
1117
b68a957b 1118 $self->log('info', "migration $status, $progress") if $should_log;
0fca250a
TL
1119
1120 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1121 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1122 if ($xbzrlebytes || $xbzrlepages) {
1123 my $bytes_h = render_bytes($xbzrlebytes, 1);
1124
1125 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1126
1127 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1128 if $xbzrle->{'cache-miss-rate'};
1129
1130 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow};
1131
b68a957b 1132 $self->log('info', "xbzrle: $msg") if $should_log;
6539865a
TL
1133 }
1134
e693c491 1135 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
6539865a
TL
1136 $downtimecounter++;
1137 }
1138 $lastrem = $rem;
1139
1140 if ($downtimecounter > 5) {
1141 $downtimecounter = 0;
1142 $migrate_downtime *= 2;
1143 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1144 eval {
1145 # migrate-set-parameters does not touch values not
1146 # specified, so this only changes downtime-limit
1147 mon_cmd($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1148 };
1149 $self->log('info', "migrate-set-parameters error: $@") if $@;
1150 }
1e3baf05 1151 }
6539865a 1152
e693c491 1153 $last_mem_transferred = $memstat->{transferred};
a05b47a8 1154 }
0783c3c2
FE
1155
1156 if ($self->{storage_migration}) {
1157 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1158 # to avoid it trying to re-establish it. We are in blockjob ready state,
1159 # thus, this command changes to it to blockjob complete (see qapi docs)
1160 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}, 'cancel'); };
1161 if (my $err = $@) {
1162 die "Failed to complete storage migration: $err\n";
1163 }
1164 }
1e3baf05 1165}
16e903f2 1166
c04b5b04
AD
1167sub phase2_cleanup {
1168 my ($self, $vmid, $err) = @_;
1169
af30308f
DM
1170 return if !$self->{errors};
1171 $self->{phase2errors} = 1;
1172
c04b5b04
AD
1173 $self->log('info', "aborting phase 2 - cleanup resources");
1174
19168b91
SP
1175 $self->log('info', "migrate_cancel");
1176 eval {
0a13e08e 1177 mon_cmd($vmid, "migrate_cancel");
19168b91
SP
1178 };
1179 $self->log('info', "migrate_cancel error: $@") if $@;
1180
c04b5b04
AD
1181 my $conf = $self->{vmconf};
1182 delete $conf->{lock};
ffda963f 1183 eval { PVE::QemuConfig->write_config($vmid, $conf) };
c04b5b04
AD
1184 if (my $err = $@) {
1185 $self->log('err', $err);
1186 }
1187
af30308f 1188 # cleanup ressources on target host
3b4cf0f0 1189 if ($self->{storage_migration}) {
b74cad8a
AD
1190 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1191 if (my $err = $@) {
1192 $self->log('err', $err);
1193 }
9b3f5a5c 1194 }
b74cad8a 1195
9b3f5a5c
FG
1196 eval { $self->cleanup_bitmaps() };
1197 if (my $err =$@) {
1198 $self->log('err', $err);
b74cad8a
AD
1199 }
1200
af30308f 1201 my $nodename = PVE::INotify::nodename();
370b05e7 1202
af30308f
DM
1203 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1204 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1205 if (my $err = $@) {
1206 $self->log('err', $err);
1207 $self->{errors} = 1;
1208 }
386c6ba7 1209
9b3f5a5c
FG
1210 # cleanup after stopping, otherwise disks might be in-use by target VM!
1211 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1212 if (my $err = $@) {
1213 $self->log('err', $err);
1214 }
1215
1216
386c6ba7
WL
1217 if ($self->{tunnel}) {
1218 eval { finish_tunnel($self, $self->{tunnel}); };
1219 if (my $err = $@) {
1220 $self->log('err', $err);
1221 $self->{errors} = 1;
1222 }
1223 }
c04b5b04
AD
1224}
1225
16e903f2
DM
1226sub phase3 {
1227 my ($self, $vmid) = @_;
f5eb281a 1228
ad8b9d5e 1229 return;
16e903f2
DM
1230}
1231
1232sub phase3_cleanup {
1233 my ($self, $vmid, $err) = @_;
1234
1235 my $conf = $self->{vmconf};
af30308f 1236 return if $self->{phase2errors};
16e903f2 1237
1d5aaa1d
FG
1238 my $tunnel = $self->{tunnel};
1239
97ece9dd 1240 if ($self->{volume_map}) {
38311a1d
TL
1241 my $target_drives = $self->{target_drive};
1242
1243 # FIXME: for NBD storage migration we now only update the volid, and
1244 # not the full drivestr from the target node. Workaround that until we
1245 # got some real rescan, to avoid things like wrong format in the drive
1246 delete $conf->{$_} for keys %$target_drives;
97ece9dd 1247 PVE::QemuConfig->update_volume_ids($conf, $self->{volume_map});
38311a1d
TL
1248
1249 for my $drive (keys %$target_drives) {
1250 $conf->{$drive} = $target_drives->{$drive}->{drivestr};
1251 }
37666e4c
FE
1252 PVE::QemuConfig->write_config($vmid, $conf);
1253 }
1254
dbc9420b 1255 # transfer replication state before move config
c2c96d73 1256 $self->transfer_replication_state() if $self->{is_replicated};
27fa645e 1257 PVE::QemuConfig->move_config_to_node($vmid, $self->{node});
c2c96d73 1258 $self->switch_replication_job_target() if $self->{is_replicated};
dbc9420b 1259
5bc1e039 1260 if ($self->{livemigration}) {
3e802221
TL
1261 if ($self->{stopnbd}) {
1262 $self->log('info', "stopping NBD storage migration server on target.");
504105c6
FG
1263 # stop nbd server on remote vm - requirement for resume since 2.9
1264 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
1265
1266 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1267 if (my $err = $@) {
1268 $self->log('err', $err);
1269 $self->{errors} = 1;
1270 }
1271 }
1d5aaa1d 1272
877e2ea7 1273 # config moved and nbd server stopped - now we can resume vm on target
1d5aaa1d
FG
1274 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1275 eval {
1276 $self->write_tunnel($tunnel, 30, "resume $vmid");
1277 };
1278 if (my $err = $@) {
1279 $self->log('err', $err);
1280 $self->{errors} = 1;
1281 }
1282 } else {
1283 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1284 my $logf = sub {
1285 my $line = shift;
1286 $self->log('err', $line);
1287 };
1288 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1289 if (my $err = $@) {
1290 $self->log('err', $err);
1291 $self->{errors} = 1;
1292 }
b67900f1 1293 }
ca662131
SI
1294
1295 if ($self->{storage_migration} && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks} && $self->{running}) {
1296 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1297 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1298 }
b67900f1
AD
1299 }
1300
2e7fee87
FG
1301 # close tunnel on successful migration, on error phase2_cleanup closed it
1302 if ($tunnel) {
1303 eval { finish_tunnel($self, $tunnel); };
1304 if (my $err = $@) {
1305 $self->log('err', $err);
1306 $self->{errors} = 1;
1307 }
1308 }
1309
fd8469f7 1310 eval {
fd8469f7
AD
1311 my $timer = 0;
1312 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1313 $self->log('info', "Waiting for spice server migration");
1314 while (1) {
0a13e08e 1315 my $res = mon_cmd($vmid, 'query-spice');
fd8469f7
AD
1316 last if int($res->{'migrated'}) == 1;
1317 last if $timer > 50;
1318 $timer ++;
1319 usleep(200000);
769f187d 1320 }
fd8469f7
AD
1321 }
1322 };
95a4b4a9 1323
16e903f2
DM
1324 # always stop local VM
1325 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1326 if (my $err = $@) {
1327 $self->log('err', "stopping vm failed - $err");
1328 $self->{errors} = 1;
1329 }
1330
1331 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1332 eval {
1333 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1334 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1335 };
1336 if (my $err = $@) {
1337 $self->log('err', $err);
1338 $self->{errors} = 1;
1339 }
1340
4b26ffbf 1341 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
9b6efe43 1342
4b26ffbf
FE
1343 # destroy local copies
1344 foreach my $volid (@not_replicated_volumes) {
ad8b9d5e
FE
1345 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1346 if (my $err = $@) {
1347 $self->log('err', "removing local copy of '$volid' failed - $err");
1348 $self->{errors} = 1;
1349 last if $err =~ /^interrupted by signal$/;
b74cad8a 1350 }
b74cad8a
AD
1351 }
1352
16e903f2
DM
1353 # clear migrate lock
1354 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1355 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1356}
1357
1358sub final_cleanup {
1359 my ($self, $vmid) = @_;
1360
1361 # nothing to do
1362}
1363
50d8dd5d
AD
1364sub round_powerof2 {
1365 return 1 if $_[0] < 2;
1366 return 2 << int(log($_[0]-1)/log(2));
1367}
1368
16e903f2 13691;