]> git.proxmox.com Git - pve-ha-manager.git/blobdiff - src/PVE/HA/LRM.pm
followup code cleanup
[pve-ha-manager.git] / src / PVE / HA / LRM.pm
index 71862902aa217d690c2f5822c8e01078442504e9..417619b5d16852880da783f1fa34330f47c122dd 100644 (file)
@@ -4,12 +4,12 @@ package PVE::HA::LRM;
 
 use strict;
 use warnings;
-use Data::Dumper;
 use POSIX qw(:sys_wait_h);
 
 use PVE::SafeSyslog;
 use PVE::Tools;
-use PVE::HA::Tools;
+use PVE::HA::Tools ':exit_codes';
+use PVE::HA::Resources;
 
 # Server can have several states:
 
@@ -29,9 +29,12 @@ sub new {
        status => { state => 'startup' },
        workers => {},
        results => {},
+       restart_tries => {},
        shutdown_request => 0,
+       shutdown_errors => 0,
        # mode can be: active, reboot, shutdown, restart
        mode => 'active',
+       cluster_state_update => 0,
     }, $class;
 
     $self->set_local_status({ state =>         'wait_for_agent_lock' });   
@@ -42,9 +45,66 @@ sub new {
 sub shutdown_request {
     my ($self) = @_;
 
-    $self->{shutdown_request} = 1;
+    return if $self->{shutdown_request}; # already in shutdown mode
+
+    my $haenv = $self->{haenv};
 
-    $self->{mode} = 'restart'; # fixme: detect shutdown/reboot
+    my $nodename = $haenv->nodename();
+
+    my ($shutdown, $reboot) = $haenv->is_node_shutdown();
+
+    my $dc_ha_cfg = $haenv->get_ha_settings();
+    my $shutdown_policy = $dc_ha_cfg->{shutdown_policy} // 'conditional';
+
+    if ($shutdown) { # don't log this on service restart, only on node shutdown
+       $haenv->log('info', "got shutdown request with shutdown policy '$shutdown_policy'");
+    }
+
+    my $freeze_all;
+    if ($shutdown_policy eq 'conditional') {
+       $freeze_all = $reboot;
+    } elsif ($shutdown_policy eq 'freeze') {
+       $freeze_all = 1;
+    } elsif ($shutdown_policy eq 'failover') {
+       $freeze_all = 0;
+    } else {
+       $haenv->log('err', "unknown shutdown policy '$shutdown_policy', fall back to conditional");
+       $freeze_all = $reboot;
+    }
+
+    if ($shutdown) {
+       # *always* queue stop jobs for all services if the node shuts down,
+       # independent if it's a reboot or a poweroff, else we may corrupt
+       # services or hinder node shutdown
+       my $ss = $self->{service_status};
+
+       foreach my $sid (keys %$ss) {
+           my $sd = $ss->{$sid};
+           next if !$sd->{node};
+           next if $sd->{node} ne $nodename;
+           # Note: use undef uid to mark shutdown/stop jobs
+           $self->queue_resource_command($sid, undef, 'request_stop');
+       }
+    }
+
+    if ($shutdown) {
+       if ($freeze_all) {
+           if ($reboot) {
+               $haenv->log('info', "reboot LRM, stop and freeze all services");
+           } else {
+               $haenv->log('info', "shutdown LRM, stop and freeze all services");
+           }
+           $self->{mode} = 'restart';
+       } else {
+           $haenv->log('info', "shutdown LRM, stop all services");
+           $self->{mode} = 'shutdown';
+       }
+    } else {
+       $haenv->log('info', "restart LRM, freeze all services");
+       $self->{mode} = 'restart';
+    }
+
+    $self->{shutdown_request} = 1;
 
     eval { $self->update_lrm_status(); };
     if (my $err = $@) {
@@ -82,9 +142,13 @@ sub update_lrm_status {
 
     my $haenv = $self->{haenv};
 
+    return 0 if !$haenv->quorate();
+    
     my $lrm_status = { 
+       state => $self->{status}->{state},
        mode => $self->{mode},
        results => $self->{results},
+       timestamp => $haenv->get_time(),
     };
     
     eval { $haenv->write_lrm_status($lrm_status); };
@@ -96,6 +160,21 @@ sub update_lrm_status {
     return 1;
 }
 
+sub update_service_status {
+    my ($self) = @_;
+
+    my $haenv = $self->{haenv};
+
+    my $ms = eval { $haenv->read_manager_status(); };
+    if (my $err = $@) {
+       $haenv->log('err', "updating service status from manager failed: $err");
+       return undef;
+    } else {
+       $self->{service_status} = $ms->{service_status} || {};
+       return 1;
+    }
+}
+
 sub get_protected_ha_agent_lock {
     my ($self) = @_;
 
@@ -146,6 +225,8 @@ sub active_service_count {
        next if !defined($req_state);
        next if $req_state eq 'stopped';
        next if $req_state eq 'freeze';
+       # erroneous services are not managed by HA, don't count them as active
+       next if $req_state eq 'error';
 
        $count++;
     }
@@ -160,8 +241,24 @@ sub do_one_iteration {
 
     my $haenv = $self->{haenv};
 
+    $haenv->loop_start_hook();
+
+    $self->{cluster_state_update} = $haenv->cluster_state_update();
+
+    my $res = $self->work();
+
+    $haenv->loop_end_hook();
+
+    return $res;
+}
+
+sub work {
+    my ($self) = @_;
+
+    my $haenv = $self->{haenv};
+
     if (!$wrote_lrm_status_at_startup) {
-       if ($haenv->quorate() && $self->update_lrm_status()) {
+       if ($self->update_lrm_status()) {
            $wrote_lrm_status_at_startup = 1;
        } else {
            # do nothing
@@ -173,8 +270,7 @@ sub do_one_iteration {
     my $status = $self->get_local_status();
     my $state = $status->{state};
 
-    my $ms = $haenv->read_manager_status();
-    $self->{service_status} =  $ms->{service_status} || {};
+    $self->update_service_status();
 
     my $fence_request = PVE::HA::Tools::count_fenced_services($self->{service_status}, $haenv->nodename());
     
@@ -218,7 +314,9 @@ sub do_one_iteration {
     if ($state eq 'wait_for_agent_lock') {
 
        return 0 if $self->{shutdown_request};
-
+       
+       $self->update_lrm_status();
+       
        $haenv->sleep(5);
           
     } elsif ($state eq 'active') {
@@ -233,22 +331,54 @@ sub do_one_iteration {
        eval {
            # fixme: set alert timer
 
+           # if we could not get the current service status there's no point
+           # in doing anything, try again next round.
+           return if !$self->update_service_status();
+
            if ($self->{shutdown_request}) {
 
-               # fixme: request service stop or relocate ?
+               if ($self->{mode} eq 'restart') {
 
-               my $service_count = $self->active_service_count();
+                   my $service_count = $self->active_service_count();
 
-               if ($service_count == 0) {
+                   if ($service_count == 0) {
 
-                   if ($self->{ha_agent_wd}) {
-                       $haenv->watchdog_close($self->{ha_agent_wd});
-                       delete $self->{ha_agent_wd};
+                       if ($self->run_workers() == 0) {
+                           if ($self->{ha_agent_wd}) {
+                               $haenv->watchdog_close($self->{ha_agent_wd});
+                               delete $self->{ha_agent_wd};
+                           }
+
+                           $shutdown = 1;
+
+                           # restart with no or freezed services, release the lock
+                           $haenv->release_ha_agent_lock();
+                       }
                    }
+               } else {
 
-                   $shutdown = 1;
+                   if ($self->run_workers() == 0) {
+                       if ($self->{shutdown_errors} == 0) {
+                           if ($self->{ha_agent_wd}) {
+                               $haenv->watchdog_close($self->{ha_agent_wd});
+                               delete $self->{ha_agent_wd};
+                           }
+
+                           # shutdown with all services stopped thus release the lock
+                           $haenv->release_ha_agent_lock();
+                       }
+
+                       $shutdown = 1;
+                   }
                }
            } else {
+               if (!$self->{cluster_state_update}) {
+                   # update failed but we could still renew our lock (cfs restart?),
+                   # safely skip manage and expect to update just fine next round
+                   $haenv->log('notice', "temporary inconsistent cluster state " .
+                               "(cfs restart?), skip round");
+                   return;
+               }
 
                $self->manage_resources();
 
@@ -258,6 +388,8 @@ sub do_one_iteration {
            $haenv->log('err', "got unexpected error - $err");
        }
 
+       $self->update_lrm_status();
+       
        return 0 if $shutdown;
 
        $haenv->sleep_until($startime + $max_time);
@@ -300,60 +432,40 @@ sub do_one_iteration {
     return 1;
 }
 
-sub manage_resources {
+sub run_workers {
     my ($self) = @_;
 
     my $haenv = $self->{haenv};
 
-    my $nodename = $haenv->nodename();
-
-    my $ss = $self->{service_status};
-
-    foreach my $sid (keys %$ss) {
-       my $sd = $ss->{$sid};
-       next if !$sd->{node};
-       next if !$sd->{uid};
-       next if $sd->{node} ne $nodename;
-       my $req_state = $sd->{state};
-       next if !defined($req_state);
-       next if $req_state eq 'freeze';
-       eval {
-           $self->queue_resource_command($sid, $sd->{uid}, $req_state, $sd->{target});
-       };
-       if (my $err = $@) {
-           $haenv->log('err', "unable to run resource agent for '$sid' - $err"); # fixme
-       }
-    }
-
     my $starttime = $haenv->get_time();
 
-    # start workers
-    my $max_workers = 4;
+    # number of workers to start, if 0 we exec the command directly witouth forking
+    my $max_workers = $haenv->get_max_workers();
 
     my $sc = $haenv->read_service_config();
 
     while (($haenv->get_time() - $starttime) < 5) {
        my $count =  $self->check_active_workers();
 
-       foreach my $sid (keys %{$self->{workers}}) {
-           last if $count >= $max_workers;
+       foreach my $sid (sort keys %{$self->{workers}}) {
+           last if $count >= $max_workers && $max_workers > 0;
+
            my $w = $self->{workers}->{$sid};
-           my $cd = $sc->{$sid};
-           if (!$cd) {
-               $haenv->log('err', "missing resource configuration for '$sid'");
-               next;
-           }
            if (!$w->{pid}) {
-               if ($haenv->can_fork()) {
+               # only fork if we may else call exec_resource_agent
+               # directly (e.g. for regression tests)
+               if ($max_workers > 0) {
                    my $pid = fork();
                    if (!defined($pid)) {
                        $haenv->log('err', "fork worker failed");
                        $count = 0; last; # abort, try later
                    } elsif ($pid == 0) {
+                       $haenv->after_fork(); # cleanup
+
                        # do work
                        my $res = -1;
                        eval {
-                           $res = $haenv->exec_resource_agent($sid, $cd, $w->{state}, $w->{target});
+                           $res = $self->exec_resource_agent($sid, $sc->{$sid}, $w->{state}, $w->{target});
                        };
                        if (my $err = $@) {
                            $haenv->log('err', $err);
@@ -367,12 +479,17 @@ sub manage_resources {
                } else {
                    my $res = -1;
                    eval {
-                       $res = $haenv->exec_resource_agent($sid, $cd, $w->{state}, $w->{target});
+                       $res = $self->exec_resource_agent($sid, $sc->{$sid}, $w->{state}, $w->{target});
+                       $res = $res << 8 if $res > 0;
                    };
                    if (my $err = $@) {
                        $haenv->log('err', $err);
-                   }               
-                   $self->resource_command_finished($sid, $w->{uid}, $res);
+                   }
+                   if (defined($w->{uid})) {
+                       $self->resource_command_finished($sid, $w->{uid}, $res);
+                   } else {
+                       $self->stop_command_finished($sid, $res);
+                   }
                }
            }
        }
@@ -381,12 +498,48 @@ sub manage_resources {
 
        $haenv->sleep(1);
     }
+
+    return scalar(keys %{$self->{workers}});
+}
+
+sub manage_resources {
+    my ($self) = @_;
+
+    my $haenv = $self->{haenv};
+
+    my $nodename = $haenv->nodename();
+
+    my $ss = $self->{service_status};
+
+    foreach my $sid (keys %{$self->{restart_tries}}) {
+       delete $self->{restart_tries}->{$sid} if !$ss->{$sid};
+    }
+
+    foreach my $sid (keys %$ss) {
+       my $sd = $ss->{$sid};
+       next if !$sd->{node};
+       next if !$sd->{uid};
+       next if $sd->{node} ne $nodename;
+       my $req_state = $sd->{state};
+       next if !defined($req_state);
+       next if $req_state eq 'freeze';
+       $self->queue_resource_command($sid, $sd->{uid}, $req_state, $sd->{target});
+    }
+
+    return $self->run_workers();
 }
 
-# fixme: use a queue an limit number of parallel workers?
 sub queue_resource_command {
     my ($self, $sid, $uid, $state, $target) = @_;
 
+    # do not queue the excatly same command twice as this may lead to
+    # an inconsistent HA state when the first command fails but the CRM
+    # does not process its failure right away and the LRM starts a second
+    # try, without the CRM knowing of it (race condition)
+    # The 'stopped' command is an exception as we do not process its result
+    # in the CRM and we want to execute it always (even with no active CRM)
+    return if $state ne 'stopped' && $uid && defined($self->{results}->{$uid});
+
     if (my $w = $self->{workers}->{$sid}) {
        return if $w->{pid}; # already started
        # else, delete and overwrite queue entry with new command
@@ -413,7 +566,11 @@ sub check_active_workers {
            # check status
            my $waitpid = waitpid($pid, WNOHANG);
            if (defined($waitpid) && ($waitpid == $pid)) {
-               $self->resource_command_finished($sid, $w->{uid}, $?);
+               if (defined($w->{uid})) {
+                   $self->resource_command_finished($sid, $w->{uid}, $?);
+               } else {
+                   $self->stop_command_finished($sid, $?);
+               }
            } else {
                $count++;
            }
@@ -423,6 +580,29 @@ sub check_active_workers {
     return $count;
 }
 
+sub stop_command_finished {
+    my ($self, $sid, $status) = @_;
+
+    my $haenv = $self->{haenv};
+
+    my $w = delete $self->{workers}->{$sid};
+    return if !$w; # should not happen
+
+    my $exit_code = -1;
+
+    if ($status == -1) {
+       $haenv->log('err', "resource agent $sid finished - failed to execute");
+    }  elsif (my $sig = ($status & 127)) {
+       $haenv->log('err', "resource agent $sid finished - got signal $sig");
+    } else {
+       $exit_code = ($status >> 8);
+    }
+
+    if ($exit_code != 0) {
+       $self->{shutdown_errors}++;
+    }
+}
+
 sub resource_command_finished {
     my ($self, $sid, $uid, $status) = @_;
 
@@ -441,6 +621,10 @@ sub resource_command_finished {
        $exit_code = ($status >> 8);
     }
 
+    $exit_code = $self->handle_service_exitcode($sid, $w->{state}, $exit_code);
+
+    return if $exit_code == ETRY_AGAIN; # tell nobody, simply retry
+
     $self->{results}->{$uid} = {
        sid => $w->{sid},
        state => $w->{state},
@@ -463,8 +647,165 @@ sub resource_command_finished {
        $results->{$id} = $self->{results}->{$id};
     }
     $self->{results} = $results;
+}
+
+# processes the exit code from a finished resource agent, so that the CRM knows
+# if the LRM wants to retry an action based on the current recovery policies for
+# the failed service, or the CRM itself must try to recover from the failure.
+sub handle_service_exitcode {
+    my ($self, $sid, $cmd, $exit_code) = @_;
+
+    my $haenv = $self->{haenv};
+    my $tries = $self->{restart_tries};
+
+    my $sc = $haenv->read_service_config();
+
+    my $max_restart = 0;
+
+    if (my $cd = $sc->{$sid}) {
+       $max_restart = $cd->{max_restart};
+    }
+
+    if ($cmd eq 'started') {
+
+       if ($exit_code == SUCCESS) {
+
+           $tries->{$sid} = 0;
+
+           return $exit_code;
+
+       } elsif ($exit_code == ERROR) {
+
+           $tries->{$sid} = 0 if !defined($tries->{$sid});
+
+           if ($tries->{$sid} >= $max_restart) {
+               $haenv->log('err', "unable to start service $sid on local node".
+                          " after $tries->{$sid} retries");
+               $tries->{$sid} = 0;
+               return ERROR;
+           }
+
+           $tries->{$sid}++;
+
+           $haenv->log('warning', "restart policy: retry number $tries->{$sid}" .
+                       " for service '$sid'");
+           # tell CRM that we retry the start
+           return ETRY_AGAIN;
+       }
+    }
+
+    return $exit_code;
+
+}
+
+sub exec_resource_agent {
+    my ($self, $sid, $service_config, $cmd, @params) = @_;
+
+    # setup execution environment
+
+    $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
+
+    my $haenv = $self->{haenv};
+
+    my $nodename = $haenv->nodename();
+
+    my (undef, $service_type, $service_name) = $haenv->parse_sid($sid);
+
+    my $plugin = PVE::HA::Resources->lookup($service_type);
+    if (!$plugin) {
+       $haenv->log('err', "service type '$service_type' not implemented");
+       return EUNKNOWN_SERVICE_TYPE;
+    }
+
+    if (!$service_config) {
+       $haenv->log('err', "missing resource configuration for '$sid'");
+       return EUNKNOWN_SERVICE;
+    }
+
+    # process error state early
+    if ($cmd eq 'error') {
+
+       $haenv->log('err', "service $sid is in an error state and needs manual " .
+                   "intervention. Look up 'ERROR RECOVERY' in the documentation.");
+
+       return SUCCESS; # error always succeeds
+    }
+
+    if ($service_config->{node} ne $nodename) {
+       $haenv->log('err', "service '$sid' not on this node");
+       return EWRONG_NODE;
+    }
+
+    my $id = $service_name;
+
+    my $running = $plugin->check_running($haenv, $id);
+
+    if ($cmd eq 'started') {
+
+       return SUCCESS if $running;
+
+       $haenv->log("info", "starting service $sid");
+
+       $plugin->start($haenv, $id);
 
-    $self->update_lrm_status();
+       $running = $plugin->check_running($haenv, $id);
+
+       if ($running) {
+           $haenv->log("info", "service status $sid started");
+           return SUCCESS;
+       } else {
+           $haenv->log("warning", "unable to start service $sid");
+           return ERROR;
+       }
+
+    } elsif ($cmd eq 'request_stop' || $cmd eq 'stopped') {
+
+       return SUCCESS if !$running;
+
+       $haenv->log("info", "stopping service $sid");
+
+       $plugin->shutdown($haenv, $id);
+
+       $running = $plugin->check_running($haenv, $id);
+
+       if (!$running) {
+           $haenv->log("info", "service status $sid stopped");
+           return SUCCESS;
+       } else {
+           $haenv->log("info", "unable to stop stop service $sid (still running)");
+           return ERROR;
+       }
+
+    } elsif ($cmd eq 'migrate' || $cmd eq 'relocate') {
+
+       my $target = $params[0];
+       if (!defined($target)) {
+           die "$cmd '$sid' failed - missing target\n" if !defined($target);
+           return EINVALID_PARAMETER;
+       }
+
+       if ($service_config->{node} eq $target) {
+           # already there
+           return SUCCESS;
+       }
+
+       my $online = ($cmd eq 'migrate') ? 1 : 0;
+
+       my $res = $plugin->migrate($haenv, $id, $target, $online);
+
+       # something went wrong if service is still on this node
+       if (!$res) {
+           $haenv->log("err", "service $sid not moved (migration error)");
+           return ERROR;
+       }
+
+       return SUCCESS;
+
+    }
+
+    $haenv->log("err", "implement me (cmd '$cmd')");
+    return EUNKNOWN_COMMAND;
 }
 
+
 1;