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/;
12 require Danga::Socket;
14 require PublicInbox::Listener;
17 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
18 my $worker_processes = 1;
25 END { $cleanup->() if $cleanup };
27 sub daemon_prepare ($) {
28 my ($default_listen) = @_;
30 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
31 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
33 'l|listen=s' => \@cfg_listen,
34 '1|stdout=s' => \$stdout,
35 '2|stderr=s' => \$stderr,
36 'W|worker-processes=i' => \$worker_processes,
37 'P|pid-file=s' => \$pid_file,
39 'g|group=s' => \$group,
40 'D|daemonize' => \$daemonize,
42 GetOptions(%opts) or die "bad command-line args\n";
44 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
45 die "--pid-file cannot end with '.oldbin'\n";
47 @listeners = inherit();
48 # ignore daemonize when inheriting
49 $daemonize = undef if scalar @listeners;
51 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
53 foreach my $l (@cfg_listen) {
54 next if $listener_names{$l}; # already inherited
55 require IO::Socket::INET6; # works for IPv4, too
61 if (my $s = IO::Socket::INET6->new(%o)) {
62 $listener_names{sockname($s)} = $s;
65 warn "error binding $l: $!\n";
68 die "No listeners bound\n" unless @listeners;
72 chdir '/' or die "chdir failed: $!";
73 open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
75 return unless (defined $pid_file || defined $group || defined $user
78 require Net::Server::Daemonize;
80 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
81 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
83 $gid = Net::Server::Daemonize::get_gid($group);
84 $gid = (split /\s+/, $gid)[0];
85 } elsif (defined $uid) {
86 $gid = (getpwuid($uid))[3];
89 # We change users in the worker to ensure upgradability,
90 # The upgrade will create the ".oldbin" pid file in the
91 # same directory as the given pid file.
92 $uid and $set_user = sub {
93 Net::Server::Daemonize::set_user($uid, $gid);
97 my ($pid, $err) = do_fork();
98 die "could not fork: $err\n" unless defined $pid;
101 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
102 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
104 ($pid, $err) = do_fork();
105 die "could not fork: $err\n" unless defined $pid;
108 if (defined $pid_file) {
109 write_pid($pid_file);
112 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
118 # killing again terminates immediately:
119 exit unless @listeners;
123 # give slow clients 30s to finish reading/writing whatever
124 Danga::Socket->AddTimer(30, sub { exit });
126 # drop idle connections and try to quit gracefully
127 Danga::Socket->SetPostLoopCallback(sub {
128 my ($dmap, undef) = @_;
131 foreach my $s (values %$dmap) {
132 if ($s->can('busy') && $s->busy) {
135 # close as much as possible, early as possible
139 $n; # true: loop continues, false: loop breaks
145 open STDOUT, '>>', $stdout or
146 warn "failed to redirect stdout to $stdout: $!\n";
147 STDOUT->autoflush(1);
151 open STDERR, '>>', $stderr or
152 warn "failed to redirect stderr to $stderr: $!\n";
153 STDERR->autoflush(1);
160 my $addr = getsockname($s) or return;
161 my ($host, $port) = host_with_port($addr);
165 sub host_with_port ($) {
168 if (length($addr) >= 28) {
170 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
171 $host = '['.Socket6::inet_ntop(Socket6::AF_INET6(), $host).']';
173 ($port, $host) = Socket::sockaddr_in($addr);
174 $host = Socket::inet_ntoa($host);
180 return () if ($ENV{LISTEN_PID} || 0) != $$;
181 my $fds = $ENV{LISTEN_FDS} or return ();
182 my $end = $fds + 2; # LISTEN_FDS_START - 1
184 foreach my $fd (3..$end) {
185 my $s = IO::Handle->new;
186 $s->fdopen($fd, 'r');
187 if (my $k = sockname($s)) {
188 $listener_names{$k} = $s;
191 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
199 warn "upgrade in-progress: $reexec_pid\n";
202 if (defined $pid_file) {
203 if ($pid_file =~ /\.oldbin\z/) {
204 warn "BUG: .oldbin suffix exists: $pid_file\n";
207 unlink_pid_file_safe_ish($$, $pid_file);
208 $pid_file .= '.oldbin';
209 write_pid($pid_file);
211 my ($pid, $err) = do_fork();
212 unless (defined $pid) {
213 warn "fork failed: $err\n";
217 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
218 $ENV{LISTEN_FDS} = scalar @listeners;
219 $ENV{LISTEN_PID} = $$;
220 foreach my $s (@listeners) {
221 my $fl = fcntl($s, F_GETFD, 0);
222 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
225 die "Failed to exec: $!\n";
230 sub kill_workers ($) {
233 while (my ($pid, $id) = each %pids) {
239 my $new = POSIX::SigSet->new;
241 my $old = POSIX::SigSet->new;
242 POSIX::sigprocmask(&POSIX::SIG_BLOCK, $new, $old) or die "SIG_BLOCK: $!";
245 POSIX::sigprocmask(&POSIX::SIG_SETMASK, $old) or die "SIG_SETMASK: $!";
249 sub upgrade_aborted ($) {
251 warn "reexec PID($p) died with: $?\n";
253 return unless $pid_file;
255 my $file = $pid_file;
256 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
257 unlink_pid_file_safe_ish($$, $pid_file);
259 eval { write_pid($pid_file) };
263 sub reap_children () {
265 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
266 if (defined $reexec_pid && $p == $reexec_pid) {
268 } elsif (defined(my $id = delete $pids{$p})) {
269 warn "worker[$id] PID($p) died with: $?\n";
271 warn "unknown PID($p) reaped: $?\n";
278 sub unlink_pid_file_safe_ish ($$) {
279 my ($unlink_pid, $file) = @_;
280 return unless defined $unlink_pid && $unlink_pid == $$;
282 open my $fh, '<', $file or return;
283 defined(my $read_pid = <$fh>) or return;
285 if ($read_pid == $unlink_pid) {
286 Net::Server::Daemonize::unlink_pid_file($file);
291 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
292 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
293 IO::Handle::blocking($w, 0);
294 my $set_workers = $worker_processes;
297 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
299 return if $$ != $master_pid;
307 while (my $s = shift @caught) {
311 } elsif ($s eq 'USR2') {
313 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
314 # drops pipes and causes children to die
316 } elsif ($s eq 'WINCH') {
317 $worker_processes = 0;
318 } elsif ($s eq 'HUP') {
319 $worker_processes = $set_workers;
321 } elsif ($s eq 'TTIN') {
322 if ($set_workers > $worker_processes) {
325 $worker_processes = ++$set_workers;
327 } elsif ($s eq 'TTOU') {
328 if ($set_workers > 0) {
329 $worker_processes = --$set_workers;
331 } elsif ($s eq 'CHLD') {
336 my $n = scalar keys %pids;
337 if ($n > $worker_processes) {
338 while (my ($k, $v) = each %pids) {
339 kill('TERM', $k) if $v >= $worker_processes;
341 $n = $worker_processes;
343 foreach my $i ($n..($worker_processes - 1)) {
344 my ($pid, $err) = do_fork();
346 warn "failed to fork worker[$i]: $err\n";
347 } elsif ($pid == 0) {
348 $set_user->() if $set_user;
349 return $p0; # run normal work code
351 warn "PID=$pid is worker[$i]\n";
355 # just wait on signal events here:
356 sysread($r, my $buf, 8);
358 exit # never gets here, just for documentation
361 sub daemon_loop ($$) {
362 my ($refresh, $post_accept) = @_;
364 if ($worker_processes > 0) {
365 $refresh->(); # preload by default
366 $parent_pipe = master_loop(); # returns if in child process
367 my $fd = fileno($parent_pipe);
368 Danga::Socket->AddOtherFds($fd => sub { kill('TERM', $$) } );
371 $set_user->() if $set_user;
372 $SIG{USR2} = sub { worker_quit() if upgrade() };
377 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
378 $SIG{USR1} = *reopen_logs;
379 $SIG{HUP} = $refresh;
380 # this calls epoll_create:
381 PublicInbox::Listener->new($_, $post_accept) for @listeners;
382 Danga::Socket->EventLoop;
383 $parent_pipe = undef;
388 my ($default, $refresh, $post_accept) = @_;
389 daemon_prepare($default);
391 daemon_loop($refresh, $post_accept);
396 if (defined $uid and !chown($uid, $gid, $path)) {
397 warn "could not chown $path: $!\n";
403 Net::Server::Daemonize::create_pid_file($path);