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