]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: flatten + reuse @events, epoll_wait style fixes
[public-inbox.git] / lib / PublicInbox / DS.pm
1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
3 #
4 # This license differs from the rest of public-inbox
5 #
6 # This is a fork of the unmaintained Danga::Socket (1.61) with
7 # significant changes.  See Documentation/technical/ds.txt in our
8 # source for details.
9 #
10 # Do not expect this to be a stable API like Danga::Socket,
11 # but it will evolve to suite our needs and to take advantage of
12 # newer Linux and *BSD features.
13 # Bugs encountered were reported to bug-Danga-Socket@rt.cpan.org,
14 # fixed in Danga::Socket 1.62 and visible at:
15 # https://rt.cpan.org/Public/Dist/Display.html?Name=Danga-Socket
16 #
17 # fields:
18 # sock: underlying socket
19 # rbuf: scalarref, usually undef
20 # wbuf: arrayref of coderefs or tmpio (autovivified))
21 #        (tmpio = [ GLOB, offset, [ length ] ])
22 package PublicInbox::DS;
23 use strict;
24 use bytes;
25 use POSIX qw(WNOHANG);
26 use IO::Handle qw();
27 use Fcntl qw(SEEK_SET :DEFAULT O_APPEND);
28 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
29 use parent qw(Exporter);
30 our @EXPORT_OK = qw(now msg_more);
31 use 5.010_001;
32 use Scalar::Util qw(blessed);
33 use PublicInbox::Syscall qw(:epoll);
34 use PublicInbox::Tmpfile;
35 use Errno qw(EAGAIN EINVAL);
36 use Carp qw(confess carp);
37
38 my $nextq; # queue for next_tick
39 my $wait_pids; # list of [ pid, callback, callback_arg ]
40 my $later_queue; # list of callbacks to run at some later interval
41 my $EXPMAP; # fd -> idle_time
42 our $EXPTIME = 180; # 3 minutes
43 my ($later_timer, $reap_armed, $exp_timer);
44 my $ToClose; # sockets to close when event loop is done
45 our (
46      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
47      $Epoll,                     # Global epoll fd (or DSKQXS ref)
48      $_io,                       # IO::Handle for Epoll
49
50      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
51
52      $LoopTimeout,               # timeout of event loop in milliseconds
53      @Timers,                    # timers
54      $in_loop,
55      );
56
57 Reset();
58
59 #####################################################################
60 ### C L A S S   M E T H O D S
61 #####################################################################
62
63 =head2 C<< CLASS->Reset() >>
64
65 Reset all state
66
67 =cut
68 sub Reset {
69     %DescriptorMap = ();
70     $in_loop = $wait_pids = $later_queue = $reap_armed = undef;
71     $EXPMAP = {};
72     $nextq = $ToClose = $later_timer = $exp_timer = undef;
73     $LoopTimeout = -1;  # no timeout by default
74     @Timers = ();
75
76     $PostLoopCallback = undef;
77
78     $_io = undef; # closes real $Epoll FD
79     $Epoll = undef; # may call DSKQXS::DESTROY
80 }
81
82 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
83
84 Set the loop timeout for the event loop to some value in milliseconds.
85
86 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
87 immediately.
88
89 =cut
90 sub SetLoopTimeout { $LoopTimeout = $_[1] + 0 }
91
92 =head2 C<< PublicInbox::DS::add_timer( $seconds, $coderef, $arg) >>
93
94 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
95 are not guaranteed to fire at the exact time you ask for.
96
97 =cut
98 sub add_timer ($$;$) {
99     my ($secs, $coderef, $arg) = @_;
100
101     my $fire_time = now() + $secs;
102
103     my $timer = [$fire_time, $coderef, $arg];
104
105     if (!@Timers || $fire_time >= $Timers[-1][0]) {
106         push @Timers, $timer;
107         return $timer;
108     }
109
110     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
111     # but it was compared against calendar queues, heaps, naive push/sort,
112     # and a bunch of other versions, and found to be fastest with a large
113     # variety of datasets.)
114     for (my $i = 0; $i < @Timers; $i++) {
115         if ($Timers[$i][0] > $fire_time) {
116             splice(@Timers, $i, 0, $timer);
117             return $timer;
118         }
119     }
120
121     die "Shouldn't get here.";
122 }
123
124 # keeping this around in case we support other FD types for now,
125 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
126 sub set_cloexec ($) {
127     my ($fd) = @_;
128
129     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
130     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
131     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
132 }
133
134 # caller sets return value to $Epoll
135 sub _InitPoller
136 {
137     if (PublicInbox::Syscall::epoll_defined())  {
138         my $fd = epoll_create();
139         set_cloexec($fd) if (defined($fd) && $fd >= 0);
140         $fd;
141     } else {
142         my $cls;
143         for (qw(DSKQXS DSPoll)) {
144             $cls = "PublicInbox::$_";
145             last if eval "require $cls";
146         }
147         $cls->import(qw(epoll_ctl epoll_wait));
148         $cls->new;
149     }
150 }
151
152 =head2 C<< CLASS->EventLoop() >>
153
154 Start processing IO events. In most daemon programs this never exits. See
155 C<PostLoopCallback> below for how to exit the loop.
156
157 =cut
158
159 sub now () { clock_gettime(CLOCK_MONOTONIC) }
160
161 sub next_tick () {
162     my $q = $nextq or return;
163     $nextq = undef;
164     for (@$q) {
165         # we avoid "ref" on blessed refs to workaround a Perl 5.16.3 leak:
166         # https://rt.perl.org/Public/Bug/Display.html?id=114340
167         if (blessed($_)) {
168             $_->event_step;
169         } else {
170             $_->();
171         }
172     }
173 }
174
175 # runs timers and returns milliseconds for next one, or next event loop
176 sub RunTimers {
177     next_tick();
178
179     return (($nextq || $ToClose) ? 0 : $LoopTimeout) unless @Timers;
180
181     my $now = now();
182
183     # Run expired timers
184     while (@Timers && $Timers[0][0] <= $now) {
185         my $to_run = shift(@Timers);
186         $to_run->[1]->($to_run->[2]);
187     }
188
189     # timers may enqueue into nextq:
190     return 0 if ($nextq || $ToClose);
191
192     return $LoopTimeout unless @Timers;
193
194     # convert time to an even number of milliseconds, adding 1
195     # extra, otherwise floating point fun can occur and we'll
196     # call RunTimers like 20-30 times, each returning a timeout
197     # of 0.0000212 seconds
198     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
199
200     # -1 is an infinite timeout, so prefer a real timeout
201     ($LoopTimeout < 0 || $LoopTimeout >= $timeout) ? $timeout : $LoopTimeout;
202 }
203
204 # We can't use waitpid(-1) safely here since it can hit ``, system(),
205 # and other things.  So we scan the $wait_pids list, which is hopefully
206 # not too big.  We keep $wait_pids small by not calling dwaitpid()
207 # until we've hit EOF when reading the stdout of the child.
208
209 sub reap_pids {
210         $reap_armed = undef;
211         my $tmp = $wait_pids or return;
212         $wait_pids = undef;
213         foreach my $ary (@$tmp) {
214                 my ($pid, $cb, $arg) = @$ary;
215                 my $ret = waitpid($pid, WNOHANG);
216                 if ($ret == 0) {
217                         push @$wait_pids, $ary; # autovivifies @$wait_pids
218                 } elsif ($cb) {
219                         eval { $cb->($arg, $pid) };
220                 }
221         }
222         # we may not be done, yet, and could've missed/masked a SIGCHLD:
223         $reap_armed //= requeue(\&reap_pids) if $wait_pids;
224 }
225
226 # reentrant SIGCHLD handler (since reap_pids is not reentrant)
227 sub enqueue_reap () { $reap_armed //= requeue(\&reap_pids) }
228
229 sub in_loop () { $in_loop }
230
231 # Internal function: run the post-event callback, send read events
232 # for pushed-back data, and close pending connections.  returns 1
233 # if event loop should continue, or 0 to shut it all down.
234 sub PostEventLoop () {
235         # now we can close sockets that wanted to close during our event
236         # processing.  (we didn't want to close them during the loop, as we
237         # didn't want fd numbers being reused and confused during the event
238         # loop)
239         if (my $close_now = $ToClose) {
240                 $ToClose = undef; # will be autovivified on push
241                 @$close_now = map { fileno($_) } @$close_now;
242
243                 # order matters, destroy expiry times, first:
244                 delete @$EXPMAP{@$close_now};
245
246                 # ->DESTROY methods may populate ToClose
247                 delete @DescriptorMap{@$close_now};
248         }
249
250         # by default we keep running, unless a postloop callback cancels it
251         $PostLoopCallback ? $PostLoopCallback->(\%DescriptorMap) : 1;
252 }
253
254 sub EventLoop {
255     $Epoll //= _InitPoller();
256     local $in_loop = 1;
257     my @events;
258     do {
259         my $timeout = RunTimers();
260
261         # get up to 1000 events
262         epoll_wait($Epoll, 1000, $timeout, \@events);
263         for my $fd (@events) {
264             # it's possible epoll_wait returned many events, including some at the end
265             # that ones in the front triggered unregister-interest actions.  if we
266             # can't find the %sock entry, it's because we're no longer interested
267             # in that event.
268             $DescriptorMap{$fd}->event_step;
269         }
270     } while (PostEventLoop());
271     _run_later();
272 }
273
274 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
275
276 Sets post loop callback function.  Pass a subref and it will be
277 called every time the event loop finishes.
278
279 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
280 and it will exit.
281
282 The callback function will be passed two parameters: \%DescriptorMap
283
284 =cut
285 sub SetPostLoopCallback {
286     my ($class, $ref) = @_;
287
288     # global callback
289     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
290 }
291
292 #####################################################################
293 ### PublicInbox::DS-the-object code
294 #####################################################################
295
296 =head2 OBJECT METHODS
297
298 =head2 C<< CLASS->new( $socket ) >>
299
300 Create a new PublicInbox::DS subclass object for the given I<socket> which will
301 react to events on it during the C<EventLoop>.
302
303 This is normally (always?) called from your subclass via:
304
305   $class->SUPER::new($socket);
306
307 =cut
308 sub new {
309     my ($self, $sock, $ev) = @_;
310     $self->{sock} = $sock;
311     my $fd = fileno($sock);
312
313     $Epoll //= _InitPoller();
314 retry:
315     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
316         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
317             $ev &= ~EPOLLEXCLUSIVE;
318             goto retry;
319         }
320         die "couldn't add epoll watch for $fd: $!\n";
321     }
322     confess("DescriptorMap{$fd} defined ($DescriptorMap{$fd})")
323         if defined($DescriptorMap{$fd});
324
325     $DescriptorMap{$fd} = $self;
326 }
327
328
329 #####################################################################
330 ### I N S T A N C E   M E T H O D S
331 #####################################################################
332
333 sub requeue ($) { push @$nextq, $_[0] } # autovivifies
334
335 =head2 C<< $obj->close >>
336
337 Close the socket.
338
339 =cut
340 sub close {
341     my ($self) = @_;
342     my $sock = delete $self->{sock} or return;
343
344     # we need to flush our write buffer, as there may
345     # be self-referential closures (sub { $client->close })
346     # preventing the object from being destroyed
347     delete $self->{wbuf};
348
349     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
350     # notifications about it
351     my $fd = fileno($sock);
352     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
353         confess("EPOLL_CTL_DEL: $!");
354
355     # we explicitly don't delete from DescriptorMap here until we
356     # actually close the socket, as we might be in the middle of
357     # processing an epoll_wait/etc that returned hundreds of fds, one
358     # of which is not yet processed and is what we're closing.  if we
359     # keep it in DescriptorMap, then the event harnesses can just
360     # looked at $pob->{sock} == undef and ignore it.  but if it's an
361     # un-accounted for fd, then it (understandably) freak out a bit
362     # and emit warnings, thinking their state got off.
363
364     # defer closing the actual socket until the event loop is done
365     # processing this round of events.  (otherwise we might reuse fds)
366     push @$ToClose, $sock; # autovivifies $ToClose
367
368     return 0;
369 }
370
371 # portable, non-thread-safe sendfile emulation (no pread, yet)
372 sub send_tmpio ($$) {
373     my ($sock, $tmpio) = @_;
374
375     sysseek($tmpio->[0], $tmpio->[1], SEEK_SET) or return;
376     my $n = $tmpio->[2] // 65536;
377     $n = 65536 if $n > 65536;
378     defined(my $to_write = sysread($tmpio->[0], my $buf, $n)) or return;
379     my $written = 0;
380     while ($to_write > 0) {
381         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
382             $written += $w;
383             $to_write -= $w;
384         } else {
385             return if $written == 0;
386             last;
387         }
388     }
389     $tmpio->[1] += $written; # offset
390     $tmpio->[2] -= $written if defined($tmpio->[2]); # length
391     $written;
392 }
393
394 sub epbit ($$) { # (sock, default)
395         $_[0]->can('stop_SSL') ? PublicInbox::TLS::epollbit() : $_[1];
396 }
397
398 # returns 1 if done, 0 if incomplete
399 sub flush_write ($) {
400     my ($self) = @_;
401     my $sock = $self->{sock} or return;
402     my $wbuf = $self->{wbuf} or return 1;
403
404 next_buf:
405     while (my $bref = $wbuf->[0]) {
406         if (ref($bref) ne 'CODE') {
407             while ($sock) {
408                 my $w = send_tmpio($sock, $bref); # bref is tmpio
409                 if (defined $w) {
410                     if ($w == 0) {
411                         shift @$wbuf;
412                         goto next_buf;
413                     }
414                 } elsif ($! == EAGAIN) {
415                     my $ev = epbit($sock, EPOLLOUT) or return $self->close;
416                     epwait($sock, $ev | EPOLLONESHOT);
417                     return 0;
418                 } else {
419                     return $self->close;
420                 }
421             }
422         } else { #(ref($bref) eq 'CODE') {
423             shift @$wbuf;
424             my $before = scalar(@$wbuf);
425             $bref->($self);
426
427             # bref may be enqueueing more CODE to call (see accept_tls_step)
428             return 0 if (scalar(@$wbuf) > $before);
429         }
430     } # while @$wbuf
431
432     delete $self->{wbuf};
433     1; # all done
434 }
435
436 sub rbuf_idle ($$) {
437     my ($self, $rbuf) = @_;
438     if ($$rbuf eq '') { # who knows how long till we can read again
439         delete $self->{rbuf};
440     } else {
441         $self->{rbuf} = $rbuf;
442     }
443 }
444
445 sub do_read ($$$;$) {
446     my ($self, $rbuf, $len, $off) = @_;
447     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
448     return ($r == 0 ? $self->close : $r) if defined $r;
449     # common for clients to break connections without warning,
450     # would be too noisy to log here:
451     if ($! == EAGAIN) {
452         my $ev = epbit($sock, EPOLLIN) or return $self->close;
453         epwait($sock, $ev | EPOLLONESHOT);
454         rbuf_idle($self, $rbuf);
455         0;
456     } else {
457         $self->close;
458     }
459 }
460
461 # drop the socket if we hit unrecoverable errors on our system which
462 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
463 sub drop {
464     my $self = shift;
465     carp(@_);
466     $self->close;
467 }
468
469 # n.b.: use ->write/->read for this buffer to allow compatibility with
470 # PerlIO::mmap or PerlIO::scalar if needed
471 sub tmpio ($$$) {
472     my ($self, $bref, $off) = @_;
473     my $fh = tmpfile('wbuf', $self->{sock}, O_APPEND) or
474         return drop($self, "tmpfile $!");
475     $fh->autoflush(1);
476     my $len = bytes::length($$bref) - $off;
477     $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
478     [ $fh, 0 ] # [1] = offset, [2] = length, not set by us
479 }
480
481 =head2 C<< $obj->write( $data ) >>
482
483 Write the specified data to the underlying handle.  I<data> may be scalar,
484 scalar ref, code ref (to run when there).
485 Returns 1 if writes all went through, or 0 if there are writes in queue. If
486 it returns 1, caller should stop waiting for 'writable' events)
487
488 =cut
489 sub write {
490     my ($self, $data) = @_;
491
492     # nobody should be writing to closed sockets, but caller code can
493     # do two writes within an event, have the first fail and
494     # disconnect the other side (whose destructor then closes the
495     # calling object, but it's still in a method), and then the
496     # now-dead object does its second write.  that is this case.  we
497     # just lie and say it worked.  it'll be dead soon and won't be
498     # hurt by this lie.
499     my $sock = $self->{sock} or return 1;
500     my $ref = ref $data;
501     my $bref = $ref ? $data : \$data;
502     my $wbuf = $self->{wbuf};
503     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
504         if ($ref eq 'CODE') {
505             push @$wbuf, $bref;
506         } else {
507             my $tmpio = $wbuf->[-1];
508             if ($tmpio && !defined($tmpio->[2])) { # append to tmp file buffer
509                 $tmpio->[0]->print($$bref) or return drop($self, "print: $!");
510             } else {
511                 my $tmpio = tmpio($self, $bref, 0) or return 0;
512                 push @$wbuf, $tmpio;
513             }
514         }
515         return 0;
516     } elsif ($ref eq 'CODE') {
517         $bref->($self);
518         return 1;
519     } else {
520         my $to_write = bytes::length($$bref);
521         my $written = syswrite($sock, $$bref, $to_write);
522
523         if (defined $written) {
524             return 1 if $written == $to_write;
525             requeue($self); # runs: event_step -> flush_write
526         } elsif ($! == EAGAIN) {
527             my $ev = epbit($sock, EPOLLOUT) or return $self->close;
528             epwait($sock, $ev | EPOLLONESHOT);
529             $written = 0;
530         } else {
531             return $self->close;
532         }
533
534         # deal with EAGAIN or partial write:
535         my $tmpio = tmpio($self, $bref, $written) or return 0;
536
537         # wbuf may be an empty array if we're being called inside
538         # ->flush_write via CODE bref:
539         push @{$self->{wbuf}}, $tmpio; # autovivifies
540         return 0;
541     }
542 }
543
544 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
545
546 sub msg_more ($$) {
547     my $self = $_[0];
548     my $sock = $self->{sock} or return 1;
549     my $wbuf = $self->{wbuf};
550
551     if (MSG_MORE && (!defined($wbuf) || !scalar(@$wbuf)) &&
552                 !$sock->can('stop_SSL')) {
553         my $n = send($sock, $_[1], MSG_MORE);
554         if (defined $n) {
555             my $nlen = bytes::length($_[1]) - $n;
556             return 1 if $nlen == 0; # all done!
557             # queue up the unwritten substring:
558             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
559             push @{$self->{wbuf}}, $tmpio; # autovivifies
560             epwait($sock, EPOLLOUT|EPOLLONESHOT);
561             return 0;
562         }
563     }
564
565     # don't redispatch into NNTPdeflate::write
566     PublicInbox::DS::write($self, \($_[1]));
567 }
568
569 sub epwait ($$) {
570     my ($sock, $ev) = @_;
571     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
572         confess("EPOLL_CTL_MOD $!");
573 }
574
575 # return true if complete, false if incomplete (or failure)
576 sub accept_tls_step ($) {
577     my ($self) = @_;
578     my $sock = $self->{sock} or return;
579     return 1 if $sock->accept_SSL;
580     return $self->close if $! != EAGAIN;
581     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
582     epwait($sock, $ev | EPOLLONESHOT);
583     unshift(@{$self->{wbuf}}, \&accept_tls_step); # autovivifies
584     0;
585 }
586
587 # return true if complete, false if incomplete (or failure)
588 sub shutdn_tls_step ($) {
589     my ($self) = @_;
590     my $sock = $self->{sock} or return;
591     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
592     return $self->close if $! != EAGAIN;
593     my $ev = PublicInbox::TLS::epollbit() or return $self->close;
594     epwait($sock, $ev | EPOLLONESHOT);
595     unshift(@{$self->{wbuf}}, \&shutdn_tls_step); # autovivifies
596     0;
597 }
598
599 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
600 # or fork w/o exec, so no inadvertent socket sharing
601 sub shutdn ($) {
602     my ($self) = @_;
603     my $sock = $self->{sock} or return;
604     if ($sock->can('stop_SSL')) {
605         shutdn_tls_step($self);
606     } else {
607         $self->close;
608     }
609 }
610
611 # must be called with eval, PublicInbox::DS may not be loaded (see t/qspawn.t)
612 sub dwaitpid ($$$) {
613         die "Not in EventLoop\n" unless $in_loop;
614         push @$wait_pids, [ @_ ]; # [ $pid, $cb, $arg ]
615
616         # We could've just missed our SIGCHLD, cover it, here:
617         enqueue_reap();
618 }
619
620 sub _run_later () {
621         my $run = $later_queue or return;
622         $later_timer = $later_queue = undef;
623         $_->() for @$run;
624 }
625
626 sub later ($) {
627         push @$later_queue, $_[0]; # autovivifies @$later_queue
628         $later_timer //= add_timer(60, \&_run_later);
629 }
630
631 sub expire_old () {
632         my $now = now();
633         my $exp = $EXPTIME;
634         my $old = $now - $exp;
635         my %new;
636         while (my ($fd, $idle_at) = each %$EXPMAP) {
637                 if ($idle_at < $old) {
638                         my $ds_obj = $DescriptorMap{$fd};
639                         $new{$fd} = $idle_at if !$ds_obj->shutdn;
640                 } else {
641                         $new{$fd} = $idle_at;
642                 }
643         }
644         $EXPMAP = \%new;
645         $exp_timer = scalar(keys %new) ? later(\&expire_old) : undef;
646 }
647
648 sub update_idle_time {
649         my ($self) = @_;
650         my $sock = $self->{sock} or return;
651         $EXPMAP->{fileno($sock)} = now();
652         $exp_timer //= later(\&expire_old);
653 }
654
655 sub not_idle_long {
656         my ($self, $now) = @_;
657         my $sock = $self->{sock} or return;
658         my $idle_at = $EXPMAP->{fileno($sock)} or return;
659         ($idle_at + $EXPTIME) > $now;
660 }
661
662 1;
663
664 =head1 AUTHORS (Danga::Socket)
665
666 Brad Fitzpatrick <brad@danga.com> - author
667
668 Michael Granger <ged@danga.com> - docs, testing
669
670 Mark Smith <junior@danga.com> - contributor, heavy user, testing
671
672 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits