]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: get rid of {closed} field
[public-inbox.git] / lib / PublicInbox / DS.pm
1 # This library is free software; you can redistribute it and/or modify
2 # it under the same terms as Perl itself.
3 #
4 # This license differs from the rest of public-inbox
5 #
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.
9 #
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;
17 use strict;
18 use bytes;
19 use POSIX ();
20 use Time::HiRes ();
21 use IO::Handle qw();
22 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
23
24 use warnings;
25
26 use PublicInbox::Syscall qw(:epoll);
27
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.)
32             );
33
34 use Errno  qw(EAGAIN EINVAL);
35 use Carp   qw(croak confess);
36
37 use constant DebugLevel => 0;
38
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;
44
45 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
46
47 our (
48      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
49      $HaveKQueue,
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
55
56      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
57
58      $LoopTimeout,               # timeout of event loop in milliseconds
59      $DoneInit,                  # if we've done the one-time module init yet
60      @Timers,                    # timers
61      );
62
63 # this may be set to zero with old kernels
64 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
65 Reset();
66
67 #####################################################################
68 ### C L A S S   M E T H O D S
69 #####################################################################
70
71 =head2 C<< CLASS->Reset() >>
72
73 Reset all state
74
75 =cut
76 sub Reset {
77     %DescriptorMap = ();
78     @ToClose = ();
79     $LoopTimeout = -1;  # no timeout by default
80     @Timers = ();
81
82     $PostLoopCallback = undef;
83     $DoneInit = 0;
84
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;
88     $KQueue = undef;
89
90     $_io = undef; # close $Epoll
91     $Epoll = undef;
92
93     *EventLoop = *FirstTimeEventLoop;
94 }
95
96 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
97
98 Set the loop timeout for the event loop to some value in milliseconds.
99
100 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
101 immediately.
102
103 =cut
104 sub SetLoopTimeout {
105     return $LoopTimeout = $_[1] + 0;
106 }
107
108 =head2 C<< CLASS->DebugMsg( $format, @args ) >>
109
110 Print the debugging message specified by the C<sprintf>-style I<format> and
111 I<args>
112
113 =cut
114 sub DebugMsg {
115     my ( $class, $fmt, @args ) = @_;
116     chomp $fmt;
117     printf STDERR ">>> $fmt\n", @args;
118 }
119
120 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
121
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.
124
125 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
126
127 =cut
128 sub AddTimer {
129     my $class = shift;
130     my ($secs, $coderef) = @_;
131
132     my $fire_time = Time::HiRes::time() + $secs;
133
134     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
135
136     if (!@Timers || $fire_time >= $Timers[-1][0]) {
137         push @Timers, $timer;
138         return $timer;
139     }
140
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);
148             return $timer;
149         }
150     }
151
152     die "Shouldn't get here.";
153 }
154
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 ($) {
158     my ($fd) = @_;
159
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);
163 }
164
165 sub _InitPoller
166 {
167     return if $DoneInit;
168     $DoneInit = 1;
169
170     if ($HAVE_KQUEUE) {
171         $KQueue = IO::KQueue->new();
172         $HaveKQueue = defined $KQueue;
173         if ($HaveKQueue) {
174             *EventLoop = *KQueueEventLoop;
175         }
176     }
177     elsif (PublicInbox::Syscall::epoll_defined()) {
178         $Epoll = eval { epoll_create(1024); };
179         $HaveEpoll = defined $Epoll && $Epoll >= 0;
180         if ($HaveEpoll) {
181             set_cloexec($Epoll);
182             *EventLoop = *EpollEventLoop;
183         }
184     }
185
186     if (!$HaveEpoll && !$HaveKQueue) {
187         require IO::Poll;
188         *EventLoop = *PollEventLoop;
189     }
190 }
191
192 =head2 C<< CLASS->EventLoop() >>
193
194 Start processing IO events. In most daemon programs this never exits. See
195 C<PostLoopCallback> below for how to exit the loop.
196
197 =cut
198 sub FirstTimeEventLoop {
199     my $class = shift;
200
201     _InitPoller();
202
203     if ($HaveEpoll) {
204         EpollEventLoop($class);
205     } elsif ($HaveKQueue) {
206         KQueueEventLoop($class);
207     } else {
208         PollEventLoop($class);
209     }
210 }
211
212 # runs timers and returns milliseconds for next one, or next event loop
213 sub RunTimers {
214     return $LoopTimeout unless @Timers;
215
216     my $now = Time::HiRes::time();
217
218     # Run expired timers
219     while (@Timers && $Timers[0][0] <= $now) {
220         my $to_run = shift(@Timers);
221         $to_run->[1]->($now) if $to_run->[1];
222     }
223
224     return $LoopTimeout unless @Timers;
225
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;
231
232     # -1 is an infinite timeout, so prefer a real timeout
233     return $timeout     if $LoopTimeout == -1;
234
235     # otherwise pick the lower of our regular timeout and time until
236     # the next timer
237     return $LoopTimeout if $LoopTimeout < $timeout;
238     return $timeout;
239 }
240
241 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
242 ### okay.
243 sub EpollEventLoop {
244     my $class = shift;
245
246     while (1) {
247         my @events;
248         my $i;
249         my $timeout = RunTimers();
250
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
257             # in that event.
258             $DescriptorMap{$events[$i]->[0]}->event_step;
259         }
260         return unless PostEventLoop();
261     }
262     exit 0;
263 }
264
265 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
266 ### IO::Epoll fails to load.
267 sub PollEventLoop {
268     my $class = shift;
269
270     my PublicInbox::DS $pob;
271
272     while (1) {
273         my $timeout = RunTimers();
274
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.
279         my @poll;
280         while ( my ($fd, $sock) = each %DescriptorMap ) {
281             push @poll, $fd, $sock->{event_watch};
282         }
283
284         # if nothing to poll, either end immediately (if no timeout)
285         # or just keep calling the callback
286         unless (@poll) {
287             select undef, undef, undef, ($timeout / 1000);
288             return unless PostEventLoop();
289             next;
290         }
291
292         my $count = IO::Poll::_poll($timeout, @poll);
293         unless ($count >= 0) {
294             return unless PostEventLoop();
295             next;
296         }
297
298         # Fetch handles with read events
299         while (@poll) {
300             my ($fd, $state) = splice(@poll, 0, 2);
301             $DescriptorMap{$fd}->event_step if $state;
302         }
303
304         return unless PostEventLoop();
305     }
306
307     exit 0;
308 }
309
310 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
311 ### okay.
312 sub KQueueEventLoop {
313     my $class = shift;
314
315     while (1) {
316         my $timeout = RunTimers();
317         my @ret = eval { $KQueue->kevent($timeout) };
318         if (my $err = $@) {
319             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
320             if ($err =~ /Interrupted system call/) {
321                 @ret = ();
322             } else {
323                 die $err;
324             }
325         }
326
327         foreach my $kev (@ret) {
328             $DescriptorMap{$kev->[0]}->event_step;
329         }
330         return unless PostEventLoop();
331     }
332
333     exit(0);
334 }
335
336 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
337
338 Sets post loop callback function.  Pass a subref and it will be
339 called every time the event loop finishes.
340
341 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
342 and it will exit.
343
344 The callback function will be passed two parameters: \%DescriptorMap
345
346 =cut
347 sub SetPostLoopCallback {
348     my ($class, $ref) = @_;
349
350     # global callback
351     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
352 }
353
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.
357 sub PostEventLoop {
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);
363
364         # close the socket.  (not a PublicInbox::DS close)
365         $sock->close;
366
367         # and now we can finally remove the fd from the map.  see
368         # comment above in ->close.
369         delete $DescriptorMap{$fd};
370     }
371
372
373     # by default we keep running, unless a postloop callback (either per-object
374     # or global) cancels it
375     my $keep_running = 1;
376
377     # now we're at the very end, call callback if defined
378     if (defined $PostLoopCallback) {
379         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
380     }
381
382     return $keep_running;
383 }
384
385 #####################################################################
386 ### PublicInbox::DS-the-object code
387 #####################################################################
388
389 =head2 OBJECT METHODS
390
391 =head2 C<< CLASS->new( $socket ) >>
392
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>.
395
396 This is normally (always?) called from your subclass via:
397
398   $class->SUPER::new($socket);
399
400 =cut
401 sub new {
402     my ($self, $sock, $exclusive) = @_;
403     $self = fields::new($self) unless ref $self;
404
405     $self->{sock} = $sock;
406     my $fd = fileno($sock);
407
408     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
409         unless $sock && $fd;
410
411     $self->{wbuf} = [];
412     $self->{wbuf_off} = 0;
413
414     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
415
416     _InitPoller();
417
418     if ($HaveEpoll) {
419         if ($exclusive) {
420             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
421         }
422 retry:
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;
427                 goto retry;
428             }
429             die "couldn't add epoll watch for $fd: $!\n";
430         }
431     }
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());
438     }
439
440     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
441         if $DescriptorMap{$fd};
442
443     $DescriptorMap{$fd} = $self;
444     return $self;
445 }
446
447
448 #####################################################################
449 ### I N S T A N C E   M E T H O D S
450 #####################################################################
451
452 =head2 C<< $obj->close >>
453
454 Close the socket.
455
456 =cut
457 sub close {
458     my ($self) = @_;
459     my $sock = delete $self->{sock} or return;
460
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}} = ();
465
466     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
467     # notifications about it
468     if ($HaveEpoll) {
469         my $fd = fileno($sock);
470         epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
471             confess("EPOLL_CTL_DEL: $!");
472     }
473
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.
482
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;
486
487     return 0;
488 }
489
490 =head2 C<< $obj->sock() >>
491
492 Returns the underlying IO::Handle for the object.
493
494 =cut
495 sub sock {
496     my PublicInbox::DS $self = shift;
497     return $self->{sock};
498 }
499
500 =head2 C<< $obj->write( $data ) >>
501
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)
506
507 =cut
508 sub write {
509     my PublicInbox::DS $self;
510     my $data;
511     ($self, $data) = @_;
512
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
519     # hurt by this lie.
520     return 1 unless $self->{sock};
521
522     my $bref;
523
524     # just queue data if there's already a wait
525     my $need_queue;
526     my $wbuf = $self->{wbuf};
527
528     if (defined $data) {
529         $bref = ref $data ? $data : \$data;
530         if (scalar @$wbuf) {
531             push @$wbuf, $bref;
532             return 0;
533         }
534
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
538         $need_queue = 1;
539     }
540
541   WRITE:
542     while (1) {
543         return 1 unless $bref ||= $wbuf->[0];
544
545         my $len;
546         eval {
547             $len = length($$bref); # this will die if $bref is a code ref, caught below
548         };
549         if ($@) {
550             if (UNIVERSAL::isa($bref, "CODE")) {
551                 unless ($need_queue) {
552                     shift @$wbuf;
553                 }
554                 $bref->();
555
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.
559                 $need_queue = 0;
560
561                 undef $bref;
562                 next WRITE;
563             }
564             die "Write error: $@ <$bref>";
565         }
566
567         my $to_write = $len - $self->{wbuf_off};
568         my $written = syswrite($self->{sock}, $$bref, $to_write,
569                                $self->{wbuf_off});
570
571         if (! defined $written) {
572             if ($! == EAGAIN) {
573                 # since connection has stuff to write, it should now be
574                 # interested in pending writes:
575                 if ($need_queue) {
576                     push @$wbuf, $bref;
577                 }
578                 $self->watch_write(1);
579                 return 0;
580             }
581
582             return $self->close;
583         } elsif ($written != $to_write) {
584             if ($need_queue) {
585                 push @$wbuf, $bref;
586             }
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;
591             return 0;
592         } elsif ($written == $to_write) {
593             $self->{wbuf_off} = 0;
594             $self->watch_write(0);
595
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;
601
602             shift @$wbuf;
603             undef $bref;
604             next WRITE;
605         }
606     }
607 }
608
609 sub on_incomplete_write {
610     my PublicInbox::DS $self = shift;
611     $self->watch_write(1);
612 }
613
614 =head2 C<< $obj->watch_read( $boolean ) >>
615
616 Turn 'readable' event notification on or off.
617
618 =cut
619 sub watch_read {
620     my PublicInbox::DS $self = shift;
621     my $sock = $self->{sock} or return;
622
623     my $val = shift;
624     my $event = $self->{event_watch};
625
626     $event &= ~POLLIN if ! $val;
627     $event |=  POLLIN if   $val;
628
629     my $fd = fileno($sock);
630     # If it changed, set it
631     if ($event != $self->{event_watch}) {
632         if ($HaveKQueue) {
633             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
634                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
635         }
636         elsif ($HaveEpoll) {
637             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
638                 confess("EPOLL_CTL_MOD: $!");
639         }
640         $self->{event_watch} = $event;
641     }
642 }
643
644 =head2 C<< $obj->watch_write( $boolean ) >>
645
646 Turn 'writable' event notification on or off.
647
648 =cut
649 sub watch_write {
650     my PublicInbox::DS $self = shift;
651     my $sock = $self->{sock} or return;
652
653     my $val = shift;
654     my $event = $self->{event_watch};
655
656     $event &= ~POLLOUT if ! $val;
657     $event |=  POLLOUT if   $val;
658     my $fd = fileno($sock);
659
660     # If it changed, set it
661     if ($event != $self->{event_watch}) {
662         if ($HaveKQueue) {
663             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
664                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
665         }
666         elsif ($HaveEpoll) {
667             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
668                     confess "EPOLL_CTL_MOD: $!";
669         }
670         $self->{event_watch} = $event;
671     }
672 }
673
674 =head2 C<< $obj->dump_error( $message ) >>
675
676 Prints to STDERR a backtrace with information about this socket and what lead
677 up to the dump_error call.
678
679 =cut
680 sub dump_error {
681     my $i = 0;
682     my @list;
683     while (my ($file, $line, $sub) = (caller($i++))[1..3]) {
684         push @list, "\t$file:$line called $sub\n";
685     }
686
687     warn "ERROR: $_[1]\n" .
688         "\t$_[0] = " . $_[0]->as_string . "\n" .
689         join('', @list);
690 }
691
692 =head2 C<< $obj->debugmsg( $format, @args ) >>
693
694 Print the debugging message specified by the C<sprintf>-style I<format> and
695 I<args>.
696
697 =cut
698 sub debugmsg {
699     my ( $self, $fmt, @args ) = @_;
700     confess "Not an object" unless ref $self;
701
702     chomp $fmt;
703     printf STDERR ">>> $fmt\n", @args;
704 }
705
706 =head2 C<< $obj->as_string() >>
707
708 Returns a string describing this socket.
709
710 =cut
711 sub as_string {
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');
716     return $ret;
717 }
718
719 package PublicInbox::DS::Timer;
720 # [$abs_float_firetime, $coderef];
721 sub cancel {
722     $_[0][1] = undef;
723 }
724
725 1;
726
727 =head1 AUTHORS (Danga::Socket)
728
729 Brad Fitzpatrick <brad@danga.com> - author
730
731 Michael Granger <ged@danga.com> - docs, testing
732
733 Mark Smith <junior@danga.com> - contributor, heavy user, testing
734
735 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits