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