]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/IPC.pm
lei: fork + FD cleanup
[public-inbox.git] / lib / PublicInbox / IPC.pm
index 5bca362788d629b438b757d9c624ae7603d29e41..88f81e477ec07d58c97f80f8ccb091d88f7f6d2d 100644 (file)
@@ -12,6 +12,7 @@ use POSIX qw(WNOHANG);
 use Socket qw(AF_UNIX MSG_EOR);
 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
 use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
+my $WQ_MAX_WORKERS = 4096;
 my ($enc, $dec);
 # ->imports at BEGIN turns sereal_*_with_object into custom ops on 5.14+
 # and eliminate method call overhead
@@ -36,17 +37,39 @@ if ($enc && $dec) { # should be custom ops
        } // warn("Storable (part of Perl) missing: $@\n");
 }
 
+my $recv_cmd1; # PublicInbox::CmdIPC1::recv_cmd1;
 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
 my $send_cmd = PublicInbox::Spawn->can('send_cmd4') // do {
        require PublicInbox::CmdIPC4;
        $recv_cmd //= PublicInbox::CmdIPC4->can('recv_cmd4');
        PublicInbox::CmdIPC4->can('send_cmd4');
 } // do {
+       # IO::FDPass only allows sending a single FD at-a-time, which
+       # means we can't guarantee all packets end up on the same worker,
+       # so we cap WQ_MAX_WORKERS
        require PublicInbox::CmdIPC1;
-       $recv_cmd = PublicInbox::CmdIPC1->can('recv_cmd1');
+       $recv_cmd1 = PublicInbox::CmdIPC1->can('recv_cmd1');
+       $WQ_MAX_WORKERS = 1 if $recv_cmd1;
+       wq_set_recv_fds(3);
        PublicInbox::CmdIPC1->can('send_cmd1');
 };
 
+# needed to tell recv_cmd1 how many times to loop IO::FDPass::recv
+sub wq_set_recv_fds {
+       return unless $recv_cmd1;
+       my $nfds = pop;
+       my $sub = sub {
+               my ($sock, $fds, undef, $flags) = @_;
+               $recv_cmd1->($sock, $fds, $_[2], $flags, $nfds);
+       };
+       my $self = pop;
+       if (ref $self) {
+               $self->{-wq_recv_cmd} = $sub;
+       } else {
+               $recv_cmd = $sub;
+       }
+}
+
 sub _get_rec ($) {
        my ($r) = @_;
        defined(my $len = <$r>) or return;
@@ -103,11 +126,10 @@ sub ipc_worker_spawn {
        pipe(my ($r_res, $w_res)) or die "pipe: $!";
        my $sigset = $oldset // PublicInbox::DS::block_signals();
        my $parent = $$;
-       $self->ipc_atfork_parent;
+       $self->ipc_atfork_prepare;
        defined(my $pid = fork) or die "fork: $!";
        if ($pid == 0) {
                eval { PublicInbox::DS->Reset };
-               $self->{-ipc_parent_pid} = $parent;
                $w_req = $r_res = undef;
                $w_res->autoflush(1);
                $SIG{$_} = 'IGNORE' for (qw(TERM INT QUIT));
@@ -133,8 +155,14 @@ sub ipc_worker_reap { # dwaitpid callback
 }
 
 # for base class, override in sub classes
-sub ipc_atfork_parent {}
-sub ipc_atfork_child {}
+sub ipc_atfork_prepare {}
+
+sub ipc_atfork_child {
+       my ($self) = @_;
+       my $io = delete($self->{-ipc_atfork_child_close}) or return;
+       close($_) for @$io;
+       undef;
+}
 
 # idempotent, can be called regardless of whether worker is active or not
 sub ipc_worker_stop {
@@ -229,45 +257,61 @@ sub ipc_sibling_atfork_child {
        $pid == $$ and die "BUG: $$ ipc_atfork_child called on itself";
 }
 
+sub _close_recvd ($) {
+       my ($self) = @_;
+       close($_) for (grep { defined } (delete @$self{0..2}));
+}
+
 sub wq_worker_loop ($) {
        my ($self) = @_;
        my $buf;
        my $len = $self->{wq_req_len} // (4096 * 33);
-       my ($rec, $sub, @args);
+       my ($sub, $args);
        my $s2 = $self->{-wq_s2} // die 'BUG: no -wq_s2';
-       until ($self->{-wq_quit}) {
-               my (@fds) = $recv_cmd->($s2, $buf, $len) or return; # EOF
+       local $SIG{PIPE} = sub {
+               my $cur_sub = $sub;
+               _close_recvd($self);
+               die(bless(\$cur_sub, __PACKAGE__.'::PIPE')) if $cur_sub;
+       };
+       my $rcv = $self->{-wq_recv_cmd} // $recv_cmd;
+       while (1) {
+               my (@fds) = $rcv->($s2, $buf, $len) or return; # EOF
                my $i = 0;
                my @m = @{$self->{wq_open_modes} // [qw( +<&= >&= >&= )]};
                for my $fd (@fds) {
                        my $mode = shift(@m);
-                       if (open(my $fh, $mode, $fd)) {
-                               $self->{$i++} = $fh;
+                       if (open(my $cmdfh, $mode, $fd)) {
+                               $self->{$i++} = $cmdfh;
+                               $cmdfh->autoflush(1);
                        } else {
                                die "$$ open($mode$fd) (FD:$i): $!";
                        }
                }
-               # Sereal dies, Storable returns undef
-               $rec = thaw($buf) //
+               # Sereal dies on truncated data, Storable returns undef
+               $args = thaw($buf) //
                        die "thaw error on buffer of size:".length($buf);
-               ($sub, @args) = @$rec;
-               eval { $self->$sub(@args) };
-               warn "$$ wq_worker: $@" if $@;
-               delete @$self{0, 1, 2};
+               eval {
+                       $sub = shift @$args;
+                       eval { $self->$sub(@$args) };
+                       undef $sub; # quiet SIG{PIPE} handler
+                       die $@ if $@;
+               };
+               warn "$$ wq_worker: $@" if $@ && ref $@ ne __PACKAGE__.'::PIPE';
+               # need to close explicitly to avoid warnings after SIGPIPE
+               _close_recvd($self);
        }
 }
 
 sub wq_do { # always async
-       my ($self, $sub, $in, $out, $err, @args) = @_;
+       my ($self, $sub, $ios, @args) = @_;
        if (my $s1 = $self->{-wq_s1}) { # run in worker
-               $_ = fileno($_) for ($in, $out, $err);
-               $send_cmd->($s1, $in, $out, $err,
-                               freeze([$sub, @args]), MSG_EOR);
+               my $fds = [ map { fileno($_) } @$ios ];
+               $send_cmd->($s1, $fds, freeze([$sub, @args]), MSG_EOR);
        } else {
-               @$self{0, 1, 2} = ($in, $out, $err);
+               @$self{0..$#$ios} = @$ios;
                eval { $self->$sub(@args) };
                warn "wq_do: $@" if $@;
-               delete @$self{0, 1, 2};
+               delete @$self{0..$#$ios};
        }
 }
 
@@ -277,16 +321,18 @@ sub _wq_worker_start ($$) {
        if ($pid == 0) {
                eval { PublicInbox::DS->Reset };
                close(delete $self->{-wq_s1});
-               delete $self->{qw(-wq_workers -wq_quit)};
-               my $quit = sub { $self->{-wq_quit} = 1 };
-               $SIG{$_} = $quit for (qw(TERM INT QUIT));
-               $SIG{$_} = 'IGNORE' for (qw(TTOU TTIN));
+               delete $self->{qw(-wq_workers -wq_ppid)};
+               $SIG{$_} = 'IGNORE' for (qw(PIPE TTOU TTIN));
+               $SIG{$_} = 'DEFAULT' for (qw(TERM QUIT INT CHLD));
                local $0 = $self->{-wq_ident};
                PublicInbox::DS::sig_setmask($oldset);
+               # ensure we properly exit even if warn() dies:
+               my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
                my $on_destroy = $self->ipc_atfork_child;
                eval { wq_worker_loop($self) };
-               die "worker $self->{-wq_ident} PID:$$ died: $@\n" if $@;
-               exit;
+               warn "worker $self->{-wq_ident} PID:$$ died: $@" if $@;
+               undef $on_destroy;
+               undef $end; # trigger exit
        } else {
                $self->{-wq_workers}->{$pid} = \undef;
        }
@@ -299,8 +345,9 @@ sub wq_workers_start {
        return if $self->{-wq_s1}; # idempotent
        my ($s1, $s2);
        socketpair($s1, $s2, AF_UNIX, $SEQPACKET, 0) or die "socketpair: $!";
-       $self->ipc_atfork_parent;
+       $self->ipc_atfork_prepare;
        $nr_workers //= 4;
+       $nr_workers = $WQ_MAX_WORKERS if $nr_workers > $WQ_MAX_WORKERS;
        my $sigset = $oldset // PublicInbox::DS::block_signals();
        $self->{-wq_workers} = {};
        $self->{-wq_ident} = $ident;
@@ -314,7 +361,8 @@ sub wq_workers_start {
 sub wq_worker_incr { # SIGTTIN handler
        my ($self, $oldset) = @_;
        $self->{-wq_s2} or return;
-       $self->ipc_atfork_parent;
+       return if wq_workers($self) >= $WQ_MAX_WORKERS;
+       $self->ipc_atfork_prepare;
        my $sigset = $oldset // PublicInbox::DS::block_signals();
        _wq_worker_start($self, $sigset);
        PublicInbox::DS::sig_setmask($sigset) unless $oldset;
@@ -327,10 +375,9 @@ sub wq_exit { # wakes up wq_worker_decr_wait
 
 sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
        my ($self) = @_;
-       my $workers = $self->{-wq_workers} or return;
+       return unless wq_workers($self);
        my $s2 = $self->{-wq_s2} // die 'BUG: no wq_s2';
-       $self->wq_do('wq_exit', $s2, $s2, $s2);
-       $self->{-wq_exit_pending}++;
+       $self->wq_do('wq_exit', [ $s2, $s2, $s2 ]);
        # caller must call wq_worker_decr_wait in main loop
 }
 
@@ -344,14 +391,27 @@ sub wq_worker_decr_wait {
        recv($s1, my $pid, 64, 0) // croak "recv: $!";
        my $workers = $self->{-wq_workers} // croak 'BUG: no wq_workers';
        delete $workers->{$pid} // croak "BUG: PID:$pid invalid";
-       $self->{-wq_exit_pending}--;
        dwaitpid($pid, \&ipc_worker_reap, $self);
 }
 
+# set or retrieve number of workers
+sub wq_workers {
+       my ($self, $nr) = @_;
+       my $cur = $self->{-wq_workers} or return;
+       if (defined $nr) {
+               while (scalar(keys(%$cur)) > $nr) {
+                       $self->wq_worker_decr;
+                       $self->wq_worker_decr_wait;
+               }
+               $self->wq_worker_incr while scalar(keys(%$cur)) < $nr;
+       }
+       scalar(keys(%$cur));
+}
+
 sub wq_close {
        my ($self) = @_;
        delete @$self{qw(-wq_s1 -wq_s2)} or return;
-       my $ppid = delete $self->{-wq_ppid} // die 'BUG: no wq_ppid';
+       my $ppid = delete $self->{-wq_ppid} or return;
        my $workers = delete $self->{-wq_workers} // die 'BUG: no wq_workers';
        return if $ppid != $$; # can't reap siblings or parents
        for my $pid (keys %$workers) {
@@ -359,4 +419,11 @@ sub wq_close {
        }
 }
 
+sub WQ_MAX_WORKERS { $WQ_MAX_WORKERS }
+
+sub DESTROY {
+       wq_close($_[0]);
+       ipc_worker_stop($_[0]);
+}
+
 1;