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