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