]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
add comments and rename volhash
[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
231 my $sharedvm = 1;
232
233 my @sids = PVE::Storage::storage_ids($self->{storecfg});
234 foreach my $storeid (@sids) {
235 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
236 next if $scfg->{shared};
237 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
238
239 # get list from PVE::Storage (for unused volumes)
240 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
241
242 next if @{$dl->{$storeid}} == 0;
243
244 # check if storage is available on target node
245 PVE::Storage::storage_check_node($self->{storecfg}, $storeid, $self->{node});
246 $sharedvm = 0; # there is a non-shared disk
247
248 PVE::Storage::foreach_volid($dl, sub {
249 my ($volid, $sid, $volname) = @_;
250
251 $local_volumes->{$volid} = 'storage';
252 });
253 }
254
255 my $test_volid = sub {
256 my ($volid, $is_cdrom, $snapname) = @_;
257
258 return if !$volid;
259
260 die "can't migrate local file/device '$volid'\n" if $volid =~ m|^/|;
261
262 if ($is_cdrom) {
263 die "can't migrate local cdrom drive\n" if $volid eq 'cdrom';
264 return if $volid eq 'none';
265 }
266
267 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
268
269 # check if storage is available on both nodes
270 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
271 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
272
273 return if $scfg->{shared};
274
275 $sharedvm = 0;
276
277 $local_volumes->{$volid} = defined($snapname) ? 'snapshot' : 'config';
278
279 die "can't migrate local cdrom '$volid'\n" if $is_cdrom;
280
281 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
282
283 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
284 if !$owner || ($owner != $self->{vmid});
285
286 if (defined($snapname)) {
287 # we cannot migrate shapshots on local storage
288 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
289
290 my $format = PVE::QemuServer::qemu_img_format($scfg, $volname);
291
292 if (($scfg->{type} eq 'zfspool') || ($format eq 'qcow2')) {
293 return;
294 }
295
296 die "can't migrate snapshot of local volume '$volid'\n";
297
298 }
299 };
300
301 my $test_drive = sub {
302 my ($ds, $drive, $snapname) = @_;
303
304 &$test_volid($drive->{file}, PVE::QemuServer::drive_is_cdrom($drive), $snapname);
305 };
306
307 foreach my $snapname (keys %{$conf->{snapshots}}) {
308 &$test_volid($conf->{snapshots}->{$snapname}->{'vmstate'}, 0, undef)
309 if defined($conf->{snapshots}->{$snapname}->{'vmstate'});
310 PVE::QemuServer::foreach_drive($conf->{snapshots}->{$snapname}, $test_drive, $snapname);
311 }
312 PVE::QemuServer::foreach_drive($conf, $test_drive);
313
314 foreach my $vol (sort keys %$local_volumes) {
315 if ($local_volumes->{$vol} eq 'storage') {
316 $self->log('info', "found local disk '$vol' (via storage)\n");
317 } elsif ($local_volumes->{$vol} eq 'config') {
318 $self->log('info', "found local disk '$vol' (in current VM config)\n");
319 } elsif ($local_volumes->{$vol} eq 'snapshot') {
320 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
321 } else {
322 $self->log('info', "found local disk '$vol'\n");
323 }
324 }
325
326 if ($self->{running} && !$sharedvm) {
327 die "can't do online migration - VM uses local disks\n";
328 }
329
330 # additional checks for local storage
331 foreach my $volid (keys %$local_volumes) {
332 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
333 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
334
335 my $migratable = ($scfg->{type} eq 'dir') || ($scfg->{type} eq 'zfspool') ||
336 ($scfg->{type} eq 'lvmthin') || ($scfg->{type} eq 'lvm');
337
338 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
339 if !$migratable;
340
341 # image is a linked clone on local storage, se we can't migrate.
342 if (my $basename = (PVE::Storage::parse_volname($self->{storecfg}, $volid))[3]) {
343 die "can't migrate '$volid' as it's a clone of '$basename'";
344 }
345 }
346
347 foreach my $volid (keys %$local_volumes) {
348 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
349 push @{$self->{volumes}}, $volid;
350 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{nodeip}, $sid);
351 }
352 };
353 die "Failed to sync data - $@" if $@;
354 }
355
356 sub phase1 {
357 my ($self, $vmid) = @_;
358
359 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
360
361 my $conf = $self->{vmconf};
362
363 # set migrate lock in config file
364 $conf->{lock} = 'migrate';
365 PVE::QemuConfig->write_config($vmid, $conf);
366
367 sync_disks($self, $vmid);
368
369 };
370
371 sub phase1_cleanup {
372 my ($self, $vmid, $err) = @_;
373
374 $self->log('info', "aborting phase 1 - cleanup resources");
375
376 my $conf = $self->{vmconf};
377 delete $conf->{lock};
378 eval { PVE::QemuConfig->write_config($vmid, $conf) };
379 if (my $err = $@) {
380 $self->log('err', $err);
381 }
382
383 if ($self->{volumes}) {
384 foreach my $volid (@{$self->{volumes}}) {
385 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
386 # fixme: try to remove ?
387 }
388 }
389 }
390
391 sub phase2 {
392 my ($self, $vmid) = @_;
393
394 my $conf = $self->{vmconf};
395
396 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
397
398 my $raddr;
399 my $rport;
400 my $ruri; # the whole migration dst. URI (protocol:address[:port])
401 my $nodename = PVE::INotify::nodename();
402
403 ## start on remote node
404 my $cmd = [@{$self->{rem_ssh}}];
405
406 my $spice_ticket;
407 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
408 my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
409 $spice_ticket = $res->{ticket};
410 }
411
412 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
413
414 # we use TCP only for unsecure migrations as TCP ssh forward tunnels often
415 # did appeared to late (they are hard, if not impossible, to check for)
416 # secure migration use UNIX sockets now, this *breaks* compatibilty when trying
417 # to migrate from new to old but *not* from old to new.
418 my $datacenterconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
419 my $secure_migration = ($datacenterconf->{migration_unsecure}) ? 0 : 1;
420
421 if (!$secure_migration) {
422 push @$cmd, '--stateuri', 'tcp';
423 } else {
424 push @$cmd, '--stateuri', 'unix';
425 }
426
427 if ($self->{forcemachine}) {
428 push @$cmd, '--machine', $self->{forcemachine};
429 }
430
431 my $spice_port;
432
433 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
434 # instead we pipe it through STDIN
435 PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
436 my $line = shift;
437
438 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
439 $raddr = $1;
440 $rport = int($2);
441 $ruri = "tcp:$raddr:$rport";
442 }
443 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
444 $raddr = $1;
445 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
446 $ruri = "unix:$raddr";
447 }
448 elsif ($line =~ m/^migration listens on port (\d+)$/) {
449 $raddr = "localhost";
450 $rport = int($1);
451 $ruri = "tcp:$raddr:$rport";
452 }
453 elsif ($line =~ m/^spice listens on port (\d+)$/) {
454 $spice_port = int($1);
455 }
456 }, errfunc => sub {
457 my $line = shift;
458 $self->log('info', $line);
459 });
460
461 die "unable to detect remote migration address\n" if !$raddr;
462
463 if ($secure_migration) {
464 $self->log('info', "start remote tunnel");
465
466 if ($ruri =~ /^unix:/) {
467 unlink $raddr;
468 $self->{tunnel} = $self->fork_tunnel("$raddr:$raddr");
469 $self->{tunnel}->{sock_addr} = $raddr;
470
471 my $unix_socket_try = 0; # wait for the socket to become ready
472 while (! -S $raddr) {
473 $unix_socket_try++;
474 if ($unix_socket_try > 100) {
475 $self->{errors} = 1;
476 $self->finish_tunnel($self->{tunnel});
477 die "Timeout, migration socket $ruri did not get ready";
478 }
479
480 usleep(50000);
481 }
482
483 } elsif ($ruri =~ /^tcp:/) {
484 my $tunnel_addr;
485 if ($raddr eq "localhost") {
486 # for backwards compatibility with older qemu-server versions
487 my $pfamily = PVE::Tools::get_host_address_family($nodename);
488 my $lport = PVE::Tools::next_migrate_port($pfamily);
489 $tunnel_addr = "$lport:localhost:$rport";
490 }
491
492 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
493
494 } else {
495 die "unsupported protocol in migration URI: $ruri\n";
496 }
497 }
498
499 my $start = time();
500 $self->log('info', "starting online/live migration on $ruri");
501 $self->{livemigration} = 1;
502
503 # load_defaults
504 my $defaults = PVE::QemuServer::load_defaults();
505
506 # always set migrate speed (overwrite kvm default of 32m)
507 # we set a very hight default of 8192m which is basically unlimited
508 my $migrate_speed = $defaults->{migrate_speed} || 8192;
509 $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
510 $migrate_speed = $migrate_speed * 1048576;
511 $self->log('info', "migrate_set_speed: $migrate_speed");
512 eval {
513 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
514 };
515 $self->log('info', "migrate_set_speed error: $@") if $@;
516
517 my $migrate_downtime = $defaults->{migrate_downtime};
518 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
519 if (defined($migrate_downtime)) {
520 $self->log('info', "migrate_set_downtime: $migrate_downtime");
521 eval {
522 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
523 };
524 $self->log('info', "migrate_set_downtime error: $@") if $@;
525 }
526
527 $self->log('info', "set migration_caps");
528 eval {
529 PVE::QemuServer::set_migration_caps($vmid);
530 };
531 warn $@ if $@;
532
533 #set cachesize 10% of the total memory
534 my $cachesize = int($conf->{memory}*1048576/10);
535 $self->log('info', "set cachesize: $cachesize");
536 eval {
537 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => int($cachesize));
538 };
539 $self->log('info', "migrate-set-cache-size error: $@") if $@;
540
541 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
542 my $rpcenv = PVE::RPCEnvironment::get();
543 my $authuser = $rpcenv->get_user();
544
545 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
546
547 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
548 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
549
550 $self->log('info', "spice client_migrate_info");
551
552 eval {
553 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
554 hostname => $proxyticket, 'tls-port' => $spice_port,
555 'cert-subject' => $subject);
556 };
557 $self->log('info', "client_migrate_info error: $@") if $@;
558
559 }
560
561 $self->log('info', "start migrate command to $ruri");
562 eval {
563 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => $ruri);
564 };
565 my $merr = $@;
566 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
567
568 my $lstat = 0;
569 my $usleep = 2000000;
570 my $i = 0;
571 my $err_count = 0;
572 my $lastrem = undef;
573 my $downtimecounter = 0;
574 while (1) {
575 $i++;
576 my $avglstat = $lstat/$i if $lstat;
577
578 usleep($usleep);
579 my $stat;
580 eval {
581 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
582 };
583 if (my $err = $@) {
584 $err_count++;
585 warn "query migrate failed: $err\n";
586 $self->log('info', "query migrate failed: $err");
587 if ($err_count <= 5) {
588 usleep(1000000);
589 next;
590 }
591 die "too many query migrate failures - aborting\n";
592 }
593
594 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
595 sleep(1);
596 next;
597 }
598
599 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
600 $merr = undef;
601 $err_count = 0;
602 if ($stat->{status} eq 'completed') {
603 my $delay = time() - $start;
604 if ($delay > 0) {
605 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
606 my $downtime = $stat->{downtime} || 0;
607 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
608 }
609 }
610
611 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
612 $self->log('info', "migration status error: $stat->{status}");
613 die "aborting\n"
614 }
615
616 if ($stat->{status} ne 'active') {
617 $self->log('info', "migration status: $stat->{status}");
618 last;
619 }
620
621 if ($stat->{ram}->{transferred} ne $lstat) {
622 my $trans = $stat->{ram}->{transferred} || 0;
623 my $rem = $stat->{ram}->{remaining} || 0;
624 my $total = $stat->{ram}->{total} || 0;
625 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
626 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
627 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
628 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
629 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
630 #reduce sleep if remainig memory if lower than the everage transfert
631 $usleep = 300000 if $avglstat && $rem < $avglstat;
632
633 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
634 "remaining ${rem}), total ${total})");
635
636 if (${xbzrlecachesize}) {
637 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
638 }
639
640 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
641 $downtimecounter++;
642 }
643 $lastrem = $rem;
644
645 if ($downtimecounter > 5) {
646 $downtimecounter = 0;
647 $migrate_downtime *= 2;
648 $self->log('info', "migrate_set_downtime: $migrate_downtime");
649 eval {
650 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
651 };
652 $self->log('info', "migrate_set_downtime error: $@") if $@;
653 }
654
655 }
656
657
658 $lstat = $stat->{ram}->{transferred};
659
660 } else {
661 die $merr if $merr;
662 die "unable to parse migration status '$stat->{status}' - aborting\n";
663 }
664 }
665
666 # just to be sure that the tunnel gets closed on successful migration, on error
667 # phase2_cleanup closes it *after* stopping the remote waiting VM
668 if (!$self->{errors} && $self->{tunnel}) {
669 eval { finish_tunnel($self, $self->{tunnel}); };
670 if (my $err = $@) {
671 $self->log('err', $err);
672 $self->{errors} = 1;
673 }
674 }
675 }
676
677 sub phase2_cleanup {
678 my ($self, $vmid, $err) = @_;
679
680 return if !$self->{errors};
681 $self->{phase2errors} = 1;
682
683 $self->log('info', "aborting phase 2 - cleanup resources");
684
685 $self->log('info', "migrate_cancel");
686 eval {
687 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
688 };
689 $self->log('info', "migrate_cancel error: $@") if $@;
690
691 my $conf = $self->{vmconf};
692 delete $conf->{lock};
693 eval { PVE::QemuConfig->write_config($vmid, $conf) };
694 if (my $err = $@) {
695 $self->log('err', $err);
696 }
697
698 # cleanup ressources on target host
699 my $nodename = PVE::INotify::nodename();
700
701 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
702 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
703 if (my $err = $@) {
704 $self->log('err', $err);
705 $self->{errors} = 1;
706 }
707
708 if ($self->{tunnel}) {
709 eval { finish_tunnel($self, $self->{tunnel}); };
710 if (my $err = $@) {
711 $self->log('err', $err);
712 $self->{errors} = 1;
713 }
714 }
715 }
716
717 sub phase3 {
718 my ($self, $vmid) = @_;
719
720 my $volids = $self->{volumes};
721 return if $self->{phase2errors};
722
723 # destroy local copies
724 foreach my $volid (@$volids) {
725 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
726 if (my $err = $@) {
727 $self->log('err', "removing local copy of '$volid' failed - $err");
728 $self->{errors} = 1;
729 last if $err =~ /^interrupted by signal$/;
730 }
731 }
732 }
733
734 sub phase3_cleanup {
735 my ($self, $vmid, $err) = @_;
736
737 my $conf = $self->{vmconf};
738 return if $self->{phase2errors};
739
740 # move config to remote node
741 my $conffile = PVE::QemuConfig->config_file($vmid);
742 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
743
744 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
745 if !rename($conffile, $newconffile);
746
747 if ($self->{livemigration}) {
748 # now that config file is move, we can resume vm on target if livemigrate
749 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
750 eval{ PVE::Tools::run_command($cmd, outfunc => sub {},
751 errfunc => sub {
752 my $line = shift;
753 $self->log('err', $line);
754 });
755 };
756 if (my $err = $@) {
757 $self->log('err', $err);
758 $self->{errors} = 1;
759 }
760 }
761
762 eval {
763
764 my $timer = 0;
765 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
766 $self->log('info', "Waiting for spice server migration");
767 while (1) {
768 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
769 last if int($res->{'migrated'}) == 1;
770 last if $timer > 50;
771 $timer ++;
772 usleep(200000);
773 }
774 }
775 };
776
777 # always stop local VM
778 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
779 if (my $err = $@) {
780 $self->log('err', "stopping vm failed - $err");
781 $self->{errors} = 1;
782 }
783
784 # always deactivate volumes - avoid lvm LVs to be active on several nodes
785 eval {
786 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
787 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
788 };
789 if (my $err = $@) {
790 $self->log('err', $err);
791 $self->{errors} = 1;
792 }
793
794 # clear migrate lock
795 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
796 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
797 }
798
799 sub final_cleanup {
800 my ($self, $vmid) = @_;
801
802 # nothing to do
803 }
804
805 1;