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 POLLIN => 1;
38 use constant POLLOUT => 4;
39 use constant POLLERR => 8;
40 use constant POLLHUP => 16;
41 use constant POLLNVAL => 32;
43 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
46 $HaveEpoll, # Flag -- is epoll available? initially undefined.
48 %DescriptorMap, # fd (num) -> PublicInbox::DS object
49 $Epoll, # Global epoll fd (for epoll mode only)
50 $KQueue, # Global kqueue fd ref (for kqueue mode only)
51 $_io, # IO::Handle for Epoll
52 @ToClose, # sockets to close when event loop is done
54 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
56 $LoopTimeout, # timeout of event loop in milliseconds
57 $DoneInit, # if we've done the one-time module init yet
61 # this may be set to zero with old kernels
62 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
65 #####################################################################
66 ### C L A S S M E T H O D S
67 #####################################################################
69 =head2 C<< CLASS->Reset() >>
77 $LoopTimeout = -1; # no timeout by default
80 $PostLoopCallback = undef;
83 # NOTE kqueue is close-on-fork, and we don't account for it, yet
84 # OTOH, we (public-inbox) don't need this sub outside of tests...
85 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
88 $_io = undef; # close $Epoll
91 *EventLoop = *FirstTimeEventLoop;
94 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
96 Set the loop timeout for the event loop to some value in milliseconds.
98 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
103 return $LoopTimeout = $_[1] + 0;
106 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
108 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
109 are not guaranteed to fire at the exact time you ask for.
111 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
116 my ($secs, $coderef) = @_;
118 my $fire_time = Time::HiRes::time() + $secs;
120 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
122 if (!@Timers || $fire_time >= $Timers[-1][0]) {
123 push @Timers, $timer;
127 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
128 # but it was compared against calendar queues, heaps, naive push/sort,
129 # and a bunch of other versions, and found to be fastest with a large
130 # variety of datasets.)
131 for (my $i = 0; $i < @Timers; $i++) {
132 if ($Timers[$i][0] > $fire_time) {
133 splice(@Timers, $i, 0, $timer);
138 die "Shouldn't get here.";
141 # keeping this around in case we support other FD types for now,
142 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
143 sub set_cloexec ($) {
146 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
147 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
148 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
157 $KQueue = IO::KQueue->new();
158 $HaveKQueue = defined $KQueue;
160 *EventLoop = *KQueueEventLoop;
163 elsif (PublicInbox::Syscall::epoll_defined()) {
164 $Epoll = eval { epoll_create(1024); };
165 $HaveEpoll = defined $Epoll && $Epoll >= 0;
168 *EventLoop = *EpollEventLoop;
172 if (!$HaveEpoll && !$HaveKQueue) {
174 *EventLoop = *PollEventLoop;
178 =head2 C<< CLASS->EventLoop() >>
180 Start processing IO events. In most daemon programs this never exits. See
181 C<PostLoopCallback> below for how to exit the loop.
184 sub FirstTimeEventLoop {
190 EpollEventLoop($class);
191 } elsif ($HaveKQueue) {
192 KQueueEventLoop($class);
194 PollEventLoop($class);
198 # runs timers and returns milliseconds for next one, or next event loop
200 return $LoopTimeout unless @Timers;
202 my $now = Time::HiRes::time();
205 while (@Timers && $Timers[0][0] <= $now) {
206 my $to_run = shift(@Timers);
207 $to_run->[1]->($now) if $to_run->[1];
210 return $LoopTimeout unless @Timers;
212 # convert time to an even number of milliseconds, adding 1
213 # extra, otherwise floating point fun can occur and we'll
214 # call RunTimers like 20-30 times, each returning a timeout
215 # of 0.0000212 seconds
216 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
218 # -1 is an infinite timeout, so prefer a real timeout
219 return $timeout if $LoopTimeout == -1;
221 # otherwise pick the lower of our regular timeout and time until
223 return $LoopTimeout if $LoopTimeout < $timeout;
227 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
235 my $timeout = RunTimers();
237 # get up to 1000 events
238 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
239 for ($i=0; $i<$evcount; $i++) {
240 # it's possible epoll_wait returned many events, including some at the end
241 # that ones in the front triggered unregister-interest actions. if we
242 # can't find the %sock entry, it's because we're no longer interested
244 $DescriptorMap{$events[$i]->[0]}->event_step;
246 return unless PostEventLoop();
251 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
252 ### IO::Epoll fails to load.
256 my PublicInbox::DS $pob;
259 my $timeout = RunTimers();
261 # the following sets up @poll as a series of ($poll,$event_mask)
262 # items, then uses IO::Poll::_poll, implemented in XS, which
263 # modifies the array in place with the even elements being
264 # replaced with the event masks that occured.
266 while ( my ($fd, $sock) = each %DescriptorMap ) {
267 push @poll, $fd, $sock->{event_watch};
270 # if nothing to poll, either end immediately (if no timeout)
271 # or just keep calling the callback
273 select undef, undef, undef, ($timeout / 1000);
274 return unless PostEventLoop();
278 my $count = IO::Poll::_poll($timeout, @poll);
279 unless ($count >= 0) {
280 return unless PostEventLoop();
284 # Fetch handles with read events
286 my ($fd, $state) = splice(@poll, 0, 2);
287 $DescriptorMap{$fd}->event_step if $state;
290 return unless PostEventLoop();
296 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
298 sub KQueueEventLoop {
302 my $timeout = RunTimers();
303 my @ret = eval { $KQueue->kevent($timeout) };
305 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
306 if ($err =~ /Interrupted system call/) {
313 foreach my $kev (@ret) {
314 $DescriptorMap{$kev->[0]}->event_step;
316 return unless PostEventLoop();
322 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
324 Sets post loop callback function. Pass a subref and it will be
325 called every time the event loop finishes.
327 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
330 The callback function will be passed two parameters: \%DescriptorMap
333 sub SetPostLoopCallback {
334 my ($class, $ref) = @_;
337 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
340 # Internal function: run the post-event callback, send read events
341 # for pushed-back data, and close pending connections. returns 1
342 # if event loop should continue, or 0 to shut it all down.
344 # now we can close sockets that wanted to close during our event processing.
345 # (we didn't want to close them during the loop, as we didn't want fd numbers
346 # being reused and confused during the event loop)
347 while (my $sock = shift @ToClose) {
348 my $fd = fileno($sock);
350 # close the socket. (not a PublicInbox::DS close)
353 # and now we can finally remove the fd from the map. see
354 # comment above in ->close.
355 delete $DescriptorMap{$fd};
359 # by default we keep running, unless a postloop callback (either per-object
360 # or global) cancels it
361 my $keep_running = 1;
363 # now we're at the very end, call callback if defined
364 if (defined $PostLoopCallback) {
365 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
368 return $keep_running;
371 #####################################################################
372 ### PublicInbox::DS-the-object code
373 #####################################################################
375 =head2 OBJECT METHODS
377 =head2 C<< CLASS->new( $socket ) >>
379 Create a new PublicInbox::DS subclass object for the given I<socket> which will
380 react to events on it during the C<EventLoop>.
382 This is normally (always?) called from your subclass via:
384 $class->SUPER::new($socket);
388 my ($self, $sock, $exclusive) = @_;
389 $self = fields::new($self) unless ref $self;
391 $self->{sock} = $sock;
392 my $fd = fileno($sock);
394 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
398 $self->{wbuf_off} = 0;
400 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
406 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
409 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
410 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
411 $EPOLLEXCLUSIVE = 0; # old kernel
412 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
415 die "couldn't add epoll watch for $fd: $!\n";
418 elsif ($HaveKQueue) {
419 # Add them to the queue but disabled for now
420 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
421 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
422 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
423 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
426 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
427 if $DescriptorMap{$fd};
429 $DescriptorMap{$fd} = $self;
434 #####################################################################
435 ### I N S T A N C E M E T H O D S
436 #####################################################################
438 =head2 C<< $obj->close >>
445 my $sock = delete $self->{sock} or return;
447 # we need to flush our write buffer, as there may
448 # be self-referential closures (sub { $client->close })
449 # preventing the object from being destroyed
450 @{$self->{wbuf}} = ();
452 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
453 # notifications about it
455 my $fd = fileno($sock);
456 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
457 confess("EPOLL_CTL_DEL: $!");
460 # we explicitly don't delete from DescriptorMap here until we
461 # actually close the socket, as we might be in the middle of
462 # processing an epoll_wait/etc that returned hundreds of fds, one
463 # of which is not yet processed and is what we're closing. if we
464 # keep it in DescriptorMap, then the event harnesses can just
465 # looked at $pob->{sock} == undef and ignore it. but if it's an
466 # un-accounted for fd, then it (understandably) freak out a bit
467 # and emit warnings, thinking their state got off.
469 # defer closing the actual socket until the event loop is done
470 # processing this round of events. (otherwise we might reuse fds)
471 push @ToClose, $sock;
476 =head2 C<< $obj->write( $data ) >>
478 Write the specified data to the underlying handle. I<data> may be scalar,
479 scalar ref, code ref (to run when there), or undef just to kick-start.
480 Returns 1 if writes all went through, or 0 if there are writes in queue. If
481 it returns 1, caller should stop waiting for 'writable' events)
485 my PublicInbox::DS $self;
489 # nobody should be writing to closed sockets, but caller code can
490 # do two writes within an event, have the first fail and
491 # disconnect the other side (whose destructor then closes the
492 # calling object, but it's still in a method), and then the
493 # now-dead object does its second write. that is this case. we
494 # just lie and say it worked. it'll be dead soon and won't be
496 return 1 unless $self->{sock};
500 # just queue data if there's already a wait
502 my $wbuf = $self->{wbuf};
505 $bref = ref $data ? $data : \$data;
511 # this flag says we're bypassing the queue system, knowing we're the
512 # only outstanding write, and hoping we don't ever need to use it.
513 # if so later, though, we'll need to queue
519 return 1 unless $bref ||= $wbuf->[0];
523 $len = length($$bref); # this will die if $bref is a code ref, caught below
526 if (UNIVERSAL::isa($bref, "CODE")) {
527 unless ($need_queue) {
532 # code refs are just run and never get reenqueued
533 # (they're one-shot), so turn off the flag indicating the
534 # outstanding data needs queueing.
540 die "Write error: $@ <$bref>";
543 my $to_write = $len - $self->{wbuf_off};
544 my $written = syswrite($self->{sock}, $$bref, $to_write,
547 if (! defined $written) {
549 # since connection has stuff to write, it should now be
550 # interested in pending writes:
554 $self->watch_write(1);
559 } elsif ($written != $to_write) {
563 # since connection has stuff to write, it should now be
564 # interested in pending writes:
565 $self->{wbuf_off} += $written;
566 $self->on_incomplete_write;
568 } elsif ($written == $to_write) {
569 $self->{wbuf_off} = 0;
570 $self->watch_write(0);
572 # this was our only write, so we can return immediately
573 # since we avoided incrementing the buffer size or
574 # putting it in the buffer. we also know there
575 # can't be anything else to write.
576 return 1 if $need_queue;
585 sub on_incomplete_write {
586 my PublicInbox::DS $self = shift;
587 $self->watch_write(1);
590 =head2 C<< $obj->watch_read( $boolean ) >>
592 Turn 'readable' event notification on or off.
596 my PublicInbox::DS $self = shift;
597 my $sock = $self->{sock} or return;
600 my $event = $self->{event_watch};
602 $event &= ~POLLIN if ! $val;
603 $event |= POLLIN if $val;
605 my $fd = fileno($sock);
606 # If it changed, set it
607 if ($event != $self->{event_watch}) {
609 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
610 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
613 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
614 confess("EPOLL_CTL_MOD: $!");
616 $self->{event_watch} = $event;
620 =head2 C<< $obj->watch_write( $boolean ) >>
622 Turn 'writable' event notification on or off.
626 my PublicInbox::DS $self = shift;
627 my $sock = $self->{sock} or return;
630 my $event = $self->{event_watch};
632 $event &= ~POLLOUT if ! $val;
633 $event |= POLLOUT if $val;
634 my $fd = fileno($sock);
636 # If it changed, set it
637 if ($event != $self->{event_watch}) {
639 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
640 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
643 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
644 confess "EPOLL_CTL_MOD: $!";
646 $self->{event_watch} = $event;
650 package PublicInbox::DS::Timer;
651 # [$abs_float_firetime, $coderef];
658 =head1 AUTHORS (Danga::Socket)
660 Brad Fitzpatrick <brad@danga.com> - author
662 Michael Granger <ged@danga.com> - docs, testing
664 Mark Smith <junior@danga.com> - contributor, heavy user, testing
666 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits