]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/IPC.pm
ipc: wq_do => wq_io_do
[public-inbox.git] / lib / PublicInbox / IPC.pm
index 50de1bed22d71ba4ac72cc3a6f781368907881c3..728f726c4adb99a47891536ebe3d959c4d75f7fc 100644 (file)
@@ -3,22 +3,21 @@
 
 # base class for remote IPC calls and workqueues, requires Storable or Sereal
 # - ipc_do and ipc_worker_* is for a single worker/producer and uses pipes
-# - wq_do and wq_worker* is for a single producer and multiple workers,
+# - wq_io_do and wq_worker* is for a single producer and multiple workers,
 #   using SOCK_SEQPACKET for work distribution
 # use ipc_do when you need work done on a certain process
-# use wq_do when your work can be done on any idle worker
+# use wq_io_do when your work can be done on any idle worker
 package PublicInbox::IPC;
 use strict;
 use v5.10.1;
 use parent qw(Exporter);
-use Carp qw(confess croak);
+use Carp qw(croak);
 use PublicInbox::DS qw(dwaitpid);
 use PublicInbox::Spawn;
 use PublicInbox::OnDestroy;
 use PublicInbox::WQWorker;
 use Socket qw(AF_UNIX MSG_EOR SOCK_STREAM);
 my $SEQPACKET = eval { Socket::SOCK_SEQPACKET() }; # portable enough?
-use constant PIPE_BUF => $^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF();
 our @EXPORT_OK = qw(ipc_freeze ipc_thaw);
 my $WQ_MAX_WORKERS = 4096;
 my ($enc, $dec);
@@ -38,12 +37,9 @@ if ($enc && $dec) { # should be custom ops
        *ipc_freeze = sub ($) { sereal_encode_with_object $enc, $_[0] };
        *ipc_thaw = sub ($) { sereal_decode_with_object $dec, $_[0], my $ret };
 } else {
-       eval { # some distros have Storable as a separate package from Perl
-               require Storable;
-               *ipc_freeze = \&Storable::freeze;
-               *ipc_thaw = \&Storable::thaw;
-               $enc = 1;
-       } // warn("Storable (part of Perl) missing: $@\n");
+       require Storable;
+       *ipc_freeze = \&Storable::freeze;
+       *ipc_thaw = \&Storable::thaw;
 }
 
 my $recv_cmd = PublicInbox::Spawn->can('recv_cmd4');
@@ -62,15 +58,10 @@ sub _get_rec ($) {
        ipc_thaw($buf);
 }
 
-sub _pack_rec ($) {
-       my ($ref) = @_;
-       my $buf = ipc_freeze($ref);
-       length($buf) . "\n" . $buf;
-}
-
 sub _send_rec ($$) {
        my ($w, $ref) = @_;
-       print $w _pack_rec($ref) or croak "print: $!";
+       my $buf = ipc_freeze($ref);
+       print $w length($buf), "\n", $buf or croak "print: $!";
 }
 
 sub ipc_return ($$$) {
@@ -101,8 +92,7 @@ sub ipc_worker_loop ($$$) {
 
 # starts a worker if Sereal or Storable is installed
 sub ipc_worker_spawn {
-       my ($self, $ident, $oldset) = @_;
-       return unless $enc; # no Sereal or Storable
+       my ($self, $ident, $oldset, $fields) = @_;
        return if ($self->{-ipc_ppid} // -1) == $$; # idempotent
        delete(@$self{qw(-ipc_req -ipc_res -ipc_ppid -ipc_pid)});
        pipe(my ($r_req, $w_req)) or die "pipe: $!";
@@ -123,11 +113,13 @@ sub ipc_worker_spawn {
                # ensure we properly exit even if warn() dies:
                my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
                eval {
+                       $fields //= {};
+                       local @$self{keys %$fields} = values(%$fields);
                        my $on_destroy = $self->ipc_atfork_child;
                        local %SIG = %SIG;
                        ipc_worker_loop($self, $r_req, $w_res);
                };
-               die "worker $ident PID:$$ died: $@\n" if $@;
+               warn "worker $ident PID:$$ died: $@\n" if $@;
                undef $end; # trigger exit
        }
        PublicInbox::DS::sig_setmask($sigset) unless $oldset;
@@ -148,9 +140,10 @@ sub ipc_worker_reap { # dwaitpid callback
 }
 
 sub wq_wait_old {
-       my ($self, $args) = @_;
+       my ($self, @args) = @_;
+       my $cb = ref($args[0]) eq 'CODE' ? shift(@args) : \&ipc_worker_reap;
        my $pids = delete $self->{"-wq_old_pids.$$"} or return;
-       dwaitpid($_, \&ipc_worker_reap, [$self, $args]) for @$pids;
+       dwaitpid($_, $cb, [$self, @args]) for @$pids;
 }
 
 # for base class, override in sub classes
@@ -189,21 +182,6 @@ sub ipc_lock_init {
        $self->{-ipc_lock} //= bless { lock_path => $f }, 'PublicInbox::Lock'
 }
 
-sub ipc_async_wait ($$) {
-       my ($self, $max) = @_; # max == -1 to wait for all
-       my $aif = $self->{-async_inflight} or return;
-       my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
-       while (my ($sub, $bytes, $cb, $cb_arg) = splice(@$aif, 0, 4)) {
-               my $ret = _get_rec($r_res) //
-                       die "no response on $sub (req.size=$bytes)";
-               $self->{-async_inflight_bytes} -= $bytes;
-
-               eval { $cb->($cb_arg, $ret) };
-               warn "E: $sub callback error: $@\n" if $@;
-               return if --$max == 0;
-       }
-}
-
 # call $self->$sub(@args), on a worker if ipc_worker_spawn was used
 sub ipc_do {
        my ($self, $sub, @args) = @_;
@@ -211,8 +189,7 @@ sub ipc_do {
                my $ipc_lock = $self->{-ipc_lock};
                my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
                if (defined(wantarray)) {
-                       my $r_res = $self->{-ipc_res} or die 'BUG: no ipc_res';
-                       ipc_async_wait($self, -1);
+                       my $r_res = $self->{-ipc_res} or die 'no ipc_res';
                        _send_rec($w_req, [ wantarray, $sub, @args ]);
                        my $ret = _get_rec($r_res) // die "no response on $sub";
                        die $$ret if ref($ret) eq 'PublicInbox::IPC::Die';
@@ -225,30 +202,6 @@ sub ipc_do {
        }
 }
 
-sub ipc_async {
-       my ($self, $sub, $sub_args, $cb, $cb_arg) = @_;
-       if (my $w_req = $self->{-ipc_req}) { # run in worker
-               my $rec = _pack_rec([ 1, $sub, @$sub_args ]);
-               my $cur_bytes = \($self->{-async_inflight_bytes} //= 0);
-               while (($$cur_bytes + length($rec)) > PIPE_BUF) {
-                       ipc_async_wait($self, 1);
-               }
-               my $ipc_lock = $self->{-ipc_lock};
-               my $lock = $ipc_lock ? $ipc_lock->lock_for_scope : undef;
-               print $w_req $rec or croak "print: $!";
-               $$cur_bytes += length($rec);
-               push @{$self->{-async_inflight}},
-                               $sub, length($rec), $cb, $cb_arg;
-       } else {
-               my $ret = [ eval { $self->$sub(@$sub_args) } ];
-               if (my $exc = $@) {
-                       $ret = ( bless(\$exc, 'PublicInbox::IPC::Die') );
-               }
-               eval { $cb->($cb_arg, $ret) };
-               warn "E: $sub callback error: $@\n" if $@;
-       }
-}
-
 # needed when there's multiple IPC workers and the parent forking
 # causes newer siblings to inherit older siblings sockets
 sub ipc_sibling_atfork_child {
@@ -295,12 +248,12 @@ sub wq_worker_loop ($) {
        PublicInbox::DS->Reset;
 }
 
-sub do_sock_stream { # via wq_do, for big requests
+sub do_sock_stream { # via wq_io_do, for big requests
        my ($self, $len) = @_;
        recv_and_run($self, delete $self->{0}, $len, 1);
 }
 
-sub wq_do { # always async
+sub wq_io_do { # always async
        my ($self, $sub, $ios, @args) = @_;
        if (my $s1 = $self->{-wq_s1}) { # run in worker
                my $fds = [ map { fileno($_) } @$ios ];
@@ -325,7 +278,7 @@ sub wq_do { # always async
        } else {
                @$self{0..$#$ios} = @$ios;
                eval { $self->$sub(@args) };
-               warn "wq_do: $@" if $@;
+               warn "wq_io_do: $@" if $@;
                delete @$self{0..$#$ios}; # don't close
        }
 }
@@ -338,7 +291,6 @@ sub _wq_worker_start ($$$) {
                srand($seed);
                eval { PublicInbox::DS->Reset };
                delete @$self{qw(-wq_s1 -wq_workers -wq_ppid)};
-               @$self{keys %$fields} = values(%$fields) if $fields;
                $SIG{$_} = 'IGNORE' for (qw(PIPE));
                $SIG{$_} = 'DEFAULT' for (qw(TTOU TTIN TERM QUIT INT CHLD));
                local $0 = $self->{-wq_ident};
@@ -346,6 +298,8 @@ sub _wq_worker_start ($$$) {
                # ensure we properly exit even if warn() dies:
                my $end = PublicInbox::OnDestroy->new($$, sub { exit(!!$@) });
                eval {
+                       $fields //= {};
+                       local @$self{keys %$fields} = values(%$fields);
                        my $on_destroy = $self->ipc_atfork_child;
                        local %SIG = %SIG;
                        wq_worker_loop($self);
@@ -360,7 +314,7 @@ sub _wq_worker_start ($$$) {
 # starts workqueue workers if Sereal or Storable is installed
 sub wq_workers_start {
        my ($self, $ident, $nr_workers, $oldset, $fields) = @_;
-       ($enc && $send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
+       ($send_cmd && $recv_cmd && defined($SEQPACKET)) or return;
        return if $self->{-wq_s1}; # idempotent
        $self->{-wq_s1} = $self->{-wq_s2} = undef;
        socketpair($self->{-wq_s1}, $self->{-wq_s2}, AF_UNIX, $SEQPACKET, 0) or
@@ -395,7 +349,7 @@ sub wq_worker_decr { # SIGTTOU handler, kills first idle worker
        my ($self) = @_;
        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_io_do('wq_exit', [ $s2, $s2, $s2 ]);
        # caller must call wq_worker_decr_wait in main loop
 }
 
@@ -463,7 +417,23 @@ sub DESTROY {
        ipc_worker_stop($self);
 }
 
-# Sereal doesn't have dclone
-sub deep_clone { ipc_thaw(ipc_freeze($_[-1])) }
+sub detect_nproc () {
+       # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
+       return POSIX::sysconf(84) if $^O eq 'linux';
+       return POSIX::sysconf(58) if $^O eq 'freebsd';
+       # TODO: more OSes
+
+       # getconf(1) is POSIX, but *NPROCESSORS* vars are not
+       for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
+               `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
+       }
+       for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
+               `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
+       }
+
+       # should we bother with `sysctl hw.ncpu`?  Those only give
+       # us total processor count, not online processor count.
+       undef
+}
 
 1;