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