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