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