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/;
12 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
15 require PublicInbox::DS;
16 require PublicInbox::EvCleanup;
18 require PublicInbox::Listener;
19 require PublicInbox::ParentPipe;
22 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
23 my $worker_processes = 1;
30 END { $cleanup->() if $cleanup };
32 sub daemon_prepare ($) {
33 my ($default_listen) = @_;
35 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
36 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
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,
44 'g|group=s' => \$group,
45 'D|daemonize' => \$daemonize,
47 GetOptions(%opts) or die "bad command-line args\n";
49 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
50 die "--pid-file cannot end with '.oldbin'\n";
52 @listeners = inherit();
53 # ignore daemonize when inheriting
54 $daemonize = undef if scalar @listeners;
56 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
58 foreach my $l (@cfg_listen) {
59 next if $listener_names{$l}; # already inherited
61 if (index($l, '/') == 0) {
62 $sock_pkg = 'IO::Socket::UNIX';
65 %o = (Type => SOCK_STREAM, Peer => $l);
67 my $c = $sock_pkg->new(%o);
68 if (!defined($c) && $!{ECONNREFUSED}) {
70 "failed to unlink stale socket=$l: $!\n";
71 } # else: let the bind fail
73 $o{Local} = delete $o{Peer};
75 # both work for IPv4, too
76 for (qw(IO::Socket::IP IO::Socket::INET6)) {
82 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
85 my $prev = umask 0000;
86 my $s = eval { $sock_pkg->new(%o) };
87 warn "error binding $l: $! ($@)\n" unless $s;
91 $listener_names{sockname($s)} = $s;
95 die "No listeners bound\n" unless @listeners;
98 sub check_absolute ($$) {
100 if (defined $val && index($val, '/') != 0) {
102 "--$var must be an absolute path when using --daemonize: $val\n";
108 foreach my $i (0..$#ARGV) {
111 $ARGV[$i] = abs_path($arg);
113 check_absolute('stdout', $stdout);
114 check_absolute('stderr', $stderr);
115 check_absolute('pid-file', $pid_file);
117 chdir '/' or die "chdir failed: $!";
120 return unless (defined $pid_file || defined $group || defined $user
123 eval { require Net::Server::Daemonize };
126 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
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];
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 {
143 Net::Server::Daemonize::set_user($uid, $gid);
148 die "could not fork: $!\n" unless defined $pid;
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";
157 die "could not fork: $!\n" unless defined $pid;
160 if (defined $pid_file) {
161 write_pid($pid_file);
164 $cleanup = undef; # avoid cyclic reference
165 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
173 # killing again terminates immediately:
174 exit unless @listeners;
176 $_->close foreach @listeners; # call PublicInbox::DS::close
178 $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
182 # drop idle connections and try to quit gracefully
183 PublicInbox::DS->SetPostLoopCallback(sub {
184 my ($dmap, undef) = @_;
186 my $now = clock_gettime(CLOCK_MONOTONIC);
188 foreach my $s (values %$dmap) {
189 $s->can('busy') or next;
190 if ($s->busy($now)) {
193 # close as much as possible, early as possible
198 if (($warn + 5) < time) {
199 warn "$$ quitting, $n client(s) left\n";
202 unless (defined $proc_name) {
203 $proc_name = (split(/\s+/, $0))[0];
204 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
206 $0 = "$proc_name quitting, $n client(s) left";
208 $n; # true: loop continues, false: loop breaks
214 open STDOUT, '>>', $stdout or
215 warn "failed to redirect stdout to $stdout: $!\n";
216 STDOUT->autoflush(1);
220 open STDERR, '>>', $stderr or
221 warn "failed to redirect stderr to $stderr: $!\n";
222 STDERR->autoflush(1);
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);
238 sub unpack_ipv6 ($) {
242 # Socket.pm in Perl 5.14+ supports IPv6:
244 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
245 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
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):
254 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
255 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
260 sub host_with_port ($) {
264 # this eval will die on Unix sockets:
266 if (length($addr) >= 28) {
267 ($host, $port) = unpack_ipv6($addr);
270 ($port, $host) = Socket::sockaddr_in($addr);
271 $host = Socket::inet_ntoa($host);
274 $@ ? ('127.0.0.1', 0) : ($host, $port);
278 return () if ($ENV{LISTEN_PID} || 0) != $$;
279 my $fds = $ENV{LISTEN_FDS} or return ();
280 my $end = $fds + 2; # LISTEN_FDS_START - 1
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;
288 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
296 warn "upgrade in-progress: $reexec_pid\n";
299 if (defined $pid_file) {
300 if ($pid_file =~ /\.oldbin\z/) {
301 warn "BUG: .oldbin suffix exists: $pid_file\n";
304 unlink_pid_file_safe_ish($$, $pid_file);
305 $pid_file .= '.oldbin';
306 write_pid($pid_file);
309 unless (defined $pid) {
310 warn "fork failed: $!\n";
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);
322 die "Failed to exec: $!\n";
327 sub kill_workers ($) {
330 while (my ($pid, $id) = each %pids) {
335 sub upgrade_aborted ($) {
337 warn "reexec PID($p) died with: $?\n";
339 return unless $pid_file;
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);
345 eval { write_pid($pid_file) };
349 sub reap_children () {
351 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
352 if (defined $reexec_pid && $p == $reexec_pid) {
354 } elsif (defined(my $id = delete $pids{$p})) {
355 warn "worker[$id] PID($p) died with: $?\n";
357 warn "unknown PID($p) reaped: $?\n";
364 sub unlink_pid_file_safe_ish ($$) {
365 my ($unlink_pid, $file) = @_;
366 return unless defined $unlink_pid && $unlink_pid == $$;
368 open my $fh, '<', $file or return;
370 defined(my $read_pid = <$fh>) or return;
372 if ($read_pid == $unlink_pid) {
373 Net::Server::Daemonize::unlink_pid_file($file);
378 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
379 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
381 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ = 1031
382 fcntl($_, 1031, 4096) for ($w, $p1);
385 IO::Handle::blocking($w, 0);
386 my $set_workers = $worker_processes;
389 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
391 return if $$ != $master_pid;
400 while (my $s = shift @caught) {
404 } elsif ($s eq 'USR2') {
406 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
409 } elsif ($s eq 'WINCH') {
410 if (-t STDIN || -t STDOUT || -t STDERR) {
412 "ignoring SIGWINCH since we are not daemonized\n";
413 $SIG{WINCH} = 'IGNORE';
415 $worker_processes = 0;
417 } elsif ($s eq 'HUP') {
418 $worker_processes = $set_workers;
420 } elsif ($s eq 'TTIN') {
421 if ($set_workers > $worker_processes) {
424 $worker_processes = ++$set_workers;
426 } elsif ($s eq 'TTOU') {
427 if ($set_workers > 0) {
428 $worker_processes = --$set_workers;
430 } elsif ($s eq 'CHLD') {
435 my $n = scalar keys %pids;
438 $set_workers = $worker_processes = $n = 0;
441 if ($n > $worker_processes) {
442 while (my ($k, $v) = each %pids) {
443 kill('TERM', $k) if $v >= $worker_processes;
445 $n = $worker_processes;
447 foreach my $i ($n..($worker_processes - 1)) {
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
455 warn "PID=$pid is worker[$i]\n";
459 # just wait on signal events here:
460 sysread($r, my $buf, 8);
462 exit # never gets here, just for documentation
465 sub daemon_loop ($$) {
466 my ($refresh, $post_accept) = @_;
467 PublicInbox::EvCleanup::enable(); # early for $refresh
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);
475 $set_user->() if $set_user;
476 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
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:
488 PublicInbox::Listener->new($_, $post_accept)
490 PublicInbox::DS->EventLoop;
491 $parent_pipe = undef;
496 my ($default, $refresh, $post_accept) = @_;
497 daemon_prepare($default);
499 daemon_loop($refresh, $post_accept);
504 if (defined $uid and !chown($uid, $gid, $path)) {
505 warn "could not chown $path: $!\n";
511 Net::Server::Daemonize::create_pid_file($path);