1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (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 require Danga::Socket;
16 require PublicInbox::Listener;
17 require PublicInbox::ParentPipe;
20 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
21 my $worker_processes = 1;
28 END { $cleanup->() if $cleanup };
30 sub daemon_prepare ($) {
31 my ($default_listen) = @_;
33 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
34 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
36 'l|listen=s' => \@cfg_listen,
37 '1|stdout=s' => \$stdout,
38 '2|stderr=s' => \$stderr,
39 'W|worker-processes=i' => \$worker_processes,
40 'P|pid-file=s' => \$pid_file,
42 'g|group=s' => \$group,
43 'D|daemonize' => \$daemonize,
45 GetOptions(%opts) or die "bad command-line args\n";
47 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
48 die "--pid-file cannot end with '.oldbin'\n";
50 @listeners = inherit();
51 # ignore daemonize when inheriting
52 $daemonize = undef if scalar @listeners;
54 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
56 foreach my $l (@cfg_listen) {
57 next if $listener_names{$l}; # already inherited
59 if (index($l, '/') == 0) {
60 $sock_pkg = 'IO::Socket::UNIX';
63 %o = (Type => SOCK_STREAM, Peer => $l);
65 my $c = $sock_pkg->new(%o);
66 if (!defined($c) && $!{ECONNREFUSED}) {
68 "failed to unlink stale socket=$l: $!\n";
69 } # else: let the bind fail
71 $o{Local} = delete $o{Peer};
73 # both work for IPv4, too
74 for (qw(IO::Socket::IP IO::Socket::INET6)) {
80 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
83 my $prev = umask 0000;
84 my $s = eval { $sock_pkg->new(%o) };
85 warn "error binding $l: $! ($@)\n" unless $s;
89 $listener_names{sockname($s)} = $s;
93 die "No listeners bound\n" unless @listeners;
96 sub check_absolute ($$) {
98 if (defined $val && index($val, '/') != 0) {
100 "--$var must be an absolute path when using --daemonize: $val\n";
105 foreach my $i (0..$#ARGV) {
108 $ARGV[$i] = abs_path($arg);
110 check_absolute('stdout', $stdout);
111 check_absolute('stderr', $stderr);
112 check_absolute('pid-file', $pid_file);
114 chdir '/' or die "chdir failed: $!";
115 open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
117 return unless (defined $pid_file || defined $group || defined $user
120 eval { require Net::Server::Daemonize };
123 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
126 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
127 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
128 if (defined $group) {
129 $gid = Net::Server::Daemonize::get_gid($group);
130 $gid = (split /\s+/, $gid)[0];
131 } elsif (defined $uid) {
132 $gid = (getpwuid($uid))[3];
135 # We change users in the worker to ensure upgradability,
136 # The upgrade will create the ".oldbin" pid file in the
137 # same directory as the given pid file.
138 $uid and $set_user = sub {
140 Net::Server::Daemonize::set_user($uid, $gid);
145 die "could not fork: $!\n" unless defined $pid;
148 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
149 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
152 die "could not fork: $!\n" unless defined $pid;
155 if (defined $pid_file) {
156 write_pid($pid_file);
159 $cleanup = undef; # avoid cyclic reference
160 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
168 # killing again terminates immediately:
169 exit unless @listeners;
171 $_->close foreach @listeners; # call Danga::Socket::close
173 $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
177 # drop idle connections and try to quit gracefully
178 Danga::Socket->SetPostLoopCallback(sub {
179 my ($dmap, undef) = @_;
182 foreach my $s (values %$dmap) {
183 if ($s->can('busy') && $s->busy) {
186 # close as much as possible, early as possible
191 if (($warn + 5) < time) {
192 warn "$$ quitting, $n client(s) left\n";
195 unless (defined $proc_name) {
196 $proc_name = (split(/\s+/, $0))[0];
197 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
199 $0 = "$proc_name quitting, $n client(s) left";
201 $n; # true: loop continues, false: loop breaks
207 open STDOUT, '>>', $stdout or
208 warn "failed to redirect stdout to $stdout: $!\n";
209 STDOUT->autoflush(1);
213 open STDERR, '>>', $stderr or
214 warn "failed to redirect stderr to $stderr: $!\n";
215 STDERR->autoflush(1);
222 my $addr = getsockname($s) or return;
223 my ($host, $port) = host_with_port($addr);
224 if ($port == 0 && $host eq '127.0.0.1') {
225 my ($path) = Socket::sockaddr_un($addr);
231 sub host_with_port ($) {
235 # this eval will die on Unix sockets:
237 if (length($addr) >= 28) {
239 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
240 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
243 ($port, $host) = Socket::sockaddr_in($addr);
244 $host = Socket::inet_ntoa($host);
247 $@ ? ('127.0.0.1', 0) : ($host, $port);
251 return () if ($ENV{LISTEN_PID} || 0) != $$;
252 my $fds = $ENV{LISTEN_FDS} or return ();
253 my $end = $fds + 2; # LISTEN_FDS_START - 1
255 foreach my $fd (3..$end) {
256 my $s = IO::Handle->new_from_fd($fd, 'r');
257 if (my $k = sockname($s)) {
258 $listener_names{$k} = $s;
261 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
269 warn "upgrade in-progress: $reexec_pid\n";
272 if (defined $pid_file) {
273 if ($pid_file =~ /\.oldbin\z/) {
274 warn "BUG: .oldbin suffix exists: $pid_file\n";
277 unlink_pid_file_safe_ish($$, $pid_file);
278 $pid_file .= '.oldbin';
279 write_pid($pid_file);
282 unless (defined $pid) {
283 warn "fork failed: $!\n";
287 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
288 $ENV{LISTEN_FDS} = scalar @listeners;
289 $ENV{LISTEN_PID} = $$;
290 foreach my $s (@listeners) {
291 my $fl = fcntl($s, F_GETFD, 0);
292 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
295 die "Failed to exec: $!\n";
300 sub kill_workers ($) {
303 while (my ($pid, $id) = each %pids) {
308 sub upgrade_aborted ($) {
310 warn "reexec PID($p) died with: $?\n";
312 return unless $pid_file;
314 my $file = $pid_file;
315 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
316 unlink_pid_file_safe_ish($$, $pid_file);
318 eval { write_pid($pid_file) };
322 sub reap_children () {
324 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
325 if (defined $reexec_pid && $p == $reexec_pid) {
327 } elsif (defined(my $id = delete $pids{$p})) {
328 warn "worker[$id] PID($p) died with: $?\n";
330 warn "unknown PID($p) reaped: $?\n";
337 sub unlink_pid_file_safe_ish ($$) {
338 my ($unlink_pid, $file) = @_;
339 return unless defined $unlink_pid && $unlink_pid == $$;
341 open my $fh, '<', $file or return;
343 defined(my $read_pid = <$fh>) or return;
345 if ($read_pid == $unlink_pid) {
346 Net::Server::Daemonize::unlink_pid_file($file);
351 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
352 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
353 IO::Handle::blocking($w, 0);
354 my $set_workers = $worker_processes;
357 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
359 return if $$ != $master_pid;
368 while (my $s = shift @caught) {
372 } elsif ($s eq 'USR2') {
374 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
377 } elsif ($s eq 'WINCH') {
378 if (-t STDIN || -t STDOUT || -t STDERR) {
380 "ignoring SIGWINCH while connected to terminal\n";
381 $SIG{WINCH} = 'IGNORE';
383 $worker_processes = 0;
385 } elsif ($s eq 'HUP') {
386 $worker_processes = $set_workers;
388 } elsif ($s eq 'TTIN') {
389 if ($set_workers > $worker_processes) {
392 $worker_processes = ++$set_workers;
394 } elsif ($s eq 'TTOU') {
395 if ($set_workers > 0) {
396 $worker_processes = --$set_workers;
398 } elsif ($s eq 'CHLD') {
403 my $n = scalar keys %pids;
406 $set_workers = $worker_processes = $n = 0;
409 if ($n > $worker_processes) {
410 while (my ($k, $v) = each %pids) {
411 kill('TERM', $k) if $v >= $worker_processes;
413 $n = $worker_processes;
415 foreach my $i ($n..($worker_processes - 1)) {
418 warn "failed to fork worker[$i]: $!\n";
419 } elsif ($pid == 0) {
420 $set_user->() if $set_user;
421 return $p0; # run normal work code
423 warn "PID=$pid is worker[$i]\n";
427 # just wait on signal events here:
428 sysread($r, my $buf, 8);
430 exit # never gets here, just for documentation
433 sub daemon_loop ($$) {
434 my ($refresh, $post_accept) = @_;
436 if ($worker_processes > 0) {
437 $refresh->(); # preload by default
438 my $fh = master_loop(); # returns if in child process
439 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
442 $set_user->() if $set_user;
443 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
448 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
449 $SIG{USR1} = *reopen_logs;
450 $SIG{HUP} = $refresh;
451 # this calls epoll_create:
453 PublicInbox::Listener->new($_, $post_accept)
455 Danga::Socket->EventLoop;
456 $parent_pipe = undef;
461 my ($default, $refresh, $post_accept) = @_;
462 daemon_prepare($default);
464 daemon_loop($refresh, $post_accept);
469 if (defined $uid and !chown($uid, $gid, $path)) {
470 warn "could not chown $path: $!\n";
476 Net::Server::Daemonize::create_pid_file($path);