1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
4 # This license differs from the rest of public-inbox
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.
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;
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 write_in_full);
27 use PublicInbox::Syscall qw(:epoll);
29 use fields ('sock', # underlying socket
30 'wbuf', # arrayref of coderefs or GLOB refs
31 'wbuf_off', # offset into first element of wbuf to start writing at
32 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
35 use Errno qw(EAGAIN EINVAL);
36 use Carp qw(croak confess);
37 use File::Temp qw(tempfile);
39 use constant POLLIN => 1;
40 use constant POLLOUT => 4;
41 use constant POLLERR => 8;
42 use constant POLLHUP => 16;
43 use constant POLLNVAL => 32;
45 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
48 $HaveEpoll, # Flag -- is epoll available? initially undefined.
50 %DescriptorMap, # fd (num) -> PublicInbox::DS object
51 $Epoll, # Global epoll fd (for epoll mode only)
52 $KQueue, # Global kqueue fd ref (for kqueue mode only)
53 $_io, # IO::Handle for Epoll
54 @ToClose, # sockets to close when event loop is done
56 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
58 $LoopTimeout, # timeout of event loop in milliseconds
59 $DoneInit, # if we've done the one-time module init yet
63 # this may be set to zero with old kernels
64 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
67 #####################################################################
68 ### C L A S S M E T H O D S
69 #####################################################################
71 =head2 C<< CLASS->Reset() >>
79 $LoopTimeout = -1; # no timeout by default
82 $PostLoopCallback = undef;
85 # NOTE kqueue is close-on-fork, and we don't account for it, yet
86 # OTOH, we (public-inbox) don't need this sub outside of tests...
87 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
90 $_io = undef; # close $Epoll
93 *EventLoop = *FirstTimeEventLoop;
96 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
98 Set the loop timeout for the event loop to some value in milliseconds.
100 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
105 return $LoopTimeout = $_[1] + 0;
108 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
110 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
111 are not guaranteed to fire at the exact time you ask for.
113 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
117 my ($class, $secs, $coderef) = @_;
120 my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
121 unshift(@Timers, $timer);
125 my $fire_time = now() + $secs;
127 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
129 if (!@Timers || $fire_time >= $Timers[-1][0]) {
130 push @Timers, $timer;
134 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
135 # but it was compared against calendar queues, heaps, naive push/sort,
136 # and a bunch of other versions, and found to be fastest with a large
137 # variety of datasets.)
138 for (my $i = 0; $i < @Timers; $i++) {
139 if ($Timers[$i][0] > $fire_time) {
140 splice(@Timers, $i, 0, $timer);
145 die "Shouldn't get here.";
148 # keeping this around in case we support other FD types for now,
149 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
150 sub set_cloexec ($) {
153 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
154 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
155 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
164 $KQueue = IO::KQueue->new();
165 $HaveKQueue = defined $KQueue;
167 *EventLoop = *KQueueEventLoop;
170 elsif (PublicInbox::Syscall::epoll_defined()) {
171 $Epoll = eval { epoll_create(1024); };
172 $HaveEpoll = defined $Epoll && $Epoll >= 0;
175 *EventLoop = *EpollEventLoop;
179 if (!$HaveEpoll && !$HaveKQueue) {
181 *EventLoop = *PollEventLoop;
185 =head2 C<< CLASS->EventLoop() >>
187 Start processing IO events. In most daemon programs this never exits. See
188 C<PostLoopCallback> below for how to exit the loop.
191 sub FirstTimeEventLoop {
197 EpollEventLoop($class);
198 } elsif ($HaveKQueue) {
199 KQueueEventLoop($class);
201 PollEventLoop($class);
205 sub now () { clock_gettime(CLOCK_MONOTONIC) }
207 # runs timers and returns milliseconds for next one, or next event loop
209 return $LoopTimeout unless @Timers;
214 while (@Timers && $Timers[0][0] <= $now) {
215 my $to_run = shift(@Timers);
216 $to_run->[1]->($now) if $to_run->[1];
219 return $LoopTimeout unless @Timers;
221 # convert time to an even number of milliseconds, adding 1
222 # extra, otherwise floating point fun can occur and we'll
223 # call RunTimers like 20-30 times, each returning a timeout
224 # of 0.0000212 seconds
225 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
227 # -1 is an infinite timeout, so prefer a real timeout
228 return $timeout if $LoopTimeout == -1;
230 # otherwise pick the lower of our regular timeout and time until
232 return $LoopTimeout if $LoopTimeout < $timeout;
236 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
244 my $timeout = RunTimers();
246 # get up to 1000 events
247 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
248 for ($i=0; $i<$evcount; $i++) {
249 # it's possible epoll_wait returned many events, including some at the end
250 # that ones in the front triggered unregister-interest actions. if we
251 # can't find the %sock entry, it's because we're no longer interested
253 $DescriptorMap{$events[$i]->[0]}->event_step;
255 return unless PostEventLoop();
260 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
261 ### IO::Epoll fails to load.
265 my PublicInbox::DS $pob;
268 my $timeout = RunTimers();
270 # the following sets up @poll as a series of ($poll,$event_mask)
271 # items, then uses IO::Poll::_poll, implemented in XS, which
272 # modifies the array in place with the even elements being
273 # replaced with the event masks that occured.
275 while ( my ($fd, $sock) = each %DescriptorMap ) {
276 push @poll, $fd, $sock->{event_watch};
279 # if nothing to poll, either end immediately (if no timeout)
280 # or just keep calling the callback
282 select undef, undef, undef, ($timeout / 1000);
283 return unless PostEventLoop();
287 my $count = IO::Poll::_poll($timeout, @poll);
288 unless ($count >= 0) {
289 return unless PostEventLoop();
293 # Fetch handles with read events
295 my ($fd, $state) = splice(@poll, 0, 2);
296 $DescriptorMap{$fd}->event_step if $state;
299 return unless PostEventLoop();
305 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
307 sub KQueueEventLoop {
311 my $timeout = RunTimers();
312 my @ret = eval { $KQueue->kevent($timeout) };
314 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
315 if ($err =~ /Interrupted system call/) {
322 foreach my $kev (@ret) {
323 $DescriptorMap{$kev->[0]}->event_step;
325 return unless PostEventLoop();
331 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
333 Sets post loop callback function. Pass a subref and it will be
334 called every time the event loop finishes.
336 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
339 The callback function will be passed two parameters: \%DescriptorMap
342 sub SetPostLoopCallback {
343 my ($class, $ref) = @_;
346 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
349 # Internal function: run the post-event callback, send read events
350 # for pushed-back data, and close pending connections. returns 1
351 # if event loop should continue, or 0 to shut it all down.
353 # now we can close sockets that wanted to close during our event processing.
354 # (we didn't want to close them during the loop, as we didn't want fd numbers
355 # being reused and confused during the event loop)
356 while (my $sock = shift @ToClose) {
357 my $fd = fileno($sock);
359 # close the socket. (not a PublicInbox::DS close)
362 # and now we can finally remove the fd from the map. see
363 # comment above in ->close.
364 delete $DescriptorMap{$fd};
368 # by default we keep running, unless a postloop callback (either per-object
369 # or global) cancels it
370 my $keep_running = 1;
372 # now we're at the very end, call callback if defined
373 if (defined $PostLoopCallback) {
374 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
377 return $keep_running;
380 #####################################################################
381 ### PublicInbox::DS-the-object code
382 #####################################################################
384 =head2 OBJECT METHODS
386 =head2 C<< CLASS->new( $socket ) >>
388 Create a new PublicInbox::DS subclass object for the given I<socket> which will
389 react to events on it during the C<EventLoop>.
391 This is normally (always?) called from your subclass via:
393 $class->SUPER::new($socket);
397 my ($self, $sock, $exclusive) = @_;
398 $self = fields::new($self) unless ref $self;
400 $self->{sock} = $sock;
401 my $fd = fileno($sock);
403 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
406 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
412 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
415 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
416 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
417 $EPOLLEXCLUSIVE = 0; # old kernel
418 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
421 die "couldn't add epoll watch for $fd: $!\n";
424 elsif ($HaveKQueue) {
425 # Add them to the queue but disabled for now
426 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
427 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
428 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
429 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
432 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
433 if $DescriptorMap{$fd};
435 $DescriptorMap{$fd} = $self;
440 #####################################################################
441 ### I N S T A N C E M E T H O D S
442 #####################################################################
444 =head2 C<< $obj->close >>
451 my $sock = delete $self->{sock} or return;
453 # we need to flush our write buffer, as there may
454 # be self-referential closures (sub { $client->close })
455 # preventing the object from being destroyed
456 delete $self->{wbuf};
458 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
459 # notifications about it
461 my $fd = fileno($sock);
462 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
463 confess("EPOLL_CTL_DEL: $!");
466 # we explicitly don't delete from DescriptorMap here until we
467 # actually close the socket, as we might be in the middle of
468 # processing an epoll_wait/etc that returned hundreds of fds, one
469 # of which is not yet processed and is what we're closing. if we
470 # keep it in DescriptorMap, then the event harnesses can just
471 # looked at $pob->{sock} == undef and ignore it. but if it's an
472 # un-accounted for fd, then it (understandably) freak out a bit
473 # and emit warnings, thinking their state got off.
475 # defer closing the actual socket until the event loop is done
476 # processing this round of events. (otherwise we might reuse fds)
477 push @ToClose, $sock;
482 # portable, non-thread-safe sendfile emulation (no pread, yet)
483 sub psendfile ($$$) {
484 my ($sock, $fh, $off) = @_;
486 sysseek($fh, $$off, SEEK_SET) or return;
487 defined(my $to_write = sysread($fh, my $buf, 16384)) or return;
489 while ($to_write > 0) {
490 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
494 return if $written == 0;
502 # returns 1 if done, 0 if incomplete
503 sub flush_write ($) {
505 my $wbuf = $self->{wbuf} or return 1;
506 my $sock = $self->{sock} or return 1;
509 while (my $bref = $wbuf->[0]) {
510 if (ref($bref) ne 'CODE') {
511 my $off = delete($self->{wbuf_off}) // 0;
513 my $w = psendfile($sock, $bref, \$off);
519 } elsif ($! == EAGAIN) {
520 $self->{wbuf_off} = $off;
521 watch_write($self, 1);
527 } else { #($ref eq 'CODE') {
533 delete $self->{wbuf};
534 $self->watch_write(0);
538 sub write_in_full ($$$$) {
539 my ($fh, $bref, $len, $off) = @_;
542 my $w = syswrite($fh, $$bref, $len, $off);
543 return ($rv ? $rv : $w) unless $w; # undef or 0
552 my ($bref, $off) = @_;
553 # open(my $fh, '+>>', undef) doesn't set O_APPEND
554 my ($fh, $path) = tempfile('wbuf-XXXXXXX', TMPDIR => 1);
555 open $fh, '+>>', $path or die "open: $!";
557 my $to_write = bytes::length($$bref) - $off;
558 my $w = write_in_full($fh, $bref, $to_write, $off);
559 die "write_in_full ($to_write): $!" unless defined $w;
560 $w == $to_write ? $fh : die("short write $w < $to_write");
563 =head2 C<< $obj->write( $data ) >>
565 Write the specified data to the underlying handle. I<data> may be scalar,
566 scalar ref, code ref (to run when there).
567 Returns 1 if writes all went through, or 0 if there are writes in queue. If
568 it returns 1, caller should stop waiting for 'writable' events)
572 my ($self, $data) = @_;
574 # nobody should be writing to closed sockets, but caller code can
575 # do two writes within an event, have the first fail and
576 # disconnect the other side (whose destructor then closes the
577 # calling object, but it's still in a method), and then the
578 # now-dead object does its second write. that is this case. we
579 # just lie and say it worked. it'll be dead soon and won't be
581 my $sock = $self->{sock} or return 1;
583 my $bref = $ref ? $data : \$data;
584 if (my $wbuf = $self->{wbuf}) { # already buffering, can't write more...
585 if ($ref eq 'CODE') {
588 my $last = $wbuf->[-1];
589 if (ref($last) eq 'GLOB') { # append to tmp file buffer
590 write_in_full($last, $bref, bytes::length($$bref), 0);
592 push @$wbuf, tmpbuf($bref, 0);
596 } elsif ($ref eq 'CODE') {
600 my $to_write = bytes::length($$bref);
601 my $written = syswrite($sock, $$bref, $to_write);
603 if (defined $written) {
604 return 1 if $written == $to_write;
605 } elsif ($! == EAGAIN) {
610 $self->{wbuf} = [ tmpbuf($bref, $written) ];
611 watch_write($self, 1);
616 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
620 my $sock = $self->{sock} or return 1;
622 if (MSG_MORE && !$self->{wbuf}) {
623 my $n = send($sock, $_[1], MSG_MORE);
625 my $nlen = bytes::length($_[1]) - $n;
626 return 1 if $nlen == 0; # all done!
628 # queue up the unwritten substring:
629 $self->{wbuf} = [ tmpbuf(\($_[1]), $n) ];
630 watch_write($self, 1);
634 $self->write(\($_[1]));
637 =head2 C<< $obj->watch_read( $boolean ) >>
639 Turn 'readable' event notification on or off.
643 my PublicInbox::DS $self = shift;
644 my $sock = $self->{sock} or return;
647 my $event = $self->{event_watch};
649 $event &= ~POLLIN if ! $val;
650 $event |= POLLIN if $val;
652 my $fd = fileno($sock);
653 # If it changed, set it
654 if ($event != $self->{event_watch}) {
656 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
657 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
660 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
661 confess("EPOLL_CTL_MOD: $!");
663 $self->{event_watch} = $event;
667 =head2 C<< $obj->watch_write( $boolean ) >>
669 Turn 'writable' event notification on or off.
673 my PublicInbox::DS $self = shift;
674 my $sock = $self->{sock} or return;
677 my $event = $self->{event_watch};
679 $event &= ~POLLOUT if ! $val;
680 $event |= POLLOUT if $val;
681 my $fd = fileno($sock);
683 # If it changed, set it
684 if ($event != $self->{event_watch}) {
686 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
687 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
690 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
691 confess "EPOLL_CTL_MOD: $!";
693 $self->{event_watch} = $event;
697 package PublicInbox::DS::Timer;
698 # [$abs_float_firetime, $coderef];
705 =head1 AUTHORS (Danga::Socket)
707 Brad Fitzpatrick <brad@danga.com> - author
709 Michael Granger <ged@danga.com> - docs, testing
711 Mark Smith <junior@danga.com> - contributor, heavy user, testing
713 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits