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