]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
httpd/async: switch to buffering-as-fast-as-possible
[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 (for now) unmaintained Danga::Socket 1.61.
7 # Unused features will be removed, and updates will be made to take
8 # advantage of newer kernels.
9 #
10 # API changes to diverge from Danga::Socket will happen to better
11 # accomodate new features and improve scalability.  Do not expect
12 # this to be a stable API like Danga::Socket.
13 # Bugs encountered (and likely fixed) are reported to
14 # bug-Danga-Socket@rt.cpan.org 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 ();
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
28 use PublicInbox::Syscall qw(:epoll);
29
30 use fields ('sock',              # underlying socket
31             'rbuf',              # scalarref, usually undef
32             'wbuf',              # arrayref of coderefs or GLOB refs
33             'wbuf_off',  # offset into first element of wbuf to start writing at
34             );
35
36 use Errno  qw(EAGAIN EINVAL EEXIST);
37 use Carp   qw(croak confess carp);
38 require File::Spec;
39
40 my $nextq = []; # queue for next_tick
41 our (
42      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
43      $Epoll,                     # Global epoll fd (or DSKQXS ref)
44      $_io,                       # IO::Handle for Epoll
45      @ToClose,                   # sockets to close when event loop is done
46
47      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
48
49      $LoopTimeout,               # timeout of event loop in milliseconds
50      $DoneInit,                  # if we've done the one-time module init yet
51      @Timers,                    # timers
52      );
53
54 Reset();
55
56 #####################################################################
57 ### C L A S S   M E T H O D S
58 #####################################################################
59
60 =head2 C<< CLASS->Reset() >>
61
62 Reset all state
63
64 =cut
65 sub Reset {
66     %DescriptorMap = ();
67     @ToClose = ();
68     $LoopTimeout = -1;  # no timeout by default
69     @Timers = ();
70
71     $PostLoopCallback = undef;
72     $DoneInit = 0;
73
74     $_io = undef; # closes real $Epoll FD
75     $Epoll = undef; # may call DSKQXS::DESTROY
76
77     *EventLoop = *FirstTimeEventLoop;
78 }
79
80 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
81
82 Set the loop timeout for the event loop to some value in milliseconds.
83
84 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
85 immediately.
86
87 =cut
88 sub SetLoopTimeout {
89     return $LoopTimeout = $_[1] + 0;
90 }
91
92 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
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 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
98
99 =cut
100 sub AddTimer {
101     my ($class, $secs, $coderef) = @_;
102
103     my $fire_time = now() + $secs;
104
105     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
106
107     if (!@Timers || $fire_time >= $Timers[-1][0]) {
108         push @Timers, $timer;
109         return $timer;
110     }
111
112     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
113     # but it was compared against calendar queues, heaps, naive push/sort,
114     # and a bunch of other versions, and found to be fastest with a large
115     # variety of datasets.)
116     for (my $i = 0; $i < @Timers; $i++) {
117         if ($Timers[$i][0] > $fire_time) {
118             splice(@Timers, $i, 0, $timer);
119             return $timer;
120         }
121     }
122
123     die "Shouldn't get here.";
124 }
125
126 # keeping this around in case we support other FD types for now,
127 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
128 sub set_cloexec ($) {
129     my ($fd) = @_;
130
131     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
132     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
133     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
134 }
135
136 sub _InitPoller
137 {
138     return if $DoneInit;
139     $DoneInit = 1;
140
141     if (PublicInbox::Syscall::epoll_defined())  {
142         $Epoll = epoll_create();
143         set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
144     } else {
145         my $cls;
146         for (qw(DSKQXS DSPoll)) {
147             $cls = "PublicInbox::$_";
148             last if eval "require $cls";
149         }
150         $cls->import(qw(epoll_ctl epoll_wait));
151         $Epoll = $cls->new;
152     }
153     *EventLoop = *EpollEventLoop;
154 }
155
156 =head2 C<< CLASS->EventLoop() >>
157
158 Start processing IO events. In most daemon programs this never exits. See
159 C<PostLoopCallback> below for how to exit the loop.
160
161 =cut
162 sub FirstTimeEventLoop {
163     my $class = shift;
164
165     _InitPoller();
166
167     EventLoop($class);
168 }
169
170 sub now () { clock_gettime(CLOCK_MONOTONIC) }
171
172 sub next_tick () {
173     my $q = $nextq;
174     $nextq = [];
175     for (@$q) {
176         if (ref($_) eq 'CODE') {
177             $_->();
178         } else {
179             $_->event_step;
180         }
181     }
182 }
183
184 # runs timers and returns milliseconds for next one, or next event loop
185 sub RunTimers {
186     next_tick();
187
188     return ((@$nextq || @ToClose) ? 0 : $LoopTimeout) unless @Timers;
189
190     my $now = now();
191
192     # Run expired timers
193     while (@Timers && $Timers[0][0] <= $now) {
194         my $to_run = shift(@Timers);
195         $to_run->[1]->($now) if $to_run->[1];
196     }
197
198     # timers may enqueue into nextq:
199     return 0 if (@$nextq || @ToClose);
200
201     return $LoopTimeout unless @Timers;
202
203     # convert time to an even number of milliseconds, adding 1
204     # extra, otherwise floating point fun can occur and we'll
205     # call RunTimers like 20-30 times, each returning a timeout
206     # of 0.0000212 seconds
207     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
208
209     # -1 is an infinite timeout, so prefer a real timeout
210     return $timeout     if $LoopTimeout == -1;
211
212     # otherwise pick the lower of our regular timeout and time until
213     # the next timer
214     return $LoopTimeout if $LoopTimeout < $timeout;
215     return $timeout;
216 }
217
218 sub EpollEventLoop {
219     while (1) {
220         my @events;
221         my $i;
222         my $timeout = RunTimers();
223
224         # get up to 1000 events
225         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
226         for ($i=0; $i<$evcount; $i++) {
227             # it's possible epoll_wait returned many events, including some at the end
228             # that ones in the front triggered unregister-interest actions.  if we
229             # can't find the %sock entry, it's because we're no longer interested
230             # in that event.
231             $DescriptorMap{$events[$i]->[0]}->event_step;
232         }
233         return unless PostEventLoop();
234     }
235 }
236
237 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
238
239 Sets post loop callback function.  Pass a subref and it will be
240 called every time the event loop finishes.
241
242 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
243 and it will exit.
244
245 The callback function will be passed two parameters: \%DescriptorMap
246
247 =cut
248 sub SetPostLoopCallback {
249     my ($class, $ref) = @_;
250
251     # global callback
252     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
253 }
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 processing.
260     # (we didn't want to close them during the loop, as we didn't want fd numbers
261     #  being reused and confused during the event loop)
262     while (my $sock = shift @ToClose) {
263         my $fd = fileno($sock);
264
265         # close the socket. (not a PublicInbox::DS close)
266         CORE::close($sock);
267
268         # and now we can finally remove the fd from the map.  see
269         # comment above in ->close.
270         delete $DescriptorMap{$fd};
271     }
272
273
274     # by default we keep running, unless a postloop callback (either per-object
275     # or global) cancels it
276     my $keep_running = 1;
277
278     # now we're at the very end, call callback if defined
279     if (defined $PostLoopCallback) {
280         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
281     }
282
283     return $keep_running;
284 }
285
286 #####################################################################
287 ### PublicInbox::DS-the-object code
288 #####################################################################
289
290 =head2 OBJECT METHODS
291
292 =head2 C<< CLASS->new( $socket ) >>
293
294 Create a new PublicInbox::DS subclass object for the given I<socket> which will
295 react to events on it during the C<EventLoop>.
296
297 This is normally (always?) called from your subclass via:
298
299   $class->SUPER::new($socket);
300
301 =cut
302 sub new {
303     my ($self, $sock, $ev) = @_;
304     $self = fields::new($self) unless ref $self;
305
306     $self->{sock} = $sock;
307     my $fd = fileno($sock);
308
309     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
310         unless $sock && $fd;
311
312     _InitPoller();
313
314     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
315         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
316             $ev &= ~EPOLLEXCLUSIVE;
317             goto retry;
318         }
319         die "couldn't add epoll watch for $fd: $!\n";
320     }
321     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
322         if $DescriptorMap{$fd};
323
324     $DescriptorMap{$fd} = $self;
325     return $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] }
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;
367
368     return 0;
369 }
370
371 # portable, non-thread-safe sendfile emulation (no pread, yet)
372 sub psendfile ($$$) {
373     my ($sock, $fh, $off) = @_;
374
375     seek($fh, $$off, SEEK_SET) or return;
376     defined(my $to_write = read($fh, my $buf, 16384)) or return;
377     my $written = 0;
378     while ($to_write > 0) {
379         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
380             $written += $w;
381             $to_write -= $w;
382         } else {
383             return if $written == 0;
384             last;
385         }
386     }
387     $$off += $written;
388     $written;
389 }
390
391 sub epbit ($$) { # (sock, default)
392     ref($_[0]) eq 'IO::Socket::SSL' ? PublicInbox::TLS::epollbit() : $_[1];
393 }
394
395 # returns 1 if done, 0 if incomplete
396 sub flush_write ($) {
397     my ($self) = @_;
398     my $wbuf = $self->{wbuf} or return 1;
399     my $sock = $self->{sock};
400
401 next_buf:
402     while (my $bref = $wbuf->[0]) {
403         if (ref($bref) ne 'CODE') {
404             my $off = delete($self->{wbuf_off}) // 0;
405             while ($sock) {
406                 my $w = psendfile($sock, $bref, \$off);
407                 if (defined $w) {
408                     if ($w == 0) {
409                         shift @$wbuf;
410                         goto next_buf;
411                     }
412                 } elsif ($! == EAGAIN) {
413                     epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
414                     $self->{wbuf_off} = $off;
415                     return 0;
416                 } else {
417                     return $self->close;
418                 }
419             }
420         } else { #($ref eq 'CODE') {
421             shift @$wbuf;
422             my $before = scalar(@$wbuf);
423             $bref->($self);
424
425             # bref may be enqueueing more CODE to call (see accept_tls_step)
426             return 0 if (scalar(@$wbuf) > $before);
427         }
428     } # while @$wbuf
429
430     delete $self->{wbuf};
431     1; # all done
432 }
433
434 sub rbuf_idle ($$) {
435     my ($self, $rbuf) = @_;
436     if ($$rbuf eq '') { # who knows how long till we can read again
437         delete $self->{rbuf};
438     } else {
439         $self->{rbuf} = $rbuf;
440     }
441 }
442
443 sub do_read ($$$;$) {
444     my ($self, $rbuf, $len, $off) = @_;
445     my $r = sysread(my $sock = $self->{sock}, $$rbuf, $len, $off // 0);
446     return ($r == 0 ? $self->close : $r) if defined $r;
447     # common for clients to break connections without warning,
448     # would be too noisy to log here:
449     if ($! == EAGAIN) {
450         epwait($sock, epbit($sock, EPOLLIN) | EPOLLONESHOT);
451         rbuf_idle($self, $rbuf);
452     } else {
453         $self->close;
454     }
455 }
456
457 # drop the socket if we hit unrecoverable errors on our system which
458 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
459 sub drop {
460     my $self = shift;
461     carp(@_);
462     $self->close;
463 }
464
465 # n.b.: use ->write/->read for this buffer to allow compatibility with
466 # PerlIO::mmap or PerlIO::scalar if needed
467 sub tmpio ($$$) {
468     my ($self, $bref, $off) = @_;
469     my $fh; # open(my $fh, '+>>', undef) doesn't set O_APPEND
470     do {
471         my $fn = File::Spec->tmpdir . '/wbuf-' . rand;
472         if (sysopen($fh, $fn, O_RDWR|O_CREAT|O_EXCL|O_APPEND, 0600)) { # likely
473             unlink($fn) or return drop($self, "unlink($fn) $!");
474         } elsif ($! != EEXIST) { # EMFILE/ENFILE/ENOSPC/ENOMEM
475             return drop($self, "open: $!");
476         }
477     } until (defined $fh);
478     $fh->autoflush(1);
479     my $len = bytes::length($$bref) - $off;
480     $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
481     $fh
482 }
483
484 =head2 C<< $obj->write( $data ) >>
485
486 Write the specified data to the underlying handle.  I<data> may be scalar,
487 scalar ref, code ref (to run when there).
488 Returns 1 if writes all went through, or 0 if there are writes in queue. If
489 it returns 1, caller should stop waiting for 'writable' events)
490
491 =cut
492 sub write {
493     my ($self, $data) = @_;
494
495     # nobody should be writing to closed sockets, but caller code can
496     # do two writes within an event, have the first fail and
497     # disconnect the other side (whose destructor then closes the
498     # calling object, but it's still in a method), and then the
499     # now-dead object does its second write.  that is this case.  we
500     # just lie and say it worked.  it'll be dead soon and won't be
501     # hurt by this lie.
502     my $sock = $self->{sock} or return 1;
503     my $ref = ref $data;
504     my $bref = $ref ? $data : \$data;
505     my $wbuf = $self->{wbuf};
506     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
507         if ($ref eq 'CODE') {
508             push @$wbuf, $bref;
509         } else {
510             my $last = $wbuf->[-1];
511             if (ref($last) eq 'GLOB') { # append to tmp file buffer
512                 $last->print($$bref) or return drop($self, "print: $!");
513             } else {
514                 my $tmpio = tmpio($self, $bref, 0) or return 0;
515                 push @$wbuf, $tmpio;
516             }
517         }
518         return 0;
519     } elsif ($ref eq 'CODE') {
520         $bref->($self);
521         return 1;
522     } else {
523         my $to_write = bytes::length($$bref);
524         my $written = syswrite($sock, $$bref, $to_write);
525
526         if (defined $written) {
527             return 1 if $written == $to_write;
528             requeue($self); # runs: event_step -> flush_write
529         } elsif ($! == EAGAIN) {
530             epwait($sock, epbit($sock, EPOLLOUT) | EPOLLONESHOT);
531             $written = 0;
532         } else {
533             return $self->close;
534         }
535
536         # deal with EAGAIN or partial write:
537         my $tmpio = tmpio($self, $bref, $written) or return 0;
538
539         # wbuf may be an empty array if we're being called inside
540         # ->flush_write via CODE bref:
541         push @{$self->{wbuf} ||= []}, $tmpio;
542         return 0;
543     }
544 }
545
546 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
547
548 sub msg_more ($$) {
549     my $self = $_[0];
550     my $sock = $self->{sock} or return 1;
551
552     if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::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             $self->{wbuf} = [ $tmpio ];
560             epwait($sock, EPOLLOUT|EPOLLONESHOT);
561             return 0;
562         }
563     }
564     $self->write(\($_[1]));
565 }
566
567 sub epwait ($$) {
568     my ($sock, $ev) = @_;
569     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
570         confess("EPOLL_CTL_MOD $!");
571     0;
572 }
573
574 # return true if complete, false if incomplete (or failure)
575 sub accept_tls_step ($) {
576     my ($self) = @_;
577     my $sock = $self->{sock} or return;
578     return 1 if $sock->accept_SSL;
579     return $self->close if $! != EAGAIN;
580     epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
581     unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
582 }
583
584 sub shutdn_tls_step ($) {
585     my ($self) = @_;
586     my $sock = $self->{sock} or return;
587     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
588     return $self->close if $! != EAGAIN;
589     epwait($sock, PublicInbox::TLS::epollbit() | EPOLLONESHOT);
590     unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
591 }
592
593 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
594 # or fork w/o exec, so no inadvertant socket sharing
595 sub shutdn ($) {
596     my ($self) = @_;
597     my $sock = $self->{sock} or return;
598     if (ref($sock) eq 'IO::Socket::SSL') {
599         shutdn_tls_step($self);
600     } else {
601         $self->close;
602     }
603 }
604 package PublicInbox::DS::Timer;
605 # [$abs_float_firetime, $coderef];
606 sub cancel {
607     $_[0][1] = undef;
608 }
609
610 1;
611
612 =head1 AUTHORS (Danga::Socket)
613
614 Brad Fitzpatrick <brad@danga.com> - author
615
616 Michael Granger <ged@danga.com> - docs, testing
617
618 Mark Smith <junior@danga.com> - contributor, heavy user, testing
619
620 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits