]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: split out from ->flush_write and ->write
[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
407     my $ev = $self->{event_watch} = POLLERR|POLLHUP|POLLNVAL;
408
409     _InitPoller();
410
411     if ($HaveEpoll) {
412         if ($exclusive) {
413             $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP|$EPOLLEXCLUSIVE;
414         }
415 retry:
416         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
417             if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
418                 $EPOLLEXCLUSIVE = 0; # old kernel
419                 $ev = $self->{event_watch} = EPOLLIN|EPOLLERR|EPOLLHUP;
420                 goto retry;
421             }
422             die "couldn't add epoll watch for $fd: $!\n";
423         }
424     }
425     elsif ($HaveKQueue) {
426         # Add them to the queue but disabled for now
427         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
428                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
429         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
430                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
431     }
432
433     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
434         if $DescriptorMap{$fd};
435
436     $DescriptorMap{$fd} = $self;
437     return $self;
438 }
439
440
441 #####################################################################
442 ### I N S T A N C E   M E T H O D S
443 #####################################################################
444
445 =head2 C<< $obj->close >>
446
447 Close the socket.
448
449 =cut
450 sub close {
451     my ($self) = @_;
452     my $sock = delete $self->{sock} or return;
453
454     # we need to flush our write buffer, as there may
455     # be self-referential closures (sub { $client->close })
456     # preventing the object from being destroyed
457     @{$self->{wbuf}} = ();
458
459     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
460     # notifications about it
461     if ($HaveEpoll) {
462         my $fd = fileno($sock);
463         epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, $self->{event_watch}) and
464             confess("EPOLL_CTL_DEL: $!");
465     }
466
467     # we explicitly don't delete from DescriptorMap here until we
468     # actually close the socket, as we might be in the middle of
469     # processing an epoll_wait/etc that returned hundreds of fds, one
470     # of which is not yet processed and is what we're closing.  if we
471     # keep it in DescriptorMap, then the event harnesses can just
472     # looked at $pob->{sock} == undef and ignore it.  but if it's an
473     # un-accounted for fd, then it (understandably) freak out a bit
474     # and emit warnings, thinking their state got off.
475
476     # defer closing the actual socket until the event loop is done
477     # processing this round of events.  (otherwise we might reuse fds)
478     push @ToClose, $sock;
479
480     return 0;
481 }
482
483 # returns 1 if done, 0 if incomplete
484 sub flush_write ($) {
485     my ($self) = @_;
486     my $sock = $self->{sock} or return 1;
487     my $wbuf = $self->{wbuf};
488
489     while (my $bref = $wbuf->[0]) {
490         my $ref = ref($bref);
491         if ($ref eq 'SCALAR') {
492             my $len = bytes::length($$bref);
493             my $off = $self->{wbuf_off} || 0;
494             my $to_write = $len - $off;
495             my $written = syswrite($sock, $$bref, $to_write, $off);
496             if (defined $written) {
497                 if ($written == $to_write) {
498                     shift @$wbuf;
499                 } else {
500                     $self->{wbuf_off} = $off + $written;
501                 }
502                 next; # keep going until EAGAIN
503             } elsif ($! == EAGAIN) {
504                 $self->watch_write(1);
505             } else {
506                 $self->close;
507             }
508             return 0;
509         } else { #($ref eq 'CODE') {
510             shift @$wbuf;
511             $bref->();
512         }
513     } # while @$wbuf
514
515     $self->watch_write(0);
516     1; # all done
517 }
518
519 =head2 C<< $obj->write( $data ) >>
520
521 Write the specified data to the underlying handle.  I<data> may be scalar,
522 scalar ref, code ref (to run when there), or undef just to kick-start.
523 Returns 1 if writes all went through, or 0 if there are writes in queue. If
524 it returns 1, caller should stop waiting for 'writable' events)
525
526 =cut
527 sub write {
528     my ($self, $data) = @_;
529     return flush_write($self) unless defined $data;
530
531     # nobody should be writing to closed sockets, but caller code can
532     # do two writes within an event, have the first fail and
533     # disconnect the other side (whose destructor then closes the
534     # calling object, but it's still in a method), and then the
535     # now-dead object does its second write.  that is this case.  we
536     # just lie and say it worked.  it'll be dead soon and won't be
537     # hurt by this lie.
538     my $sock = $self->{sock} or return 1;
539     my $ref = ref $data;
540     my $bref = $ref ? $data : \$data;
541     my $wbuf = $self->{wbuf};
542     if (@$wbuf) { # already buffering, can't write more...
543         push @$wbuf, $bref;
544         return 0;
545     } elsif ($ref eq 'CODE') {
546         $bref->();
547         return 1;
548     } else {
549         my $to_write = bytes::length($$bref);
550         my $written = syswrite($sock, $$bref, $to_write);
551
552         if (defined $written) {
553             return 1 if $written == $to_write;
554             $self->{wbuf_off} = $written;
555             push @$wbuf, $bref;
556             return flush_write($self); # try until EAGAIN
557         } elsif ($! == EAGAIN) {
558             push @$wbuf, $bref;
559             $self->watch_write(1);
560         } else {
561             $self->close;
562         }
563         return 0;
564     }
565 }
566
567 =head2 C<< $obj->watch_read( $boolean ) >>
568
569 Turn 'readable' event notification on or off.
570
571 =cut
572 sub watch_read {
573     my PublicInbox::DS $self = shift;
574     my $sock = $self->{sock} or return;
575
576     my $val = shift;
577     my $event = $self->{event_watch};
578
579     $event &= ~POLLIN if ! $val;
580     $event |=  POLLIN if   $val;
581
582     my $fd = fileno($sock);
583     # If it changed, set it
584     if ($event != $self->{event_watch}) {
585         if ($HaveKQueue) {
586             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
587                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
588         }
589         elsif ($HaveEpoll) {
590             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
591                 confess("EPOLL_CTL_MOD: $!");
592         }
593         $self->{event_watch} = $event;
594     }
595 }
596
597 =head2 C<< $obj->watch_write( $boolean ) >>
598
599 Turn 'writable' event notification on or off.
600
601 =cut
602 sub watch_write {
603     my PublicInbox::DS $self = shift;
604     my $sock = $self->{sock} or return;
605
606     my $val = shift;
607     my $event = $self->{event_watch};
608
609     $event &= ~POLLOUT if ! $val;
610     $event |=  POLLOUT if   $val;
611     my $fd = fileno($sock);
612
613     # If it changed, set it
614     if ($event != $self->{event_watch}) {
615         if ($HaveKQueue) {
616             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
617                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
618         }
619         elsif ($HaveEpoll) {
620             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
621                     confess "EPOLL_CTL_MOD: $!";
622         }
623         $self->{event_watch} = $event;
624     }
625 }
626
627 package PublicInbox::DS::Timer;
628 # [$abs_float_firetime, $coderef];
629 sub cancel {
630     $_[0][1] = undef;
631 }
632
633 1;
634
635 =head1 AUTHORS (Danga::Socket)
636
637 Brad Fitzpatrick <brad@danga.com> - author
638
639 Michael Granger <ged@danga.com> - docs, testing
640
641 Mark Smith <junior@danga.com> - contributor, heavy user, testing
642
643 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits