1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 # inot: Linux::Inotify2-like object
6 # pathmap => { inboxdir => [ ibx, watch1, watch2, watch3... ] } mapping
7 package PublicInbox::InboxIdle;
9 use parent qw(PublicInbox::DS);
10 use PublicInbox::Syscall qw(EPOLLIN EPOLLET);
11 my $IN_MODIFY = 0x02; # match Linux inotify
13 if ($^O eq 'linux' && eval { require Linux::Inotify2; 1 }) {
14 $IN_MODIFY = Linux::Inotify2::IN_MODIFY();
15 $ino_cls = 'Linux::Inotify2';
16 } elsif (eval { require PublicInbox::KQNotify }) {
17 $IN_MODIFY = PublicInbox::KQNotify::NOTE_WRITE();
18 $ino_cls = 'PublicInbox::KQNotify';
20 require PublicInbox::In2Tie if $ino_cls;
22 sub in2_arm ($$) { # PublicInbox::Config::each_inbox callback
23 my ($ibx, $self) = @_;
24 my $dir = $ibx->{inboxdir};
25 my $inot = $self->{inot};
26 my $cur = $self->{pathmap}->{$dir} //= [];
27 my $lock = "$dir/".($ibx->version >= 2 ? 'inbox.lock' : 'ssoma.lock');
29 # transfer old subscriptions to the current inbox, cancel the old watch
30 my $old_ibx = $cur->[0];
33 $ibx->{unlock_subs} and
34 die "BUG: $dir->{unlock_subs} should not exist";
35 $ibx->{unlock_subs} = $old_ibx->{unlock_subs};
37 # Linux::Inotify2::Watch::name matches if watches are the
38 # same, no point in replacing a watch of the same name
39 if ($cur->[1]->name eq $lock) {
40 $self->{on_unlock}->{$lock} = $ibx;
43 # rare, name changed (v1 inbox converted to v2)
44 $cur->[1]->cancel; # Linux::Inotify2::Watch::cancel
47 if (my $w = $cur->[1] = $inot->watch($lock, $IN_MODIFY)) {
48 $self->{on_unlock}->{$w->name} = $ibx;
50 warn "E: ".ref($inot)."->watch($lock, IN_MODIFY) failed: $!\n";
51 if ($!{ENOSPC} && $^O eq 'linux') {
53 I: consider increasing /proc/sys/fs/inotify/max_user_watches
58 # TODO: detect deleted packs (and possibly other files)
62 my ($self, $pi_cfg) = @_;
63 $pi_cfg->each_inbox(\&in2_arm, $self);
66 # internal API for ease-of-use
67 sub watch_inbox { in2_arm($_[1], $_[0]) };
70 my ($class, $pi_cfg) = @_;
71 my $self = bless {}, $class;
74 $inot = $ino_cls->new or die "E: $ino_cls->new: $!";
75 my $io = PublicInbox::In2Tie::io($inot);
76 $self->SUPER::new($io, EPOLLIN | EPOLLET);
78 require PublicInbox::FakeInotify;
79 $inot = PublicInbox::FakeInotify->new;
81 $self->{inot} = $inot;
82 $self->{pathmap} = {}; # inboxdir => [ ibx, watch1, watch2, watch3...]
83 $self->{on_unlock} = {}; # lock path => ibx
84 refresh($self, $pi_cfg) if $pi_cfg;
85 PublicInbox::FakeInotify::poll_once($self) if !$ino_cls;
92 my @events = $self->{inot}->read; # Linux::Inotify2::read
93 my $on_unlock = $self->{on_unlock};
94 for my $ev (@events) {
95 my $fn = $ev->fullname // next; # cancelled
96 if (my $ibx = $on_unlock->{$fn}) {
101 warn "{inot}->read err: $@\n" if $@;
104 # for graceful shutdown in PublicInbox::Daemon,
105 # just ensure the FD gets closed ASAP and subscribers