]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
allow migration of local qcow2 snapshots
[qemu-server.git] / PVE / QemuMigrate.pm
1 package PVE::QemuMigrate;
2
3 use strict;
4 use warnings;
5 use PVE::AbstractMigrate;
6 use IO::File;
7 use IPC::Open2;
8 use POSIX qw( WNOHANG );
9 use PVE::INotify;
10 use PVE::Tools;
11 use PVE::Cluster;
12 use PVE::Storage;
13 use PVE::QemuServer;
14 use Time::HiRes qw( usleep );
15 use PVE::RPCEnvironment;
16
17 use base qw(PVE::AbstractMigrate);
18
19 sub fork_command_pipe {
20 my ($self, $cmd) = @_;
21
22 my $reader = IO::File->new();
23 my $writer = IO::File->new();
24
25 my $orig_pid = $$;
26
27 my $cpid;
28
29 eval { $cpid = open2($reader, $writer, @$cmd); };
30
31 my $err = $@;
32
33 # catch exec errors
34 if ($orig_pid != $$) {
35 $self->log('err', "can't fork command pipe\n");
36 POSIX::_exit(1);
37 kill('KILL', $$);
38 }
39
40 die $err if $err;
41
42 return { writer => $writer, reader => $reader, pid => $cpid };
43 }
44
45 sub finish_command_pipe {
46 my ($self, $cmdpipe, $timeout) = @_;
47
48 my $cpid = $cmdpipe->{pid};
49 return if !defined($cpid);
50
51 my $writer = $cmdpipe->{writer};
52 my $reader = $cmdpipe->{reader};
53
54 $writer->close();
55 $reader->close();
56
57 my $collect_child_process = sub {
58 my $res = waitpid($cpid, WNOHANG);
59 if (defined($res) && ($res == $cpid)) {
60 delete $cmdpipe->{cpid};
61 return 1;
62 } else {
63 return 0;
64 }
65 };
66
67 if ($timeout) {
68 for (my $i = 0; $i < $timeout; $i++) {
69 return if &$collect_child_process();
70 sleep(1);
71 }
72 }
73
74 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
75 kill(15, $cpid);
76
77 # wait again
78 for (my $i = 0; $i < 10; $i++) {
79 return if &$collect_child_process();
80 sleep(1);
81 }
82
83 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
84 kill 9, $cpid;
85 sleep 1;
86
87 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
88 if !&$collect_child_process();
89 }
90
91 sub fork_tunnel {
92 my ($self, $tunnel_addr) = @_;
93
94 my @localtunnelinfo = defined($tunnel_addr) ? ('-L' , $tunnel_addr ) : ();
95
96 my $cmd = [@{$self->{rem_ssh}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, 'qm', 'mtunnel' ];
97
98 my $tunnel = $self->fork_command_pipe($cmd);
99
100 my $reader = $tunnel->{reader};
101
102 my $helo;
103 eval {
104 PVE::Tools::run_with_timeout(60, sub { $helo = <$reader>; });
105 die "no reply\n" if !$helo;
106 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
107 die "got strange reply from mtunnel ('$helo')\n"
108 if $helo !~ m/^tunnel online$/;
109 };
110 my $err = $@;
111
112 if ($err) {
113 $self->finish_command_pipe($tunnel);
114 die "can't open migration tunnel - $err";
115 }
116 return $tunnel;
117 }
118
119 sub finish_tunnel {
120 my ($self, $tunnel) = @_;
121
122 my $writer = $tunnel->{writer};
123
124 eval {
125 PVE::Tools::run_with_timeout(30, sub {
126 print $writer "quit\n";
127 $writer->flush();
128 });
129 };
130 my $err = $@;
131
132 $self->finish_command_pipe($tunnel, 30);
133
134 if ($tunnel->{sock_addr}) {
135 # ssh does not clean up on local host
136 my $cmd = ['rm', '-f', $tunnel->{sock_addr}]; #
137 PVE::Tools::run_command($cmd);
138
139 # .. and just to be sure check on remote side
140 unshift @{$cmd}, @{$self->{rem_ssh}};
141 PVE::Tools::run_command($cmd);
142 }
143
144 die $err if $err;
145 }
146
147 sub lock_vm {
148 my ($self, $vmid, $code, @param) = @_;
149
150 return PVE::QemuConfig->lock_config($vmid, $code, @param);
151 }
152
153 sub prepare {
154 my ($self, $vmid) = @_;
155
156 my $online = $self->{opts}->{online};
157
158 $self->{storecfg} = PVE::Storage::config();
159
160 # test if VM exists
161 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
162
163 PVE::QemuConfig->check_lock($conf);
164
165 my $running = 0;
166 if (my $pid = PVE::QemuServer::check_running($vmid)) {
167 die "can't migrate running VM without --online\n" if !$online;
168 $running = $pid;
169
170 $self->{forcemachine} = PVE::QemuServer::qemu_machine_pxe($vmid, $conf);
171
172 }
173
174 if (my $loc_res = PVE::QemuServer::check_local_resources($conf, 1)) {
175 if ($self->{running} || !$self->{opts}->{force}) {
176 die "can't migrate VM which uses local devices\n";
177 } else {
178 $self->log('info', "migrating VM which uses local devices");
179 }
180 }
181
182 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
183
184 my $need_activate = [];
185 foreach my $volid (@$vollist) {
186 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
187
188 # check if storage is available on both nodes
189 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
190 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
191
192 if ($scfg->{shared}) {
193 # PVE::Storage::activate_storage checks this for non-shared storages
194 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
195 warn "Used shared storage '$sid' is not online on source node!\n"
196 if !$plugin->check_connection($sid, $scfg);
197 } else {
198 # only activate if not shared
199 push @$need_activate, $volid;
200 }
201 }
202
203 # activate volumes
204 PVE::Storage::activate_volumes($self->{storecfg}, $need_activate);
205
206 # test ssh connection
207 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
208 eval { $self->cmd_quiet($cmd); };
209 die "Can't connect to destination address using public key\n" if $@;
210
211 return $running;
212 }
213
214 sub sync_disks {
215 my ($self, $vmid) = @_;
216
217 $self->log('info', "copying disk images");
218
219 my $conf = $self->{vmconf};
220
221 # local volumes which have been copied
222 $self->{volumes} = [];
223
224 my $res = [];
225
226 eval {
227
228 # found local volumes and their origin
229 my $local_volumes = {};
230 my $local_volumes_errors = {};
231 my $other_errors = [];
232 my $abort = 0;
233
234 my $sharedvm = 1;
235
236 my $log_error = sub {
237 my ($msg, $volid) = @_;
238
239 if (defined($volid)) {
240 $local_volumes_errors->{$volid} = $msg;
241 } else {
242 push @$other_errors, $msg;
243 }
244 $abort = 1;
245 };
246
247 my @sids = PVE::Storage::storage_ids($self->{storecfg});
248 foreach my $storeid (@sids) {
249 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
250 next if $scfg->{shared};
251 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
252
253 # get list from PVE::Storage (for unused volumes)
254 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
255
256 next if @{$dl->{$storeid}} == 0;
257
258 # check if storage is available on target node
259 PVE::Storage::storage_check_node($self->{storecfg}, $storeid, $self->{node});
260 $sharedvm = 0; # there is a non-shared disk
261
262 PVE::Storage::foreach_volid($dl, sub {
263 my ($volid, $sid, $volname) = @_;
264
265 $local_volumes->{$volid} = 'storage';
266 });
267 }
268
269 my $test_volid = sub {
270 my ($volid, $is_cdrom, $snapname) = @_;
271
272 return if !$volid;
273
274 if ($volid =~ m|^/|) {
275 $local_volumes->{$volid} = 'config';
276 die "local file/device\n";
277 }
278
279 if ($is_cdrom) {
280 if ($volid eq 'cdrom') {
281 my $msg = "can't migrate local cdrom drive";
282 $msg .= " (referenced in snapshot '$snapname')"
283 if defined($snapname);
284
285 &$log_error("$msg\n");
286 return;
287 }
288 return if $volid eq 'none';
289 }
290
291 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
292
293 # check if storage is available on both nodes
294 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
295 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
296
297 return if $scfg->{shared};
298
299 $sharedvm = 0;
300
301 $local_volumes->{$volid} = defined($snapname) ? 'snapshot' : 'config';
302
303 die "local cdrom image\n" if $is_cdrom;
304
305 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
306
307 die "owned by other VM (owner = VM $owner)\n"
308 if !$owner || ($owner != $self->{vmid});
309
310 if (defined($snapname)) {
311 # we cannot migrate shapshots on local storage
312 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
313
314 my $format = PVE::QemuServer::qemu_img_format($scfg, $volname);
315
316 if (!($scfg->{type} eq 'zfspool' || $format eq 'qcow2')) {
317 die "non-migratable snapshot exists\n";
318 }
319 }
320
321 die "referenced by linked clone(s)\n"
322 if PVE::Storage::volume_is_base_and_used($self->{storecfg}, $volid);
323 };
324
325 my $test_drive = sub {
326 my ($ds, $drive, $snapname) = @_;
327
328 eval {
329 &$test_volid($drive->{file}, PVE::QemuServer::drive_is_cdrom($drive), $snapname);
330 };
331
332 &$log_error($@, $drive->{file}) if $@;
333 };
334
335 foreach my $snapname (keys %{$conf->{snapshots}}) {
336 eval {
337 &$test_volid($conf->{snapshots}->{$snapname}->{'vmstate'}, 0, undef)
338 if defined($conf->{snapshots}->{$snapname}->{'vmstate'});
339 };
340 &$log_error($@, $conf->{snapshots}->{$snapname}->{'vmstate'}) if $@;
341
342 PVE::QemuServer::foreach_drive($conf->{snapshots}->{$snapname}, $test_drive, $snapname);
343 }
344 PVE::QemuServer::foreach_drive($conf, $test_drive);
345
346 foreach my $vol (sort keys %$local_volumes) {
347 if ($local_volumes->{$vol} eq 'storage') {
348 $self->log('info', "found local disk '$vol' (via storage)\n");
349 } elsif ($local_volumes->{$vol} eq 'config') {
350 $self->log('info', "found local disk '$vol' (in current VM config)\n");
351 } elsif ($local_volumes->{$vol} eq 'snapshot') {
352 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
353 } else {
354 $self->log('info', "found local disk '$vol'\n");
355 }
356 }
357
358 foreach my $vol (sort keys %$local_volumes_errors) {
359 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
360 }
361 foreach my $err (@$other_errors) {
362 $self->log('warn', "$err");
363 }
364
365 if ($self->{running} && !$sharedvm) {
366 die "can't do online migration - VM uses local disks\n";
367 }
368
369 if ($abort) {
370 die "can't migrate VM - check log\n";
371 }
372
373 # additional checks for local storage
374 foreach my $volid (keys %$local_volumes) {
375 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
376 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
377
378 my $migratable = ($scfg->{type} eq 'dir') || ($scfg->{type} eq 'zfspool') ||
379 ($scfg->{type} eq 'lvmthin') || ($scfg->{type} eq 'lvm');
380
381 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
382 if !$migratable;
383
384 # image is a linked clone on local storage, se we can't migrate.
385 if (my $basename = (PVE::Storage::parse_volname($self->{storecfg}, $volid))[3]) {
386 die "can't migrate '$volid' as it's a clone of '$basename'";
387 }
388 }
389
390 foreach my $volid (keys %$local_volumes) {
391 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
392 push @{$self->{volumes}}, $volid;
393 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{nodeip}, $sid);
394 }
395 };
396 die "Failed to sync data - $@" if $@;
397 }
398
399 sub phase1 {
400 my ($self, $vmid) = @_;
401
402 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
403
404 my $conf = $self->{vmconf};
405
406 # set migrate lock in config file
407 $conf->{lock} = 'migrate';
408 PVE::QemuConfig->write_config($vmid, $conf);
409
410 sync_disks($self, $vmid);
411
412 };
413
414 sub phase1_cleanup {
415 my ($self, $vmid, $err) = @_;
416
417 $self->log('info', "aborting phase 1 - cleanup resources");
418
419 my $conf = $self->{vmconf};
420 delete $conf->{lock};
421 eval { PVE::QemuConfig->write_config($vmid, $conf) };
422 if (my $err = $@) {
423 $self->log('err', $err);
424 }
425
426 if ($self->{volumes}) {
427 foreach my $volid (@{$self->{volumes}}) {
428 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
429 # fixme: try to remove ?
430 }
431 }
432 }
433
434 sub phase2 {
435 my ($self, $vmid) = @_;
436
437 my $conf = $self->{vmconf};
438
439 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
440
441 my $raddr;
442 my $rport;
443 my $ruri; # the whole migration dst. URI (protocol:address[:port])
444 my $nodename = PVE::INotify::nodename();
445
446 ## start on remote node
447 my $cmd = [@{$self->{rem_ssh}}];
448
449 my $spice_ticket;
450 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
451 my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
452 $spice_ticket = $res->{ticket};
453 }
454
455 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
456
457 # we use TCP only for unsecure migrations as TCP ssh forward tunnels often
458 # did appeared to late (they are hard, if not impossible, to check for)
459 # secure migration use UNIX sockets now, this *breaks* compatibilty when trying
460 # to migrate from new to old but *not* from old to new.
461 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
462
463 my $migration_type = 'secure';
464 if (defined($self->{opts}->{migration_type})) {
465 $migration_type = $self->{opts}->{migration_type};
466 } elsif (defined($datacenterconf->{migration}->{type})) {
467 $migration_type = $datacenterconf->{migration}->{type};
468 }
469
470 push @$cmd, '--migration_type', $migration_type;
471
472 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
473 if $self->{opts}->{migration_network};
474
475 if ($migration_type eq 'insecure') {
476 push @$cmd, '--stateuri', 'tcp';
477 } else {
478 push @$cmd, '--stateuri', 'unix';
479 }
480
481 if ($self->{forcemachine}) {
482 push @$cmd, '--machine', $self->{forcemachine};
483 }
484
485 my $spice_port;
486
487 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
488 # instead we pipe it through STDIN
489 PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
490 my $line = shift;
491
492 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
493 $raddr = $1;
494 $rport = int($2);
495 $ruri = "tcp:$raddr:$rport";
496 }
497 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
498 $raddr = $1;
499 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
500 $ruri = "unix:$raddr";
501 }
502 elsif ($line =~ m/^migration listens on port (\d+)$/) {
503 $raddr = "localhost";
504 $rport = int($1);
505 $ruri = "tcp:$raddr:$rport";
506 }
507 elsif ($line =~ m/^spice listens on port (\d+)$/) {
508 $spice_port = int($1);
509 }
510 }, errfunc => sub {
511 my $line = shift;
512 $self->log('info', $line);
513 });
514
515 die "unable to detect remote migration address\n" if !$raddr;
516
517 if ($migration_type eq 'secure') {
518 $self->log('info', "start remote tunnel");
519
520 if ($ruri =~ /^unix:/) {
521 unlink $raddr;
522 $self->{tunnel} = $self->fork_tunnel("$raddr:$raddr");
523 $self->{tunnel}->{sock_addr} = $raddr;
524
525 my $unix_socket_try = 0; # wait for the socket to become ready
526 while (! -S $raddr) {
527 $unix_socket_try++;
528 if ($unix_socket_try > 100) {
529 $self->{errors} = 1;
530 $self->finish_tunnel($self->{tunnel});
531 die "Timeout, migration socket $ruri did not get ready";
532 }
533
534 usleep(50000);
535 }
536
537 } elsif ($ruri =~ /^tcp:/) {
538 my $tunnel_addr;
539 if ($raddr eq "localhost") {
540 # for backwards compatibility with older qemu-server versions
541 my $pfamily = PVE::Tools::get_host_address_family($nodename);
542 my $lport = PVE::Tools::next_migrate_port($pfamily);
543 $tunnel_addr = "$lport:localhost:$rport";
544 }
545
546 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
547
548 } else {
549 die "unsupported protocol in migration URI: $ruri\n";
550 }
551 }
552
553 my $start = time();
554 $self->log('info', "starting online/live migration on $ruri");
555 $self->{livemigration} = 1;
556
557 # load_defaults
558 my $defaults = PVE::QemuServer::load_defaults();
559
560 # always set migrate speed (overwrite kvm default of 32m)
561 # we set a very hight default of 8192m which is basically unlimited
562 my $migrate_speed = $defaults->{migrate_speed} || 8192;
563 $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
564 $migrate_speed = $migrate_speed * 1048576;
565 $self->log('info', "migrate_set_speed: $migrate_speed");
566 eval {
567 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
568 };
569 $self->log('info', "migrate_set_speed error: $@") if $@;
570
571 my $migrate_downtime = $defaults->{migrate_downtime};
572 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
573 if (defined($migrate_downtime)) {
574 $self->log('info', "migrate_set_downtime: $migrate_downtime");
575 eval {
576 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
577 };
578 $self->log('info', "migrate_set_downtime error: $@") if $@;
579 }
580
581 $self->log('info', "set migration_caps");
582 eval {
583 PVE::QemuServer::set_migration_caps($vmid);
584 };
585 warn $@ if $@;
586
587 #set cachesize 10% of the total memory
588 my $cachesize = int($conf->{memory}*1048576/10);
589 $self->log('info', "set cachesize: $cachesize");
590 eval {
591 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => int($cachesize));
592 };
593 $self->log('info', "migrate-set-cache-size error: $@") if $@;
594
595 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
596 my $rpcenv = PVE::RPCEnvironment::get();
597 my $authuser = $rpcenv->get_user();
598
599 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
600
601 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
602 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
603
604 $self->log('info', "spice client_migrate_info");
605
606 eval {
607 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
608 hostname => $proxyticket, 'tls-port' => $spice_port,
609 'cert-subject' => $subject);
610 };
611 $self->log('info', "client_migrate_info error: $@") if $@;
612
613 }
614
615 $self->log('info', "start migrate command to $ruri");
616 eval {
617 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => $ruri);
618 };
619 my $merr = $@;
620 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
621
622 my $lstat = 0;
623 my $usleep = 2000000;
624 my $i = 0;
625 my $err_count = 0;
626 my $lastrem = undef;
627 my $downtimecounter = 0;
628 while (1) {
629 $i++;
630 my $avglstat = $lstat/$i if $lstat;
631
632 usleep($usleep);
633 my $stat;
634 eval {
635 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
636 };
637 if (my $err = $@) {
638 $err_count++;
639 warn "query migrate failed: $err\n";
640 $self->log('info', "query migrate failed: $err");
641 if ($err_count <= 5) {
642 usleep(1000000);
643 next;
644 }
645 die "too many query migrate failures - aborting\n";
646 }
647
648 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
649 sleep(1);
650 next;
651 }
652
653 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
654 $merr = undef;
655 $err_count = 0;
656 if ($stat->{status} eq 'completed') {
657 my $delay = time() - $start;
658 if ($delay > 0) {
659 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
660 my $downtime = $stat->{downtime} || 0;
661 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
662 }
663 }
664
665 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
666 $self->log('info', "migration status error: $stat->{status}");
667 die "aborting\n"
668 }
669
670 if ($stat->{status} ne 'active') {
671 $self->log('info', "migration status: $stat->{status}");
672 last;
673 }
674
675 if ($stat->{ram}->{transferred} ne $lstat) {
676 my $trans = $stat->{ram}->{transferred} || 0;
677 my $rem = $stat->{ram}->{remaining} || 0;
678 my $total = $stat->{ram}->{total} || 0;
679 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
680 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
681 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
682 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
683 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
684 #reduce sleep if remainig memory if lower than the everage transfert
685 $usleep = 300000 if $avglstat && $rem < $avglstat;
686
687 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
688 "remaining ${rem}), total ${total})");
689
690 if (${xbzrlecachesize}) {
691 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
692 }
693
694 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
695 $downtimecounter++;
696 }
697 $lastrem = $rem;
698
699 if ($downtimecounter > 5) {
700 $downtimecounter = 0;
701 $migrate_downtime *= 2;
702 $self->log('info', "migrate_set_downtime: $migrate_downtime");
703 eval {
704 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
705 };
706 $self->log('info', "migrate_set_downtime error: $@") if $@;
707 }
708
709 }
710
711
712 $lstat = $stat->{ram}->{transferred};
713
714 } else {
715 die $merr if $merr;
716 die "unable to parse migration status '$stat->{status}' - aborting\n";
717 }
718 }
719
720 # just to be sure that the tunnel gets closed on successful migration, on error
721 # phase2_cleanup closes it *after* stopping the remote waiting VM
722 if (!$self->{errors} && $self->{tunnel}) {
723 eval { finish_tunnel($self, $self->{tunnel}); };
724 if (my $err = $@) {
725 $self->log('err', $err);
726 $self->{errors} = 1;
727 }
728 }
729 }
730
731 sub phase2_cleanup {
732 my ($self, $vmid, $err) = @_;
733
734 return if !$self->{errors};
735 $self->{phase2errors} = 1;
736
737 $self->log('info', "aborting phase 2 - cleanup resources");
738
739 $self->log('info', "migrate_cancel");
740 eval {
741 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
742 };
743 $self->log('info', "migrate_cancel error: $@") if $@;
744
745 my $conf = $self->{vmconf};
746 delete $conf->{lock};
747 eval { PVE::QemuConfig->write_config($vmid, $conf) };
748 if (my $err = $@) {
749 $self->log('err', $err);
750 }
751
752 # cleanup ressources on target host
753 my $nodename = PVE::INotify::nodename();
754
755 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
756 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
757 if (my $err = $@) {
758 $self->log('err', $err);
759 $self->{errors} = 1;
760 }
761
762 if ($self->{tunnel}) {
763 eval { finish_tunnel($self, $self->{tunnel}); };
764 if (my $err = $@) {
765 $self->log('err', $err);
766 $self->{errors} = 1;
767 }
768 }
769 }
770
771 sub phase3 {
772 my ($self, $vmid) = @_;
773
774 my $volids = $self->{volumes};
775 return if $self->{phase2errors};
776
777 # destroy local copies
778 foreach my $volid (@$volids) {
779 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
780 if (my $err = $@) {
781 $self->log('err', "removing local copy of '$volid' failed - $err");
782 $self->{errors} = 1;
783 last if $err =~ /^interrupted by signal$/;
784 }
785 }
786 }
787
788 sub phase3_cleanup {
789 my ($self, $vmid, $err) = @_;
790
791 my $conf = $self->{vmconf};
792 return if $self->{phase2errors};
793
794 # move config to remote node
795 my $conffile = PVE::QemuConfig->config_file($vmid);
796 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
797
798 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
799 if !rename($conffile, $newconffile);
800
801 if ($self->{livemigration}) {
802 # now that config file is move, we can resume vm on target if livemigrate
803 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
804 eval{ PVE::Tools::run_command($cmd, outfunc => sub {},
805 errfunc => sub {
806 my $line = shift;
807 $self->log('err', $line);
808 });
809 };
810 if (my $err = $@) {
811 $self->log('err', $err);
812 $self->{errors} = 1;
813 }
814 }
815
816 eval {
817
818 my $timer = 0;
819 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
820 $self->log('info', "Waiting for spice server migration");
821 while (1) {
822 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
823 last if int($res->{'migrated'}) == 1;
824 last if $timer > 50;
825 $timer ++;
826 usleep(200000);
827 }
828 }
829 };
830
831 # always stop local VM
832 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
833 if (my $err = $@) {
834 $self->log('err', "stopping vm failed - $err");
835 $self->{errors} = 1;
836 }
837
838 # always deactivate volumes - avoid lvm LVs to be active on several nodes
839 eval {
840 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
841 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
842 };
843 if (my $err = $@) {
844 $self->log('err', $err);
845 $self->{errors} = 1;
846 }
847
848 # clear migrate lock
849 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
850 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
851 }
852
853 sub final_cleanup {
854 my ($self, $vmid) = @_;
855
856 # nothing to do
857 }
858
859 1;