]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Daemon.pm
daemon: document optional Net::Server dependency
[public-inbox.git] / lib / PublicInbox / Daemon.pm
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;
6 use strict;
7 use warnings;
8 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
9 use IO::Handle;
10 use IO::Socket;
11 STDOUT->autoflush(1);
12 STDERR->autoflush(1);
13 require Danga::Socket;
14 require POSIX;
15 require PublicInbox::Listener;
16 my @CMD;
17 my $set_user;
18 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
19 my $worker_processes = 1;
20 my @listeners;
21 my %pids;
22 my %listener_names;
23 my $reexec_pid;
24 my $cleanup;
25 my ($uid, $gid);
26 END { $cleanup->() if $cleanup };
27
28 sub daemon_prepare ($) {
29         my ($default_listen) = @_;
30         @CMD = ($0, @ARGV);
31         $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
32                 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
33         my %opts = (
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,
39                 'u|user=s' => \$user,
40                 'g|group=s' => \$group,
41                 'D|daemonize' => \$daemonize,
42         );
43         GetOptions(%opts) or die "bad command-line args\n";
44
45         if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
46                 die "--pid-file cannot end with '.oldbin'\n";
47         }
48         @listeners = inherit();
49         # ignore daemonize when inheriting
50         $daemonize = undef if scalar @listeners;
51
52         push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
53
54         foreach my $l (@cfg_listen) {
55                 next if $listener_names{$l}; # already inherited
56                 my (%o, $sock_pkg);
57                 if (index($l, '/') == 0) {
58                         $sock_pkg = 'IO::Socket::UNIX';
59                         eval "use $sock_pkg";
60                         die $@ if $@;
61                         %o = (Type => SOCK_STREAM, Peer => $l);
62                         if (-S $l) {
63                                 my $c = $sock_pkg->new(%o);
64                                 if (!defined($c) && $!{ECONNREFUSED}) {
65                                         unlink $l or die
66 "failed to unlink stale socket=$l: $!\n";
67                                 } # else: let the bind fail
68                         }
69                         $o{Local} = delete $o{Peer};
70                 } else {
71                         $sock_pkg = 'IO::Socket::INET6'; # works for IPv4, too
72                         eval "use $sock_pkg";
73                         die $@ if $@;
74                         %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
75                 }
76                 $o{Listen} = 1024;
77                 my $prev = umask 0000;
78                 my $s = eval { $sock_pkg->new(%o) };
79                 warn "error binding $l: $!\n" unless $s;
80                 umask $prev;
81
82                 if ($s) {
83                         $listener_names{sockname($s)} = $s;
84                         push @listeners, $s;
85                 }
86         }
87         die "No listeners bound\n" unless @listeners;
88 }
89
90 sub daemonize () {
91         chdir '/' or die "chdir failed: $!";
92         open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!";
93
94         return unless (defined $pid_file || defined $group || defined $user
95                         || $daemonize);
96
97         eval { require Net::Server::Daemonize };
98         if ($@) {
99                 die
100 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
101         }
102
103         Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
104         $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
105         if (defined $group) {
106                 $gid = Net::Server::Daemonize::get_gid($group);
107                 $gid = (split /\s+/, $gid)[0];
108         } elsif (defined $uid) {
109                 $gid = (getpwuid($uid))[3];
110         }
111
112         # We change users in the worker to ensure upgradability,
113         # The upgrade will create the ".oldbin" pid file in the
114         # same directory as the given pid file.
115         $uid and $set_user = sub {
116                 $set_user = undef;
117                 Net::Server::Daemonize::set_user($uid, $gid);
118         };
119
120         if ($daemonize) {
121                 my ($pid, $err) = do_fork();
122                 die "could not fork: $err\n" unless defined $pid;
123                 exit if $pid;
124
125                 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
126                 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
127                 POSIX::setsid();
128                 ($pid, $err) = do_fork();
129                 die "could not fork: $err\n" unless defined $pid;
130                 exit if $pid;
131         }
132         if (defined $pid_file) {
133                 write_pid($pid_file);
134                 my $unlink_pid = $$;
135                 $cleanup = sub {
136                         $cleanup = undef; # avoid cyclic reference
137                         unlink_pid_file_safe_ish($unlink_pid, $pid_file);
138                 };
139         }
140 }
141
142 sub worker_quit () {
143         # killing again terminates immediately:
144         exit unless @listeners;
145
146         $_->close foreach @listeners; # call Danga::Socket::close
147         @listeners = ();
148
149         # give slow clients 30s to finish reading/writing whatever
150         Danga::Socket->AddTimer(30, sub { exit });
151
152         # drop idle connections and try to quit gracefully
153         Danga::Socket->SetPostLoopCallback(sub {
154                 my ($dmap, undef) = @_;
155                 my $n = 0;
156
157                 foreach my $s (values %$dmap) {
158                         if ($s->can('busy') && $s->busy) {
159                                 $n = 1;
160                         } else {
161                                 # close as much as possible, early as possible
162                                 $s->close;
163                         }
164                 }
165                 $n; # true: loop continues, false: loop breaks
166         });
167 }
168
169 sub reopen_logs {
170         if ($stdout) {
171                 open STDOUT, '>>', $stdout or
172                         warn "failed to redirect stdout to $stdout: $!\n";
173                 STDOUT->autoflush(1);
174                 do_chown($stdout);
175         }
176         if ($stderr) {
177                 open STDERR, '>>', $stderr or
178                         warn "failed to redirect stderr to $stderr: $!\n";
179                 STDERR->autoflush(1);
180                 do_chown($stderr);
181         }
182 }
183
184 sub sockname ($) {
185         my ($s) = @_;
186         my $addr = getsockname($s) or return;
187         my ($host, $port) = host_with_port($addr);
188         "$host:$port";
189 }
190
191 sub host_with_port ($) {
192         my ($addr) = @_;
193         my ($port, $host);
194
195         # this eval will die on Unix sockets:
196         eval {
197                 if (length($addr) >= 28) {
198                         require Socket6;
199                         ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
200                         $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
201                         $host = "[$host]";
202                 } else {
203                         ($port, $host) = Socket::sockaddr_in($addr);
204                         $host = Socket::inet_ntoa($host);
205                 }
206         };
207         $@ ? ('127.0.0.1', 0) : ($host, $port);
208 }
209
210 sub inherit () {
211         return () if ($ENV{LISTEN_PID} || 0) != $$;
212         my $fds = $ENV{LISTEN_FDS} or return ();
213         my $end = $fds + 2; # LISTEN_FDS_START - 1
214         my @rv = ();
215         foreach my $fd (3..$end) {
216                 my $s = IO::Handle->new_from_fd($fd, 'r');
217                 if (my $k = sockname($s)) {
218                         $listener_names{$k} = $s;
219                         push @rv, $s;
220                 } else {
221                         warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
222                 }
223         }
224         @rv
225 }
226
227 sub upgrade () {
228         if ($reexec_pid) {
229                 warn "upgrade in-progress: $reexec_pid\n";
230                 return;
231         }
232         if (defined $pid_file) {
233                 if ($pid_file =~ /\.oldbin\z/) {
234                         warn "BUG: .oldbin suffix exists: $pid_file\n";
235                         return;
236                 }
237                 unlink_pid_file_safe_ish($$, $pid_file);
238                 $pid_file .= '.oldbin';
239                 write_pid($pid_file);
240         }
241         my ($pid, $err) = do_fork();
242         unless (defined $pid) {
243                 warn "fork failed: $err\n";
244                 return;
245         }
246         if ($pid == 0) {
247                 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
248                 $ENV{LISTEN_FDS} = scalar @listeners;
249                 $ENV{LISTEN_PID} = $$;
250                 foreach my $s (@listeners) {
251                         my $fl = fcntl($s, F_GETFD, 0);
252                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
253                 }
254                 exec @CMD;
255                 die "Failed to exec: $!\n";
256         }
257         $reexec_pid = $pid;
258 }
259
260 sub kill_workers ($) {
261         my ($s) = @_;
262
263         while (my ($pid, $id) = each %pids) {
264                 kill $s, $pid;
265         }
266 }
267
268 sub do_fork () {
269         my $new = POSIX::SigSet->new;
270         $new->fillset;
271         my $old = POSIX::SigSet->new;
272         POSIX::sigprocmask(&POSIX::SIG_BLOCK, $new, $old) or die "SIG_BLOCK: $!";
273         my $pid = fork;
274         my $err = $!;
275         POSIX::sigprocmask(&POSIX::SIG_SETMASK, $old) or die "SIG_SETMASK: $!";
276         ($pid, $err);
277 }
278
279 sub upgrade_aborted ($) {
280         my ($p) = @_;
281         warn "reexec PID($p) died with: $?\n";
282         $reexec_pid = undef;
283         return unless $pid_file;
284
285         my $file = $pid_file;
286         $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
287         unlink_pid_file_safe_ish($$, $pid_file);
288         $pid_file = $file;
289         eval { write_pid($pid_file) };
290         warn $@, "\n" if $@;
291 }
292
293 sub reap_children () {
294         while (1) {
295                 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
296                 if (defined $reexec_pid && $p == $reexec_pid) {
297                         upgrade_aborted($p);
298                 } elsif (defined(my $id = delete $pids{$p})) {
299                         warn "worker[$id] PID($p) died with: $?\n";
300                 } elsif ($p > 0) {
301                         warn "unknown PID($p) reaped: $?\n";
302                 } else {
303                         return;
304                 }
305         }
306 }
307
308 sub unlink_pid_file_safe_ish ($$) {
309         my ($unlink_pid, $file) = @_;
310         return unless defined $unlink_pid && $unlink_pid == $$;
311
312         open my $fh, '<', $file or return;
313         defined(my $read_pid = <$fh>) or return;
314         chomp $read_pid;
315         if ($read_pid == $unlink_pid) {
316                 Net::Server::Daemonize::unlink_pid_file($file);
317         }
318 }
319
320 sub master_loop {
321         pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
322         pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
323         IO::Handle::blocking($w, 0);
324         my $set_workers = $worker_processes;
325         my @caught;
326         my $master_pid = $$;
327         foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
328                 $SIG{$s} = sub {
329                         return if $$ != $master_pid;
330                         push @caught, $s;
331                         syswrite($w, '.');
332                 };
333         }
334         reopen_logs();
335         # main loop
336         while (1) {
337                 while (my $s = shift @caught) {
338                         if ($s eq 'USR1') {
339                                 reopen_logs();
340                                 kill_workers($s);
341                         } elsif ($s eq 'USR2') {
342                                 upgrade();
343                         } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
344                                 # drops pipes and causes children to die
345                                 exit
346                         } elsif ($s eq 'WINCH') {
347                                 $worker_processes = 0;
348                         } elsif ($s eq 'HUP') {
349                                 $worker_processes = $set_workers;
350                                 kill_workers($s);
351                         } elsif ($s eq 'TTIN') {
352                                 if ($set_workers > $worker_processes) {
353                                         ++$worker_processes;
354                                 } else {
355                                         $worker_processes = ++$set_workers;
356                                 }
357                         } elsif ($s eq 'TTOU') {
358                                 if ($set_workers > 0) {
359                                         $worker_processes = --$set_workers;
360                                 }
361                         } elsif ($s eq 'CHLD') {
362                                 reap_children();
363                         }
364                 }
365
366                 my $n = scalar keys %pids;
367                 if ($n > $worker_processes) {
368                         while (my ($k, $v) = each %pids) {
369                                 kill('TERM', $k) if $v >= $worker_processes;
370                         }
371                         $n = $worker_processes;
372                 }
373                 foreach my $i ($n..($worker_processes - 1)) {
374                         my ($pid, $err) = do_fork();
375                         if (!defined $pid) {
376                                 warn "failed to fork worker[$i]: $err\n";
377                         } elsif ($pid == 0) {
378                                 $set_user->() if $set_user;
379                                 return $p0; # run normal work code
380                         } else {
381                                 warn "PID=$pid is worker[$i]\n";
382                                 $pids{$pid} = $i;
383                         }
384                 }
385                 # just wait on signal events here:
386                 sysread($r, my $buf, 8);
387         }
388         exit # never gets here, just for documentation
389 }
390
391 sub daemon_loop ($$) {
392         my ($refresh, $post_accept) = @_;
393         my $parent_pipe;
394         if ($worker_processes > 0) {
395                 $refresh->(); # preload by default
396                 $parent_pipe = master_loop(); # returns if in child process
397                 my $fd = fileno($parent_pipe);
398                 Danga::Socket->AddOtherFds($fd => *worker_quit);
399         } else {
400                 reopen_logs();
401                 $set_user->() if $set_user;
402                 $SIG{USR2} = sub { worker_quit() if upgrade() };
403                 $refresh->();
404         }
405         $uid = $gid = undef;
406         reopen_logs();
407         $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
408         $SIG{USR1} = *reopen_logs;
409         $SIG{HUP} = $refresh;
410         # this calls epoll_create:
411         @listeners = map {
412                 PublicInbox::Listener->new($_, $post_accept)
413         } @listeners;
414         Danga::Socket->EventLoop;
415         $parent_pipe = undef;
416 }
417
418
419 sub run ($$$) {
420         my ($default, $refresh, $post_accept) = @_;
421         daemon_prepare($default);
422         daemonize();
423         daemon_loop($refresh, $post_accept);
424 }
425
426 sub do_chown ($) {
427         my ($path) = @_;
428         if (defined $uid and !chown($uid, $gid, $path)) {
429                 warn "could not chown $path: $!\n";
430         }
431 }
432
433 sub write_pid ($) {
434         my ($path) = @_;
435         Net::Server::Daemonize::create_pid_file($path);
436         do_chown($path);
437 }
438
439 1;