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