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