]> git.proxmox.com Git - qemu-server.git/blobdiff - PVE/QemuMigrate.pm
add vmxnet3 to list of available network card models
[qemu-server.git] / PVE / QemuMigrate.pm
index 0dc81a50612de03032e1c54f67af47f093f6b015..634c305bca07d4f3b67a1430c644de9471504577 100644 (file)
@@ -6,9 +6,12 @@ use PVE::AbstractMigrate;
 use IO::File;
 use IPC::Open2;
 use PVE::INotify;
+use PVE::Tools;
 use PVE::Cluster;
 use PVE::Storage;
 use PVE::QemuServer;
+use Time::HiRes qw( usleep );
+use PVE::RPCEnvironment;
 
 use base qw(PVE::AbstractMigrate);
 
@@ -73,8 +76,9 @@ sub finish_command_pipe {
 sub fork_tunnel {
     my ($self, $nodeip, $lport, $rport) = @_;
 
-    my $cmd = [@{$self->{rem_ssh}}, '-L', "$lport:localhost:$rport",
-              'qm', 'mtunnel' ];
+    my @localtunnelinfo = $lport ? ('-L' , "$lport:localhost:$rport" ) : ();
+
+    my $cmd = [@{$self->{rem_ssh}}, @localtunnelinfo, 'qm', 'mtunnel' ];
 
     my $tunnel = $self->fork_command_pipe($cmd);
 
@@ -117,7 +121,7 @@ sub finish_tunnel {
 
 sub lock_vm {
     my ($self, $vmid, $code, @param) = @_;
-    
+
     return PVE::QemuServer::lock_config($vmid, $code, @param);
 }
 
@@ -137,6 +141,7 @@ sub prepare {
     if (my $pid = PVE::QemuServer::check_running($vmid)) {
        die "cant migrate running VM without --online\n" if !$online;
        $running = $pid;
+       $self->{forcemachine} = PVE::QemuServer::get_current_qemu_machine($vmid);
     }
 
     if (my $loc_res = PVE::QemuServer::check_local_resources($conf, 1)) {
@@ -177,32 +182,37 @@ sub sync_disks {
        my $volhash = {};
        my $cdromhash = {};
 
-       # get list from PVE::Storage (for unused volumes)
-       my $dl = PVE::Storage::vdisk_list($self->{storecfg}, undef, $vmid);
-       PVE::Storage::foreach_volid($dl, sub {
-           my ($volid, $sid, $volname) = @_;
+       my $sharedvm = 1;
 
-           # check if storage is available on both nodes
-           my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
-           PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
+       my @sids = PVE::Storage::storage_ids($self->{storecfg});
+        foreach my $storeid (@sids) {
+           my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
+            next if $scfg->{shared};
+           next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
 
-           return if $scfg->{shared};
+            # get list from PVE::Storage (for unused volumes)
+            my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
+            PVE::Storage::foreach_volid($dl, sub {
+                my ($volid, $sid, $volname) = @_;
 
-           $volhash->{$volid} = 1;
-       });
+                # check if storage is available on target node
+                PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
 
-       # and add used,owned/non-shared disks (just to be sure we have all)
+                $volhash->{$volid} = 1;
+               $sharedvm = 0; # there is a non-shared disk
+            });
+        }
 
-       my $sharedvm = 1;
-       PVE::QemuServer::foreach_drive($conf, sub {
-           my ($ds, $drive) = @_;
+       # and add used, owned/non-shared disks (just to be sure we have all)
+
+       PVE::QemuServer::foreach_volid($conf, sub {
+           my ($volid, $is_cdrom) = @_;
 
-           my $volid = $drive->{file};
            return if !$volid;
 
            die "cant migrate local file/device '$volid'\n" if $volid =~ m|^/|;
 
-           if (PVE::QemuServer::drive_is_cdrom($drive)) {
+           if ($is_cdrom) {
                die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
                return if $volid eq 'none';
                $cdromhash->{$volid} = 1;
@@ -239,6 +249,12 @@ sub sync_disks {
 
            die "can't migrate '$volid' - storagy type '$scfg->{type}' not supported\n"
                if $scfg->{type} ne 'dir';
+
+           # if file, check if a backing file exist
+           if (($scfg->{type} eq 'dir') && (!$sharedvm)) {
+               my (undef, undef, undef, $parent) = PVE::Storage::volume_size_info($self->{storecfg}, $volid, 1);
+               die "can't migrate '$volid' as it's a clone of '$parent'" if $parent;
+           }
        }
 
        foreach my $volid (keys %$volhash) {
@@ -263,12 +279,6 @@ sub phase1 {
 
     sync_disks($self, $vmid);
 
-    # move config to remote node
-    my $conffile = PVE::QemuServer::config_file($vmid);
-    my $newconffile = PVE::QemuServer::config_file($vmid, $self->{node});
-
-    die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
-       if !rename($conffile, $newconffile);
 };
 
 sub phase1_cleanup {
@@ -282,7 +292,7 @@ sub phase1_cleanup {
     if (my $err = $@) {
        $self->log('err', $err);
     }
-  
+
     if ($self->{volumes}) {
        foreach my $volid (@{$self->{volumes}}) {
            $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
@@ -298,82 +308,248 @@ sub phase2 {
 
     $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
 
+    my $raddr;
     my $rport;
+    my $nodename = PVE::INotify::nodename();
 
     ## start on remote node
-    my $cmd = [@{$self->{rem_ssh}}, 'qm', 'start', 
-              $vmid, '--stateuri', 'tcp', '--skiplock'];
+    my $cmd = [@{$self->{rem_ssh}}];
+
+    my $spice_ticket;
+    if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
+       my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
+       $spice_ticket = $res->{ticket};
+    }
+
+    push @$cmd , 'qm', 'start', $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename;
+
+    if ($self->{forcemachine}) {
+       push @$cmd, '--machine', $self->{forcemachine};
+    }
+
+    my $spice_port;
 
-    PVE::Tools::run_command($cmd, outfunc => sub {
+    # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
+    # instead we pipe it through STDIN
+    PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
        my $line = shift;
 
-       if ($line =~ m/^migration listens on port (\d+)$/) {
-           $rport = $1;
+       if ($line =~ m/^migration listens on tcp:([\d\.]+|localhost):(\d+)$/) {
+           $raddr = $1;
+           $rport = int($2);
        }
-    }, errfunc => sub {});
-
-    die "unable to detect remote migration port\n" if !$rport;
+       elsif ($line =~ m/^migration listens on port (\d+)$/) {
+           $raddr = "localhost";
+           $rport = int($1);
+       }
+        elsif ($line =~ m/^spice listens on port (\d+)$/) {
+           $spice_port = int($1);
+       }
+    }, errfunc => sub {
+       my $line = shift;
+       $self->log('info', $line);
+    });
 
-    $self->log('info', "starting migration tunnel");
+    die "unable to detect remote migration address\n" if !$raddr;
 
     ## create tunnel to remote port
-    my $lport = PVE::QemuServer::next_migrate_port();
+    $self->log('info', "starting ssh migration tunnel");
+    my $lport = ($raddr eq "localhost") ? PVE::Tools::next_migrate_port() : undef;
     $self->{tunnel} = $self->fork_tunnel($self->{nodeip}, $lport, $rport);
 
-    $self->log('info', "starting online/live migration on port $lport");
-    # start migration
-
     my $start = time();
+    $self->log('info', "starting online/live migration on $raddr:$rport");
+    $self->{livemigration} = 1;
+
+    # load_defaults
+    my $defaults = PVE::QemuServer::load_defaults();
+
+    # always set migrate speed (overwrite kvm default of 32m)
+    # we set a very hight default of 8192m which is basically unlimited
+    my $migrate_speed = $defaults->{migrate_speed} || 8192;
+    $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
+    $migrate_speed = $migrate_speed * 1048576;
+    $self->log('info', "migrate_set_speed: $migrate_speed");
+    eval {
+        PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
+    };
+    $self->log('info', "migrate_set_speed error: $@") if $@;
+
+    my $migrate_downtime = $defaults->{migrate_downtime};
+    $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
+    if (defined($migrate_downtime)) {
+       $self->log('info', "migrate_set_downtime: $migrate_downtime");
+       eval {
+           PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
+       };
+       $self->log('info', "migrate_set_downtime error: $@") if $@;
+    }
+
+    my $capabilities = {};
+    $capabilities->{capability} =  "xbzrle";
+    $capabilities->{state} = JSON::false;
+
+    eval {
+       PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => [$capabilities]);
+    };
 
-    my $merr = PVE::QemuServer::vm_monitor_command($vmid, "migrate -d \"tcp:localhost:$lport\"", 1);
+    #set cachesize 10% of the total memory
+    my $cachesize = int($conf->{memory}*1048576/10);
+    eval {
+       PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => $cachesize);
+    };
+       
+    if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
+       my $rpcenv = PVE::RPCEnvironment::get();
+       my $authuser = $rpcenv->get_user();
+
+       my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
+
+       my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
+        my $subject = PVE::QemuServer::read_x509_subject_spice($filename);
+
+       $self->log('info', "spice client_migrate_info");
+
+       eval {
+           PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice', 
+                                               hostname => $proxyticket, 'tls-port' => $spice_port, 
+                                               'cert-subject' => $subject);
+       };
+       $self->log('info', "client_migrate_info error: $@") if $@;
 
-    my $lstat = '';
+    }
+
+    eval {
+        PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:$raddr:$rport");
+    };
+    my $merr = $@;
+    $self->log('info', "migrate uri => tcp:$raddr:$rport failed: $merr") if $merr;
+
+    my $lstat = 0;
+    my $usleep = 2000000;
+    my $i = 0;
+    my $err_count = 0;
+    my $lastrem = undef;
+    my $downtimecounter = 0;
     while (1) {
-       sleep (2);
-       my $stat = PVE::QemuServer::vm_monitor_command($vmid, "info migrate", 1);
-       if ($stat =~ m/^Migration status: (active|completed|failed|cancelled)$/im) {
-           $merr = undef;
-           my $ms = $1;
-
-           if ($stat ne $lstat) {
-               if ($ms eq 'active') {
-                   my ($trans, $rem, $total) = (0, 0, 0);
-                   $trans = $1 if $stat =~ m/^transferred ram: (\d+) kbytes$/im;
-                   $rem = $1 if $stat =~ m/^remaining ram: (\d+) kbytes$/im;
-                   $total = $1 if $stat =~ m/^total ram: (\d+) kbytes$/im;
-
-                   $self->log('info', "migration status: $ms (transferred ${trans}KB, " .
-                              "remaining ${rem}KB), total ${total}KB)");
-               } else {
-                   $self->log('info', "migration status: $ms");
-               }
+       $i++;
+       my $avglstat = $lstat/$i if $lstat;
+
+       usleep($usleep);
+       my $stat;
+       eval {
+           $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
+       };
+       if (my $err = $@) {
+           $err_count++;
+           warn "query migrate failed: $err\n";
+           if ($err_count <= 5) {
+               usleep(1000000);
+               next;
            }
-
-           if ($ms eq 'completed') {
+           die "too many query migrate failures - aborting\n";
+       }
+       if ($stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
+           $merr = undef;
+           $err_count = 0;
+           if ($stat->{status} eq 'completed') {
                my $delay = time() - $start;
                if ($delay > 0) {
                    my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
-                   $self->log('info', "migration speed: $mbps MB/s");
+                   my $downtime = $stat->{downtime} || 0;
+                   $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
                }
            }
-           
-           if ($ms eq 'failed' || $ms eq 'cancelled') {
+
+           if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
                die "aborting\n"
            }
 
-           last if $ms ne 'active';
+           if ($stat->{status} ne 'active') {
+               $self->log('info', "migration status: $stat->{status}");
+               last;
+           }
+
+           if ($stat->{ram}->{transferred} ne $lstat) {
+               my $trans = $stat->{ram}->{transferred} || 0;
+               my $rem = $stat->{ram}->{remaining} || 0;
+               my $total = $stat->{ram}->{total} || 0;
+               my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
+               my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
+               my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
+               my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
+               my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
+               #reduce sleep if remainig memory if lower than the everage transfert 
+               $usleep = 300000 if $avglstat && $rem < $avglstat;
+
+               $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
+                          "remaining ${rem}), total ${total})");
+
+               #$self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
+               if (($lastrem  && $rem > $lastrem ) || ($rem == 0)) {
+                   $downtimecounter++;
+               }
+               $lastrem = $rem;
+
+               if ($downtimecounter > 5) {
+                   $downtimecounter = 0;
+                   $migrate_downtime *= 2;
+                   $self->log('info', "migrate_set_downtime: $migrate_downtime");
+                   eval {
+                       PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
+                   };
+                   $self->log('info', "migrate_set_downtime error: $@") if $@;
+               }
+
+           }
+
+
+           $lstat = $stat->{ram}->{transferred};
+           
        } else {
            die $merr if $merr;
-           die "unable to parse migration status '$stat' - aborting\n";
+           die "unable to parse migration status '$stat->{status}' - aborting\n";
        }
-       $lstat = $stat;
+    }
+}
+
+sub phase2_cleanup {
+    my ($self, $vmid, $err) = @_;
+
+    return if !$self->{errors};
+    $self->{phase2errors} = 1;
+
+    $self->log('info', "aborting phase 2 - cleanup resources");
+
+    $self->log('info', "migrate_cancel");
+    eval {
+       PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
     };
+    $self->log('info', "migrate_cancel error: $@") if $@;
+
+    my $conf = $self->{vmconf};
+    delete $conf->{lock};
+    eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
+    if (my $err = $@) {
+        $self->log('err', $err);
+    }
+
+    # cleanup ressources on target host
+    my $nodename = PVE::INotify::nodename();
+    my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
+    eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
+    if (my $err = $@) {
+        $self->log('err', $err);
+        $self->{errors} = 1;
+    }
 }
 
 sub phase3 {
     my ($self, $vmid) = @_;
-    
+
     my $volids = $self->{volumes};
+    return if $self->{phase2errors};
 
     # destroy local copies
     foreach my $volid (@$volids) {
@@ -390,6 +566,44 @@ sub phase3_cleanup {
     my ($self, $vmid, $err) = @_;
 
     my $conf = $self->{vmconf};
+    return if $self->{phase2errors};
+
+    # move config to remote node
+    my $conffile = PVE::QemuServer::config_file($vmid);
+    my $newconffile = PVE::QemuServer::config_file($vmid, $self->{node});
+
+    die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
+        if !rename($conffile, $newconffile);
+
+    if ($self->{livemigration}) {
+       # now that config file is move, we can resume vm on target if livemigrate
+       my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock'];
+       eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, 
+               errfunc => sub {
+                   my $line = shift;
+                   $self->log('err', $line);
+               });
+       };
+       if (my $err = $@) {
+           $self->log('err', $err);
+           $self->{errors} = 1;
+       }
+    }
+
+    eval {
+
+       my $timer = 0;
+       if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
+           $self->log('info', "Waiting for spice server migration");
+           while (1) {
+               my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
+               last if int($res->{'migrated'}) == 1;
+               last if $timer > 50;
+               $timer ++;
+               usleep(200000);
+           }
+       }
+    };
 
     # always stop local VM
     eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };