]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Daemon.pm
update copyrights for 2018
[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 Danga::Socket;
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 Danga::Socket::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         Danga::Socket->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 host_with_port ($) {
238         my ($addr) = @_;
239         my ($port, $host);
240
241         # this eval will die on Unix sockets:
242         eval {
243                 if (length($addr) >= 28) {
244                         require Socket6;
245                         ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
246                         $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
247                         $host = "[$host]";
248                 } else {
249                         ($port, $host) = Socket::sockaddr_in($addr);
250                         $host = Socket::inet_ntoa($host);
251                 }
252         };
253         $@ ? ('127.0.0.1', 0) : ($host, $port);
254 }
255
256 sub inherit () {
257         return () if ($ENV{LISTEN_PID} || 0) != $$;
258         my $fds = $ENV{LISTEN_FDS} or return ();
259         my $end = $fds + 2; # LISTEN_FDS_START - 1
260         my @rv = ();
261         foreach my $fd (3..$end) {
262                 my $s = IO::Handle->new_from_fd($fd, 'r');
263                 if (my $k = sockname($s)) {
264                         $listener_names{$k} = $s;
265                         push @rv, $s;
266                 } else {
267                         warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
268                 }
269         }
270         @rv
271 }
272
273 sub upgrade () {
274         if ($reexec_pid) {
275                 warn "upgrade in-progress: $reexec_pid\n";
276                 return;
277         }
278         if (defined $pid_file) {
279                 if ($pid_file =~ /\.oldbin\z/) {
280                         warn "BUG: .oldbin suffix exists: $pid_file\n";
281                         return;
282                 }
283                 unlink_pid_file_safe_ish($$, $pid_file);
284                 $pid_file .= '.oldbin';
285                 write_pid($pid_file);
286         }
287         my $pid = fork;
288         unless (defined $pid) {
289                 warn "fork failed: $!\n";
290                 return;
291         }
292         if ($pid == 0) {
293                 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
294                 $ENV{LISTEN_FDS} = scalar @listeners;
295                 $ENV{LISTEN_PID} = $$;
296                 foreach my $s (@listeners) {
297                         my $fl = fcntl($s, F_GETFD, 0);
298                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
299                 }
300                 exec @CMD;
301                 die "Failed to exec: $!\n";
302         }
303         $reexec_pid = $pid;
304 }
305
306 sub kill_workers ($) {
307         my ($s) = @_;
308
309         while (my ($pid, $id) = each %pids) {
310                 kill $s, $pid;
311         }
312 }
313
314 sub upgrade_aborted ($) {
315         my ($p) = @_;
316         warn "reexec PID($p) died with: $?\n";
317         $reexec_pid = undef;
318         return unless $pid_file;
319
320         my $file = $pid_file;
321         $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
322         unlink_pid_file_safe_ish($$, $pid_file);
323         $pid_file = $file;
324         eval { write_pid($pid_file) };
325         warn $@, "\n" if $@;
326 }
327
328 sub reap_children () {
329         while (1) {
330                 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
331                 if (defined $reexec_pid && $p == $reexec_pid) {
332                         upgrade_aborted($p);
333                 } elsif (defined(my $id = delete $pids{$p})) {
334                         warn "worker[$id] PID($p) died with: $?\n";
335                 } elsif ($p > 0) {
336                         warn "unknown PID($p) reaped: $?\n";
337                 } else {
338                         return;
339                 }
340         }
341 }
342
343 sub unlink_pid_file_safe_ish ($$) {
344         my ($unlink_pid, $file) = @_;
345         return unless defined $unlink_pid && $unlink_pid == $$;
346
347         open my $fh, '<', $file or return;
348         local $/ = "\n";
349         defined(my $read_pid = <$fh>) or return;
350         chomp $read_pid;
351         if ($read_pid == $unlink_pid) {
352                 Net::Server::Daemonize::unlink_pid_file($file);
353         }
354 }
355
356 sub master_loop {
357         pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
358         pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
359         IO::Handle::blocking($w, 0);
360         my $set_workers = $worker_processes;
361         my @caught;
362         my $master_pid = $$;
363         foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
364                 $SIG{$s} = sub {
365                         return if $$ != $master_pid;
366                         push @caught, $s;
367                         syswrite($w, '.');
368                 };
369         }
370         reopen_logs();
371         # main loop
372         my $quit = 0;
373         while (1) {
374                 while (my $s = shift @caught) {
375                         if ($s eq 'USR1') {
376                                 reopen_logs();
377                                 kill_workers($s);
378                         } elsif ($s eq 'USR2') {
379                                 upgrade();
380                         } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
381                                 exit if $quit++;
382                                 kill_workers($s);
383                         } elsif ($s eq 'WINCH') {
384                                 if (-t STDIN || -t STDOUT || -t STDERR) {
385                                         warn
386 "ignoring SIGWINCH since we are not daemonized\n";
387                                         $SIG{WINCH} = 'IGNORE';
388                                 } else {
389                                         $worker_processes = 0;
390                                 }
391                         } elsif ($s eq 'HUP') {
392                                 $worker_processes = $set_workers;
393                                 kill_workers($s);
394                         } elsif ($s eq 'TTIN') {
395                                 if ($set_workers > $worker_processes) {
396                                         ++$worker_processes;
397                                 } else {
398                                         $worker_processes = ++$set_workers;
399                                 }
400                         } elsif ($s eq 'TTOU') {
401                                 if ($set_workers > 0) {
402                                         $worker_processes = --$set_workers;
403                                 }
404                         } elsif ($s eq 'CHLD') {
405                                 reap_children();
406                         }
407                 }
408
409                 my $n = scalar keys %pids;
410                 if ($quit) {
411                         exit if $n == 0;
412                         $set_workers = $worker_processes = $n = 0;
413                 }
414
415                 if ($n > $worker_processes) {
416                         while (my ($k, $v) = each %pids) {
417                                 kill('TERM', $k) if $v >= $worker_processes;
418                         }
419                         $n = $worker_processes;
420                 }
421                 foreach my $i ($n..($worker_processes - 1)) {
422                         my $pid = fork;
423                         if (!defined $pid) {
424                                 warn "failed to fork worker[$i]: $!\n";
425                         } elsif ($pid == 0) {
426                                 $set_user->() if $set_user;
427                                 return $p0; # run normal work code
428                         } else {
429                                 warn "PID=$pid is worker[$i]\n";
430                                 $pids{$pid} = $i;
431                         }
432                 }
433                 # just wait on signal events here:
434                 sysread($r, my $buf, 8);
435         }
436         exit # never gets here, just for documentation
437 }
438
439 sub daemon_loop ($$) {
440         my ($refresh, $post_accept) = @_;
441         my $parent_pipe;
442         if ($worker_processes > 0) {
443                 $refresh->(); # preload by default
444                 my $fh = master_loop(); # returns if in child process
445                 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
446         } else {
447                 reopen_logs();
448                 $set_user->() if $set_user;
449                 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
450                 $refresh->();
451         }
452         $uid = $gid = undef;
453         reopen_logs();
454         $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
455         $SIG{USR1} = *reopen_logs;
456         $SIG{HUP} = $refresh;
457         $SIG{CHLD} = 'DEFAULT';
458         $SIG{$_} = 'IGNORE' for qw(USR2 TTIN TTOU WINCH);
459         # this calls epoll_create:
460         @listeners = map {
461                 PublicInbox::Listener->new($_, $post_accept)
462         } @listeners;
463         Danga::Socket->EventLoop;
464         $parent_pipe = undef;
465 }
466
467
468 sub run ($$$) {
469         my ($default, $refresh, $post_accept) = @_;
470         daemon_prepare($default);
471         daemonize();
472         daemon_loop($refresh, $post_accept);
473 }
474
475 sub do_chown ($) {
476         my ($path) = @_;
477         if (defined $uid and !chown($uid, $gid, $path)) {
478                 warn "could not chown $path: $!\n";
479         }
480 }
481
482 sub write_pid ($) {
483         my ($path) = @_;
484         Net::Server::Daemonize::create_pid_file($path);
485         do_chown($path);
486 }
487
488 1;