]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: get rid of redundant and unnecessary POLL* constants
[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 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);
25 use warnings;
26
27 use PublicInbox::Syscall qw(:epoll);
28
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
33                                  # (EPOLLIN,OUT,etc.)
34             );
35
36 use Errno  qw(EAGAIN EINVAL);
37 use Carp   qw(croak confess);
38 use File::Temp qw(tempfile);
39
40 our $HAVE_KQUEUE = eval { require IO::KQueue; 1 };
41
42 our (
43      $HaveEpoll,                 # Flag -- is epoll available?  initially undefined.
44      $HaveKQueue,
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
50
51      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
52
53      $LoopTimeout,               # timeout of event loop in milliseconds
54      $DoneInit,                  # if we've done the one-time module init yet
55      @Timers,                    # timers
56      );
57
58 # this may be set to zero with old kernels
59 our $EPOLLEXCLUSIVE = EPOLLEXCLUSIVE;
60 Reset();
61
62 #####################################################################
63 ### C L A S S   M E T H O D S
64 #####################################################################
65
66 =head2 C<< CLASS->Reset() >>
67
68 Reset all state
69
70 =cut
71 sub Reset {
72     %DescriptorMap = ();
73     @ToClose = ();
74     $LoopTimeout = -1;  # no timeout by default
75     @Timers = ();
76
77     $PostLoopCallback = undef;
78     $DoneInit = 0;
79
80     # NOTE kqueue is close-on-fork, and we don't account for it, yet
81     # OTOH, we (public-inbox) don't need this sub outside of tests...
82     POSIX::close($$KQueue) if !$_io && $KQueue && $$KQueue >= 0;
83     $KQueue = undef;
84
85     $_io = undef; # close $Epoll
86     $Epoll = undef;
87
88     *EventLoop = *FirstTimeEventLoop;
89 }
90
91 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
92
93 Set the loop timeout for the event loop to some value in milliseconds.
94
95 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
96 immediately.
97
98 =cut
99 sub SetLoopTimeout {
100     return $LoopTimeout = $_[1] + 0;
101 }
102
103 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
104
105 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
106 are not guaranteed to fire at the exact time you ask for.
107
108 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
109
110 =cut
111 sub AddTimer {
112     my ($class, $secs, $coderef) = @_;
113
114     if (!$secs) {
115         my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
116         unshift(@Timers, $timer);
117         return $timer;
118     }
119
120     my $fire_time = now() + $secs;
121
122     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
123
124     if (!@Timers || $fire_time >= $Timers[-1][0]) {
125         push @Timers, $timer;
126         return $timer;
127     }
128
129     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
130     # but it was compared against calendar queues, heaps, naive push/sort,
131     # and a bunch of other versions, and found to be fastest with a large
132     # variety of datasets.)
133     for (my $i = 0; $i < @Timers; $i++) {
134         if ($Timers[$i][0] > $fire_time) {
135             splice(@Timers, $i, 0, $timer);
136             return $timer;
137         }
138     }
139
140     die "Shouldn't get here.";
141 }
142
143 # keeping this around in case we support other FD types for now,
144 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
145 sub set_cloexec ($) {
146     my ($fd) = @_;
147
148     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
149     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
150     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
151 }
152
153 sub _InitPoller
154 {
155     return if $DoneInit;
156     $DoneInit = 1;
157
158     if ($HAVE_KQUEUE) {
159         $KQueue = IO::KQueue->new();
160         $HaveKQueue = defined $KQueue;
161         if ($HaveKQueue) {
162             *EventLoop = *KQueueEventLoop;
163         }
164     }
165     elsif (PublicInbox::Syscall::epoll_defined()) {
166         $Epoll = eval { epoll_create(1024); };
167         $HaveEpoll = defined $Epoll && $Epoll >= 0;
168         if ($HaveEpoll) {
169             set_cloexec($Epoll);
170             *EventLoop = *EpollEventLoop;
171         }
172     }
173
174     if (!$HaveEpoll && !$HaveKQueue) {
175         require IO::Poll;
176         *EventLoop = *PollEventLoop;
177     }
178 }
179
180 =head2 C<< CLASS->EventLoop() >>
181
182 Start processing IO events. In most daemon programs this never exits. See
183 C<PostLoopCallback> below for how to exit the loop.
184
185 =cut
186 sub FirstTimeEventLoop {
187     my $class = shift;
188
189     _InitPoller();
190
191     if ($HaveEpoll) {
192         EpollEventLoop($class);
193     } elsif ($HaveKQueue) {
194         KQueueEventLoop($class);
195     } else {
196         PollEventLoop($class);
197     }
198 }
199
200 sub now () { clock_gettime(CLOCK_MONOTONIC) }
201
202 # runs timers and returns milliseconds for next one, or next event loop
203 sub RunTimers {
204     return $LoopTimeout unless @Timers;
205
206     my $now = now();
207
208     # Run expired timers
209     while (@Timers && $Timers[0][0] <= $now) {
210         my $to_run = shift(@Timers);
211         $to_run->[1]->($now) if $to_run->[1];
212     }
213
214     return $LoopTimeout unless @Timers;
215
216     # convert time to an even number of milliseconds, adding 1
217     # extra, otherwise floating point fun can occur and we'll
218     # call RunTimers like 20-30 times, each returning a timeout
219     # of 0.0000212 seconds
220     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
221
222     # -1 is an infinite timeout, so prefer a real timeout
223     return $timeout     if $LoopTimeout == -1;
224
225     # otherwise pick the lower of our regular timeout and time until
226     # the next timer
227     return $LoopTimeout if $LoopTimeout < $timeout;
228     return $timeout;
229 }
230
231 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
232 ### okay.
233 sub EpollEventLoop {
234     my $class = shift;
235
236     while (1) {
237         my @events;
238         my $i;
239         my $timeout = RunTimers();
240
241         # get up to 1000 events
242         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
243         for ($i=0; $i<$evcount; $i++) {
244             # it's possible epoll_wait returned many events, including some at the end
245             # that ones in the front triggered unregister-interest actions.  if we
246             # can't find the %sock entry, it's because we're no longer interested
247             # in that event.
248             $DescriptorMap{$events[$i]->[0]}->event_step;
249         }
250         return unless PostEventLoop();
251     }
252     exit 0;
253 }
254
255 ### The fallback IO::Poll-based event loop. Gets installed as EventLoop if
256 ### IO::Epoll fails to load.
257 sub PollEventLoop {
258     my $class = shift;
259
260     my PublicInbox::DS $pob;
261
262     while (1) {
263         my $timeout = RunTimers();
264
265         # the following sets up @poll as a series of ($poll,$event_mask)
266         # items, then uses IO::Poll::_poll, implemented in XS, which
267         # modifies the array in place with the even elements being
268         # replaced with the event masks that occured.
269         my @poll;
270         while ( my ($fd, $sock) = each %DescriptorMap ) {
271             push @poll, $fd, $sock->{event_watch};
272         }
273
274         # if nothing to poll, either end immediately (if no timeout)
275         # or just keep calling the callback
276         unless (@poll) {
277             select undef, undef, undef, ($timeout / 1000);
278             return unless PostEventLoop();
279             next;
280         }
281
282         my $count = IO::Poll::_poll($timeout, @poll);
283         unless ($count >= 0) {
284             return unless PostEventLoop();
285             next;
286         }
287
288         # Fetch handles with read events
289         while (@poll) {
290             my ($fd, $state) = splice(@poll, 0, 2);
291             $DescriptorMap{$fd}->event_step if $state;
292         }
293
294         return unless PostEventLoop();
295     }
296
297     exit 0;
298 }
299
300 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
301 ### okay.
302 sub KQueueEventLoop {
303     my $class = shift;
304
305     while (1) {
306         my $timeout = RunTimers();
307         my @ret = eval { $KQueue->kevent($timeout) };
308         if (my $err = $@) {
309             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
310             if ($err =~ /Interrupted system call/) {
311                 @ret = ();
312             } else {
313                 die $err;
314             }
315         }
316
317         foreach my $kev (@ret) {
318             $DescriptorMap{$kev->[0]}->event_step;
319         }
320         return unless PostEventLoop();
321     }
322
323     exit(0);
324 }
325
326 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
327
328 Sets post loop callback function.  Pass a subref and it will be
329 called every time the event loop finishes.
330
331 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
332 and it will exit.
333
334 The callback function will be passed two parameters: \%DescriptorMap
335
336 =cut
337 sub SetPostLoopCallback {
338     my ($class, $ref) = @_;
339
340     # global callback
341     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
342 }
343
344 # Internal function: run the post-event callback, send read events
345 # for pushed-back data, and close pending connections.  returns 1
346 # if event loop should continue, or 0 to shut it all down.
347 sub PostEventLoop {
348     # now we can close sockets that wanted to close during our event processing.
349     # (we didn't want to close them during the loop, as we didn't want fd numbers
350     #  being reused and confused during the event loop)
351     while (my $sock = shift @ToClose) {
352         my $fd = fileno($sock);
353
354         # close the socket.  (not a PublicInbox::DS close)
355         $sock->close;
356
357         # and now we can finally remove the fd from the map.  see
358         # comment above in ->close.
359         delete $DescriptorMap{$fd};
360     }
361
362
363     # by default we keep running, unless a postloop callback (either per-object
364     # or global) cancels it
365     my $keep_running = 1;
366
367     # now we're at the very end, call callback if defined
368     if (defined $PostLoopCallback) {
369         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
370     }
371
372     return $keep_running;
373 }
374
375 #####################################################################
376 ### PublicInbox::DS-the-object code
377 #####################################################################
378
379 =head2 OBJECT METHODS
380
381 =head2 C<< CLASS->new( $socket ) >>
382
383 Create a new PublicInbox::DS subclass object for the given I<socket> which will
384 react to events on it during the C<EventLoop>.
385
386 This is normally (always?) called from your subclass via:
387
388   $class->SUPER::new($socket);
389
390 =cut
391 sub new {
392     my ($self, $sock, $exclusive) = @_;
393     $self = fields::new($self) unless ref $self;
394
395     $self->{sock} = $sock;
396     my $fd = fileno($sock);
397
398     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
399         unless $sock && $fd;
400
401     my $ev = $self->{event_watch} = 0;
402
403     _InitPoller();
404
405     if ($HaveEpoll) {
406         if ($exclusive) {
407             $ev = $self->{event_watch} = EPOLLIN|$EPOLLEXCLUSIVE;
408         }
409 retry:
410         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
411             if ($! == EINVAL && ($ev & $EPOLLEXCLUSIVE)) {
412                 $EPOLLEXCLUSIVE = 0; # old kernel
413                 $ev = $self->{event_watch} = EPOLLIN;
414                 goto retry;
415             }
416             die "couldn't add epoll watch for $fd: $!\n";
417         }
418     }
419     elsif ($HaveKQueue) {
420         # Add them to the queue but disabled for now
421         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
422                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
423         $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
424                         IO::KQueue::EV_ADD() | IO::KQueue::EV_DISABLE());
425     }
426
427     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
428         if $DescriptorMap{$fd};
429
430     $DescriptorMap{$fd} = $self;
431     return $self;
432 }
433
434
435 #####################################################################
436 ### I N S T A N C E   M E T H O D S
437 #####################################################################
438
439 =head2 C<< $obj->close >>
440
441 Close the socket.
442
443 =cut
444 sub close {
445     my ($self) = @_;
446     my $sock = delete $self->{sock} or return;
447
448     # we need to flush our write buffer, as there may
449     # be self-referential closures (sub { $client->close })
450     # preventing the object from being destroyed
451     delete $self->{wbuf};
452
453     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
454     # notifications about it
455     if ($HaveEpoll) {
456         my $fd = fileno($sock);
457         epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
458             confess("EPOLL_CTL_DEL: $!");
459     }
460
461     # we explicitly don't delete from DescriptorMap here until we
462     # actually close the socket, as we might be in the middle of
463     # processing an epoll_wait/etc that returned hundreds of fds, one
464     # of which is not yet processed and is what we're closing.  if we
465     # keep it in DescriptorMap, then the event harnesses can just
466     # looked at $pob->{sock} == undef and ignore it.  but if it's an
467     # un-accounted for fd, then it (understandably) freak out a bit
468     # and emit warnings, thinking their state got off.
469
470     # defer closing the actual socket until the event loop is done
471     # processing this round of events.  (otherwise we might reuse fds)
472     push @ToClose, $sock;
473
474     return 0;
475 }
476
477 # portable, non-thread-safe sendfile emulation (no pread, yet)
478 sub psendfile ($$$) {
479     my ($sock, $fh, $off) = @_;
480
481     sysseek($fh, $$off, SEEK_SET) or return;
482     defined(my $to_write = sysread($fh, my $buf, 16384)) or return;
483     my $written = 0;
484     while ($to_write > 0) {
485         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
486             $written += $w;
487             $to_write -= $w;
488         } else {
489             return if $written == 0;
490             last;
491         }
492     }
493     $$off += $written;
494     $written;
495 }
496
497 # returns 1 if done, 0 if incomplete
498 sub flush_write ($) {
499     my ($self) = @_;
500     my $wbuf = $self->{wbuf} or return 1;
501     my $sock = $self->{sock} or return 1;
502
503 next_buf:
504     while (my $bref = $wbuf->[0]) {
505         if (ref($bref) ne 'CODE') {
506             my $off = delete($self->{wbuf_off}) // 0;
507             while (1) {
508                 my $w = psendfile($sock, $bref, \$off);
509                 if (defined $w) {
510                     if ($w == 0) {
511                         shift @$wbuf;
512                         goto next_buf;
513                     }
514                 } elsif ($! == EAGAIN) {
515                     $self->{wbuf_off} = $off;
516                     watch_write($self, 1);
517                     return 0;
518                 } else {
519                     return $self->close;
520                 }
521             }
522         } else { #($ref eq 'CODE') {
523             shift @$wbuf;
524             $bref->();
525         }
526     } # while @$wbuf
527
528     delete $self->{wbuf};
529     $self->watch_write(0);
530     1; # all done
531 }
532
533 sub write_in_full ($$$$) {
534     my ($fh, $bref, $len, $off) = @_;
535     my $rv = 0;
536     while ($len > 0) {
537         my $w = syswrite($fh, $$bref, $len, $off);
538         return ($rv ? $rv : $w) unless $w; # undef or 0
539         $rv += $w;
540         $len -= $w;
541         $off += $w;
542     }
543     $rv
544 }
545
546 sub tmpbuf ($$) {
547     my ($bref, $off) = @_;
548     # open(my $fh, '+>>', undef) doesn't set O_APPEND
549     my ($fh, $path) = tempfile('wbuf-XXXXXXX', TMPDIR => 1);
550     open $fh, '+>>', $path or die "open: $!";
551     unlink $path;
552     my $to_write = bytes::length($$bref) - $off;
553     my $w = write_in_full($fh, $bref, $to_write, $off);
554     die "write_in_full ($to_write): $!" unless defined $w;
555     $w == $to_write ? $fh : die("short write $w < $to_write");
556 }
557
558 =head2 C<< $obj->write( $data ) >>
559
560 Write the specified data to the underlying handle.  I<data> may be scalar,
561 scalar ref, code ref (to run when there).
562 Returns 1 if writes all went through, or 0 if there are writes in queue. If
563 it returns 1, caller should stop waiting for 'writable' events)
564
565 =cut
566 sub write {
567     my ($self, $data) = @_;
568
569     # nobody should be writing to closed sockets, but caller code can
570     # do two writes within an event, have the first fail and
571     # disconnect the other side (whose destructor then closes the
572     # calling object, but it's still in a method), and then the
573     # now-dead object does its second write.  that is this case.  we
574     # just lie and say it worked.  it'll be dead soon and won't be
575     # hurt by this lie.
576     my $sock = $self->{sock} or return 1;
577     my $ref = ref $data;
578     my $bref = $ref ? $data : \$data;
579     if (my $wbuf = $self->{wbuf}) { # already buffering, can't write more...
580         if ($ref eq 'CODE') {
581             push @$wbuf, $bref;
582         } else {
583             my $last = $wbuf->[-1];
584             if (ref($last) eq 'GLOB') { # append to tmp file buffer
585                 write_in_full($last, $bref, bytes::length($$bref), 0);
586             } else {
587                 push @$wbuf, tmpbuf($bref, 0);
588             }
589         }
590         return 0;
591     } elsif ($ref eq 'CODE') {
592         $bref->();
593         return 1;
594     } else {
595         my $to_write = bytes::length($$bref);
596         my $written = syswrite($sock, $$bref, $to_write);
597
598         if (defined $written) {
599             return 1 if $written == $to_write;
600         } elsif ($! == EAGAIN) {
601             $written = 0;
602         } else {
603             return $self->close;
604         }
605         $self->{wbuf} = [ tmpbuf($bref, $written) ];
606         watch_write($self, 1);
607         return 0;
608     }
609 }
610
611 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
612
613 sub msg_more ($$) {
614     my $self = $_[0];
615     my $sock = $self->{sock} or return 1;
616
617     if (MSG_MORE && !$self->{wbuf}) {
618         my $n = send($sock, $_[1], MSG_MORE);
619         if (defined $n) {
620             my $nlen = bytes::length($_[1]) - $n;
621             return 1 if $nlen == 0; # all done!
622
623             # queue up the unwritten substring:
624             $self->{wbuf} = [ tmpbuf(\($_[1]), $n) ];
625             watch_write($self, 1);
626             return 0;
627         }
628     }
629     $self->write(\($_[1]));
630 }
631
632 =head2 C<< $obj->watch_read( $boolean ) >>
633
634 Turn 'readable' event notification on or off.
635
636 =cut
637 sub watch_read {
638     my PublicInbox::DS $self = shift;
639     my $sock = $self->{sock} or return;
640
641     my $val = shift;
642     my $event = $self->{event_watch};
643
644     $event &= ~EPOLLIN if ! $val;
645     $event |=  EPOLLIN if   $val;
646
647     my $fd = fileno($sock);
648     # If it changed, set it
649     if ($event != $self->{event_watch}) {
650         if ($HaveKQueue) {
651             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_READ(),
652                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
653         }
654         elsif ($HaveEpoll) {
655             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
656                 confess("EPOLL_CTL_MOD: $!");
657         }
658         $self->{event_watch} = $event;
659     }
660 }
661
662 =head2 C<< $obj->watch_write( $boolean ) >>
663
664 Turn 'writable' event notification on or off.
665
666 =cut
667 sub watch_write {
668     my PublicInbox::DS $self = shift;
669     my $sock = $self->{sock} or return;
670
671     my $val = shift;
672     my $event = $self->{event_watch};
673
674     $event &= ~EPOLLOUT if ! $val;
675     $event |=  EPOLLOUT if   $val;
676     my $fd = fileno($sock);
677
678     # If it changed, set it
679     if ($event != $self->{event_watch}) {
680         if ($HaveKQueue) {
681             $KQueue->EV_SET($fd, IO::KQueue::EVFILT_WRITE(),
682                             $val ? IO::KQueue::EV_ENABLE() : IO::KQueue::EV_DISABLE());
683         }
684         elsif ($HaveEpoll) {
685             epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $event) and
686                     confess "EPOLL_CTL_MOD: $!";
687         }
688         $self->{event_watch} = $event;
689     }
690 }
691
692 package PublicInbox::DS::Timer;
693 # [$abs_float_firetime, $coderef];
694 sub cancel {
695     $_[0][1] = undef;
696 }
697
698 1;
699
700 =head1 AUTHORS (Danga::Socket)
701
702 Brad Fitzpatrick <brad@danga.com> - author
703
704 Michael Granger <ged@danga.com> - docs, testing
705
706 Mark Smith <junior@danga.com> - contributor, heavy user, testing
707
708 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits