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.
116 my ($class, $secs, $coderef) = @_;
119 my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
120 unshift(@Timers, $timer);
124 my $fire_time = now() + $secs;
126 my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
128 if (!@Timers || $fire_time >= $Timers[-1][0]) {
129 push @Timers, $timer;
133 # Now, where do we insert? (NOTE: this appears slow, algorithm-wise,
134 # but it was compared against calendar queues, heaps, naive push/sort,
135 # and a bunch of other versions, and found to be fastest with a large
136 # variety of datasets.)
137 for (my $i = 0; $i < @Timers; $i++) {
138 if ($Timers[$i][0] > $fire_time) {
139 splice(@Timers, $i, 0, $timer);
144 die "Shouldn't get here.";
147 # keeping this around in case we support other FD types for now,
148 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
149 sub set_cloexec ($) {
152 $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
153 defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
154 fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
163 $KQueue = IO::KQueue->new();
164 $HaveKQueue = defined $KQueue;
166 *EventLoop = *KQueueEventLoop;
169 elsif (PublicInbox::Syscall::epoll_defined()) {
170 $Epoll = eval { epoll_create(1024); };
171 $HaveEpoll = defined $Epoll && $Epoll >= 0;
174 *EventLoop = *EpollEventLoop;
178 if (!$HaveEpoll && !$HaveKQueue) {
180 *EventLoop = *PollEventLoop;
184 =head2 C<< CLASS->EventLoop() >>
186 Start processing IO events. In most daemon programs this never exits. See
187 C<PostLoopCallback> below for how to exit the loop.
190 sub FirstTimeEventLoop {
196 EpollEventLoop($class);
197 } elsif ($HaveKQueue) {
198 KQueueEventLoop($class);
200 PollEventLoop($class);
204 sub now () { clock_gettime(CLOCK_MONOTONIC) }
206 # runs timers and returns milliseconds for next one, or next event loop
208 return $LoopTimeout unless @Timers;
213 while (@Timers && $Timers[0][0] <= $now) {
214 my $to_run = shift(@Timers);
215 $to_run->[1]->($now) if $to_run->[1];
218 return $LoopTimeout unless @Timers;
220 # convert time to an even number of milliseconds, adding 1
221 # extra, otherwise floating point fun can occur and we'll
222 # call RunTimers like 20-30 times, each returning a timeout
223 # of 0.0000212 seconds
224 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
226 # -1 is an infinite timeout, so prefer a real timeout
227 return $timeout if $LoopTimeout == -1;
229 # otherwise pick the lower of our regular timeout and time until
231 return $LoopTimeout if $LoopTimeout < $timeout;
235 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
243 my $timeout = RunTimers();
245 # get up to 1000 events
246 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
247 for ($i=0; $i<$evcount; $i++) {
248 # it's possible epoll_wait returned many events, including some at the end
249 # that ones in the front triggered unregister-interest actions. if we
250 # can't find the %sock entry, it's because we're no longer interested
252 $DescriptorMap{$events[$i]->[0]}->event_step;
254 return unless PostEventLoop();
259 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
260 ### IO::Epoll fails to load.
264 my PublicInbox::DS $pob;
267 my $timeout = RunTimers();
269 # the following sets up @poll as a series of ($poll,$event_mask)
270 # items, then uses IO::Poll::_poll, implemented in XS, which
271 # modifies the array in place with the even elements being
272 # replaced with the event masks that occured.
274 while ( my ($fd, $sock) = each %DescriptorMap ) {
275 push @poll, $fd, $sock->{event_watch};
278 # if nothing to poll, either end immediately (if no timeout)
279 # or just keep calling the callback
281 select undef, undef, undef, ($timeout / 1000);
282 return unless PostEventLoop();
286 my $count = IO::Poll::_poll($timeout, @poll);
287 unless ($count >= 0) {
288 return unless PostEventLoop();
292 # Fetch handles with read events
294 my ($fd, $state) = splice(@poll, 0, 2);
295 $DescriptorMap{$fd}->event_step if $state;
298 return unless PostEventLoop();
304 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
306 sub KQueueEventLoop {
310 my $timeout = RunTimers();
311 my @ret = eval { $KQueue->kevent($timeout) };
313 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
314 if ($err =~ /Interrupted system call/) {
321 foreach my $kev (@ret) {
322 $DescriptorMap{$kev->[0]}->event_step;
324 return unless PostEventLoop();
330 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
332 Sets post loop callback function. Pass a subref and it will be
333 called every time the event loop finishes.
335 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
338 The callback function will be passed two parameters: \%DescriptorMap
341 sub SetPostLoopCallback {
342 my ($class, $ref) = @_;
345 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
348 # Internal function: run the post-event callback, send read events
349 # for pushed-back data, and close pending connections. returns 1
350 # if event loop should continue, or 0 to shut it all down.
352 # now we can close sockets that wanted to close during our event processing.
353 # (we didn't want to close them during the loop, as we didn't want fd numbers
354 # being reused and confused during the event loop)
355 while (my $sock = shift @ToClose) {
356 my $fd = fileno($sock);
358 # close the socket. (not a PublicInbox::DS close)
361 # and now we can finally remove the fd from the map. see
362 # comment above in ->close.
363 delete $DescriptorMap{$fd};
367 # by default we keep running, unless a postloop callback (either per-object
368 # or global) cancels it
369 my $keep_running = 1;
371 # now we're at the very end, call callback if defined
372 if (defined $PostLoopCallback) {
373 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
376 return $keep_running;
379 #####################################################################
380 ### PublicInbox::DS-the-object code
381 #####################################################################
383 =head2 OBJECT METHODS
385 =head2 C<< CLASS->new( $socket ) >>
387 Create a new PublicInbox::DS subclass object for the given I<socket> which will
388 react to events on it during the C<EventLoop>.
390 This is normally (always?) called from your subclass via:
392 $class->SUPER::new($socket);
396 my ($self, $sock, $exclusive) = @_;
397 $self = fields::new($self) unless ref $self;
399 $self->{sock} = $sock;
400 my $fd = fileno($sock);
402 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
406 $self->{wbuf_off} = 0;
408 my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
414 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
417 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
418 if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
419 $EPOLLEXCLUSIVE = 0; # old kernel
420 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
423 die "couldn't add epoll watch for $fd: $!\n";
426 elsif ($HaveKQueue) {
427 # Add them to the queue but disabled for now
428 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
429 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
430 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
431 IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
434 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
435 if $DescriptorMap{$fd};
437 $DescriptorMap{$fd} = $self;
442 #####################################################################
443 ### I N S T A N C E M E T H O D S
444 #####################################################################
446 =head2 C<< $obj->close >>
453 my $sock = delete $self->{sock} or return;
455 # we need to flush our write buffer, as there may
456 # be self-referential closures (sub { $client->close })
457 # preventing the object from being destroyed
458 @{$self->{wbuf}} = ();
460 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
461 # notifications about it
463 my $fd = fileno($sock);
464 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
465 confess("EPOLL_CTL_DEL: $!");
468 # we explicitly don't delete from DescriptorMap here until we
469 # actually close the socket, as we might be in the middle of
470 # processing an epoll_wait/etc that returned hundreds of fds, one
471 # of which is not yet processed and is what we're closing. if we
472 # keep it in DescriptorMap, then the event harnesses can just
473 # looked at $pob->{sock} == undef and ignore it. but if it's an
474 # un-accounted for fd, then it (understandably) freak out a bit
475 # and emit warnings, thinking their state got off.
477 # defer closing the actual socket until the event loop is done
478 # processing this round of events. (otherwise we might reuse fds)
479 push @ToClose, $sock;
484 =head2 C<< $obj->write( $data ) >>
486 Write the specified data to the underlying handle. I<data> may be scalar,
487 scalar ref, code ref (to run when there), or undef just to kick-start.
488 Returns 1 if writes all went through, or 0 if there are writes in queue. If
489 it returns 1, caller should stop waiting for 'writable' events)
493 my PublicInbox::DS $self;
497 # nobody should be writing to closed sockets, but caller code can
498 # do two writes within an event, have the first fail and
499 # disconnect the other side (whose destructor then closes the
500 # calling object, but it's still in a method), and then the
501 # now-dead object does its second write. that is this case. we
502 # just lie and say it worked. it'll be dead soon and won't be
504 return 1 unless $self->{sock};
508 # just queue data if there's already a wait
510 my $wbuf = $self->{wbuf};
513 $bref = ref $data ? $data : \$data;
519 # this flag says we're bypassing the queue system, knowing we're the
520 # only outstanding write, and hoping we don't ever need to use it.
521 # if so later, though, we'll need to queue
527 return 1 unless $bref ||= $wbuf->[0];
531 $len = length($$bref); # this will die if $bref is a code ref, caught below
534 if (UNIVERSAL::isa($bref, "CODE")) {
535 unless ($need_queue) {
540 # code refs are just run and never get reenqueued
541 # (they're one-shot), so turn off the flag indicating the
542 # outstanding data needs queueing.
548 die "Write error: $@ <$bref>";
551 my $to_write = $len - $self->{wbuf_off};
552 my $written = syswrite($self->{sock}, $$bref, $to_write,
555 if (! defined $written) {
557 # since connection has stuff to write, it should now be
558 # interested in pending writes:
562 $self->watch_write(1);
567 } elsif ($written != $to_write) {
571 # since connection has stuff to write, it should now be
572 # interested in pending writes:
573 $self->{wbuf_off} += $written;
574 $self->on_incomplete_write;
576 } elsif ($written == $to_write) {
577 $self->{wbuf_off} = 0;
578 $self->watch_write(0);
580 # this was our only write, so we can return immediately
581 # since we avoided incrementing the buffer size or
582 # putting it in the buffer. we also know there
583 # can't be anything else to write.
584 return 1 if $need_queue;
593 sub on_incomplete_write {
594 my PublicInbox::DS $self = shift;
595 $self->watch_write(1);
598 =head2 C<< $obj->watch_read( $boolean ) >>
600 Turn 'readable' event notification on or off.
604 my PublicInbox::DS $self = shift;
605 my $sock = $self->{sock} or return;
608 my $event = $self->{event_watch};
610 $event &= ~POLLIN if ! $val;
611 $event |= POLLIN if $val;
613 my $fd = fileno($sock);
614 # If it changed, set it
615 if ($event != $self->{event_watch}) {
617 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
618 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
621 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
622 confess("EPOLL_CTL_MOD: $!");
624 $self->{event_watch} = $event;
628 =head2 C<< $obj->watch_write( $boolean ) >>
630 Turn 'writable' event notification on or off.
634 my PublicInbox::DS $self = shift;
635 my $sock = $self->{sock} or return;
638 my $event = $self->{event_watch};
640 $event &= ~POLLOUT if ! $val;
641 $event |= POLLOUT if $val;
642 my $fd = fileno($sock);
644 # If it changed, set it
645 if ($event != $self->{event_watch}) {
647 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
648 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
651 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
652 confess "EPOLL_CTL_MOD: $!";
654 $self->{event_watch} = $event;
658 package PublicInbox::DS::Timer;
659 # [$abs_float_firetime, $coderef];
666 =head1 AUTHORS (Danga::Socket)
668 Brad Fitzpatrick <brad@danga.com> - author
670 Michael Granger <ged@danga.com> - docs, testing
672 Mark Smith <junior@danga.com> - contributor, heavy user, testing
674 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits