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