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);
22 use Time::HiRes qw(clock_gettime CLOCK_MONOTONIC);
23 use parent qw(Exporter);
24 our @EXPORT_OK = qw(now);
27 use PublicInbox::Syscall qw(:epoll);
29 use fields ('sock', # underlying socket
30 'wbuf', # arrayref of scalars, scalarrefs, or coderefs to write
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);
38 use constant POLLIN => 1;
39 use constant POLLOUT => 4;
40 use constant POLLERR => 8;
41 use constant POLLHUP => 16;
42 use constant POLLNVAL => 32;
44 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
47 $HaveEpoll, # Flag -- is epoll available? initially undefined.
49 %DescriptorMap, # fd (num) -> PublicInbox::DS object
50 $Epoll, # Global epoll fd (for epoll mode only)
51 $KQueue, # Global kqueue fd ref (for kqueue mode only)
52 $_io, # IO::Handle for Epoll
53 @ToClose, # sockets to close when event loop is done
55 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
57 $LoopTimeout, # timeout of event loop in milliseconds
58 $DoneInit, # if we've done the one-time module init yet
62 # this may be set to zero with old kernels
63 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
66 #####################################################################
67 ### C L A S S M E T H O D S
68 #####################################################################
70 =head2 C<< CLASS->Reset() >>
78 $LoopTimeout = -1; # no timeout by default
81 $PostLoopCallback = undef;
84 # NOTE kqueue is close-on-fork, and we don't account for it, yet
85 # OTOH, we (public-inbox) don't need this sub outside of tests...
86 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
89 $_io = undef; # close $Epoll
92 *EventLoop = *FirstTimeEventLoop;
95 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
97 Set the loop timeout for the event loop to some value in milliseconds.
99 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
104 return $LoopTimeout = $_[1] + 0;
107 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
109 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
110 are not guaranteed to fire at the exact time you ask for.
112 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
117 my ($secs, $coderef) = @_;
119 my $fire_time = now() + $secs;
121 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
123 if (!@Timers || $fire_time >= $Timers[-1][0]) {
124 push @Timers, $timer;
128 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
129 # but it was compared against calendar queues, heaps, naive push/sort,
130 # and a bunch of other versions, and found to be fastest with a large
131 # variety of datasets.)
132 for (my $i = 0; $i < @Timers; $i++) {
133 if ($Timers[$i][0] > $fire_time) {
134 splice(@Timers, $i, 0, $timer);
139 die "Shouldn't get here.";
142 # keeping this around in case we support other FD types for now,
143 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
144 sub set_cloexec ($) {
147 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
148 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
149 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
158 $KQueue = IO::KQueue->new();
159 $HaveKQueue = defined $KQueue;
161 *EventLoop = *KQueueEventLoop;
164 elsif (PublicInbox::Syscall::epoll_defined()) {
165 $Epoll = eval { epoll_create(1024); };
166 $HaveEpoll = defined $Epoll && $Epoll >= 0;
169 *EventLoop = *EpollEventLoop;
173 if (!$HaveEpoll && !$HaveKQueue) {
175 *EventLoop = *PollEventLoop;
179 =head2 C<< CLASS->EventLoop() >>
181 Start processing IO events. In most daemon programs this never exits. See
182 C<PostLoopCallback> below for how to exit the loop.
185 sub FirstTimeEventLoop {
191 EpollEventLoop($class);
192 } elsif ($HaveKQueue) {
193 KQueueEventLoop($class);
195 PollEventLoop($class);
199 sub now () { clock_gettime(CLOCK_MONOTONIC) }
201 # runs timers and returns milliseconds for next one, or next event loop
203 return $LoopTimeout unless @Timers;
208 while (@Timers && $Timers[0][0] <= $now) {
209 my $to_run = shift(@Timers);
210 $to_run->[1]->($now) if $to_run->[1];
213 return $LoopTimeout unless @Timers;
215 # convert time to an even number of milliseconds, adding 1
216 # extra, otherwise floating point fun can occur and we'll
217 # call RunTimers like 20-30 times, each returning a timeout
218 # of 0.0000212 seconds
219 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
221 # -1 is an infinite timeout, so prefer a real timeout
222 return $timeout if $LoopTimeout == -1;
224 # otherwise pick the lower of our regular timeout and time until
226 return $LoopTimeout if $LoopTimeout < $timeout;
230 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
238 my $timeout = RunTimers();
240 # get up to 1000 events
241 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
242 for ($i=0; $i<$evcount; $i++) {
243 # it's possible epoll_wait returned many events, including some at the end
244 # that ones in the front triggered unregister-interest actions. if we
245 # can't find the %sock entry, it's because we're no longer interested
247 $DescriptorMap{$events[$i]->[0]}->event_step;
249 return unless PostEventLoop();
254 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
255 ### IO::Epoll fails to load.
259 my PublicInbox::DS $pob;
262 my $timeout = RunTimers();
264 # the following sets up @poll as a series of ($poll,$event_mask)
265 # items, then uses IO::Poll::_poll, implemented in XS, which
266 # modifies the array in place with the even elements being
267 # replaced with the event masks that occured.
269 while ( my ($fd, $sock) = each %DescriptorMap ) {
270 push @poll, $fd, $sock->{event_watch};
273 # if nothing to poll, either end immediately (if no timeout)
274 # or just keep calling the callback
276 select undef, undef, undef, ($timeout / 1000);
277 return unless PostEventLoop();
281 my $count = IO::Poll::_poll($timeout, @poll);
282 unless ($count >= 0) {
283 return unless PostEventLoop();
287 # Fetch handles with read events
289 my ($fd, $state) = splice(@poll, 0, 2);
290 $DescriptorMap{$fd}->event_step if $state;
293 return unless PostEventLoop();
299 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
301 sub KQueueEventLoop {
305 my $timeout = RunTimers();
306 my @ret = eval { $KQueue->kevent($timeout) };
308 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
309 if ($err =~ /Interrupted system call/) {
316 foreach my $kev (@ret) {
317 $DescriptorMap{$kev->[0]}->event_step;
319 return unless PostEventLoop();
325 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
327 Sets post loop callback function. Pass a subref and it will be
328 called every time the event loop finishes.
330 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
333 The callback function will be passed two parameters: \%DescriptorMap
336 sub SetPostLoopCallback {
337 my ($class, $ref) = @_;
340 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
343 # Internal function: run the post-event callback, send read events
344 # for pushed-back data, and close pending connections. returns 1
345 # if event loop should continue, or 0 to shut it all down.
347 # now we can close sockets that wanted to close during our event processing.
348 # (we didn't want to close them during the loop, as we didn't want fd numbers
349 # being reused and confused during the event loop)
350 while (my $sock = shift @ToClose) {
351 my $fd = fileno($sock);
353 # close the socket. (not a PublicInbox::DS close)
356 # and now we can finally remove the fd from the map. see
357 # comment above in ->close.
358 delete $DescriptorMap{$fd};
362 # by default we keep running, unless a postloop callback (either per-object
363 # or global) cancels it
364 my $keep_running = 1;
366 # now we're at the very end, call callback if defined
367 if (defined $PostLoopCallback) {
368 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
371 return $keep_running;
374 #####################################################################
375 ### PublicInbox::DS-the-object code
376 #####################################################################
378 =head2 OBJECT METHODS
380 =head2 C<< CLASS->new( $socket ) >>
382 Create a new PublicInbox::DS subclass object for the given I<socket> which will
383 react to events on it during the C<EventLoop>.
385 This is normally (always?) called from your subclass via:
387 $class->SUPER::new($socket);
391 my ($self, $sock, $exclusive) = @_;
392 $self = fields::new($self) unless ref $self;
394 $self->{sock} = $sock;
395 my $fd = fileno($sock);
397 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
401 $self->{wbuf_off} = 0;
403 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
409 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
412 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
413 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
414 $EPOLLEXCLUSIVE = 0; # old kernel
415 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
418 die "couldn't add epoll watch for $fd: $!\n";
421 elsif ($HaveKQueue) {
422 # Add them to the queue but disabled for now
423 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
424 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
425 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
426 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
429 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
430 if $DescriptorMap{$fd};
432 $DescriptorMap{$fd} = $self;
437 #####################################################################
438 ### I N S T A N C E M E T H O D S
439 #####################################################################
441 =head2 C<< $obj->close >>
448 my $sock = delete $self->{sock} or return;
450 # we need to flush our write buffer, as there may
451 # be self-referential closures (sub { $client->close })
452 # preventing the object from being destroyed
453 @{$self->{wbuf}} = ();
455 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
456 # notifications about it
458 my $fd = fileno($sock);
459 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
460 confess("EPOLL_CTL_DEL: $!");
463 # we explicitly don't delete from DescriptorMap here until we
464 # actually close the socket, as we might be in the middle of
465 # processing an epoll_wait/etc that returned hundreds of fds, one
466 # of which is not yet processed and is what we're closing. if we
467 # keep it in DescriptorMap, then the event harnesses can just
468 # looked at $pob->{sock} == undef and ignore it. but if it's an
469 # un-accounted for fd, then it (understandably) freak out a bit
470 # and emit warnings, thinking their state got off.
472 # defer closing the actual socket until the event loop is done
473 # processing this round of events. (otherwise we might reuse fds)
474 push @ToClose, $sock;
479 =head2 C<< $obj->write( $data ) >>
481 Write the specified data to the underlying handle. I<data> may be scalar,
482 scalar ref, code ref (to run when there), or undef just to kick-start.
483 Returns 1 if writes all went through, or 0 if there are writes in queue. If
484 it returns 1, caller should stop waiting for 'writable' events)
488 my PublicInbox::DS $self;
492 # nobody should be writing to closed sockets, but caller code can
493 # do two writes within an event, have the first fail and
494 # disconnect the other side (whose destructor then closes the
495 # calling object, but it's still in a method), and then the
496 # now-dead object does its second write. that is this case. we
497 # just lie and say it worked. it'll be dead soon and won't be
499 return 1 unless $self->{sock};
503 # just queue data if there's already a wait
505 my $wbuf = $self->{wbuf};
508 $bref = ref $data ? $data : \$data;
514 # this flag says we're bypassing the queue system, knowing we're the
515 # only outstanding write, and hoping we don't ever need to use it.
516 # if so later, though, we'll need to queue
522 return 1 unless $bref ||= $wbuf->[0];
526 $len = length($$bref); # this will die if $bref is a code ref, caught below
529 if (UNIVERSAL::isa($bref, "CODE")) {
530 unless ($need_queue) {
535 # code refs are just run and never get reenqueued
536 # (they're one-shot), so turn off the flag indicating the
537 # outstanding data needs queueing.
543 die "Write error: $@ <$bref>";
546 my $to_write = $len - $self->{wbuf_off};
547 my $written = syswrite($self->{sock}, $$bref, $to_write,
550 if (! defined $written) {
552 # since connection has stuff to write, it should now be
553 # interested in pending writes:
557 $self->watch_write(1);
562 } elsif ($written != $to_write) {
566 # since connection has stuff to write, it should now be
567 # interested in pending writes:
568 $self->{wbuf_off} += $written;
569 $self->on_incomplete_write;
571 } elsif ($written == $to_write) {
572 $self->{wbuf_off} = 0;
573 $self->watch_write(0);
575 # this was our only write, so we can return immediately
576 # since we avoided incrementing the buffer size or
577 # putting it in the buffer. we also know there
578 # can't be anything else to write.
579 return 1 if $need_queue;
588 sub on_incomplete_write {
589 my PublicInbox::DS $self = shift;
590 $self->watch_write(1);
593 =head2 C<< $obj->watch_read( $boolean ) >>
595 Turn 'readable' event notification on or off.
599 my PublicInbox::DS $self = shift;
600 my $sock = $self->{sock} or return;
603 my $event = $self->{event_watch};
605 $event &= ~POLLIN if ! $val;
606 $event |= POLLIN if $val;
608 my $fd = fileno($sock);
609 # If it changed, set it
610 if ($event != $self->{event_watch}) {
612 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
613 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
616 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
617 confess("EPOLL_CTL_MOD: $!");
619 $self->{event_watch} = $event;
623 =head2 C<< $obj->watch_write( $boolean ) >>
625 Turn 'writable' event notification on or off.
629 my PublicInbox::DS $self = shift;
630 my $sock = $self->{sock} or return;
633 my $event = $self->{event_watch};
635 $event &= ~POLLOUT if ! $val;
636 $event |= POLLOUT if $val;
637 my $fd = fileno($sock);
639 # If it changed, set it
640 if ($event != $self->{event_watch}) {
642 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
643 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
646 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
647 confess "EPOLL_CTL_MOD: $!";
649 $self->{event_watch} = $event;
653 package PublicInbox::DS::Timer;
654 # [$abs_float_firetime, $coderef];
661 =head1 AUTHORS (Danga::Socket)
663 Brad Fitzpatrick <brad@danga.com> - author
665 Michael Granger <ged@danga.com> - docs, testing
667 Mark Smith <junior@danga.com> - contributor, heavy user, testing
669 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits