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