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