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 Danga::Socket;
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 Danga::Socket::close
177 $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
181 # drop idle connections and try to quit gracefully
182 Danga::Socket->SetPostLoopCallback(sub {
183 my ($dmap, undef) = @_;
185 my $now = clock_gettime(CLOCK_MONOTONIC);
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) < time) {
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 host_with_port ($) {
241 # this eval will die on Unix sockets:
243 if (length($addr) >= 28) {
245 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
246 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
249 ($port, $host) = Socket::sockaddr_in($addr);
250 $host = Socket::inet_ntoa($host);
253 $@ ? ('127.0.0.1', 0) : ($host, $port);
257 return () if ($ENV{LISTEN_PID} || 0) != $$;
258 my $fds = $ENV{LISTEN_FDS} or return ();
259 my $end = $fds + 2; # LISTEN_FDS_START - 1
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;
267 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
275 warn "upgrade in-progress: $reexec_pid\n";
278 if (defined $pid_file) {
279 if ($pid_file =~ /\.oldbin\z/) {
280 warn "BUG: .oldbin suffix exists: $pid_file\n";
283 unlink_pid_file_safe_ish($$, $pid_file);
284 $pid_file .= '.oldbin';
285 write_pid($pid_file);
288 unless (defined $pid) {
289 warn "fork failed: $!\n";
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);
301 die "Failed to exec: $!\n";
306 sub kill_workers ($) {
309 while (my ($pid, $id) = each %pids) {
314 sub upgrade_aborted ($) {
316 warn "reexec PID($p) died with: $?\n";
318 return unless $pid_file;
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);
324 eval { write_pid($pid_file) };
328 sub reap_children () {
330 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
331 if (defined $reexec_pid && $p == $reexec_pid) {
333 } elsif (defined(my $id = delete $pids{$p})) {
334 warn "worker[$id] PID($p) died with: $?\n";
336 warn "unknown PID($p) reaped: $?\n";
343 sub unlink_pid_file_safe_ish ($$) {
344 my ($unlink_pid, $file) = @_;
345 return unless defined $unlink_pid && $unlink_pid == $$;
347 open my $fh, '<', $file or return;
349 defined(my $read_pid = <$fh>) or return;
351 if ($read_pid == $unlink_pid) {
352 Net::Server::Daemonize::unlink_pid_file($file);
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;
363 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
365 return if $$ != $master_pid;
374 while (my $s = shift @caught) {
378 } elsif ($s eq 'USR2') {
380 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
383 } elsif ($s eq 'WINCH') {
384 if (-t STDIN || -t STDOUT || -t STDERR) {
386 "ignoring SIGWINCH since we are not daemonized\n";
387 $SIG{WINCH} = 'IGNORE';
389 $worker_processes = 0;
391 } elsif ($s eq 'HUP') {
392 $worker_processes = $set_workers;
394 } elsif ($s eq 'TTIN') {
395 if ($set_workers > $worker_processes) {
398 $worker_processes = ++$set_workers;
400 } elsif ($s eq 'TTOU') {
401 if ($set_workers > 0) {
402 $worker_processes = --$set_workers;
404 } elsif ($s eq 'CHLD') {
409 my $n = scalar keys %pids;
412 $set_workers = $worker_processes = $n = 0;
415 if ($n > $worker_processes) {
416 while (my ($k, $v) = each %pids) {
417 kill('TERM', $k) if $v >= $worker_processes;
419 $n = $worker_processes;
421 foreach my $i ($n..($worker_processes - 1)) {
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
429 warn "PID=$pid is worker[$i]\n";
433 # just wait on signal events here:
434 sysread($r, my $buf, 8);
436 exit # never gets here, just for documentation
439 sub daemon_loop ($$) {
440 my ($refresh, $post_accept) = @_;
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);
448 $set_user->() if $set_user;
449 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
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:
461 PublicInbox::Listener->new($_, $post_accept)
463 $PublicInbox::EvCleanup::ENABLED = 1;
464 Danga::Socket->EventLoop;
465 $parent_pipe = undef;
470 my ($default, $refresh, $post_accept) = @_;
471 daemon_prepare($default);
473 daemon_loop($refresh, $post_accept);
478 if (defined $uid and !chown($uid, $gid, $path)) {
479 warn "could not chown $path: $!\n";
485 Net::Server::Daemonize::create_pid_file($path);