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/;
13 require Danga::Socket;
15 require PublicInbox::Listener;
18 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
19 my $worker_processes = 1;
26 END { $cleanup->() if $cleanup };
28 sub daemon_prepare ($) {
29 my ($default_listen) = @_;
31 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
32 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
34 'l|listen=s' => \@cfg_listen,
35 '1|stdout=s' => \$stdout,
36 '2|stderr=s' => \$stderr,
37 'W|worker-processes=i' => \$worker_processes,
38 'P|pid-file=s' => \$pid_file,
40 'g|group=s' => \$group,
41 'D|daemonize' => \$daemonize,
43 GetOptions(%opts) or die "bad command-line args\n";
45 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
46 die "--pid-file cannot end with '.oldbin'\n";
48 @listeners = inherit();
49 # ignore daemonize when inheriting
50 $daemonize = undef if scalar @listeners;
52 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
54 foreach my $l (@cfg_listen) {
55 next if $listener_names{$l}; # already inherited
57 if (index($l, '/') == 0) {
58 $sock_pkg = 'IO::Socket::UNIX';
61 %o = (Type => SOCK_STREAM, Peer => $l);
63 my $c = $sock_pkg->new(%o);
64 if (!defined($c) && $!{ECONNREFUSED}) {
66 "failed to unlink stale socket=$l: $!\n";
67 } # else: let the bind fail
69 $o{Local} = delete $o{Peer};
71 $sock_pkg = 'IO::Socket::INET6'; # works for IPv4, too
74 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
77 my $prev = umask 0000;
78 my $s = eval { $sock_pkg->new(%o) };
79 warn "error binding $l: $!\n" unless $s;
83 $listener_names{sockname($s)} = $s;
87 die "No listeners bound\n" unless @listeners;
91 chdir '/' or die "chdir failed: $!";
92 open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
94 return unless (defined $pid_file || defined $group || defined $user
97 require Net::Server::Daemonize;
99 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
100 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
101 if (defined $group) {
102 $gid = Net::Server::Daemonize::get_gid($group);
103 $gid = (split /\s+/, $gid)[0];
104 } elsif (defined $uid) {
105 $gid = (getpwuid($uid))[3];
108 # We change users in the worker to ensure upgradability,
109 # The upgrade will create the ".oldbin" pid file in the
110 # same directory as the given pid file.
111 $uid and $set_user = sub {
112 Net::Server::Daemonize::set_user($uid, $gid);
116 my ($pid, $err) = do_fork();
117 die "could not fork: $err\n" unless defined $pid;
120 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
121 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
123 ($pid, $err) = do_fork();
124 die "could not fork: $err\n" unless defined $pid;
127 if (defined $pid_file) {
128 write_pid($pid_file);
131 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
137 # killing again terminates immediately:
138 exit unless @listeners;
142 # give slow clients 30s to finish reading/writing whatever
143 Danga::Socket->AddTimer(30, sub { exit });
145 # drop idle connections and try to quit gracefully
146 Danga::Socket->SetPostLoopCallback(sub {
147 my ($dmap, undef) = @_;
150 foreach my $s (values %$dmap) {
151 if ($s->can('busy') && $s->busy) {
154 # close as much as possible, early as possible
158 $n; # true: loop continues, false: loop breaks
164 open STDOUT, '>>', $stdout or
165 warn "failed to redirect stdout to $stdout: $!\n";
166 STDOUT->autoflush(1);
170 open STDERR, '>>', $stderr or
171 warn "failed to redirect stderr to $stderr: $!\n";
172 STDERR->autoflush(1);
179 my $addr = getsockname($s) or return;
180 my ($host, $port) = host_with_port($addr);
184 sub host_with_port ($) {
188 # this eval will die on Unix sockets:
190 if (length($addr) >= 28) {
192 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
193 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
196 ($port, $host) = Socket::sockaddr_in($addr);
197 $host = Socket::inet_ntoa($host);
200 $@ ? ('127.0.0.1', 0) : ($host, $port);
204 return () if ($ENV{LISTEN_PID} || 0) != $$;
205 my $fds = $ENV{LISTEN_FDS} or return ();
206 my $end = $fds + 2; # LISTEN_FDS_START - 1
208 foreach my $fd (3..$end) {
209 my $s = IO::Handle->new;
210 $s->fdopen($fd, 'r');
211 if (my $k = sockname($s)) {
212 $listener_names{$k} = $s;
215 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
223 warn "upgrade in-progress: $reexec_pid\n";
226 if (defined $pid_file) {
227 if ($pid_file =~ /\.oldbin\z/) {
228 warn "BUG: .oldbin suffix exists: $pid_file\n";
231 unlink_pid_file_safe_ish($$, $pid_file);
232 $pid_file .= '.oldbin';
233 write_pid($pid_file);
235 my ($pid, $err) = do_fork();
236 unless (defined $pid) {
237 warn "fork failed: $err\n";
241 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
242 $ENV{LISTEN_FDS} = scalar @listeners;
243 $ENV{LISTEN_PID} = $$;
244 foreach my $s (@listeners) {
245 my $fl = fcntl($s, F_GETFD, 0);
246 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
249 die "Failed to exec: $!\n";
254 sub kill_workers ($) {
257 while (my ($pid, $id) = each %pids) {
263 my $new = POSIX::SigSet->new;
265 my $old = POSIX::SigSet->new;
266 POSIX::sigprocmask(&POSIX::SIG_BLOCK, $new, $old) or die "SIG_BLOCK: $!";
269 POSIX::sigprocmask(&POSIX::SIG_SETMASK, $old) or die "SIG_SETMASK: $!";
273 sub upgrade_aborted ($) {
275 warn "reexec PID($p) died with: $?\n";
277 return unless $pid_file;
279 my $file = $pid_file;
280 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
281 unlink_pid_file_safe_ish($$, $pid_file);
283 eval { write_pid($pid_file) };
287 sub reap_children () {
289 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
290 if (defined $reexec_pid && $p == $reexec_pid) {
292 } elsif (defined(my $id = delete $pids{$p})) {
293 warn "worker[$id] PID($p) died with: $?\n";
295 warn "unknown PID($p) reaped: $?\n";
302 sub unlink_pid_file_safe_ish ($$) {
303 my ($unlink_pid, $file) = @_;
304 return unless defined $unlink_pid && $unlink_pid == $$;
306 open my $fh, '<', $file or return;
307 defined(my $read_pid = <$fh>) or return;
309 if ($read_pid == $unlink_pid) {
310 Net::Server::Daemonize::unlink_pid_file($file);
315 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
316 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
317 IO::Handle::blocking($w, 0);
318 my $set_workers = $worker_processes;
321 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
323 return if $$ != $master_pid;
331 while (my $s = shift @caught) {
335 } elsif ($s eq 'USR2') {
337 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
338 # drops pipes and causes children to die
340 } elsif ($s eq 'WINCH') {
341 $worker_processes = 0;
342 } elsif ($s eq 'HUP') {
343 $worker_processes = $set_workers;
345 } elsif ($s eq 'TTIN') {
346 if ($set_workers > $worker_processes) {
349 $worker_processes = ++$set_workers;
351 } elsif ($s eq 'TTOU') {
352 if ($set_workers > 0) {
353 $worker_processes = --$set_workers;
355 } elsif ($s eq 'CHLD') {
360 my $n = scalar keys %pids;
361 if ($n > $worker_processes) {
362 while (my ($k, $v) = each %pids) {
363 kill('TERM', $k) if $v >= $worker_processes;
365 $n = $worker_processes;
367 foreach my $i ($n..($worker_processes - 1)) {
368 my ($pid, $err) = do_fork();
370 warn "failed to fork worker[$i]: $err\n";
371 } elsif ($pid == 0) {
372 $set_user->() if $set_user;
373 return $p0; # run normal work code
375 warn "PID=$pid is worker[$i]\n";
379 # just wait on signal events here:
380 sysread($r, my $buf, 8);
382 exit # never gets here, just for documentation
385 sub daemon_loop ($$) {
386 my ($refresh, $post_accept) = @_;
388 if ($worker_processes > 0) {
389 $refresh->(); # preload by default
390 $parent_pipe = master_loop(); # returns if in child process
391 my $fd = fileno($parent_pipe);
392 Danga::Socket->AddOtherFds($fd => sub { kill('TERM', $$) } );
395 $set_user->() if $set_user;
396 $SIG{USR2} = sub { worker_quit() if upgrade() };
401 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
402 $SIG{USR1} = *reopen_logs;
403 $SIG{HUP} = $refresh;
404 # this calls epoll_create:
405 PublicInbox::Listener->new($_, $post_accept) for @listeners;
406 Danga::Socket->EventLoop;
407 $parent_pipe = undef;
412 my ($default, $refresh, $post_accept) = @_;
413 daemon_prepare($default);
415 daemon_loop($refresh, $post_accept);
420 if (defined $uid and !chown($uid, $gid, $path)) {
421 warn "could not chown $path: $!\n";
427 Net::Server::Daemonize::create_pid_file($path);