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;
8 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
14 use PublicInbox::DS qw(now);
15 require PublicInbox::EvCleanup;
17 require PublicInbox::Listener;
18 require PublicInbox::ParentPipe;
21 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
22 my $worker_processes = 1;
29 END { $cleanup->() if $cleanup };
31 sub daemon_prepare ($) {
32 my ($default_listen) = @_;
34 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
35 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
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,
43 'g|group=s' => \$group,
44 'D|daemonize' => \$daemonize,
46 GetOptions(%opts) or die "bad command-line args\n";
48 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
49 die "--pid-file cannot end with '.oldbin'\n";
51 @listeners = inherit();
52 # ignore daemonize when inheriting
53 $daemonize = undef if scalar @listeners;
55 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
57 foreach my $l (@cfg_listen) {
58 next if $listener_names{$l}; # already inherited
60 if (index($l, '/') == 0) {
61 $sock_pkg = 'IO::Socket::UNIX';
64 %o = (Type => SOCK_STREAM, Peer => $l);
66 my $c = $sock_pkg->new(%o);
67 if (!defined($c) && $!{ECONNREFUSED}) {
69 "failed to unlink stale socket=$l: $!\n";
70 } # else: let the bind fail
72 $o{Local} = delete $o{Peer};
74 # both work for IPv4, too
75 for (qw(IO::Socket::IP IO::Socket::INET6)) {
81 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
84 my $prev = umask 0000;
85 my $s = eval { $sock_pkg->new(%o) };
86 warn "error binding $l: $! ($@)\n" unless $s;
90 $listener_names{sockname($s)} = $s;
94 die "No listeners bound\n" unless @listeners;
97 sub check_absolute ($$) {
99 if (defined $val && index($val, '/') != 0) {
101 "--$var must be an absolute path when using --daemonize: $val\n";
107 foreach my $i (0..$#ARGV) {
110 $ARGV[$i] = abs_path($arg);
112 check_absolute('stdout', $stdout);
113 check_absolute('stderr', $stderr);
114 check_absolute('pid-file', $pid_file);
116 chdir '/' or die "chdir failed: $!";
119 return unless (defined $pid_file || defined $group || defined $user
122 eval { require Net::Server::Daemonize };
125 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
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];
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 {
142 Net::Server::Daemonize::set_user($uid, $gid);
147 die "could not fork: $!\n" unless defined $pid;
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";
156 die "could not fork: $!\n" unless defined $pid;
159 if (defined $pid_file) {
160 write_pid($pid_file);
163 $cleanup = undef; # avoid cyclic reference
164 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
172 # killing again terminates immediately:
173 exit unless @listeners;
175 $_->close foreach @listeners; # call PublicInbox::DS::close
177 $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
181 # drop idle connections and try to quit gracefully
182 PublicInbox::DS->SetPostLoopCallback(sub {
183 my ($dmap, undef) = @_;
187 foreach my $s (values %$dmap) {
188 $s->can('busy') or next;
189 if ($s->busy($now)) {
192 # close as much as possible, early as possible
197 if (($warn + 5) < now()) {
198 warn "$$ quitting, $n client(s) left\n";
201 unless (defined $proc_name) {
202 $proc_name = (split(/\s+/, $0))[0];
203 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
205 $0 = "$proc_name quitting, $n client(s) left";
207 $n; # true: loop continues, false: loop breaks
213 open STDOUT, '>>', $stdout or
214 warn "failed to redirect stdout to $stdout: $!\n";
215 STDOUT->autoflush(1);
219 open STDERR, '>>', $stderr or
220 warn "failed to redirect stderr to $stderr: $!\n";
221 STDERR->autoflush(1);
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);
237 sub unpack_ipv6 ($) {
241 # Socket.pm in Perl 5.14+ supports IPv6:
243 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
244 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
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):
253 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
254 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
259 sub host_with_port ($) {
263 # this eval will die on Unix sockets:
265 if (length($addr) >= 28) {
266 ($host, $port) = unpack_ipv6($addr);
269 ($port, $host) = Socket::sockaddr_in($addr);
270 $host = Socket::inet_ntoa($host);
273 $@ ? ('127.0.0.1', 0) : ($host, $port);
277 return () if ($ENV{LISTEN_PID} || 0) != $$;
278 my $fds = $ENV{LISTEN_FDS} or return ();
279 my $end = $fds + 2; # LISTEN_FDS_START - 1
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;
287 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
295 warn "upgrade in-progress: $reexec_pid\n";
298 if (defined $pid_file) {
299 if ($pid_file =~ /\.oldbin\z/) {
300 warn "BUG: .oldbin suffix exists: $pid_file\n";
303 unlink_pid_file_safe_ish($$, $pid_file);
304 $pid_file .= '.oldbin';
305 write_pid($pid_file);
308 unless (defined $pid) {
309 warn "fork failed: $!\n";
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);
321 die "Failed to exec: $!\n";
326 sub kill_workers ($) {
329 while (my ($pid, $id) = each %pids) {
334 sub upgrade_aborted ($) {
336 warn "reexec PID($p) died with: $?\n";
338 return unless $pid_file;
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);
344 eval { write_pid($pid_file) };
348 sub reap_children () {
350 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
351 if (defined $reexec_pid && $p == $reexec_pid) {
353 } elsif (defined(my $id = delete $pids{$p})) {
354 warn "worker[$id] PID($p) died with: $?\n";
356 warn "unknown PID($p) reaped: $?\n";
363 sub unlink_pid_file_safe_ish ($$) {
364 my ($unlink_pid, $file) = @_;
365 return unless defined $unlink_pid && $unlink_pid == $$;
367 open my $fh, '<', $file or return;
369 defined(my $read_pid = <$fh>) or return;
371 if ($read_pid == $unlink_pid) {
372 Net::Server::Daemonize::unlink_pid_file($file);
377 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
378 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
380 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ = 1031
381 fcntl($_, 1031, 4096) for ($w, $p1);
384 IO::Handle::blocking($w, 0);
385 my $set_workers = $worker_processes;
388 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
390 return if $$ != $master_pid;
399 while (my $s = shift @caught) {
403 } elsif ($s eq 'USR2') {
405 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
408 } elsif ($s eq 'WINCH') {
409 if (-t STDIN || -t STDOUT || -t STDERR) {
411 "ignoring SIGWINCH since we are not daemonized\n";
412 $SIG{WINCH} = 'IGNORE';
414 $worker_processes = 0;
416 } elsif ($s eq 'HUP') {
417 $worker_processes = $set_workers;
419 } elsif ($s eq 'TTIN') {
420 if ($set_workers > $worker_processes) {
423 $worker_processes = ++$set_workers;
425 } elsif ($s eq 'TTOU') {
426 if ($set_workers > 0) {
427 $worker_processes = --$set_workers;
429 } elsif ($s eq 'CHLD') {
434 my $n = scalar keys %pids;
437 $set_workers = $worker_processes = $n = 0;
440 if ($n > $worker_processes) {
441 while (my ($k, $v) = each %pids) {
442 kill('TERM', $k) if $v >= $worker_processes;
444 $n = $worker_processes;
446 foreach my $i ($n..($worker_processes - 1)) {
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
454 warn "PID=$pid is worker[$i]\n";
458 # just wait on signal events here:
459 sysread($r, my $buf, 8);
461 exit # never gets here, just for documentation
464 sub daemon_loop ($$) {
465 my ($refresh, $post_accept) = @_;
466 PublicInbox::EvCleanup::enable(); # early for $refresh
468 if ($worker_processes > 0) {
469 $refresh->(); # preload by default
470 my $fh = master_loop(); # returns if in child process
471 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
474 $set_user->() if $set_user;
475 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
480 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
481 $SIG{USR1} = *reopen_logs;
482 $SIG{HUP} = $refresh;
483 $SIG{CHLD} = 'DEFAULT';
484 $SIG{$_} = 'IGNORE' for qw(USR2 TTIN TTOU WINCH);
485 # this calls epoll_create:
487 PublicInbox::Listener->new($_, $post_accept)
489 PublicInbox::DS->EventLoop;
490 $parent_pipe = undef;
495 my ($default, $refresh, $post_accept) = @_;
496 daemon_prepare($default);
498 daemon_loop($refresh, $post_accept);
503 if (defined $uid and !chown($uid, $gid, $path)) {
504 warn "could not chown $path: $!\n";
510 Net::Server::Daemonize::create_pid_file($path);