如何管理自己的SIGINT和SIGTERM信号?

时间:2020-03-23 13:10:45

标签: perl signals mojolicious mojolicious-lite

我正在使用一个简单的基于Mojolicious::Lite的服务器,该服务器包含一个websocket端点。

我想处理一些终止信号来优雅地终止websocket连接,并避免客户端(Java应用程序)中的异常。

我尝试定义信号处理程序,就像我以前使用HTTP::Daemon定义以前的服务器一样。 问题在于它们似乎被忽略了。也许是在Mojolicious层中重新定义的,但我还没有找到任何参考。

我希望看到我的终止消息,但是不会发生

[Mon Mar 23 14:01:28 2020] [info] Listening at "http://*:3000"
Server available at http://127.0.0.1:3000
^C  # <-- i want to see my signal received message here if type Ctrl-c

当服务器在终端中处于前台时,我将通过输入SIGINT直接发送Ctrl-C,并且我可以使用以下命令优雅地终止服务器(例如,以cron或其他无显示方式启动服务器) kill <pid>

在以前的某些服务器中,我尝试通过处理以下内容来使其表现出美感:

  • HUP被劫持的信号如今用于重新加载配置
  • SIGINT Ctrl-C
  • SIGQUIT Ctrl-\
  • SIGABRT,例如库异常终止
  • SIGTERM外部终止请求-“友好” kill(反对残酷的kill -9
  • TSTP用Ctrl-Z暂停
  • 使用CONTfg从Ctrl-Z恢复时
  • bg

所有这些处理程序均允许使用清理资源正常退出,以确保数据一致性或在外部更改后重新加载配置或数据模型,具体取决于程序和需求。

我找到了Mojo::IOLoop::Signal包,即“非阻塞信号处理程序”,但这似乎是另一回事。不对吗?

这是我的简化代码(以简单的perl ws_store_test.pl daemon运行):

文件ws_store_test.pl

# Automatically enables "strict", "warnings", "utf8" and Perl 5.10 features
use Mojolicious::Lite;

my $store = {};
my $ws_clients = {};

sub terminate_clients {
    for my $peer (keys %$ws_clients){
        $ws_clients->{$peer}->finish;
    }
}

$SIG{INT} = sub {
    say "SIGINT";  # to be sure to display something
    app->log->info("SIGINT / CTRL-C received. Leaving...");
    terminate_clients;
};
$SIG{TERM} = sub {
    say "SIGTERM"; # to be sure to display something
    app->log->info("SIGTERM - External termination request. Leaving...");
    terminate_clients;
};

# this simulates a change on datamodel and notifies the clients
sub update_store {
    my $t = localtime time;
    $store->{last_time} = $t;
    for my $peer (keys %$ws_clients){
        app->log->debug(sprintf 'notify %s', $peer);
        $ws_clients->{$peer}->send({ json => $store
                                       });
    }
}

# Route with placeholder - to test datamodel contents
get '/:foo' => sub {
  my $c   = shift;
  my $foo = $c->param('foo');
  $store->{$foo}++;
  $c->render(text => "Hello from $foo." . (scalar keys %$store ? " already received " . join ', ', sort keys %$store : "") );
};

# websocket service with optional parameter
websocket '/ws/tickets/*id' => { id => undef } => sub {
    my $ws = shift;
    my $id = $ws->param('id');

    my $peer = sprintf '%s', $ws->tx;
    app->log->debug(sprintf 'Client connected: %s, id=%s', $peer, $id);
    $ws_clients->{$peer} = $ws->tx;
    $store->{$id} = {};

    $ws->on( message => sub {
        my ($c, $message) = @_;
        app->log->debug(sprintf 'WS received %s from a client', $message);
             });

    $ws->on( finish => sub {
        my ($c, $code, $reason) = @_;
        app->log->debug(sprintf 'WS client disconnected: %s - %d - %s', $peer, $code, $reason);
        delete $ws_clients->{$peer};
             });
};

plugin Cron => ( '* * * * *' => \&update_store );

# Start the Mojolicious command system
app->start;

1 个答案:

答案 0 :(得分:3)

SIGINT和SIGTERM处理程序在服务器启动时重新定义。在morbo中是:

local $SIG{INT} = local $SIG{TERM} = sub {
  $self->{finished} = 1;
  kill 'TERM', $self->{worker} if $self->{worker};
};

Mojo::Server::Daemon中,这是:

local $SIG{INT} = local $SIG{TERM} = sub { $loop->stop };

如果您在顶级重新定义SIGINT / SIGTERM的处理程序,则这些local将覆盖它们。相反,我建议在before_dispatch钩子中重新定义一次。例如:

sub add_sigint_handler {
    my $old_int = $SIG{INT};
    $SIG{INT} = sub {
        say "SIGINT";  # to be sure to display something
        app->log->info("SIGINT / CTRL-C received. Leaving...");
        terminate_clients;
        $old_int->(); # Calling the old handler to cleanly exit the server
    }
}

app->hook(before_dispatch => sub {
    state $unused = add_sigint_handler();
});

在这里,我使用state来确保仅对add_sigint_handler进行一次评估(因为如果对其进行了多次评估,则$old_int在第一个评估之后将没有正确的值时间)。另一种书写方式可能是:

my $flag = 0;
app->hook(before_dispatch => sub {
    if ($flag == 0) {
        add_sigint_handler();
        $flag = 1;
    }
});

或者,

app->hook(before_dispatch => sub {
    state $flag = 0;
    if ($flag == 0) {
        add_sigint_handler();
        $flag = 1;
    }
});