]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
AddTimer: avoid clock_gettime for the '0' case
[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 IO::Handle qw();
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);
25 use warnings;
26
27 use PublicInbox::Syscall qw(:epoll);
28
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.)
33             );
34
35 use Errno  qw(EAGAIN EINVAL);
36 use Carp   qw(croak confess);
37
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;
43
44 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
45
46 our (
47      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
48      $HaveKQueue,
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
54
55      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
56
57      $LoopTimeout,               # timeout of event loop in milliseconds
58      $DoneInit,                  # if we've done the one-time module init yet
59      @Timers,                    # timers
60      );
61
62 # this may be set to zero with old kernels
63 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
64 Reset();
65
66 #####################################################################
67 ### C L A S S   M E T H O D S
68 #####################################################################
69
70 =head2 C<< CLASS->Reset() >>
71
72 Reset all state
73
74 =cut
75 sub Reset {
76     %DescriptorMap = ();
77     @ToClose = ();
78     $LoopTimeout = -1;  # no timeout by default
79     @Timers = ();
80
81     $PostLoopCallback = undef;
82     $DoneInit = 0;
83
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;
87     $KQueue = undef;
88
89     $_io = undef; # close $Epoll
90     $Epoll = undef;
91
92     *EventLoop = *FirstTimeEventLoop;
93 }
94
95 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
96
97 Set the loop timeout for the event loop to some value in milliseconds.
98
99 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
100 immediately.
101
102 =cut
103 sub SetLoopTimeout {
104     return $LoopTimeout = $_[1] + 0;
105 }
106
107 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
108
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.
111
112 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
113
114 =cut
115 sub AddTimer {
116     my ($class, $secs, $coderef) = @_;
117
118     if (!$secs) {
119         my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
120         unshift(@Timers, $timer);
121         return $timer;
122     }
123
124     my $fire_time = now() + $secs;
125
126     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
127
128     if (!@Timers || $fire_time >= $Timers[-1][0]) {
129         push @Timers, $timer;
130         return $timer;
131     }
132
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);
140             return $timer;
141         }
142     }
143
144     die "Shouldn't get here.";
145 }
146
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 ($) {
150     my ($fd) = @_;
151
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);
155 }
156
157 sub _InitPoller
158 {
159     return if $DoneInit;
160     $DoneInit = 1;
161
162     if ($HAVE_KQUEUE) {
163         $KQueue = IO::KQueue->new();
164         $HaveKQueue = defined $KQueue;
165         if ($HaveKQueue) {
166             *EventLoop = *KQueueEventLoop;
167         }
168     }
169     elsif (PublicInbox::Syscall::epoll_defined()) {
170         $Epoll = eval { epoll_create(1024); };
171         $HaveEpoll = defined $Epoll && $Epoll >= 0;
172         if ($HaveEpoll) {
173             set_cloexec($Epoll);
174             *EventLoop = *EpollEventLoop;
175         }
176     }
177
178     if (!$HaveEpoll && !$HaveKQueue) {
179         require IO::Poll;
180         *EventLoop = *PollEventLoop;
181     }
182 }
183
184 =head2 C<< CLASS->EventLoop() >>
185
186 Start processing IO events. In most daemon programs this never exits. See
187 C<PostLoopCallback> below for how to exit the loop.
188
189 =cut
190 sub FirstTimeEventLoop {
191     my $class = shift;
192
193     _InitPoller();
194
195     if ($HaveEpoll) {
196         EpollEventLoop($class);
197     } elsif ($HaveKQueue) {
198         KQueueEventLoop($class);
199     } else {
200         PollEventLoop($class);
201     }
202 }
203
204 sub now () { clock_gettime(CLOCK_MONOTONIC) }
205
206 # runs timers and returns milliseconds for next one, or next event loop
207 sub RunTimers {
208     return $LoopTimeout unless @Timers;
209
210     my $now = now();
211
212     # Run expired timers
213     while (@Timers && $Timers[0][0] <= $now) {
214         my $to_run = shift(@Timers);
215         $to_run->[1]->($now) if $to_run->[1];
216     }
217
218     return $LoopTimeout unless @Timers;
219
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;
225
226     # -1 is an infinite timeout, so prefer a real timeout
227     return $timeout     if $LoopTimeout == -1;
228
229     # otherwise pick the lower of our regular timeout and time until
230     # the next timer
231     return $LoopTimeout if $LoopTimeout < $timeout;
232     return $timeout;
233 }
234
235 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
236 ### okay.
237 sub EpollEventLoop {
238     my $class = shift;
239
240     while (1) {
241         my @events;
242         my $i;
243         my $timeout = RunTimers();
244
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
251             # in that event.
252             $DescriptorMap{$events[$i]->[0]}->event_step;
253         }
254         return unless PostEventLoop();
255     }
256     exit 0;
257 }
258
259 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
260 ### IO::Epoll fails to load.
261 sub PollEventLoop {
262     my $class = shift;
263
264     my PublicInbox::DS $pob;
265
266     while (1) {
267         my $timeout = RunTimers();
268
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.
273         my @poll;
274         while ( my ($fd, $sock) = each %DescriptorMap ) {
275             push @poll, $fd, $sock->{event_watch};
276         }
277
278         # if nothing to poll, either end immediately (if no timeout)
279         # or just keep calling the callback
280         unless (@poll) {
281             select undef, undef, undef, ($timeout / 1000);
282             return unless PostEventLoop();
283             next;
284         }
285
286         my $count = IO::Poll::_poll($timeout, @poll);
287         unless ($count >= 0) {
288             return unless PostEventLoop();
289             next;
290         }
291
292         # Fetch handles with read events
293         while (@poll) {
294             my ($fd, $state) = splice(@poll, 0, 2);
295             $DescriptorMap{$fd}->event_step if $state;
296         }
297
298         return unless PostEventLoop();
299     }
300
301     exit 0;
302 }
303
304 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
305 ### okay.
306 sub KQueueEventLoop {
307     my $class = shift;
308
309     while (1) {
310         my $timeout = RunTimers();
311         my @ret = eval { $KQueue->kevent($timeout) };
312         if (my $err = $@) {
313             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
314             if ($err =~ /Interrupted system call/) {
315                 @ret = ();
316             } else {
317                 die $err;
318             }
319         }
320
321         foreach my $kev (@ret) {
322             $DescriptorMap{$kev->[0]}->event_step;
323         }
324         return unless PostEventLoop();
325     }
326
327     exit(0);
328 }
329
330 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
331
332 Sets post loop callback function.  Pass a subref and it will be
333 called every time the event loop finishes.
334
335 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
336 and it will exit.
337
338 The callback function will be passed two parameters: \%DescriptorMap
339
340 =cut
341 sub SetPostLoopCallback {
342     my ($class, $ref) = @_;
343
344     # global callback
345     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
346 }
347
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.
351 sub PostEventLoop {
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);
357
358         # close the socket.  (not a PublicInbox::DS close)
359         $sock->close;
360
361         # and now we can finally remove the fd from the map.  see
362         # comment above in ->close.
363         delete $DescriptorMap{$fd};
364     }
365
366
367     # by default we keep running, unless a postloop callback (either per-object
368     # or global) cancels it
369     my $keep_running = 1;
370
371     # now we're at the very end, call callback if defined
372     if (defined $PostLoopCallback) {
373         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
374     }
375
376     return $keep_running;
377 }
378
379 #####################################################################
380 ### PublicInbox::DS-the-object code
381 #####################################################################
382
383 =head2 OBJECT METHODS
384
385 =head2 C<< CLASS->new( $socket ) >>
386
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>.
389
390 This is normally (always?) called from your subclass via:
391
392   $class->SUPER::new($socket);
393
394 =cut
395 sub new {
396     my ($self, $sock, $exclusive) = @_;
397     $self = fields::new($self) unless ref $self;
398
399     $self->{sock} = $sock;
400     my $fd = fileno($sock);
401
402     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
403         unless $sock && $fd;
404
405     $self->{wbuf} = [];
406     $self->{wbuf_off} = 0;
407
408     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
409
410     _InitPoller();
411
412     if ($HaveEpoll) {
413         if ($exclusive) {
414             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
415         }
416 retry:
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;
421                 goto retry;
422             }
423             die "couldn't add epoll watch for $fd: $!\n";
424         }
425     }
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());
432     }
433
434     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
435         if $DescriptorMap{$fd};
436
437     $DescriptorMap{$fd} = $self;
438     return $self;
439 }
440
441
442 #####################################################################
443 ### I N S T A N C E   M E T H O D S
444 #####################################################################
445
446 =head2 C<< $obj->close >>
447
448 Close the socket.
449
450 =cut
451 sub close {
452     my ($self) = @_;
453     my $sock = delete $self->{sock} or return;
454
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}} = ();
459
460     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
461     # notifications about it
462     if ($HaveEpoll) {
463         my $fd = fileno($sock);
464         epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
465             confess("EPOLL_CTL_DEL: $!");
466     }
467
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.
476
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;
480
481     return 0;
482 }
483
484 =head2 C<< $obj->write( $data ) >>
485
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)
490
491 =cut
492 sub write {
493     my PublicInbox::DS $self;
494     my $data;
495     ($self, $data) = @_;
496
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
503     # hurt by this lie.
504     return 1 unless $self->{sock};
505
506     my $bref;
507
508     # just queue data if there's already a wait
509     my $need_queue;
510     my $wbuf = $self->{wbuf};
511
512     if (defined $data) {
513         $bref = ref $data ? $data : \$data;
514         if (scalar @$wbuf) {
515             push @$wbuf, $bref;
516             return 0;
517         }
518
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
522         $need_queue = 1;
523     }
524
525   WRITE:
526     while (1) {
527         return 1 unless $bref ||= $wbuf->[0];
528
529         my $len;
530         eval {
531             $len = length($$bref); # this will die if $bref is a code ref, caught below
532         };
533         if ($@) {
534             if (UNIVERSAL::isa($bref, "CODE")) {
535                 unless ($need_queue) {
536                     shift @$wbuf;
537                 }
538                 $bref->();
539
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.
543                 $need_queue = 0;
544
545                 undef $bref;
546                 next WRITE;
547             }
548             die "Write error: $@ <$bref>";
549         }
550
551         my $to_write = $len - $self->{wbuf_off};
552         my $written = syswrite($self->{sock}, $$bref, $to_write,
553                                $self->{wbuf_off});
554
555         if (! defined $written) {
556             if ($! == EAGAIN) {
557                 # since connection has stuff to write, it should now be
558                 # interested in pending writes:
559                 if ($need_queue) {
560                     push @$wbuf, $bref;
561                 }
562                 $self->watch_write(1);
563                 return 0;
564             }
565
566             return $self->close;
567         } elsif ($written != $to_write) {
568             if ($need_queue) {
569                 push @$wbuf, $bref;
570             }
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;
575             return 0;
576         } elsif ($written == $to_write) {
577             $self->{wbuf_off} = 0;
578             $self->watch_write(0);
579
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;
585
586             shift @$wbuf;
587             undef $bref;
588             next WRITE;
589         }
590     }
591 }
592
593 sub on_incomplete_write {
594     my PublicInbox::DS $self = shift;
595     $self->watch_write(1);
596 }
597
598 =head2 C<< $obj->watch_read( $boolean ) >>
599
600 Turn 'readable' event notification on or off.
601
602 =cut
603 sub watch_read {
604     my PublicInbox::DS $self = shift;
605     my $sock = $self->{sock} or return;
606
607     my $val = shift;
608     my $event = $self->{event_watch};
609
610     $event &= ~POLLIN if ! $val;
611     $event |=  POLLIN if   $val;
612
613     my $fd = fileno($sock);
614     # If it changed, set it
615     if ($event != $self->{event_watch}) {
616         if ($HaveKQueue) {
617             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
618                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
619         }
620         elsif ($HaveEpoll) {
621             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
622                 confess("EPOLL_CTL_MOD: $!");
623         }
624         $self->{event_watch} = $event;
625     }
626 }
627
628 =head2 C<< $obj->watch_write( $boolean ) >>
629
630 Turn 'writable' event notification on or off.
631
632 =cut
633 sub watch_write {
634     my PublicInbox::DS $self = shift;
635     my $sock = $self->{sock} or return;
636
637     my $val = shift;
638     my $event = $self->{event_watch};
639
640     $event &= ~POLLOUT if ! $val;
641     $event |=  POLLOUT if   $val;
642     my $fd = fileno($sock);
643
644     # If it changed, set it
645     if ($event != $self->{event_watch}) {
646         if ($HaveKQueue) {
647             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
648                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
649         }
650         elsif ($HaveEpoll) {
651             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
652                     confess "EPOLL_CTL_MOD: $!";
653         }
654         $self->{event_watch} = $event;
655     }
656 }
657
658 package PublicInbox::DS::Timer;
659 # [$abs_float_firetime, $coderef];
660 sub cancel {
661     $_[0][1] = undef;
662 }
663
664 1;
665
666 =head1 AUTHORS (Danga::Socket)
667
668 Brad Fitzpatrick <brad@danga.com> - author
669
670 Michael Granger <ged@danga.com> - docs, testing
671
672 Mark Smith <junior@danga.com> - contributor, heavy user, testing
673
674 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits