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