]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Sigfd.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / Sigfd.pm
1 # Copyright (C) 2019-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Wraps a signalfd (or similar) for PublicInbox::DS
5 # fields: (sig: hashref similar to %SIG, but signal numbers as keys)
6 package PublicInbox::Sigfd;
7 use strict;
8 use parent qw(PublicInbox::DS);
9 use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET);
10 use POSIX ();
11
12 # returns a coderef to unblock signals if neither signalfd or kqueue
13 # are available.
14 sub new {
15         my ($class, $sig, $nonblock) = @_;
16         my %signo = map {;
17                 my $cb = $sig->{$_};
18                 # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD
19                 my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do {
20                         my $m = "SIG$_";
21                         POSIX->$m;
22                 };
23                 $num => $cb;
24         } keys %$sig;
25         my $self = bless { sig => \%signo }, $class;
26         my $io;
27         my $fd = signalfd([keys %signo], $nonblock);
28         if (defined $fd && $fd >= 0) {
29                 open($io, '+<&=', $fd) or die "open: $!";
30         } elsif (eval { require PublicInbox::DSKQXS }) {
31                 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $nonblock);
32         } else {
33                 return; # wake up every second to check for signals
34         }
35         if ($nonblock) { # it can go into the event loop
36                 $self->SUPER::new($io, EPOLLIN | EPOLLET);
37         } else { # master main loop
38                 $self->{sock} = $io;
39                 $self;
40         }
41 }
42
43 # PublicInbox::Daemon in master main loop (blocking)
44 sub wait_once ($) {
45         my ($self) = @_;
46         # 128 == sizeof(struct signalfd_siginfo)
47         my $r = sysread($self->{sock}, my $buf, 128 * 64);
48         if (defined($r)) {
49                 my $nr = $r / 128 - 1; # $nr may be -1
50                 for my $off (0..$nr) {
51                         # the first uint32_t of signalfd_siginfo: ssi_signo
52                         my $signo = unpack('L', substr($buf, 128 * $off, 4));
53                         my $cb = $self->{sig}->{$signo};
54                         $cb->($signo) if $cb ne 'IGNORE';
55                 }
56         }
57         $r;
58 }
59
60 # called by PublicInbox::DS in epoll_wait loop
61 sub event_step {
62         while (wait_once($_[0])) {} # non-blocking
63 }
64
65 1;