]> git.proxmox.com Git - qemu-server.git/blobdiff - PVE/QemuMigrate.pm
move qmp migrate_set_down && migrate_set_speed to qemumigrate
[qemu-server.git] / PVE / QemuMigrate.pm
index b80fa1d280c1e0c97297afb740cda9b554563886..9ca8f87ee58822f361788e01b595d5693d94f478 100644 (file)
@@ -9,6 +9,7 @@ use PVE::INotify;
 use PVE::Cluster;
 use PVE::Storage;
 use PVE::QemuServer;
+use Time::HiRes qw( usleep );
 
 use base qw(PVE::AbstractMigrate);
 
@@ -39,7 +40,7 @@ sub fork_command_pipe {
 }
 
 sub finish_command_pipe {
-    my ($self, $cmdpipe) = @_;
+    my ($self, $cmdpipe, $timeout) = @_;
 
     my $writer = $cmdpipe->{writer};
     my $reader = $cmdpipe->{reader};
@@ -49,43 +50,25 @@ sub finish_command_pipe {
 
     my $cpid = $cmdpipe->{pid};
 
-    kill(15, $cpid) if kill(0, $cpid);
-
-    waitpid($cpid, 0);
-}
-
-sub run_with_timeout {
-    my ($timeout, $code, @param) = @_;
-
-    die "got timeout\n" if $timeout <= 0;
-
-    my $prev_alarm;
-
-    my $sigcount = 0;
-
-    my $res;
-
-    eval {
-       local $SIG{ALRM} = sub { $sigcount++; die "got timeout\n"; };
-       local $SIG{PIPE} = sub { $sigcount++; die "broken pipe\n" };
-       local $SIG{__DIE__};   # see SA bug 4631
-
-       $prev_alarm = alarm($timeout);
-
-       $res = &$code(@param);
-
-       alarm(0); # avoid race conditions
-    };
-
-    my $err = $@;
-
-    alarm($prev_alarm) if defined($prev_alarm);
+    if ($timeout) {
+       for (my $i = 0; $i < $timeout; $i++) {
+           return if !PVE::ProcFSTools::check_process_running($cpid);
+           sleep(1);
+       }
+    }
 
-    die "unknown error" if $sigcount && !$err; # seems to happen sometimes
+    $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
+    kill(15, $cpid);
 
-    die $err if $err;
+    # wait again
+    for (my $i = 0; $i < 10; $i++) {
+       return if !PVE::ProcFSTools::check_process_running($cpid);
+       sleep(1);
+    }
 
-    return $res;
+    $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
+    kill 9, $cpid;
+    sleep 1;
 }
 
 sub fork_tunnel {
@@ -100,7 +83,7 @@ sub fork_tunnel {
 
     my $helo;
     eval {
-       run_with_timeout(60, sub { $helo = <$reader>; });
+       PVE::Tools::run_with_timeout(60, sub { $helo = <$reader>; });
        die "no reply\n" if !$helo;
        die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
        die "got strange reply from mtunnel ('$helo')\n"
@@ -121,21 +104,21 @@ sub finish_tunnel {
     my $writer = $tunnel->{writer};
 
     eval {
-       run_with_timeout(30, sub {
+       PVE::Tools::run_with_timeout(30, sub {
            print $writer "quit\n";
            $writer->flush();
        });
     };
     my $err = $@;
 
-    $self->finish_command_pipe($tunnel);
+    $self->finish_command_pipe($tunnel, 30);
 
     die $err if $err;
 }
 
 sub lock_vm {
     my ($self, $vmid, $code, @param) = @_;
-    
+
     return PVE::QemuServer::lock_config($vmid, $code, @param);
 }
 
@@ -195,32 +178,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;
@@ -276,16 +264,11 @@ sub phase1 {
     my $conf = $self->{vmconf};
 
     # set migrate lock in config file
-    PVE::QemuServer::change_config_nolock($vmid, { lock => 'migrate' }, {}, 1);
+    $conf->{lock} = 'migrate';
+    PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
 
     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 {
@@ -293,12 +276,13 @@ sub phase1_cleanup {
 
     $self->log('info', "aborting phase 1 - cleanup resources");
 
-    my $unset = { lock => 1 };
-    eval { PVE::QemuServer::change_config_nolock($vmid, {}, $unset, 1) };
+    my $conf = $self->{vmconf};
+    delete $conf->{lock};
+    eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
     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}'");
@@ -316,17 +300,19 @@ sub phase2 {
 
     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}}, 'qm', 'start',
+               $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename];
 
-    $self->cmd($cmd, outfunc => sub {
+    PVE::Tools::run_command($cmd, outfunc => sub {
        my $line = shift;
 
        if ($line =~ m/^migration listens on port (\d+)$/) {
            $rport = $1;
        }
-    });
+    }, errfunc => sub {});
 
     die "unable to detect remote migration port\n" if !$rport;
 
@@ -336,58 +322,154 @@ sub phase2 {
     my $lport = PVE::QemuServer::next_migrate_port();
     $self->{tunnel} = $self->fork_tunnel($self->{nodeip}, $lport, $rport);
 
-    $self->log('info', "starting online/live migration");
+    $self->log('info', "starting online/live migration on port $lport");
     # start migration
 
     my $start = time();
 
-    PVE::QemuServer::vm_monitor_command($vmid, "migrate -d \"tcp:localhost:$lport\"", 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));
+       };
+       $self->log('info', "migrate_set_downtime error: $@") if $@;
+    }
+
+    my $capabilities = {};
+    $capabilities->{capability} =  "xbzrle";
+    $capabilities->{state} = JSON::false;
 
-    my $lstat = '';
+    eval {
+       PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => [$capabilities]);
+    };
+
+    #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);
+    };
+
+    eval {
+        PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:localhost:$lport");
+    };
+    my $merr = $@;
+
+    my $lstat = 0;
+    my $usleep = 2000000;
+    my $i = 0;
+    my $err_count = 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) {
-           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");
                }
            }
-           
-           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}");
+           }
+
+           $lstat = $stat->{ram}->{transferred};
+           
        } else {
-           die "unable to parse migration status '$stat' - aborting\n";
+           die $merr if $merr;
+           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");
+
+    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) {
@@ -398,20 +480,30 @@ sub phase3 {
            last if $err =~ /^interrupted by signal$/;
        }
     }
+}
 
+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);
+
+    # now that config file is move, we can resume vm on target if livemigrate
     if ($self->{tunnel}) {
-       eval { finish_tunnel($self, $self->{tunnel});  };
+       my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock'];
+       eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
        if (my $err = $@) {
            $self->log('err', $err);
            $self->{errors} = 1;
        }
     }
-}
-
-sub phase3_cleanup {
-    my ($self, $vmid, $err) = @_;
-
-    my $conf = $self->{vmconf};
 
     # always stop local VM
     eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
@@ -420,6 +512,14 @@ sub phase3_cleanup {
        $self->{errors} = 1;
     }
 
+    if ($self->{tunnel}) {
+       eval { finish_tunnel($self, $self->{tunnel});  };
+       if (my $err = $@) {
+           $self->log('err', $err);
+           $self->{errors} = 1;
+       }
+    }
+
     # always deactivate volumes - avoid lvm LVs to be active on several nodes
     eval {
        my $vollist = PVE::QemuServer::get_vm_volumes($conf);