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