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