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