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