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>
4 # common stuff for administrative command-line tools
5 # Unstable internal API
6 package PublicInbox::Admin;
8 use parent qw(Exporter);
9 our @EXPORT_OK = qw(setup_signals);
10 use PublicInbox::Config;
11 use PublicInbox::Inbox;
12 use PublicInbox::Spawn qw(popen_rd);
14 *rel2abs_collapsed = \&PublicInbox::Config::rel2abs_collapsed;
17 my ($cb, $arg) = @_; # optional
20 # we call exit() here instead of _exit() so DESTROY methods
21 # get called (e.g. File::Temp::Dir and PublicInbox::Msgmap)
22 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub {
24 # https://www.tldp.org/LDP/abs/html/exitcodes.html
25 eval { $cb->($sig, $arg) } if $cb;
27 exit(128 + POSIX->$sig);
31 sub resolve_inboxdir {
35 while (1) { # favor v2, first
36 if (-f "$try/inbox.lock") {
38 return rel2abs_collapsed($try);
41 $root_dev_ino //= do {
42 my @root = stat('/') or die "stat /: $!\n";
45 last if "$try[0]\0$try[1]" eq $root_dev_ino;
46 $try .= '/..'; # continue, cd up
48 die "`$try' is not a directory\n";
51 # try v1 bare git dirs
52 my $cmd = [ qw(git rev-parse --git-dir) ];
53 my $fh = popen_rd($cmd, undef, {-C => $cd});
54 my $dir = do { local $/; <$fh> };
55 close $fh or die "error in @$cmd (cwd:${\($cd // '.')}): $!\n";
58 rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
61 # for unconfigured inboxes
62 sub detect_indexlevel ($) {
65 my $over = $ibx->over;
66 my $srch = $ibx->search;
67 delete @$ibx{qw(over search)}; # don't leave open FDs lying around
69 # brand new or never before indexed inboxes default to full
70 return 'full' unless $over;
72 return $l unless $srch;
73 if (my $xdb = $srch->xdb) {
75 my $m = $xdb->get_metadata('indexlevel');
80 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
83 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
88 sub unconfigured_ibx ($$) {
90 my $name = "unconfigured-$i";
91 PublicInbox::Inbox->new({
93 address => [ "$name\@example.com" ],
95 # consumers (-convert) warn on this:
100 sub resolve_inboxes ($;$$) {
101 my ($argv, $opt, $cfg) = @_;
104 $cfg //= PublicInbox::Config->new;
106 my $cfgfile = PublicInbox::Config::default_file();
107 $cfg or die "--all specified, but $cfgfile not readable\n";
108 @$argv and die "--all specified, but directories specified\n";
111 my $min_ver = $opt->{-min_inbox_version} || 0;
112 # lookup inboxes by st_dev + st_ino instead of {inboxdir} pathnames,
113 # pathnames are not unique due to symlinks and bind mounts
116 $cfg->each_inbox(sub {
118 if (-e $ibx->{inboxdir}) {
119 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
121 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
124 } else { # directories specified on the command-line
126 push @dirs, '.' if !@dirs && $opt->{-use_cwd};
127 my %s2i; # "st_dev\0st_ino" => array index
128 for (my $i = 0; $i <= $#dirs; $i++) {
130 my @st = stat($dir) or die "stat($dir): $!\n";
131 $dir = $dirs[$i] = resolve_inboxdir($dir, \(my $ver));
132 if ($ver >= $min_ver) {
133 $s2i{"$st[0]\0$st[1]"} //= $i;
140 $cfg->each_inbox(sub {
142 return if $ibx->version < $min_ver;
143 my $dir = $ibx->{inboxdir};
144 if (my @s = stat $dir) {
145 my $i = delete($s2i{"$s[0]\0$s[1]"})
148 die $done if !keys(%s2i);
150 warn "W: $ibx->{name} $dir: $!\n";
154 die $@ if $@ && $@ ne $done;
155 for my $i (sort { $a <=> $b } values %s2i) {
156 $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
158 @ibxs = grep { defined } @ibxs; # duplicates are undef
161 die "-V$min_ver inboxes not supported by $0\n\t",
162 join("\n\t", @old), "\n";
167 # TODO: make Devel::Peek optional, only used for daemon
168 my @base_mod = qw(Devel::Peek);
169 my @over_mod = qw(DBD::SQLite DBI);
171 -index => [ @base_mod, @over_mod ],
173 -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
176 sub scan_ibx_modules ($$) {
177 my ($mods, $ibx) = @_;
178 if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
179 $mods->{'Search::Xapian'} = 1;
181 $mods->{$_} = 1 foreach @over_mod;
188 while (my $mod = shift @mods) {
189 if (my $groups = $mod_groups{$mod}) {
190 push @mods, @$groups;
191 } elsif ($mod eq 'Search::Xapian') {
192 require PublicInbox::Search;
193 PublicInbox::Search::load_xapian() or
194 $err->{'Search::Xapian || Xapian'} = $@;
197 $err->{$mod} = $@ if $@;
200 scalar keys %$err ? $err : undef;
203 sub missing_mod_msg {
205 my @mods = map { "`$_'" } sort keys %$err;
206 my $last = pop @mods;
207 @mods ? (join(', ', @mods)."' and $last") : $last
211 my $err = check_require(@_) or return;
212 die missing_mod_msg($err)." required for $0\n";
215 sub indexlevel_ok_or_die ($) {
216 my ($indexlevel) = @_;
218 if ($indexlevel eq 'basic') {
220 } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
224 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
227 my $err = check_require($req) or return;
228 die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
231 sub index_terminate {
232 my (undef, $ibx) = @_; # $_[0] = signal name
237 my ($ibx, $im, $opt) = @_;
238 require PublicInbox::InboxWritable;
239 my $jobs = delete $opt->{jobs} if $opt;
240 if (my $pr = $opt->{-progress}) {
241 $pr->("indexing $ibx->{inboxdir} ...\n");
244 setup_signals(\&index_terminate, $ibx);
245 my $idx = { current_info => $ibx->{inboxdir} };
246 local $SIG{__WARN__} = sub {
247 return if PublicInbox::Eml::warn_ignore(@_);
248 warn($idx->{current_info}, ': ', @_);
250 if (ref($ibx) && $ibx->version == 2) {
251 eval { require PublicInbox::V2Writable };
252 die "v2 requirements not met: $@\n" if $@;
253 $ibx->{-creat_opt}->{nproc} = $jobs;
254 my $v2w = $im // $ibx->importer($opt->{reindex} // $jobs);
257 $v2w->{parallel} = 0;
259 my $n = $v2w->{shards};
260 if ($jobs < ($n + 1) && !$opt->{reshard}) {
262 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
269 require PublicInbox::SearchIdx;
270 $idx = PublicInbox::SearchIdx->new($ibx, 1);
272 $idx->index_sync($opt);
273 $idx->{nidx} // 0; # returns number processed
276 sub progress_prepare ($;$) {
277 my ($opt, $dst) = @_;
279 # public-inbox-index defaults to quiet, -xcpdb and -compact do not
280 if (defined($opt->{quiet}) && $opt->{quiet} < 0) {
281 $opt->{quiet} = !$opt->{verbose};
284 open my $null, '>', '/dev/null' or
285 die "failed to open /dev/null: $!\n";
286 $opt->{1} = $null; # suitable for spawn() redirect
288 $opt->{verbose} ||= 1;
289 $dst //= *STDERR{GLOB};
290 $opt->{-progress} = sub { print $dst @_ };
294 # same unit factors as git:
295 sub parse_unsigned ($) {
298 $$val =~ /\A([0-9]+)([kmg])?\z/i or return;
299 my ($n, $unit_factor) = ($1, $2 // '');
300 my %u = ( k => 1024, m => 1024**2, g => 1024**3 );
301 $$val = $n * ($u{lc($unit_factor)} // 1);
305 sub index_prepare ($$) {
306 my ($opt, $cfg) = @_;
308 if ($opt->{compact}) {
309 require PublicInbox::Xapcmd;
310 PublicInbox::Xapcmd::check_compact();
311 $opt->{compact_opt} = { -coarse_lock => 1, compact => 1 };
312 if (defined(my $jobs = $opt->{jobs})) {
313 $opt->{compact_opt}->{jobs} = $jobs;
316 for my $k (qw(max_size batch_size)) {
317 my $git_key = "publicInbox.index".ucfirst($k);
318 $git_key =~ s/_([a-z])/\U$1/g;
319 defined(my $v = $opt->{$k} // $cfg->{lc($git_key)}) or next;
320 parse_unsigned(\$v) or die "`$git_key=$v' not parsed\n";
321 $v > 0 or die "`$git_key=$v' must be positive\n";
325 # out-of-the-box builds of Xapian 1.4.x are still limited to 32-bit
326 # https://getting-started-with-xapian.readthedocs.io/en/latest/concepts/indexing/limitations.html
327 $opt->{batch_size} and
328 $env = { XAPIAN_FLUSH_THRESHOLD => '4294967295' };
330 for my $k (qw(sequential_shard)) {
331 my $git_key = "publicInbox.index".ucfirst($k);
332 $git_key =~ s/_([a-z])/\U$1/g;
333 defined(my $s = $opt->{$k} // $cfg->{lc($git_key)}) or next;
334 defined(my $v = $cfg->git_bool($s))
335 or die "`$git_key=$s' not boolean\n";