]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: reduce overhead of tempfile creation
[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(SEEK_SET :DEFAULT);
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 use 5.010_001;
27
28 use PublicInbox::Syscall qw(:epoll);
29
30 use fields ('sock',              # underlying socket
31             'wbuf',              # arrayref of coderefs or GLOB refs
32             'wbuf_off',  # offset into first element of wbuf to start writing at
33             );
34
35 use Errno  qw(EAGAIN EINVAL EEXIST);
36 use Carp   qw(croak confess carp);
37 require File::Spec;
38
39 our (
40      %DescriptorMap,             # fd (num) -> PublicInbox::DS object
41      $Epoll,                     # Global epoll fd (or DSKQXS ref)
42      $_io,                       # IO::Handle for Epoll
43      @ToClose,                   # sockets to close when event loop is done
44
45      $PostLoopCallback,          # subref to call at the end of each loop, if defined (global)
46
47      $LoopTimeout,               # timeout of event loop in milliseconds
48      $DoneInit,                  # if we've done the one-time module init yet
49      @Timers,                    # timers
50      );
51
52 Reset();
53
54 #####################################################################
55 ### C L A S S   M E T H O D S
56 #####################################################################
57
58 =head2 C<< CLASS->Reset() >>
59
60 Reset all state
61
62 =cut
63 sub Reset {
64     %DescriptorMap = ();
65     @ToClose = ();
66     $LoopTimeout = -1;  # no timeout by default
67     @Timers = ();
68
69     $PostLoopCallback = undef;
70     $DoneInit = 0;
71
72     $_io = undef; # closes real $Epoll FD
73     $Epoll = undef; # may call DSKQXS::DESTROY
74
75     *EventLoop = *FirstTimeEventLoop;
76 }
77
78 =head2 C<< CLASS->SetLoopTimeout( $timeout ) >>
79
80 Set the loop timeout for the event loop to some value in milliseconds.
81
82 A timeout of 0 (zero) means poll forever. A timeout of -1 means poll and return
83 immediately.
84
85 =cut
86 sub SetLoopTimeout {
87     return $LoopTimeout = $_[1] + 0;
88 }
89
90 =head2 C<< CLASS->AddTimer( $seconds, $coderef ) >>
91
92 Add a timer to occur $seconds from now. $seconds may be fractional, but timers
93 are not guaranteed to fire at the exact time you ask for.
94
95 Returns a timer object which you can call C<< $timer->cancel >> on if you need to.
96
97 =cut
98 sub AddTimer {
99     my ($class, $secs, $coderef) = @_;
100
101     if (!$secs) {
102         my $timer = bless([0, $coderef], 'PublicInbox::DS::Timer');
103         unshift(@Timers, $timer);
104         return $timer;
105     }
106
107     my $fire_time = now() + $secs;
108
109     my $timer = bless [$fire_time, $coderef], "PublicInbox::DS::Timer";
110
111     if (!@Timers || $fire_time >= $Timers[-1][0]) {
112         push @Timers, $timer;
113         return $timer;
114     }
115
116     # Now, where do we insert?  (NOTE: this appears slow, algorithm-wise,
117     # but it was compared against calendar queues, heaps, naive push/sort,
118     # and a bunch of other versions, and found to be fastest with a large
119     # variety of datasets.)
120     for (my $i = 0; $i < @Timers; $i++) {
121         if ($Timers[$i][0] > $fire_time) {
122             splice(@Timers, $i, 0, $timer);
123             return $timer;
124         }
125     }
126
127     die "Shouldn't get here.";
128 }
129
130 # keeping this around in case we support other FD types for now,
131 # epoll_create1(EPOLL_CLOEXEC) requires Linux 2.6.27+...
132 sub set_cloexec ($) {
133     my ($fd) = @_;
134
135     $_io = IO::Handle->new_from_fd($fd, 'r+') or return;
136     defined(my $fl = fcntl($_io, F_GETFD, 0)) or return;
137     fcntl($_io, F_SETFD, $fl | FD_CLOEXEC);
138 }
139
140 sub _InitPoller
141 {
142     return if $DoneInit;
143     $DoneInit = 1;
144
145     if (PublicInbox::Syscall::epoll_defined())  {
146         $Epoll = epoll_create();
147         set_cloexec($Epoll) if (defined($Epoll) && $Epoll >= 0);
148     } else {
149         my $cls;
150         for (qw(DSKQXS DSPoll)) {
151             $cls = "PublicInbox::$_";
152             last if eval "require $cls";
153         }
154         $cls->import;
155         $Epoll = $cls->new;
156     }
157     *EventLoop = *EpollEventLoop;
158 }
159
160 =head2 C<< CLASS->EventLoop() >>
161
162 Start processing IO events. In most daemon programs this never exits. See
163 C<PostLoopCallback> below for how to exit the loop.
164
165 =cut
166 sub FirstTimeEventLoop {
167     my $class = shift;
168
169     _InitPoller();
170
171     EventLoop($class);
172 }
173
174 sub now () { clock_gettime(CLOCK_MONOTONIC) }
175
176 # runs timers and returns milliseconds for next one, or next event loop
177 sub RunTimers {
178     return $LoopTimeout unless @Timers;
179
180     my $now = now();
181
182     # Run expired timers
183     while (@Timers && $Timers[0][0] <= $now) {
184         my $to_run = shift(@Timers);
185         $to_run->[1]->($now) if $to_run->[1];
186     }
187
188     return $LoopTimeout unless @Timers;
189
190     # convert time to an even number of milliseconds, adding 1
191     # extra, otherwise floating point fun can occur and we'll
192     # call RunTimers like 20-30 times, each returning a timeout
193     # of 0.0000212 seconds
194     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
195
196     # -1 is an infinite timeout, so prefer a real timeout
197     return $timeout     if $LoopTimeout == -1;
198
199     # otherwise pick the lower of our regular timeout and time until
200     # the next timer
201     return $LoopTimeout if $LoopTimeout < $timeout;
202     return $timeout;
203 }
204
205 sub EpollEventLoop {
206     while (1) {
207         my @events;
208         my $i;
209         my $timeout = RunTimers();
210
211         # get up to 1000 events
212         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
213         for ($i=0; $i<$evcount; $i++) {
214             # it's possible epoll_wait returned many events, including some at the end
215             # that ones in the front triggered unregister-interest actions.  if we
216             # can't find the %sock entry, it's because we're no longer interested
217             # in that event.
218             $DescriptorMap{$events[$i]->[0]}->event_step;
219         }
220         return unless PostEventLoop();
221     }
222 }
223
224 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
225
226 Sets post loop callback function.  Pass a subref and it will be
227 called every time the event loop finishes.
228
229 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
230 and it will exit.
231
232 The callback function will be passed two parameters: \%DescriptorMap
233
234 =cut
235 sub SetPostLoopCallback {
236     my ($class, $ref) = @_;
237
238     # global callback
239     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
240 }
241
242 # Internal function: run the post-event callback, send read events
243 # for pushed-back data, and close pending connections.  returns 1
244 # if event loop should continue, or 0 to shut it all down.
245 sub PostEventLoop {
246     # now we can close sockets that wanted to close during our event processing.
247     # (we didn't want to close them during the loop, as we didn't want fd numbers
248     #  being reused and confused during the event loop)
249     while (my $sock = shift @ToClose) {
250         my $fd = fileno($sock);
251
252         # close the socket. (not a PublicInbox::DS close)
253         CORE::close($sock);
254
255         # and now we can finally remove the fd from the map.  see
256         # comment above in ->close.
257         delete $DescriptorMap{$fd};
258     }
259
260
261     # by default we keep running, unless a postloop callback (either per-object
262     # or global) cancels it
263     my $keep_running = 1;
264
265     # now we're at the very end, call callback if defined
266     if (defined $PostLoopCallback) {
267         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
268     }
269
270     return $keep_running;
271 }
272
273 #####################################################################
274 ### PublicInbox::DS-the-object code
275 #####################################################################
276
277 =head2 OBJECT METHODS
278
279 =head2 C<< CLASS->new( $socket ) >>
280
281 Create a new PublicInbox::DS subclass object for the given I<socket> which will
282 react to events on it during the C<EventLoop>.
283
284 This is normally (always?) called from your subclass via:
285
286   $class->SUPER::new($socket);
287
288 =cut
289 sub new {
290     my ($self, $sock, $ev) = @_;
291     $self = fields::new($self) unless ref $self;
292
293     $self->{sock} = $sock;
294     my $fd = fileno($sock);
295
296     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
297         unless $sock && $fd;
298
299     _InitPoller();
300
301     if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
302         if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
303             $ev &= ~EPOLLEXCLUSIVE;
304             goto retry;
305         }
306         die "couldn't add epoll watch for $fd: $!\n";
307     }
308     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
309         if $DescriptorMap{$fd};
310
311     $DescriptorMap{$fd} = $self;
312     return $self;
313 }
314
315
316 #####################################################################
317 ### I N S T A N C E   M E T H O D S
318 #####################################################################
319
320 =head2 C<< $obj->close >>
321
322 Close the socket.
323
324 =cut
325 sub close {
326     my ($self) = @_;
327     my $sock = delete $self->{sock} or return;
328
329     # we need to flush our write buffer, as there may
330     # be self-referential closures (sub { $client->close })
331     # preventing the object from being destroyed
332     delete $self->{wbuf};
333
334     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
335     # notifications about it
336     my $fd = fileno($sock);
337     epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
338         confess("EPOLL_CTL_DEL: $!");
339
340     # we explicitly don't delete from DescriptorMap here until we
341     # actually close the socket, as we might be in the middle of
342     # processing an epoll_wait/etc that returned hundreds of fds, one
343     # of which is not yet processed and is what we're closing.  if we
344     # keep it in DescriptorMap, then the event harnesses can just
345     # looked at $pob->{sock} == undef and ignore it.  but if it's an
346     # un-accounted for fd, then it (understandably) freak out a bit
347     # and emit warnings, thinking their state got off.
348
349     # defer closing the actual socket until the event loop is done
350     # processing this round of events.  (otherwise we might reuse fds)
351     push @ToClose, $sock;
352
353     return 0;
354 }
355
356 # portable, non-thread-safe sendfile emulation (no pread, yet)
357 sub psendfile ($$$) {
358     my ($sock, $fh, $off) = @_;
359
360     seek($fh, $$off, SEEK_SET) or return;
361     defined(my $to_write = read($fh, my $buf, 16384)) or return;
362     my $written = 0;
363     while ($to_write > 0) {
364         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
365             $written += $w;
366             $to_write -= $w;
367         } else {
368             return if $written == 0;
369             last;
370         }
371     }
372     $$off += $written;
373     $written;
374 }
375
376 # returns 1 if done, 0 if incomplete
377 sub flush_write ($) {
378     my ($self) = @_;
379     my $wbuf = $self->{wbuf} or return 1;
380     my $sock = $self->{sock};
381
382 next_buf:
383     while (my $bref = $wbuf->[0]) {
384         if (ref($bref) ne 'CODE') {
385             my $off = delete($self->{wbuf_off}) // 0;
386             while ($sock) {
387                 my $w = psendfile($sock, $bref, \$off);
388                 if (defined $w) {
389                     if ($w == 0) {
390                         shift @$wbuf;
391                         goto next_buf;
392                     }
393                 } elsif ($! == EAGAIN) {
394                     $self->{wbuf_off} = $off;
395                     watch($self, EPOLLOUT|EPOLLONESHOT);
396                     return 0;
397                 } else {
398                     return $self->close;
399                 }
400             }
401         } else { #($ref eq 'CODE') {
402             shift @$wbuf;
403             my $before = scalar(@$wbuf);
404             $bref->($self);
405
406             # bref may be enqueueing more CODE to call (see accept_tls_step)
407             return 0 if (scalar(@$wbuf) > $before);
408         }
409     } # while @$wbuf
410
411     delete $self->{wbuf};
412     1; # all done
413 }
414
415 sub do_read ($$$$) {
416     my ($self, $rbuf, $len, $off) = @_;
417     my $r = sysread($self->{sock}, $$rbuf, $len, $off);
418     return ($r == 0 ? $self->close : $r) if defined $r;
419     # common for clients to break connections without warning,
420     # would be too noisy to log here:
421     if (ref($self) eq 'IO::Socket::SSL') {
422         my $ev = PublicInbox::TLS::epollbit() or return $self->close;
423         watch($self, $ev | EPOLLONESHOT);
424     } elsif ($! == EAGAIN) {
425         watch($self, EPOLLIN | EPOLLONESHOT);
426     } else {
427         $self->close;
428     }
429 }
430
431 # drop the socket if we hit unrecoverable errors on our system which
432 # require BOFH attention: ENOSPC, EFBIG, EIO, EMFILE, ENFILE...
433 sub drop {
434     my $self = shift;
435     carp(@_);
436     $self->close;
437 }
438
439 # n.b.: use ->write/->read for this buffer to allow compatibility with
440 # PerlIO::mmap or PerlIO::scalar if needed
441 sub tmpio ($$$) {
442     my ($self, $bref, $off) = @_;
443     my $fh; # open(my $fh, '+>>', undef) doesn't set O_APPEND
444     do {
445         my $fn = File::Spec->tmpdir . '/wbuf-' . rand;
446         if (sysopen($fh, $fn, O_RDWR|O_CREAT|O_EXCL|O_APPEND, 0600)) { # likely
447             unlink($fn) or return drop($self, "unlink($fn) $!");
448         } elsif ($! != EEXIST) { # EMFILE/ENFILE/ENOSPC/ENOMEM
449             return drop($self, "open: $!");
450         }
451     } until (defined $fh);
452     $fh->autoflush(1);
453     my $len = bytes::length($$bref) - $off;
454     $fh->write($$bref, $len, $off) or return drop($self, "write ($len): $!");
455     $fh
456 }
457
458 =head2 C<< $obj->write( $data ) >>
459
460 Write the specified data to the underlying handle.  I<data> may be scalar,
461 scalar ref, code ref (to run when there).
462 Returns 1 if writes all went through, or 0 if there are writes in queue. If
463 it returns 1, caller should stop waiting for 'writable' events)
464
465 =cut
466 sub write {
467     my ($self, $data) = @_;
468
469     # nobody should be writing to closed sockets, but caller code can
470     # do two writes within an event, have the first fail and
471     # disconnect the other side (whose destructor then closes the
472     # calling object, but it's still in a method), and then the
473     # now-dead object does its second write.  that is this case.  we
474     # just lie and say it worked.  it'll be dead soon and won't be
475     # hurt by this lie.
476     my $sock = $self->{sock} or return 1;
477     my $ref = ref $data;
478     my $bref = $ref ? $data : \$data;
479     my $wbuf = $self->{wbuf};
480     if ($wbuf && scalar(@$wbuf)) { # already buffering, can't write more...
481         if ($ref eq 'CODE') {
482             push @$wbuf, $bref;
483         } else {
484             my $last = $wbuf->[-1];
485             if (ref($last) eq 'GLOB') { # append to tmp file buffer
486                 $last->print($$bref) or return drop($self, "print: $!");
487             } else {
488                 my $tmpio = tmpio($self, $bref, 0) or return 0;
489                 push @$wbuf, $tmpio;
490             }
491         }
492         return 0;
493     } elsif ($ref eq 'CODE') {
494         $bref->($self);
495         return 1;
496     } else {
497         my $to_write = bytes::length($$bref);
498         my $written = syswrite($sock, $$bref, $to_write);
499
500         if (defined $written) {
501             return 1 if $written == $to_write;
502         } elsif ($! == EAGAIN) {
503             $written = 0;
504         } else {
505             return $self->close;
506         }
507         my $tmpio = tmpio($self, $bref, $written) or return 0;
508         $self->{wbuf} = [ $tmpio ];
509         watch($self, EPOLLOUT|EPOLLONESHOT);
510         return 0;
511     }
512 }
513
514 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
515
516 sub msg_more ($$) {
517     my $self = $_[0];
518     my $sock = $self->{sock} or return 1;
519
520     if (MSG_MORE && !$self->{wbuf} && ref($sock) ne 'IO::Socket::SSL') {
521         my $n = send($sock, $_[1], MSG_MORE);
522         if (defined $n) {
523             my $nlen = bytes::length($_[1]) - $n;
524             return 1 if $nlen == 0; # all done!
525             # queue up the unwritten substring:
526             my $tmpio = tmpio($self, \($_[1]), $n) or return 0;
527             $self->{wbuf} = [ $tmpio ];
528             watch($self, EPOLLOUT|EPOLLONESHOT);
529             return 0;
530         }
531     }
532     $self->write(\($_[1]));
533 }
534
535 sub watch ($$) {
536     my ($self, $ev) = @_;
537     my $sock = $self->{sock} or return;
538     epoll_ctl($Epoll, EPOLL_CTL_MOD, fileno($sock), $ev) and
539         confess("EPOLL_CTL_MOD $!");
540     0;
541 }
542
543 sub watch_in1 ($) { watch($_[0], EPOLLIN | EPOLLONESHOT) }
544
545 # return true if complete, false if incomplete (or failure)
546 sub accept_tls_step ($) {
547     my ($self) = @_;
548     my $sock = $self->{sock} or return;
549     return 1 if $sock->accept_SSL;
550     return $self->close if $! != EAGAIN;
551     if (my $ev = PublicInbox::TLS::epollbit()) {
552         unshift @{$self->{wbuf} ||= []}, \&accept_tls_step;
553         return watch($self, $ev | EPOLLONESHOT);
554     }
555     drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
556 }
557
558 sub shutdn_tls_step ($) {
559     my ($self) = @_;
560     my $sock = $self->{sock} or return;
561     return $self->close if $sock->stop_SSL(SSL_fast_shutdown => 1);
562     return $self->close if $! != EAGAIN;
563     if (my $ev = PublicInbox::TLS::epollbit()) {
564         unshift @{$self->{wbuf} ||= []}, \&shutdn_tls_step;
565         return watch($self, $ev | EPOLLONESHOT);
566     }
567     drop($self, 'BUG? EAGAIN but '.PublicInbox::TLS::err());
568 }
569
570 # don't bother with shutdown($sock, 2), we don't fork+exec w/o CLOEXEC
571 # or fork w/o exec, so no inadvertant socket sharing
572 sub shutdn ($) {
573     my ($self) = @_;
574     my $sock = $self->{sock} or return;
575     if (ref($sock) eq 'IO::Socket::SSL') {
576         shutdn_tls_step($self);
577     } else {
578         $self->close;
579     }
580 }
581
582 package PublicInbox::DS::Timer;
583 # [$abs_float_firetime, $coderef];
584 sub cancel {
585     $_[0][1] = undef;
586 }
587
588 1;
589
590 =head1 AUTHORS (Danga::Socket)
591
592 Brad Fitzpatrick <brad@danga.com> - author
593
594 Michael Granger <ged@danga.com> - docs, testing
595
596 Mark Smith <junior@danga.com> - contributor, heavy user, testing
597
598 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits