]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/DS.pm
ds: remove IO::Poll support (for now)
[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
173 =head2 C<< CLASS->EventLoop() >>
174
175 Start processing IO events. In most daemon programs this never exits. See
176 C<PostLoopCallback> below for how to exit the loop.
177
178 =cut
179 sub FirstTimeEventLoop {
180     my $class = shift;
181
182     _InitPoller();
183
184     if ($HaveEpoll) {
185         EpollEventLoop($class);
186     } elsif ($HaveKQueue) {
187         KQueueEventLoop($class);
188     }
189 }
190
191 sub now () { clock_gettime(CLOCK_MONOTONIC) }
192
193 # runs timers and returns milliseconds for next one, or next event loop
194 sub RunTimers {
195     return $LoopTimeout unless @Timers;
196
197     my $now = now();
198
199     # Run expired timers
200     while (@Timers && $Timers[0][0] <= $now) {
201         my $to_run = shift(@Timers);
202         $to_run->[1]->($now) if $to_run->[1];
203     }
204
205     return $LoopTimeout unless @Timers;
206
207     # convert time to an even number of milliseconds, adding 1
208     # extra, otherwise floating point fun can occur and we'll
209     # call RunTimers like 20-30 times, each returning a timeout
210     # of 0.0000212 seconds
211     my $timeout = int(($Timers[0][0] - $now) * 1000) + 1;
212
213     # -1 is an infinite timeout, so prefer a real timeout
214     return $timeout     if $LoopTimeout == -1;
215
216     # otherwise pick the lower of our regular timeout and time until
217     # the next timer
218     return $LoopTimeout if $LoopTimeout < $timeout;
219     return $timeout;
220 }
221
222 ### The epoll-based event loop. Gets installed as EventLoop if IO::Epoll loads
223 ### okay.
224 sub EpollEventLoop {
225     my $class = shift;
226
227     while (1) {
228         my @events;
229         my $i;
230         my $timeout = RunTimers();
231
232         # get up to 1000 events
233         my $evcount = epoll_wait($Epoll, 1000, $timeout, \@events);
234         for ($i=0; $i<$evcount; $i++) {
235             # it's possible epoll_wait returned many events, including some at the end
236             # that ones in the front triggered unregister-interest actions.  if we
237             # can't find the %sock entry, it's because we're no longer interested
238             # in that event.
239             $DescriptorMap{$events[$i]->[0]}->event_step;
240         }
241         return unless PostEventLoop();
242     }
243     exit 0;
244 }
245
246 ### The kqueue-based event loop. Gets installed as EventLoop if IO::KQueue works
247 ### okay.
248 sub KQueueEventLoop {
249     my $class = shift;
250
251     while (1) {
252         my $timeout = RunTimers();
253         my @ret = eval { $KQueue->kevent($timeout) };
254         if (my $err = $@) {
255             # workaround https://rt.cpan.org/Ticket/Display.html?id=116615
256             if ($err =~ /Interrupted system call/) {
257                 @ret = ();
258             } else {
259                 die $err;
260             }
261         }
262
263         foreach my $kev (@ret) {
264             $DescriptorMap{$kev->[0]}->event_step;
265         }
266         return unless PostEventLoop();
267     }
268
269     exit(0);
270 }
271
272 =head2 C<< CLASS->SetPostLoopCallback( CODEREF ) >>
273
274 Sets post loop callback function.  Pass a subref and it will be
275 called every time the event loop finishes.
276
277 Return 1 (or any true value) from the sub to make the loop continue, 0 or false
278 and it will exit.
279
280 The callback function will be passed two parameters: \%DescriptorMap
281
282 =cut
283 sub SetPostLoopCallback {
284     my ($class, $ref) = @_;
285
286     # global callback
287     $PostLoopCallback = (defined $ref && ref $ref eq 'CODE') ? $ref : undef;
288 }
289
290 # Internal function: run the post-event callback, send read events
291 # for pushed-back data, and close pending connections.  returns 1
292 # if event loop should continue, or 0 to shut it all down.
293 sub PostEventLoop {
294     # now we can close sockets that wanted to close during our event processing.
295     # (we didn't want to close them during the loop, as we didn't want fd numbers
296     #  being reused and confused during the event loop)
297     while (my $sock = shift @ToClose) {
298         my $fd = fileno($sock);
299
300         # close the socket.  (not a PublicInbox::DS close)
301         $sock->close;
302
303         # and now we can finally remove the fd from the map.  see
304         # comment above in ->close.
305         delete $DescriptorMap{$fd};
306     }
307
308
309     # by default we keep running, unless a postloop callback (either per-object
310     # or global) cancels it
311     my $keep_running = 1;
312
313     # now we're at the very end, call callback if defined
314     if (defined $PostLoopCallback) {
315         $keep_running &&= $PostLoopCallback->(\%DescriptorMap);
316     }
317
318     return $keep_running;
319 }
320
321 #####################################################################
322 ### PublicInbox::DS-the-object code
323 #####################################################################
324
325 =head2 OBJECT METHODS
326
327 =head2 C<< CLASS->new( $socket ) >>
328
329 Create a new PublicInbox::DS subclass object for the given I<socket> which will
330 react to events on it during the C<EventLoop>.
331
332 This is normally (always?) called from your subclass via:
333
334   $class->SUPER::new($socket);
335
336 =cut
337 sub new {
338     my ($self, $sock, $ev) = @_;
339     $self = fields::new($self) unless ref $self;
340
341     $self->{sock} = $sock;
342     my $fd = fileno($sock);
343
344     Carp::cluck("undef sock and/or fd in PublicInbox::DS->new.  sock=" . ($sock || "") . ", fd=" . ($fd || ""))
345         unless $sock && $fd;
346
347     $self->{event_watch} = $ev;
348
349     _InitPoller();
350
351     if ($HaveEpoll) {
352 retry:
353         if (epoll_ctl($Epoll, EPOLL_CTL_ADD, $fd, $ev)) {
354             if ($! == EINVAL && ($ev & EPOLLEXCLUSIVE)) {
355                 $self->{event_watch} = ($ev &= ~EPOLLEXCLUSIVE);
356                 goto retry;
357             }
358             die "couldn't add epoll watch for $fd: $!\n";
359         }
360     }
361     elsif ($HaveKQueue) {
362         my $f = $ev & EPOLLIN ? EV_ENABLE() : EV_DISABLE();
363         $KQueue->EV_SET($fd, EVFILT_READ(), EV_ADD() | $f);
364         $f = $ev & EPOLLOUT ? EV_ENABLE() : EV_DISABLE();
365         $KQueue->EV_SET($fd, EVFILT_WRITE(), EV_ADD() | $f);
366     }
367
368     Carp::cluck("PublicInbox::DS::new blowing away existing descriptor map for fd=$fd ($DescriptorMap{$fd})")
369         if $DescriptorMap{$fd};
370
371     $DescriptorMap{$fd} = $self;
372     return $self;
373 }
374
375
376 #####################################################################
377 ### I N S T A N C E   M E T H O D S
378 #####################################################################
379
380 =head2 C<< $obj->close >>
381
382 Close the socket.
383
384 =cut
385 sub close {
386     my ($self) = @_;
387     my $sock = delete $self->{sock} or return;
388
389     # we need to flush our write buffer, as there may
390     # be self-referential closures (sub { $client->close })
391     # preventing the object from being destroyed
392     delete $self->{wbuf};
393
394     # if we're using epoll, we have to remove this from our epoll fd so we stop getting
395     # notifications about it
396     if ($HaveEpoll) {
397         my $fd = fileno($sock);
398         epoll_ctl($Epoll, EPOLL_CTL_DEL, $fd, 0) and
399             confess("EPOLL_CTL_DEL: $!");
400     }
401
402     # we explicitly don't delete from DescriptorMap here until we
403     # actually close the socket, as we might be in the middle of
404     # processing an epoll_wait/etc that returned hundreds of fds, one
405     # of which is not yet processed and is what we're closing.  if we
406     # keep it in DescriptorMap, then the event harnesses can just
407     # looked at $pob->{sock} == undef and ignore it.  but if it's an
408     # un-accounted for fd, then it (understandably) freak out a bit
409     # and emit warnings, thinking their state got off.
410
411     # defer closing the actual socket until the event loop is done
412     # processing this round of events.  (otherwise we might reuse fds)
413     push @ToClose, $sock;
414
415     return 0;
416 }
417
418 # portable, non-thread-safe sendfile emulation (no pread, yet)
419 sub psendfile ($$$) {
420     my ($sock, $fh, $off) = @_;
421
422     sysseek($fh, $$off, SEEK_SET) or return;
423     defined(my $to_write = sysread($fh, my $buf, 16384)) or return;
424     my $written = 0;
425     while ($to_write > 0) {
426         if (defined(my $w = syswrite($sock, $buf, $to_write, $written))) {
427             $written += $w;
428             $to_write -= $w;
429         } else {
430             return if $written == 0;
431             last;
432         }
433     }
434     $$off += $written;
435     $written;
436 }
437
438 # returns 1 if done, 0 if incomplete
439 sub flush_write ($) {
440     my ($self) = @_;
441     my $wbuf = $self->{wbuf} or return 1;
442     my $sock = $self->{sock} or return 1;
443
444 next_buf:
445     while (my $bref = $wbuf->[0]) {
446         if (ref($bref) ne 'CODE') {
447             my $off = delete($self->{wbuf_off}) // 0;
448             while (1) {
449                 my $w = psendfile($sock, $bref, \$off);
450                 if (defined $w) {
451                     if ($w == 0) {
452                         shift @$wbuf;
453                         goto next_buf;
454                     }
455                 } elsif ($! == EAGAIN) {
456                     $self->{wbuf_off} = $off;
457                     watch_write($self, 1);
458                     return 0;
459                 } else {
460                     return $self->close;
461                 }
462             }
463         } else { #($ref eq 'CODE') {
464             shift @$wbuf;
465             $bref->();
466         }
467     } # while @$wbuf
468
469     delete $self->{wbuf};
470     $self->watch_write(0);
471     1; # all done
472 }
473
474 sub write_in_full ($$$$) {
475     my ($fh, $bref, $len, $off) = @_;
476     my $rv = 0;
477     while ($len > 0) {
478         my $w = syswrite($fh, $$bref, $len, $off);
479         return ($rv ? $rv : $w) unless $w; # undef or 0
480         $rv += $w;
481         $len -= $w;
482         $off += $w;
483     }
484     $rv
485 }
486
487 sub tmpbuf ($$) {
488     my ($bref, $off) = @_;
489     # open(my $fh, '+>>', undef) doesn't set O_APPEND
490     my ($fh, $path) = tempfile('wbuf-XXXXXXX', TMPDIR => 1);
491     open $fh, '+>>', $path or die "open: $!";
492     unlink $path;
493     my $to_write = bytes::length($$bref) - $off;
494     my $w = write_in_full($fh, $bref, $to_write, $off);
495     die "write_in_full ($to_write): $!" unless defined $w;
496     $w == $to_write ? $fh : die("short write $w < $to_write");
497 }
498
499 =head2 C<< $obj->write( $data ) >>
500
501 Write the specified data to the underlying handle.  I<data> may be scalar,
502 scalar ref, code ref (to run when there).
503 Returns 1 if writes all went through, or 0 if there are writes in queue. If
504 it returns 1, caller should stop waiting for 'writable' events)
505
506 =cut
507 sub write {
508     my ($self, $data) = @_;
509
510     # nobody should be writing to closed sockets, but caller code can
511     # do two writes within an event, have the first fail and
512     # disconnect the other side (whose destructor then closes the
513     # calling object, but it's still in a method), and then the
514     # now-dead object does its second write.  that is this case.  we
515     # just lie and say it worked.  it'll be dead soon and won't be
516     # hurt by this lie.
517     my $sock = $self->{sock} or return 1;
518     my $ref = ref $data;
519     my $bref = $ref ? $data : \$data;
520     if (my $wbuf = $self->{wbuf}) { # already buffering, can't write more...
521         if ($ref eq 'CODE') {
522             push @$wbuf, $bref;
523         } else {
524             my $last = $wbuf->[-1];
525             if (ref($last) eq 'GLOB') { # append to tmp file buffer
526                 write_in_full($last, $bref, bytes::length($$bref), 0);
527             } else {
528                 push @$wbuf, tmpbuf($bref, 0);
529             }
530         }
531         return 0;
532     } elsif ($ref eq 'CODE') {
533         $bref->();
534         return 1;
535     } else {
536         my $to_write = bytes::length($$bref);
537         my $written = syswrite($sock, $$bref, $to_write);
538
539         if (defined $written) {
540             return 1 if $written == $to_write;
541         } elsif ($! == EAGAIN) {
542             $written = 0;
543         } else {
544             return $self->close;
545         }
546         $self->{wbuf} = [ tmpbuf($bref, $written) ];
547         watch_write($self, 1);
548         return 0;
549     }
550 }
551
552 use constant MSG_MORE => ($^O eq 'linux') ? 0x8000 : 0;
553
554 sub msg_more ($$) {
555     my $self = $_[0];
556     my $sock = $self->{sock} or return 1;
557
558     if (MSG_MORE && !$self->{wbuf}) {
559         my $n = send($sock, $_[1], MSG_MORE);
560         if (defined $n) {
561             my $nlen = bytes::length($_[1]) - $n;
562             return 1 if $nlen == 0; # all done!
563
564             # queue up the unwritten substring:
565             $self->{wbuf} = [ tmpbuf(\($_[1]), $n) ];
566             watch_write($self, 1);
567             return 0;
568         }
569     }
570     $self->write(\($_[1]));
571 }
572
573 sub watch_chg ($$$) {
574     my ($self, $bits, $set) = @_;
575     my $sock = $self->{sock} or return;
576     my $cur = $self->{event_watch};
577     my $changes = $cur;
578     if ($set) {
579         $changes |= $bits;
580     } else {
581         $changes &= ~$bits;
582     }
583     return if $changes == $cur;
584     my $fd = fileno($sock);
585     if ($HaveEpoll) {
586         epoll_ctl($Epoll, EPOLL_CTL_MOD, $fd, $changes) and
587             confess("EPOLL_CTL_MOD $!");
588     } elsif ($HaveKQueue) {
589         my $flag = $set ? EV_ENABLE() : EV_DISABLE();
590         $KQueue->EV_SET($fd, EVFILT_READ(), $flag) if $bits & EPOLLIN;
591         $KQueue->EV_SET($fd, EVFILT_WRITE(), $flag) if $bits & EPOLLOUT;
592     }
593     $self->{event_watch} = $changes;
594 }
595
596 =head2 C<< $obj->watch_read( $boolean ) >>
597
598 Turn 'readable' event notification on or off.
599
600 =cut
601 sub watch_read ($$) { watch_chg($_[0], EPOLLIN, $_[1]) };
602
603 =head2 C<< $obj->watch_write( $boolean ) >>
604
605 Turn 'writable' event notification on or off.
606
607 =cut
608 sub watch_write ($$) { watch_chg($_[0], EPOLLOUT, $_[1]) };
609
610 package PublicInbox::DS::Timer;
611 # [$abs_float_firetime, $coderef];
612 sub cancel {
613     $_[0][1] = undef;
614 }
615
616 1;
617
618 =head1 AUTHORS (Danga::Socket)
619
620 Brad Fitzpatrick <brad@danga.com> - author
621
622 Michael Granger <ged@danga.com> - docs, testing
623
624 Mark Smith <junior@danga.com> - contributor, heavy user, testing
625
626 Matt Sergeant <matt@sergeant.org> - kqueue support, docs, timers, other bits