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;
22 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
26 use PublicInbox::Syscall qw(:epoll);
28 use fields ('sock', # underlying socket
29 'wbuf', # arrayref of scalars, scalarrefs, or coderefs to write
30 'wbuf_off', # offset into first element of wbuf to start writing at
31 'event_watch', # bitmask of events the client is interested in (POLLIN,OUT,etc.)
34 use Errno qw(EAGAIN EINVAL);
35 use Carp qw(croak confess);
37 use constant DebugLevel => 0;
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->DebugMsg( $format, @args ) >>
110 Print the debugging message specified by the C<sprintf>-style I<format> and
115 my ( $class, $fmt, @args ) = @_;
117 printf STDERR ">>> $fmt\n", @args;
120 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
122 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
123 are not guaranteed to fire at the exact time you ask for.
125 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
130 my ($secs, $coderef) = @_;
132 my $fire_time = Time::HiRes::time() + $secs;
134 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
136 if (!@Timers || $fire_time >= $Timers[-1][0]) {
137 push @Timers, $timer;
141 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
142 # but it was compared against calendar queues, heaps, naive push/sort,
143 # and a bunch of other versions, and found to be fastest with a large
144 # variety of datasets.)
145 for (my $i = 0; $i < @Timers; $i++) {
146 if ($Timers[$i][0] > $fire_time) {
147 splice(@Timers, $i, 0, $timer);
152 die "Shouldn't get here.";
155 # keeping this around in case we support other FD types for now,
156 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
157 sub set_cloexec ($) {
160 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
161 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
162 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
171 $KQueue = IO::KQueue->new();
172 $HaveKQueue = defined $KQueue;
174 *EventLoop = *KQueueEventLoop;
177 elsif (PublicInbox::Syscall::epoll_defined()) {
178 $Epoll = eval { epoll_create(1024); };
179 $HaveEpoll = defined $Epoll && $Epoll >= 0;
182 *EventLoop = *EpollEventLoop;
186 if (!$HaveEpoll && !$HaveKQueue) {
188 *EventLoop = *PollEventLoop;
192 =head2 C<< CLASS->EventLoop() >>
194 Start processing IO events. In most daemon programs this never exits. See
195 C<PostLoopCallback> below for how to exit the loop.
198 sub FirstTimeEventLoop {
204 EpollEventLoop($class);
205 } elsif ($HaveKQueue) {
206 KQueueEventLoop($class);
208 PollEventLoop($class);
212 # runs timers and returns milliseconds for next one, or next event loop
214 return $LoopTimeout unless @Timers;
216 my $now = Time::HiRes::time();
219 while (@Timers && $Timers[0][0] <= $now) {
220 my $to_run = shift(@Timers);
221 $to_run->[1]->($now) if $to_run->[1];
224 return $LoopTimeout unless @Timers;
226 # convert time to an even number of milliseconds, adding 1
227 # extra, otherwise floating point fun can occur and we'll
228 # call RunTimers like 20-30 times, each returning a timeout
229 # of 0.0000212 seconds
230 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
232 # -1 is an infinite timeout, so prefer a real timeout
233 return $timeout if $LoopTimeout == -1;
235 # otherwise pick the lower of our regular timeout and time until
237 return $LoopTimeout if $LoopTimeout < $timeout;
241 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
249 my $timeout = RunTimers();
251 # get up to 1000 events
252 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
253 for ($i=0; $i<$evcount; $i++) {
254 # it's possible epoll_wait returned many events, including some at the end
255 # that ones in the front triggered unregister-interest actions. if we
256 # can't find the %sock entry, it's because we're no longer interested
258 $DescriptorMap{$events[$i]->[0]}->event_step;
260 return unless PostEventLoop();
265 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
266 ### IO::Epoll fails to load.
270 my PublicInbox::DS $pob;
273 my $timeout = RunTimers();
275 # the following sets up @poll as a series of ($poll,$event_mask)
276 # items, then uses IO::Poll::_poll, implemented in XS, which
277 # modifies the array in place with the even elements being
278 # replaced with the event masks that occured.
280 while ( my ($fd, $sock) = each %DescriptorMap ) {
281 push @poll, $fd, $sock->{event_watch};
284 # if nothing to poll, either end immediately (if no timeout)
285 # or just keep calling the callback
287 select undef, undef, undef, ($timeout / 1000);
288 return unless PostEventLoop();
292 my $count = IO::Poll::_poll($timeout, @poll);
293 unless ($count >= 0) {
294 return unless PostEventLoop();
298 # Fetch handles with read events
300 my ($fd, $state) = splice(@poll, 0, 2);
301 $DescriptorMap{$fd}->event_step if $state;
304 return unless PostEventLoop();
310 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
312 sub KQueueEventLoop {
316 my $timeout = RunTimers();
317 my @ret = eval { $KQueue->kevent($timeout) };
319 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
320 if ($err =~ /Interrupted system call/) {
327 foreach my $kev (@ret) {
328 $DescriptorMap{$kev->[0]}->event_step;
330 return unless PostEventLoop();
336 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
338 Sets post loop callback function. Pass a subref and it will be
339 called every time the event loop finishes.
341 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
344 The callback function will be passed two parameters: \%DescriptorMap
347 sub SetPostLoopCallback {
348 my ($class, $ref) = @_;
351 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
354 # Internal function: run the post-event callback, send read events
355 # for pushed-back data, and close pending connections. returns 1
356 # if event loop should continue, or 0 to shut it all down.
358 # now we can close sockets that wanted to close during our event processing.
359 # (we didn't want to close them during the loop, as we didn't want fd numbers
360 # being reused and confused during the event loop)
361 while (my $sock = shift @ToClose) {
362 my $fd = fileno($sock);
364 # close the socket. (not a PublicInbox::DS close)
367 # and now we can finally remove the fd from the map. see
368 # comment above in ->close.
369 delete $DescriptorMap{$fd};
373 # by default we keep running, unless a postloop callback (either per-object
374 # or global) cancels it
375 my $keep_running = 1;
377 # now we're at the very end, call callback if defined
378 if (defined $PostLoopCallback) {
379 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
382 return $keep_running;
385 #####################################################################
386 ### PublicInbox::DS-the-object code
387 #####################################################################
389 =head2 OBJECT METHODS
391 =head2 C<< CLASS->new( $socket ) >>
393 Create a new PublicInbox::DS subclass object for the given I<socket> which will
394 react to events on it during the C<EventLoop>.
396 This is normally (always?) called from your subclass via:
398 $class->SUPER::new($socket);
402 my ($self, $sock, $exclusive) = @_;
403 $self = fields::new($self) unless ref $self;
405 $self->{sock} = $sock;
406 my $fd = fileno($sock);
408 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
412 $self->{wbuf_off} = 0;
414 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
420 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
423 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
424 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
425 $EPOLLEXCLUSIVE = 0; # old kernel
426 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
429 die "couldn't add epoll watch for $fd: $!\n";
432 elsif ($HaveKQueue) {
433 # Add them to the queue but disabled for now
434 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
435 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
436 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
437 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
440 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
441 if $DescriptorMap{$fd};
443 $DescriptorMap{$fd} = $self;
448 #####################################################################
449 ### I N S T A N C E M E T H O D S
450 #####################################################################
452 =head2 C<< $obj->close >>
459 my $sock = delete $self->{sock} or return;
461 # we need to flush our write buffer, as there may
462 # be self-referential closures (sub { $client->close })
463 # preventing the object from being destroyed
464 @{$self->{wbuf}} = ();
466 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
467 # notifications about it
469 my $fd = fileno($sock);
470 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
471 confess("EPOLL_CTL_DEL: $!");
474 # we explicitly don't delete from DescriptorMap here until we
475 # actually close the socket, as we might be in the middle of
476 # processing an epoll_wait/etc that returned hundreds of fds, one
477 # of which is not yet processed and is what we're closing. if we
478 # keep it in DescriptorMap, then the event harnesses can just
479 # looked at $pob->{sock} == undef and ignore it. but if it's an
480 # un-accounted for fd, then it (understandably) freak out a bit
481 # and emit warnings, thinking their state got off.
483 # defer closing the actual socket until the event loop is done
484 # processing this round of events. (otherwise we might reuse fds)
485 push @ToClose, $sock;
490 =head2 C<< $obj->sock() >>
492 Returns the underlying IO::Handle for the object.
496 my PublicInbox::DS $self = shift;
497 return $self->{sock};
500 =head2 C<< $obj->write( $data ) >>
502 Write the specified data to the underlying handle. I<data> may be scalar,
503 scalar ref, code ref (to run when there), or undef just to kick-start.
504 Returns 1 if writes all went through, or 0 if there are writes in queue. If
505 it returns 1, caller should stop waiting for 'writable' events)
509 my PublicInbox::DS $self;
513 # nobody should be writing to closed sockets, but caller code can
514 # do two writes within an event, have the first fail and
515 # disconnect the other side (whose destructor then closes the
516 # calling object, but it's still in a method), and then the
517 # now-dead object does its second write. that is this case. we
518 # just lie and say it worked. it'll be dead soon and won't be
520 return 1 unless $self->{sock};
524 # just queue data if there's already a wait
526 my $wbuf = $self->{wbuf};
529 $bref = ref $data ? $data : \$data;
535 # this flag says we're bypassing the queue system, knowing we're the
536 # only outstanding write, and hoping we don't ever need to use it.
537 # if so later, though, we'll need to queue
543 return 1 unless $bref ||= $wbuf->[0];
547 $len = length($$bref); # this will die if $bref is a code ref, caught below
550 if (UNIVERSAL::isa($bref, "CODE")) {
551 unless ($need_queue) {
556 # code refs are just run and never get reenqueued
557 # (they're one-shot), so turn off the flag indicating the
558 # outstanding data needs queueing.
564 die "Write error: $@ <$bref>";
567 my $to_write = $len - $self->{wbuf_off};
568 my $written = syswrite($self->{sock}, $$bref, $to_write,
571 if (! defined $written) {
573 # since connection has stuff to write, it should now be
574 # interested in pending writes:
578 $self->watch_write(1);
583 } elsif ($written != $to_write) {
587 # since connection has stuff to write, it should now be
588 # interested in pending writes:
589 $self->{wbuf_off} += $written;
590 $self->on_incomplete_write;
592 } elsif ($written == $to_write) {
593 $self->{wbuf_off} = 0;
594 $self->watch_write(0);
596 # this was our only write, so we can return immediately
597 # since we avoided incrementing the buffer size or
598 # putting it in the buffer. we also know there
599 # can't be anything else to write.
600 return 1 if $need_queue;
609 sub on_incomplete_write {
610 my PublicInbox::DS $self = shift;
611 $self->watch_write(1);
614 =head2 C<< $obj->watch_read( $boolean ) >>
616 Turn 'readable' event notification on or off.
620 my PublicInbox::DS $self = shift;
621 my $sock = $self->{sock} or return;
624 my $event = $self->{event_watch};
626 $event &= ~POLLIN if ! $val;
627 $event |= POLLIN if $val;
629 my $fd = fileno($sock);
630 # If it changed, set it
631 if ($event != $self->{event_watch}) {
633 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
634 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
637 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
638 confess("EPOLL_CTL_MOD: $!");
640 $self->{event_watch} = $event;
644 =head2 C<< $obj->watch_write( $boolean ) >>
646 Turn 'writable' event notification on or off.
650 my PublicInbox::DS $self = shift;
651 my $sock = $self->{sock} or return;
654 my $event = $self->{event_watch};
656 $event &= ~POLLOUT if ! $val;
657 $event |= POLLOUT if $val;
658 my $fd = fileno($sock);
660 # If it changed, set it
661 if ($event != $self->{event_watch}) {
663 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
664 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
667 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
668 confess "EPOLL_CTL_MOD: $!";
670 $self->{event_watch} = $event;
674 =head2 C<< $obj->dump_error( $message ) >>
676 Prints to STDERR a backtrace with information about this socket and what lead
677 up to the dump_error call.
683 while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
684 push @list, "\t$file:$line called $sub\n";
687 warn "ERROR: $_[1]\n" .
688 "\t$_[0] = " . $_[0]->as_string . "\n" .
692 =head2 C<< $obj->debugmsg( $format, @args ) >>
694 Print the debugging message specified by the C<sprintf>-style I<format> and
699 my ( $self, $fmt, @args ) = @_;
700 confess "Not an object" unless ref $self;
703 printf STDERR ">>> $fmt\n", @args;
706 =head2 C<< $obj->as_string() >>
708 Returns a string describing this socket.
712 my PublicInbox::DS $self = shift;
713 my $rw = "(" . ($self->{event_watch} & POLLIN ? 'R' : '') .
714 ($self->{event_watch} & POLLOUT ? 'W' : '') . ")";
715 my $ret = ref($self) . "$rw: " . ($self->{sock} ? 'open' : 'closed');
719 package PublicInbox::DS::Timer;
720 # [$abs_float_firetime, $coderef];
727 =head1 AUTHORS (Danga::Socket)
729 Brad Fitzpatrick <brad@danga.com> - author
731 Michael Granger <ged@danga.com> - docs, testing
733 Mark Smith <junior@danga.com> - contributor, heavy user, testing
735 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits