]>
git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
1 package PVE
::QemuMigrate
;
5 use PVE
::AbstractMigrate
;
8 use POSIX
qw( WNOHANG );
14 use Time
::HiRes
qw( usleep );
15 use PVE
::RPCEnvironment
;
17 use base
qw(PVE::AbstractMigrate);
19 sub fork_command_pipe
{
20 my ($self, $cmd) = @_;
22 my $reader = IO
::File-
>new();
23 my $writer = IO
::File-
>new();
29 eval { $cpid = open2
($reader, $writer, @$cmd); };
34 if ($orig_pid != $$) {
35 $self->log('err', "can't fork command pipe\n");
42 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
45 sub finish_command_pipe
{
46 my ($self, $cmdpipe, $timeout) = @_;
48 my $cpid = $cmdpipe->{pid
};
49 return if !defined($cpid);
51 my $writer = $cmdpipe->{writer
};
52 my $reader = $cmdpipe->{reader
};
57 my $collect_child_process = sub {
58 my $res = waitpid($cpid, WNOHANG
);
59 if (defined($res) && ($res == $cpid)) {
60 delete $cmdpipe->{cpid
};
68 for (my $i = 0; $i < $timeout; $i++) {
69 return if &$collect_child_process();
74 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
78 for (my $i = 0; $i < 10; $i++) {
79 return if &$collect_child_process();
83 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
87 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
88 if !&$collect_child_process();
92 my ($self, $tunnel_addr) = @_;
94 my @localtunnelinfo = defined($tunnel_addr) ?
('-L' , $tunnel_addr ) : ();
96 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, 'qm', 'mtunnel' ];
98 my $tunnel = $self->fork_command_pipe($cmd);
100 my $reader = $tunnel->{reader
};
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$/;
113 $self->finish_command_pipe($tunnel);
114 die "can't open migration tunnel - $err";
120 my ($self, $tunnel) = @_;
122 my $writer = $tunnel->{writer
};
125 PVE
::Tools
::run_with_timeout
(30, sub {
126 print $writer "quit\n";
132 $self->finish_command_pipe($tunnel, 30);
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);
139 # .. and just to be sure check on remote side
140 unshift @{$cmd}, @{$self->{rem_ssh
}};
141 PVE
::Tools
::run_command
($cmd);
148 my ($self, $vmid, $code, @param) = @_;
150 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
154 my ($self, $vmid) = @_;
156 my $online = $self->{opts
}->{online
};
158 $self->{storecfg
} = PVE
::Storage
::config
();
161 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
163 PVE
::QemuConfig-
>check_lock($conf);
166 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
167 die "can't migrate running VM without --online\n" if !$online;
170 $self->{forcemachine
} = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
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";
178 $self->log('info', "migrating VM which uses local devices");
182 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
184 my $need_activate = [];
185 foreach my $volid (@$vollist) {
186 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
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
});
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);
198 # only activate if not shared
199 push @$need_activate, $volid;
204 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
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 $@;
215 my ($self, $vmid) = @_;
217 $self->log('info', "copying disk images");
219 my $conf = $self->{vmconf
};
221 $self->{volumes
} = [];
232 my @sids = PVE
::Storage
::storage_ids
($self->{storecfg
});
233 foreach my $storeid (@sids) {
234 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
235 next if $scfg->{shared
};
236 next if !PVE
::Storage
::storage_check_enabled
($self->{storecfg
}, $storeid, undef, 1);
238 # get list from PVE::Storage (for unused volumes)
239 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
241 next if @{$dl->{$storeid}} == 0;
243 # check if storage is available on target node
244 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $storeid, $self->{node
});
245 $sharedvm = 0; # there is a non-shared disk
247 PVE
::Storage
::foreach_volid
($dl, sub {
248 my ($volid, $sid, $volname) = @_;
250 $volhash->{$volid} = 1;
254 my $test_volid = sub {
255 my ($volid, $is_cdrom, $snapname) = @_;
259 die "can't migrate local file/device '$volid'\n" if $volid =~ m
|^/|;
262 die "can't migrate local cdrom drive\n" if $volid eq 'cdrom';
263 return if $volid eq 'none';
264 $cdromhash->{$volid} = 1;
267 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
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
});
273 return if $scfg->{shared
};
277 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
279 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
281 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
282 if !$owner || ($owner != $self->{vmid
});
284 if (defined($snapname)) {
285 # we cannot migrate shapshots on local storage
286 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
288 my $format = PVE
::QemuServer
::qemu_img_format
($scfg, $volname);
290 if (($scfg->{type
} eq 'zfspool') || ($format eq 'qcow2')) {
291 $volhash->{$volid} = 1;
295 die "can't migrate snapshot of local volume '$volid'\n";
298 $volhash->{$volid} = 1;
302 my $test_drive = sub {
303 my ($ds, $drive, $snapname) = @_;
305 &$test_volid($drive->{file
}, PVE
::QemuServer
::drive_is_cdrom
($drive), $snapname);
308 PVE
::QemuServer
::foreach_drive
($conf, $test_drive);
309 foreach my $snapname (keys %{$conf->{snapshots
}}) {
310 &$test_volid($conf->{snapshots
}->{$snapname}->{'vmstate'}, 0, undef)
311 if defined($conf->{snapshots
}->{$snapname}->{'vmstate'});
312 PVE
::QemuServer
::foreach_drive
($conf->{snapshots
}->{$snapname}, $test_drive, $snapname);
315 if ($self->{running
} && !$sharedvm) {
316 die "can't do online migration - VM uses local disks\n";
319 # additional checks for local storage
320 foreach my $volid (keys %$volhash) {
321 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
322 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
324 my $migratable = ($scfg->{type
} eq 'dir') || ($scfg->{type
} eq 'zfspool') ||
325 ($scfg->{type
} eq 'lvmthin') || ($scfg->{type
} eq 'lvm');
327 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
330 # image is a linked clone on local storage, se we can't migrate.
331 if (my $basename = (PVE
::Storage
::parse_volname
($self->{storecfg
}, $volid))[3]) {
332 die "can't migrate '$volid' as it's a clone of '$basename'";
336 foreach my $volid (keys %$volhash) {
337 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
338 push @{$self->{volumes
}}, $volid;
339 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{nodeip
}, $sid);
342 die "Failed to sync data - $@" if $@;
346 my ($self, $vmid) = @_;
348 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
350 my $conf = $self->{vmconf
};
352 # set migrate lock in config file
353 $conf->{lock} = 'migrate';
354 PVE
::QemuConfig-
>write_config($vmid, $conf);
356 sync_disks
($self, $vmid);
361 my ($self, $vmid, $err) = @_;
363 $self->log('info', "aborting phase 1 - cleanup resources");
365 my $conf = $self->{vmconf
};
366 delete $conf->{lock};
367 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
369 $self->log('err', $err);
372 if ($self->{volumes
}) {
373 foreach my $volid (@{$self->{volumes
}}) {
374 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
375 # fixme: try to remove ?
381 my ($self, $vmid) = @_;
383 my $conf = $self->{vmconf
};
385 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
389 my $ruri; # the whole migration dst. URI (protocol:address[:port])
390 my $nodename = PVE
::INotify
::nodename
();
392 ## start on remote node
393 my $cmd = [@{$self->{rem_ssh
}}];
396 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
397 my $res = PVE
::QemuServer
::vm_mon_cmd
($vmid, 'query-spice');
398 $spice_ticket = $res->{ticket
};
401 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
403 # we use TCP only for unsecure migrations as TCP ssh forward tunnels often
404 # did appeared to late (they are hard, if not impossible, to check for)
405 # secure migration use UNIX sockets now, this *breaks* compatibilty when trying
406 # to migrate from new to old but *not* from old to new.
407 my $datacenterconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
408 my $secure_migration = ($datacenterconf->{migration_unsecure
}) ?
0 : 1;
410 if (!$secure_migration) {
411 push @$cmd, '--stateuri', 'tcp';
413 push @$cmd, '--stateuri', 'unix';
416 if ($self->{forcemachine
}) {
417 push @$cmd, '--machine', $self->{forcemachine
};
422 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
423 # instead we pipe it through STDIN
424 PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
427 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
430 $ruri = "tcp:$raddr:$rport";
432 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
434 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
435 $ruri = "unix:$raddr";
437 elsif ($line =~ m/^migration listens on port (\d+)$/) {
438 $raddr = "localhost";
440 $ruri = "tcp:$raddr:$rport";
442 elsif ($line =~ m/^spice listens on port (\d+)$/) {
443 $spice_port = int($1);
447 $self->log('info', $line);
450 die "unable to detect remote migration address\n" if !$raddr;
452 if ($secure_migration) {
453 $self->log('info', "start remote tunnel");
455 if ($ruri =~ /^unix:/) {
457 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
458 $self->{tunnel
}->{sock_addr
} = $raddr;
460 my $unix_socket_try = 0; # wait for the socket to become ready
461 while (! -S
$raddr) {
463 if ($unix_socket_try > 100) {
465 $self->finish_tunnel($self->{tunnel
});
466 die "Timeout, migration socket $ruri did not get ready";
472 } elsif ($ruri =~ /^tcp:/) {
474 if ($raddr eq "localhost") {
475 # for backwards compatibility with older qemu-server versions
476 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
477 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
478 $tunnel_addr = "$lport:localhost:$rport";
481 $self->{tunnel
} = $self->fork_tunnel($tunnel_addr);
484 die "unsupported protocol in migration URI: $ruri\n";
489 $self->log('info', "starting online/live migration on $ruri");
490 $self->{livemigration
} = 1;
493 my $defaults = PVE
::QemuServer
::load_defaults
();
495 # always set migrate speed (overwrite kvm default of 32m)
496 # we set a very hight default of 8192m which is basically unlimited
497 my $migrate_speed = $defaults->{migrate_speed
} || 8192;
498 $migrate_speed = $conf->{migrate_speed
} || $migrate_speed;
499 $migrate_speed = $migrate_speed * 1048576;
500 $self->log('info', "migrate_set_speed: $migrate_speed");
502 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
504 $self->log('info', "migrate_set_speed error: $@") if $@;
506 my $migrate_downtime = $defaults->{migrate_downtime
};
507 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
508 if (defined($migrate_downtime)) {
509 $self->log('info', "migrate_set_downtime: $migrate_downtime");
511 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
513 $self->log('info', "migrate_set_downtime error: $@") if $@;
516 $self->log('info', "set migration_caps");
518 PVE
::QemuServer
::set_migration_caps
($vmid);
522 #set cachesize 10% of the total memory
523 my $cachesize = int($conf->{memory
}*1048576/10);
524 $self->log('info', "set cachesize: $cachesize");
526 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate-set-cache-size", value
=> int($cachesize));
528 $self->log('info', "migrate-set-cache-size error: $@") if $@;
530 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
531 my $rpcenv = PVE
::RPCEnvironment
::get
();
532 my $authuser = $rpcenv->get_user();
534 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
536 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
537 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
539 $self->log('info', "spice client_migrate_info");
542 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "client_migrate_info", protocol
=> 'spice',
543 hostname
=> $proxyticket, 'tls-port' => $spice_port,
544 'cert-subject' => $subject);
546 $self->log('info', "client_migrate_info error: $@") if $@;
550 $self->log('info', "start migrate command to $ruri");
552 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate", uri
=> $ruri);
555 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
558 my $usleep = 2000000;
562 my $downtimecounter = 0;
565 my $avglstat = $lstat/$i if $lstat;
570 $stat = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "query-migrate");
574 warn "query migrate failed: $err\n";
575 $self->log('info', "query migrate failed: $err");
576 if ($err_count <= 5) {
580 die "too many query migrate failures - aborting\n";
583 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(setup)$/im) {
588 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
591 if ($stat->{status
} eq 'completed') {
592 my $delay = time() - $start;
594 my $mbps = sprintf "%.2f", $conf->{memory
}/$delay;
595 my $downtime = $stat->{downtime
} || 0;
596 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
600 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
601 $self->log('info', "migration status error: $stat->{status}");
605 if ($stat->{status
} ne 'active') {
606 $self->log('info', "migration status: $stat->{status}");
610 if ($stat->{ram
}->{transferred
} ne $lstat) {
611 my $trans = $stat->{ram
}->{transferred
} || 0;
612 my $rem = $stat->{ram
}->{remaining
} || 0;
613 my $total = $stat->{ram
}->{total
} || 0;
614 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
615 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
616 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
617 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
618 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
619 #reduce sleep if remainig memory if lower than the everage transfert
620 $usleep = 300000 if $avglstat && $rem < $avglstat;
622 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
623 "remaining ${rem}), total ${total})");
625 if (${xbzrlecachesize
}) {
626 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
629 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
634 if ($downtimecounter > 5) {
635 $downtimecounter = 0;
636 $migrate_downtime *= 2;
637 $self->log('info', "migrate_set_downtime: $migrate_downtime");
639 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
641 $self->log('info', "migrate_set_downtime error: $@") if $@;
647 $lstat = $stat->{ram
}->{transferred
};
651 die "unable to parse migration status '$stat->{status}' - aborting\n";
655 # just to be sure that the tunnel gets closed on successful migration, on error
656 # phase2_cleanup closes it *after* stopping the remote waiting VM
657 if (!$self->{errors
} && $self->{tunnel
}) {
658 eval { finish_tunnel
($self, $self->{tunnel
}); };
660 $self->log('err', $err);
667 my ($self, $vmid, $err) = @_;
669 return if !$self->{errors
};
670 $self->{phase2errors
} = 1;
672 $self->log('info', "aborting phase 2 - cleanup resources");
674 $self->log('info', "migrate_cancel");
676 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_cancel");
678 $self->log('info', "migrate_cancel error: $@") if $@;
680 my $conf = $self->{vmconf
};
681 delete $conf->{lock};
682 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
684 $self->log('err', $err);
687 # cleanup ressources on target host
688 my $nodename = PVE
::INotify
::nodename
();
690 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
691 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
693 $self->log('err', $err);
697 if ($self->{tunnel
}) {
698 eval { finish_tunnel
($self, $self->{tunnel
}); };
700 $self->log('err', $err);
707 my ($self, $vmid) = @_;
709 my $volids = $self->{volumes
};
710 return if $self->{phase2errors
};
712 # destroy local copies
713 foreach my $volid (@$volids) {
714 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
716 $self->log('err', "removing local copy of '$volid' failed - $err");
718 last if $err =~ /^interrupted by signal$/;
724 my ($self, $vmid, $err) = @_;
726 my $conf = $self->{vmconf
};
727 return if $self->{phase2errors
};
729 # move config to remote node
730 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
731 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
733 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
734 if !rename($conffile, $newconffile);
736 if ($self->{livemigration
}) {
737 # now that config file is move, we can resume vm on target if livemigrate
738 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
739 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {},
742 $self->log('err', $line);
746 $self->log('err', $err);
754 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
755 $self->log('info', "Waiting for spice server migration");
757 my $res = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'query-spice');
758 last if int($res->{'migrated'}) == 1;
766 # always stop local VM
767 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
769 $self->log('err', "stopping vm failed - $err");
773 # always deactivate volumes - avoid lvm LVs to be active on several nodes
775 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
776 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
779 $self->log('err', $err);
784 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
785 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
789 my ($self, $vmid) = @_;