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