]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Daemon.pm
daemon: disable USR2/TTIN/TTOU/WINCH in workers
[public-inbox.git] / lib / PublicInbox / Daemon.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # contains common daemon code for the nntpd and httpd servers.
4 # This may be used for read-only IMAP server if we decide to implement it.
5 package PublicInbox::Daemon;
6 use strict;
7 use warnings;
8 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
9 use IO::Handle;
10 use IO::Socket;
11 use Cwd qw/abs_path/;
12 STDOUT->autoflush(1);
13 STDERR->autoflush(1);
14 require Danga::Socket;
15 require POSIX;
16 require PublicInbox::Listener;
17 require PublicInbox::ParentPipe;
18 my @CMD;
19 my $set_user;
20 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
21 my $worker_processes = 1;
22 my @listeners;
23 my %pids;
24 my %listener_names;
25 my $reexec_pid;
26 my $cleanup;
27 my ($uid, $gid);
28 END { $cleanup->() if $cleanup };
29
30 sub daemon_prepare ($) {
31         my ($default_listen) = @_;
32         @CMD = ($0, @ARGV);
33         $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
34                 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
35         my %opts = (
36                 'l|listen=s' => \@cfg_listen,
37                 '1|stdout=s' => \$stdout,
38                 '2|stderr=s' => \$stderr,
39                 'W|worker-processes=i' => \$worker_processes,
40                 'P|pid-file=s' => \$pid_file,
41                 'u|user=s' => \$user,
42                 'g|group=s' => \$group,
43                 'D|daemonize' => \$daemonize,
44         );
45         GetOptions(%opts) or die "bad command-line args\n";
46
47         if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
48                 die "--pid-file cannot end with '.oldbin'\n";
49         }
50         @listeners = inherit();
51         # ignore daemonize when inheriting
52         $daemonize = undef if scalar @listeners;
53
54         push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
55
56         foreach my $l (@cfg_listen) {
57                 next if $listener_names{$l}; # already inherited
58                 my (%o, $sock_pkg);
59                 if (index($l, '/') == 0) {
60                         $sock_pkg = 'IO::Socket::UNIX';
61                         eval "use $sock_pkg";
62                         die $@ if $@;
63                         %o = (Type => SOCK_STREAM, Peer => $l);
64                         if (-S $l) {
65                                 my $c = $sock_pkg->new(%o);
66                                 if (!defined($c) && $!{ECONNREFUSED}) {
67                                         unlink $l or die
68 "failed to unlink stale socket=$l: $!\n";
69                                 } # else: let the bind fail
70                         }
71                         $o{Local} = delete $o{Peer};
72                 } else {
73                         # both work for IPv4, too
74                         for (qw(IO::Socket::IP IO::Socket::INET6)) {
75                                 $sock_pkg = $_;
76                                 eval "use $sock_pkg";
77                                 $@ or last;
78                         }
79                         die $@ if $@;
80                         %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
81                 }
82                 $o{Listen} = 1024;
83                 my $prev = umask 0000;
84                 my $s = eval { $sock_pkg->new(%o) };
85                 warn "error binding $l: $! ($@)\n" unless $s;
86                 umask $prev;
87
88                 if ($s) {
89                         $listener_names{sockname($s)} = $s;
90                         push @listeners, $s;
91                 }
92         }
93         die "No listeners bound\n" unless @listeners;
94 }
95
96 sub check_absolute ($$) {
97         my ($var, $val) = @_;
98         if (defined $val && index($val, '/') != 0) {
99                 die
100 "--$var must be an absolute path when using --daemonize: $val\n";
101         }
102 }
103
104 sub daemonize () {
105         foreach my $i (0..$#ARGV) {
106                 my $arg = $ARGV[$i];
107                 next unless -e $arg;
108                 $ARGV[$i] = abs_path($arg);
109         }
110         check_absolute('stdout', $stdout);
111         check_absolute('stderr', $stderr);
112         check_absolute('pid-file', $pid_file);
113
114         chdir '/' or die "chdir failed: $!";
115         open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
116
117         return unless (defined $pid_file || defined $group || defined $user
118                         || $daemonize);
119
120         eval { require Net::Server::Daemonize };
121         if ($@) {
122                 die
123 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
124         }
125
126         Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
127         $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
128         if (defined $group) {
129                 $gid = Net::Server::Daemonize::get_gid($group);
130                 $gid = (split /\s+/, $gid)[0];
131         } elsif (defined $uid) {
132                 $gid = (getpwuid($uid))[3];
133         }
134
135         # We change users in the worker to ensure upgradability,
136         # The upgrade will create the ".oldbin" pid file in the
137         # same directory as the given pid file.
138         $uid and $set_user = sub {
139                 $set_user = undef;
140                 Net::Server::Daemonize::set_user($uid, $gid);
141         };
142
143         if ($daemonize) {
144                 my $pid = fork;
145                 die "could not fork: $!\n" unless defined $pid;
146                 exit if $pid;
147
148                 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
149                 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
150                 POSIX::setsid();
151                 $pid = fork;
152                 die "could not fork: $!\n" unless defined $pid;
153                 exit if $pid;
154         }
155         if (defined $pid_file) {
156                 write_pid($pid_file);
157                 my $unlink_pid = $$;
158                 $cleanup = sub {
159                         $cleanup = undef; # avoid cyclic reference
160                         unlink_pid_file_safe_ish($unlink_pid, $pid_file);
161                 };
162         }
163 }
164
165
166 sub worker_quit {
167         my ($reason) = @_;
168         # killing again terminates immediately:
169         exit unless @listeners;
170
171         $_->close foreach @listeners; # call Danga::Socket::close
172         @listeners = ();
173         $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
174
175         my $proc_name;
176         my $warn = 0;
177         # drop idle connections and try to quit gracefully
178         Danga::Socket->SetPostLoopCallback(sub {
179                 my ($dmap, undef) = @_;
180                 my $n = 0;
181
182                 foreach my $s (values %$dmap) {
183                         $s->can('busy') or next;
184                         if ($s->busy) {
185                                 ++$n;
186                         } else {
187                                 # close as much as possible, early as possible
188                                 $s->close;
189                         }
190                 }
191                 if ($n) {
192                         if (($warn + 5) < time) {
193                                 warn "$$ quitting, $n client(s) left\n";
194                                 $warn = time;
195                         }
196                         unless (defined $proc_name) {
197                                 $proc_name = (split(/\s+/, $0))[0];
198                                 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
199                         }
200                         $0 = "$proc_name quitting, $n client(s) left";
201                 }
202                 $n; # true: loop continues, false: loop breaks
203         });
204 }
205
206 sub reopen_logs {
207         if ($stdout) {
208                 open STDOUT, '>>', $stdout or
209                         warn "failed to redirect stdout to $stdout: $!\n";
210                 STDOUT->autoflush(1);
211                 do_chown($stdout);
212         }
213         if ($stderr) {
214                 open STDERR, '>>', $stderr or
215                         warn "failed to redirect stderr to $stderr: $!\n";
216                 STDERR->autoflush(1);
217                 do_chown($stderr);
218         }
219 }
220
221 sub sockname ($) {
222         my ($s) = @_;
223         my $addr = getsockname($s) or return;
224         my ($host, $port) = host_with_port($addr);
225         if ($port == 0 && $host eq '127.0.0.1') {
226                 my ($path) = Socket::sockaddr_un($addr);
227                 return $path;
228         }
229         "$host:$port";
230 }
231
232 sub host_with_port ($) {
233         my ($addr) = @_;
234         my ($port, $host);
235
236         # this eval will die on Unix sockets:
237         eval {
238                 if (length($addr) >= 28) {
239                         require Socket6;
240                         ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
241                         $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
242                         $host = "[$host]";
243                 } else {
244                         ($port, $host) = Socket::sockaddr_in($addr);
245                         $host = Socket::inet_ntoa($host);
246                 }
247         };
248         $@ ? ('127.0.0.1', 0) : ($host, $port);
249 }
250
251 sub inherit () {
252         return () if ($ENV{LISTEN_PID} || 0) != $$;
253         my $fds = $ENV{LISTEN_FDS} or return ();
254         my $end = $fds + 2; # LISTEN_FDS_START - 1
255         my @rv = ();
256         foreach my $fd (3..$end) {
257                 my $s = IO::Handle->new_from_fd($fd, 'r');
258                 if (my $k = sockname($s)) {
259                         $listener_names{$k} = $s;
260                         push @rv, $s;
261                 } else {
262                         warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
263                 }
264         }
265         @rv
266 }
267
268 sub upgrade () {
269         if ($reexec_pid) {
270                 warn "upgrade in-progress: $reexec_pid\n";
271                 return;
272         }
273         if (defined $pid_file) {
274                 if ($pid_file =~ /\.oldbin\z/) {
275                         warn "BUG: .oldbin suffix exists: $pid_file\n";
276                         return;
277                 }
278                 unlink_pid_file_safe_ish($$, $pid_file);
279                 $pid_file .= '.oldbin';
280                 write_pid($pid_file);
281         }
282         my $pid = fork;
283         unless (defined $pid) {
284                 warn "fork failed: $!\n";
285                 return;
286         }
287         if ($pid == 0) {
288                 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
289                 $ENV{LISTEN_FDS} = scalar @listeners;
290                 $ENV{LISTEN_PID} = $$;
291                 foreach my $s (@listeners) {
292                         my $fl = fcntl($s, F_GETFD, 0);
293                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
294                 }
295                 exec @CMD;
296                 die "Failed to exec: $!\n";
297         }
298         $reexec_pid = $pid;
299 }
300
301 sub kill_workers ($) {
302         my ($s) = @_;
303
304         while (my ($pid, $id) = each %pids) {
305                 kill $s, $pid;
306         }
307 }
308
309 sub upgrade_aborted ($) {
310         my ($p) = @_;
311         warn "reexec PID($p) died with: $?\n";
312         $reexec_pid = undef;
313         return unless $pid_file;
314
315         my $file = $pid_file;
316         $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
317         unlink_pid_file_safe_ish($$, $pid_file);
318         $pid_file = $file;
319         eval { write_pid($pid_file) };
320         warn $@, "\n" if $@;
321 }
322
323 sub reap_children () {
324         while (1) {
325                 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
326                 if (defined $reexec_pid && $p == $reexec_pid) {
327                         upgrade_aborted($p);
328                 } elsif (defined(my $id = delete $pids{$p})) {
329                         warn "worker[$id] PID($p) died with: $?\n";
330                 } elsif ($p > 0) {
331                         warn "unknown PID($p) reaped: $?\n";
332                 } else {
333                         return;
334                 }
335         }
336 }
337
338 sub unlink_pid_file_safe_ish ($$) {
339         my ($unlink_pid, $file) = @_;
340         return unless defined $unlink_pid && $unlink_pid == $$;
341
342         open my $fh, '<', $file or return;
343         local $/ = "\n";
344         defined(my $read_pid = <$fh>) or return;
345         chomp $read_pid;
346         if ($read_pid == $unlink_pid) {
347                 Net::Server::Daemonize::unlink_pid_file($file);
348         }
349 }
350
351 sub master_loop {
352         pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
353         pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
354         IO::Handle::blocking($w, 0);
355         my $set_workers = $worker_processes;
356         my @caught;
357         my $master_pid = $$;
358         foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
359                 $SIG{$s} = sub {
360                         return if $$ != $master_pid;
361                         push @caught, $s;
362                         syswrite($w, '.');
363                 };
364         }
365         reopen_logs();
366         # main loop
367         my $quit = 0;
368         while (1) {
369                 while (my $s = shift @caught) {
370                         if ($s eq 'USR1') {
371                                 reopen_logs();
372                                 kill_workers($s);
373                         } elsif ($s eq 'USR2') {
374                                 upgrade();
375                         } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
376                                 exit if $quit++;
377                                 kill_workers($s);
378                         } elsif ($s eq 'WINCH') {
379                                 if ($daemonize) {
380                                         $worker_processes = 0;
381                                 } else {
382                                         warn
383 "ignoring SIGWINCH since we are not daemonized\n";
384                                         $SIG{WINCH} = 'IGNORE';
385                                 }
386                         } elsif ($s eq 'HUP') {
387                                 $worker_processes = $set_workers;
388                                 kill_workers($s);
389                         } elsif ($s eq 'TTIN') {
390                                 if ($set_workers > $worker_processes) {
391                                         ++$worker_processes;
392                                 } else {
393                                         $worker_processes = ++$set_workers;
394                                 }
395                         } elsif ($s eq 'TTOU') {
396                                 if ($set_workers > 0) {
397                                         $worker_processes = --$set_workers;
398                                 }
399                         } elsif ($s eq 'CHLD') {
400                                 reap_children();
401                         }
402                 }
403
404                 my $n = scalar keys %pids;
405                 if ($quit) {
406                         exit if $n == 0;
407                         $set_workers = $worker_processes = $n = 0;
408                 }
409
410                 if ($n > $worker_processes) {
411                         while (my ($k, $v) = each %pids) {
412                                 kill('TERM', $k) if $v >= $worker_processes;
413                         }
414                         $n = $worker_processes;
415                 }
416                 foreach my $i ($n..($worker_processes - 1)) {
417                         my $pid = fork;
418                         if (!defined $pid) {
419                                 warn "failed to fork worker[$i]: $!\n";
420                         } elsif ($pid == 0) {
421                                 $set_user->() if $set_user;
422                                 return $p0; # run normal work code
423                         } else {
424                                 warn "PID=$pid is worker[$i]\n";
425                                 $pids{$pid} = $i;
426                         }
427                 }
428                 # just wait on signal events here:
429                 sysread($r, my $buf, 8);
430         }
431         exit # never gets here, just for documentation
432 }
433
434 sub daemon_loop ($$) {
435         my ($refresh, $post_accept) = @_;
436         my $parent_pipe;
437         if ($worker_processes > 0) {
438                 $refresh->(); # preload by default
439                 my $fh = master_loop(); # returns if in child process
440                 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
441         } else {
442                 reopen_logs();
443                 $set_user->() if $set_user;
444                 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
445                 $refresh->();
446         }
447         $uid = $gid = undef;
448         reopen_logs();
449         $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
450         $SIG{USR1} = *reopen_logs;
451         $SIG{HUP} = $refresh;
452         $SIG{CHLD} = 'DEFAULT';
453         $SIG{$_} = 'IGNORE' for qw(USR2 TTIN TTOU WINCH);
454         # this calls epoll_create:
455         @listeners = map {
456                 PublicInbox::Listener->new($_, $post_accept)
457         } @listeners;
458         Danga::Socket->EventLoop;
459         $parent_pipe = undef;
460 }
461
462
463 sub run ($$$) {
464         my ($default, $refresh, $post_accept) = @_;
465         daemon_prepare($default);
466         daemonize();
467         daemon_loop($refresh, $post_accept);
468 }
469
470 sub do_chown ($) {
471         my ($path) = @_;
472         if (defined $uid and !chown($uid, $gid, $path)) {
473                 warn "could not chown $path: $!\n";
474         }
475 }
476
477 sub write_pid ($) {
478         my ($path) = @_;
479         Net::Server::Daemonize::create_pid_file($path);
480         do_chown($path);
481 }
482
483 1;