3 Commits

Author SHA1 Message Date
eleksir
ca0a891522 Translate comments, fix coding style 2022-01-01 17:34:45 +03:00
eleksir
0f58c30603 Implement async signal trap via Mojo::IOLoop::Signal for more robust app stop and restart 2022-01-01 17:34:07 +03:00
eleksir
637e5f8261 Pin version numbers in cpanfile 2022-01-01 17:32:57 +03:00
3 changed files with 49 additions and 26 deletions

View File

@@ -11,7 +11,7 @@ use version; our $VERSION = qw (1.0);
my $workdir; my $workdir;
# before we run, change working dir # До фактического запуска логики программы, сменим рабочий каталог, чтобы подцепить либы
BEGIN { BEGIN {
use Cwd qw (chdir abs_path); use Cwd qw (chdir abs_path);
my @CWD = split /\//xms, abs_path ($PROGRAM_NAME); my @CWD = split /\//xms, abs_path ($PROGRAM_NAME);
@@ -53,7 +53,8 @@ if (defined $C->{'log'}) {
$logfile = $C->{'debug_log'}; $logfile = $C->{'debug_log'};
} }
# if we run under root, create pid dir and set correct owner for it, same for debug log if it is defined # Если мы запускаемся под рутом, то попробуем создать необходимые служебные каталоги и простать на них корректных
# владельца и права
if ($UID == 0) { if ($UID == 0) {
my $user = $C->{user}; my $user = $C->{user};
@@ -85,7 +86,7 @@ if ($UID == 0) {
} }
} }
# drop privs # Переключаемся на "рабочего" пользователя и сбрасываем привилегии.
setgid ($gid) or die "Unable to switch to group of $user($OS_ERROR)\n"; setgid ($gid) or die "Unable to switch to group of $user($OS_ERROR)\n";
setuid ($uid) or die "Unable to switch to account $user($OS_ERROR)\n"; setuid ($uid) or die "Unable to switch to account $user($OS_ERROR)\n";
} else { } else {
@@ -98,14 +99,14 @@ if (defined $logfile) {
$log = Mojo::Log->new (path => '/dev/null', level => 'fatal'); $log = Mojo::Log->new (path => '/dev/null', level => 'fatal');
} }
# по-умолчанию, демонизируемся, если явно не указано, что этого делать не надо # По-умолчанию, демонизируемся, если явно не указано, что этого делать не надо
if (defined ($C->{daemonize}) && $C->{daemonize}) { if (defined ($C->{daemonize}) && $C->{daemonize}) {
daemonize (); daemonize ();
} elsif ( ! defined ($C->{daemonize})) { } elsif ( ! defined ($C->{daemonize})) {
daemonize (); daemonize ();
} }
# write pidfile # Запишем pid-файл
my $apath = abs_path $PROGRAM_NAME; my $apath = abs_path $PROGRAM_NAME;
unless (defined $apath) { unless (defined $apath) {
@@ -128,13 +129,15 @@ print {$MYPID} $PID or do {
close $MYPID; ## no critic (InputOutput::RequireCheckedSyscalls close $MYPID; ## no critic (InputOutput::RequireCheckedSyscalls
# При наличии хака в лице Mojo::IOLoop::Signal в Misc.pm, установка хэндлера в этом месте - это фактически
# подстраховка на случай ядерной войны.
local $SIG{INT} = \&__signal_handler; local $SIG{INT} = \&__signal_handler;
local $SIG{TERM} = \&__signal_handler; local $SIG{TERM} = \&__signal_handler;
# set correct proctitle # Поставим правильное имя процесса в proctitle
$PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars) $PROGRAM_NAME = abs_path $PROGRAM_NAME; ## no critic (Variables::RequireLocalizedPunctuationVars)
# run main app, at last # И запустим уже наш сервис
RunCraniac (); RunCraniac ();
if (-f $pidfile) { if (-f $pidfile) {
@@ -147,8 +150,6 @@ sub daemonize {
__fork (); __fork ();
POSIX::setsid (); POSIX::setsid ();
open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen) open STDIN, '<', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
#open STDOUT, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
#open STDERR, '>', '/dev/null'; ## no critic (InputOutput::RequireCheckedSyscalls, InputOutput::RequireCheckedOpen)
__fork (); __fork ();
umask 0; umask 0;
return; return;

View File

@@ -1,17 +1,21 @@
requires 'Cwd'; requires 'Cwd', '0';
requires 'Cwd::utf8'; requires 'Cwd::utf8', '==0.011';
requires 'Digest::SHA'; requires 'Digest::SHA', '==6.02';
requires 'Encode'; requires 'Encode', '==3.16';
requires 'English'; requires 'English', '==1.11';
requires 'File::Basename'; requires 'File::Basename', '0';
requires 'File::Path'; requires 'File::Path', '==2.18';
requires 'Hailo'; requires 'Hailo', '==0.75';
requires 'JSON::XS'; requires 'JSON::XS', '==4.03';
requires 'local::lib'; requires 'local::lib', '==2.000024';
requires 'Math::Random::Secure'; requires 'Math::Random::Secure', '==0.080001';
requires 'Mojo::IOLoop'; requires 'Mojolicious', '==9.22';
requires 'Mojo::Log'; requires 'Mojo::IOLoop', '0';
requires 'Mojo::Redis'; requires 'Mojo::IOLoop::Signal', '==0.003';
requires 'POSIX'; requires 'Mojo::Log', '0';
requires 'Protocol::Redis::XS'; requires 'Mojo::Redis', '==3.26';
requires 'Text::Fuzzy'; requires 'POSIX', '0';
requires 'Protocol::Redis::XS', '0';
requires 'Text::Fuzzy', '==0.29';
requires 'utf8', '0';
requires 'version', '0';

View File

@@ -20,6 +20,7 @@ use English qw ( -no_match_vars );
use Digest::SHA qw (sha1_base64); use Digest::SHA qw (sha1_base64);
use Hailo; use Hailo;
use Mojo::IOLoop; use Mojo::IOLoop;
use Mojo::IOLoop::Signal;
use Mojo::Log; use Mojo::Log;
# Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis # Чтобы "уж точно" использовать hiredis-биндинги, загрузим этот модуль перед Mojo::Redis
use Protocol::Redis::XS; use Protocol::Redis::XS;
@@ -351,6 +352,18 @@ my $parse_message = sub {
return; return;
}; };
my $__signal_handler = sub {
my ($self, $name) = @_;
$log->info ("[INFO] Caught a signal $name");
if (defined $main::pidfile && -f $main::pidfile) {
unlink $main::pidfile;
}
exit 0;
};
# Main loop, он же event loop # Main loop, он же event loop
sub RunCraniac () { sub RunCraniac () {
$log->info ("[INFO] Connecting to $c->{server}, $c->{port}"); $log->info ("[INFO] Connecting to $c->{server}, $c->{port}");
@@ -392,6 +405,11 @@ sub RunCraniac () {
); );
} }
Mojo::IOLoop::Signal->on (
TERM => $__signal_handler,
INT => $__signal_handler
);
do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running; do { Mojo::IOLoop->start } until Mojo::IOLoop->is_running;
return; return;
} }