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
36 use Errno qw(EAGAIN EINVAL);
37 use Carp qw(croak confess);
38 use File::Temp qw(tempfile);
40 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
43 $HaveEpoll, # Flag -- is epoll available? initially undefined.
45 %DescriptorMap, # fd (num) -> PublicInbox::DS object
46 $Epoll, # Global epoll fd (for epoll mode only)
47 $KQueue, # Global kqueue fd ref (for kqueue mode only)
48 $_io, # IO::Handle for Epoll
49 @ToClose, # sockets to close when event loop is done
51 $PostLoopCallback, # subref to call at the end of each loop, if defined (global)
53 $LoopTimeout, # timeout of event loop in milliseconds
54 $DoneInit, # if we've done the one-time module init yet
60 #####################################################################
61 ### C L A S S M E T H O D S
62 #####################################################################
64 =head2 C<< CLASS->Reset() >>
72 $LoopTimeout = -1; # no timeout by default
75 $PostLoopCallback = undef;
78 # NOTE kqueue is close-on-fork, and we don't account for it, yet
79 # OTOH, we (public-inbox) don't need this sub outside of tests...
80 POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
83 $_io = undef; # close $Epoll
86 *EventLoop = *FirstTimeEventLoop;
89 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
91 Set the loop timeout for the event loop to some value in milliseconds.
93 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
98 return $LoopTimeout = $_[1] + 0;
101 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
103 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
104 are not guaranteed to fire at the exact time you ask for.
106 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
110 my ($class, $secs, $coderef) = @_;
113 my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
114 unshift(@Timers, $timer);
118 my $fire_time = now() + $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 sub now () { clock_gettime(CLOCK_MONOTONIC) }
200 # runs timers and returns milliseconds for next one, or next event loop
202 return $LoopTimeout unless @Timers;
207 while (@Timers && $Timers[0][0] <= $now) {
208 my $to_run = shift(@Timers);
209 $to_run->[1]->($now) if $to_run->[1];
212 return $LoopTimeout unless @Timers;
214 # convert time to an even number of milliseconds, adding 1
215 # extra, otherwise floating point fun can occur and we'll
216 # call RunTimers like 20-30 times, each returning a timeout
217 # of 0.0000212 seconds
218 my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
220 # -1 is an infinite timeout, so prefer a real timeout
221 return $timeout if $LoopTimeout == -1;
223 # otherwise pick the lower of our regular timeout and time until
225 return $LoopTimeout if $LoopTimeout < $timeout;
229 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
237 my $timeout = RunTimers();
239 # get up to 1000 events
240 my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
241 for ($i=0; $i<$evcount; $i++) {
242 # it's possible epoll_wait returned many events, including some at the end
243 # that ones in the front triggered unregister-interest actions. if we
244 # can't find the %sock entry, it's because we're no longer interested
246 $DescriptorMap{$events[$i]->[0]}->event_step;
248 return unless PostEventLoop();
253 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
254 ### IO::Epoll fails to load.
258 my PublicInbox::DS $pob;
261 my $timeout = RunTimers();
263 # the following sets up @poll as a series of ($poll,$event_mask)
264 # items, then uses IO::Poll::_poll, implemented in XS, which
265 # modifies the array in place with the even elements being
266 # replaced with the event masks that occured.
268 while ( my ($fd, $sock) = each %DescriptorMap ) {
269 push @poll, $fd, $sock->{event_watch};
272 # if nothing to poll, either end immediately (if no timeout)
273 # or just keep calling the callback
275 select undef, undef, undef, ($timeout / 1000);
276 return unless PostEventLoop();
280 my $count = IO::Poll::_poll($timeout, @poll);
281 unless ($count >= 0) {
282 return unless PostEventLoop();
286 # Fetch handles with read events
288 my ($fd, $state) = splice(@poll, 0, 2);
289 $DescriptorMap{$fd}->event_step if $state;
292 return unless PostEventLoop();
298 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
300 sub KQueueEventLoop {
304 my $timeout = RunTimers();
305 my @ret = eval { $KQueue->kevent($timeout) };
307 # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
308 if ($err =~ /Interrupted system call/) {
315 foreach my $kev (@ret) {
316 $DescriptorMap{$kev->[0]}->event_step;
318 return unless PostEventLoop();
324 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
326 Sets post loop callback function. Pass a subref and it will be
327 called every time the event loop finishes.
329 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
332 The callback function will be passed two parameters: \%DescriptorMap
335 sub SetPostLoopCallback {
336 my ($class, $ref) = @_;
339 $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
342 # Internal function: run the post-event callback, send read events
343 # for pushed-back data, and close pending connections. returns 1
344 # if event loop should continue, or 0 to shut it all down.
346 # now we can close sockets that wanted to close during our event processing.
347 # (we didn't want to close them during the loop, as we didn't want fd numbers
348 # being reused and confused during the event loop)
349 while (my $sock = shift @ToClose) {
350 my $fd = fileno($sock);
352 # close the socket. (not a PublicInbox::DS close)
355 # and now we can finally remove the fd from the map. see
356 # comment above in ->close.
357 delete $DescriptorMap{$fd};
361 # by default we keep running, unless a postloop callback (either per-object
362 # or global) cancels it
363 my $keep_running = 1;
365 # now we're at the very end, call callback if defined
366 if (defined $PostLoopCallback) {
367 $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
370 return $keep_running;
373 #####################################################################
374 ### PublicInbox::DS-the-object code
375 #####################################################################
377 =head2 OBJECT METHODS
379 =head2 C<< CLASS->new( $socket ) >>
381 Create a new PublicInbox::DS subclass object for the given I<socket> which will
382 react to events on it during the C<EventLoop>.
384 This is normally (always?) called from your subclass via:
386 $class->SUPER::new($socket);
390 my ($self, $sock, $ev) = @_;
391 $self = fields::new($self) unless ref $self;
393 $self->{sock} = $sock;
394 my $fd = fileno($sock);
396 Carp::cluck("undef sock and/or fd in PublicInbox::DS->new. sock=" . ($sock || "") . ", fd=" . ($fd || ""))
399 $self->{event_watch} = $ev;
405 if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
406 if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
407 $self->{event_watch} = ($ev &= ~EPOLLEXCLUSIVE);
410 die "couldn't add epoll watch for $fd: $!\n";
413 elsif ($HaveKQueue) {
414 my $f = $ev & EPOLLIN ? IO::KQueue::EV_ENABLE()
415 : IO::KQueue::EV_DISABLE();
416 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
417 IO::KQueue::EV_ADD() | $f);
418 $f = $ev & EPOLLOUT ? IO::KQueue::EV_ENABLE()
419 : IO::KQueue::EV_DISABLE();
420 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
421 IO::KQueue::EV_ADD() | $f);
424 Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
425 if $DescriptorMap{$fd};
427 $DescriptorMap{$fd} = $self;
432 #####################################################################
433 ### I N S T A N C E M E T H O D S
434 #####################################################################
436 =head2 C<< $obj->close >>
443 my $sock = delete $self->{sock} or return;
445 # we need to flush our write buffer, as there may
446 # be self-referential closures (sub { $client->close })
447 # preventing the object from being destroyed
448 delete $self->{wbuf};
450 # if we're using epoll, we have to remove this from our epoll fd so we stop getting
451 # notifications about it
453 my $fd = fileno($sock);
454 epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
455 confess("EPOLL_CTL_DEL: $!");
458 # we explicitly don't delete from DescriptorMap here until we
459 # actually close the socket, as we might be in the middle of
460 # processing an epoll_wait/etc that returned hundreds of fds, one
461 # of which is not yet processed and is what we're closing. if we
462 # keep it in DescriptorMap, then the event harnesses can just
463 # looked at $pob->{sock} == undef and ignore it. but if it's an
464 # un-accounted for fd, then it (understandably) freak out a bit
465 # and emit warnings, thinking their state got off.
467 # defer closing the actual socket until the event loop is done
468 # processing this round of events. (otherwise we might reuse fds)
469 push @ToClose, $sock;
474 # portable, non-thread-safe sendfile emulation (no pread, yet)
475 sub psendfile ($$$) {
476 my ($sock, $fh, $off) = @_;
478 sysseek($fh, $$off, SEEK_SET) or return;
479 defined(my $to_write = sysread($fh, my $buf, 16384)) or return;
481 while ($to_write > 0) {
482 if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
486 return if $written == 0;
494 # returns 1 if done, 0 if incomplete
495 sub flush_write ($) {
497 my $wbuf = $self->{wbuf} or return 1;
498 my $sock = $self->{sock} or return 1;
501 while (my $bref = $wbuf->[0]) {
502 if (ref($bref) ne 'CODE') {
503 my $off = delete($self->{wbuf_off}) // 0;
505 my $w = psendfile($sock, $bref, \$off);
511 } elsif ($! == EAGAIN) {
512 $self->{wbuf_off} = $off;
513 watch_write($self, 1);
519 } else { #($ref eq 'CODE') {
525 delete $self->{wbuf};
526 $self->watch_write(0);
530 sub write_in_full ($$$$) {
531 my ($fh, $bref, $len, $off) = @_;
534 my $w = syswrite($fh, $$bref, $len, $off);
535 return ($rv ? $rv : $w) unless $w; # undef or 0
544 my ($bref, $off) = @_;
545 # open(my $fh, '+>>', undef) doesn't set O_APPEND
546 my ($fh, $path) = tempfile('wbuf-XXXXXXX', TMPDIR => 1);
547 open $fh, '+>>', $path or die "open: $!";
549 my $to_write = bytes::length($$bref) - $off;
550 my $w = write_in_full($fh, $bref, $to_write, $off);
551 die "write_in_full ($to_write): $!" unless defined $w;
552 $w == $to_write ? $fh : die("short write $w < $to_write");
555 =head2 C<< $obj->write( $data ) >>
557 Write the specified data to the underlying handle. I<data> may be scalar,
558 scalar ref, code ref (to run when there).
559 Returns 1 if writes all went through, or 0 if there are writes in queue. If
560 it returns 1, caller should stop waiting for 'writable' events)
564 my ($self, $data) = @_;
566 # nobody should be writing to closed sockets, but caller code can
567 # do two writes within an event, have the first fail and
568 # disconnect the other side (whose destructor then closes the
569 # calling object, but it's still in a method), and then the
570 # now-dead object does its second write. that is this case. we
571 # just lie and say it worked. it'll be dead soon and won't be
573 my $sock = $self->{sock} or return 1;
575 my $bref = $ref ? $data : \$data;
576 if (my $wbuf = $self->{wbuf}) { # already buffering, can't write more...
577 if ($ref eq 'CODE') {
580 my $last = $wbuf->[-1];
581 if (ref($last) eq 'GLOB') { # append to tmp file buffer
582 write_in_full($last, $bref, bytes::length($$bref), 0);
584 push @$wbuf, tmpbuf($bref, 0);
588 } elsif ($ref eq 'CODE') {
592 my $to_write = bytes::length($$bref);
593 my $written = syswrite($sock, $$bref, $to_write);
595 if (defined $written) {
596 return 1 if $written == $to_write;
597 } elsif ($! == EAGAIN) {
602 $self->{wbuf} = [ tmpbuf($bref, $written) ];
603 watch_write($self, 1);
608 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
612 my $sock = $self->{sock} or return 1;
614 if (MSG_MORE && !$self->{wbuf}) {
615 my $n = send($sock, $_[1], MSG_MORE);
617 my $nlen = bytes::length($_[1]) - $n;
618 return 1 if $nlen == 0; # all done!
620 # queue up the unwritten substring:
621 $self->{wbuf} = [ tmpbuf(\($_[1]), $n) ];
622 watch_write($self, 1);
626 $self->write(\($_[1]));
629 =head2 C<< $obj->watch_read( $boolean ) >>
631 Turn 'readable' event notification on or off.
635 my PublicInbox::DS $self = shift;
636 my $sock = $self->{sock} or return;
639 my $event = $self->{event_watch};
641 $event &= ~EPOLLIN if ! $val;
642 $event |= EPOLLIN if $val;
644 my $fd = fileno($sock);
645 # If it changed, set it
646 if ($event != $self->{event_watch}) {
648 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
649 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
652 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
653 confess("EPOLL_CTL_MOD: $!");
655 $self->{event_watch} = $event;
659 =head2 C<< $obj->watch_write( $boolean ) >>
661 Turn 'writable' event notification on or off.
665 my PublicInbox::DS $self = shift;
666 my $sock = $self->{sock} or return;
669 my $event = $self->{event_watch};
671 $event &= ~EPOLLOUT if ! $val;
672 $event |= EPOLLOUT if $val;
673 my $fd = fileno($sock);
675 # If it changed, set it
676 if ($event != $self->{event_watch}) {
678 $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
679 $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
682 epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
683 confess "EPOLL_CTL_MOD: $!";
685 $self->{event_watch} = $event;
689 package PublicInbox::DS::Timer;
690 # [$abs_float_firetime, $coderef];
697 =head1 AUTHORS (Danga::Socket)
699 Brad Fitzpatrick <brad@danga.com> - author
701 Michael Granger <ged@danga.com> - docs, testing
703 Mark Smith <junior@danga.com> - contributor, heavy user, testing
705 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits