1 # Copyright (C) 2019-2020 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);
16 my ($cb, $arg) = @_; # optional
19 # we call exit() here instead of _exit() so DESTROY methods
20 # get called (e.g. File::Temp::Dir and PublicInbox::Msgmap)
21 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub {
23 # https://www.tldp.org/LDP/abs/html/exitcodes.html
24 eval { $cb->($sig, $arg) } if $cb;
26 exit(128 + POSIX->$sig);
30 # abs_path resolves symlinks, so we want to avoid it if rel2abs
31 # is sufficient and doesn't leave "/.." or "/../"
32 sub rel2abs_collapsed ($) {
33 my $p = File::Spec->rel2abs($_[0]);
34 return $p if substr($p, -3, 3) ne '/..' && index($p, '/../') < 0; # likely
39 sub resolve_inboxdir {
43 while (1) { # favor v2, first
44 if (-f "$try/inbox.lock") {
46 return rel2abs_collapsed($try);
49 $root_dev_ino //= do {
50 my @root = stat('/') or die "stat /: $!\n";
53 last if "$try[0]\0$try[1]" eq $root_dev_ino;
54 $try .= '/..'; # continue, cd up
56 die "`$try' is not a directory\n";
59 # try v1 bare git dirs
60 my $cmd = [ qw(git rev-parse --git-dir) ];
61 my $fh = popen_rd($cmd, undef, {-C => $cd});
62 my $dir = do { local $/; <$fh> };
63 close $fh or die "error in @$cmd (cwd:${\($cd // '.')}): $!\n";
66 rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
69 # for unconfigured inboxes
70 sub detect_indexlevel ($) {
73 my $over = $ibx->over;
74 my $srch = $ibx->search;
75 delete @$ibx{qw(over search)}; # don't leave open FDs lying around
77 # brand new or never before indexed inboxes default to full
78 return 'full' unless $over;
80 return $l unless $srch;
81 if (my $xdb = $srch->xdb) {
83 my $m = $xdb->get_metadata('indexlevel');
88 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
91 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
96 sub unconfigured_ibx ($$) {
98 my $name = "unconfigured-$i";
99 PublicInbox::Inbox->new({
101 address => [ "$name\@example.com" ],
103 # consumers (-convert) warn on this:
108 sub resolve_inboxes ($;$$) {
109 my ($argv, $opt, $cfg) = @_;
112 $cfg //= PublicInbox::Config->new;
114 my $cfgfile = PublicInbox::Config::default_file();
115 $cfg or die "--all specified, but $cfgfile not readable\n";
116 @$argv and die "--all specified, but directories specified\n";
119 my $min_ver = $opt->{-min_inbox_version} || 0;
120 # lookup inboxes by st_dev + st_ino instead of {inboxdir} pathnames,
121 # pathnames are not unique due to symlinks and bind mounts
124 $cfg->each_inbox(sub {
126 if (-e $ibx->{inboxdir}) {
127 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
129 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
132 } else { # directories specified on the command-line
134 push @dirs, '.' if !@dirs && $opt->{-use_cwd};
135 my %s2i; # "st_dev\0st_ino" => array index
136 for (my $i = 0; $i <= $#dirs; $i++) {
138 my @st = stat($dir) or die "stat($dir): $!\n";
139 $dir = resolve_inboxdir($dir, \(my $ver));
140 if ($ver >= $min_ver) {
141 $s2i{"$st[0]\0$st[1]"} //= $i;
148 $cfg->each_inbox(sub {
150 return if $ibx->version < $min_ver;
151 my $dir = $ibx->{inboxdir};
152 if (my @s = stat $dir) {
153 my $i = delete($s2i{"$s[0]\0$s[1]"})
156 die $done if !keys(%s2i);
158 warn "W: $ibx->{name} $dir: $!\n";
162 die $@ if $@ && $@ ne $done;
163 for my $i (sort { $a <=> $b } values %s2i) {
164 $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
166 @ibxs = grep { defined } @ibxs; # duplicates are undef
169 die "-V$min_ver inboxes not supported by $0\n\t",
170 join("\n\t", @old), "\n";
175 # TODO: make Devel::Peek optional, only used for daemon
176 my @base_mod = qw(Devel::Peek);
177 my @over_mod = qw(DBD::SQLite DBI);
179 -index => [ @base_mod, @over_mod ],
181 -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
184 sub scan_ibx_modules ($$) {
185 my ($mods, $ibx) = @_;
186 if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
187 $mods->{'Search::Xapian'} = 1;
189 $mods->{$_} = 1 foreach @over_mod;
196 while (my $mod = shift @mods) {
197 if (my $groups = $mod_groups{$mod}) {
198 push @mods, @$groups;
199 } elsif ($mod eq 'Search::Xapian') {
200 require PublicInbox::Search;
201 PublicInbox::Search::load_xapian() or
202 $err->{'Search::Xapian || Xapian'} = $@;
205 $err->{$mod} = $@ if $@;
208 scalar keys %$err ? $err : undef;
211 sub missing_mod_msg {
213 my @mods = map { "`$_'" } sort keys %$err;
214 my $last = pop @mods;
215 @mods ? (join(', ', @mods)."' and $last") : $last
219 my $err = check_require(@_) or return;
220 die missing_mod_msg($err)." required for $0\n";
223 sub indexlevel_ok_or_die ($) {
224 my ($indexlevel) = @_;
226 if ($indexlevel eq 'basic') {
228 } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
232 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
235 my $err = check_require($req) or return;
236 die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
239 sub index_terminate {
240 my (undef, $ibx) = @_; # $_[0] = signal name
245 my ($ibx, $im, $opt) = @_;
246 require PublicInbox::InboxWritable;
247 my $jobs = delete $opt->{jobs} if $opt;
248 if (my $pr = $opt->{-progress}) {
249 $pr->("indexing $ibx->{inboxdir} ...\n");
252 setup_signals(\&index_terminate, $ibx);
253 my $warn_cb = $SIG{__WARN__} // sub { print STDERR @_ };
254 my $idx = { current_info => $ibx->{inboxdir} };
255 my $warn_ignore = PublicInbox::InboxWritable->can('warn_ignore');
256 local $SIG{__WARN__} = sub {
257 return if $warn_ignore->(@_);
258 $warn_cb->($idx->{current_info}, ': ', @_);
260 if (ref($ibx) && $ibx->version == 2) {
261 eval { require PublicInbox::V2Writable };
262 die "v2 requirements not met: $@\n" if $@;
263 $ibx->{-creat_opt}->{nproc} = $jobs;
264 my $v2w = $im // $ibx->importer($opt->{reindex} // $jobs);
267 $v2w->{parallel} = 0;
269 my $n = $v2w->{shards};
270 if ($jobs < ($n + 1) && !$opt->{reshard}) {
272 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
279 require PublicInbox::SearchIdx;
280 $idx = PublicInbox::SearchIdx->new($ibx, 1);
282 $idx->index_sync($opt);
285 sub progress_prepare ($) {
288 # public-inbox-index defaults to quiet, -xcpdb and -compact do not
289 if (defined($opt->{quiet}) && $opt->{quiet} < 0) {
290 $opt->{quiet} = !$opt->{verbose};
293 open my $null, '>', '/dev/null' or
294 die "failed to open /dev/null: $!\n";
295 $opt->{1} = $null; # suitable for spawn() redirect
297 $opt->{verbose} ||= 1;
298 $opt->{-progress} = sub { print STDERR @_ };
302 # same unit factors as git:
303 sub parse_unsigned ($) {
306 $$val =~ /\A([0-9]+)([kmg])?\z/i or return;
307 my ($n, $unit_factor) = ($1, $2 // '');
308 my %u = ( k => 1024, m => 1024**2, g => 1024**3 );
309 $$val = $n * ($u{lc($unit_factor)} // 1);
313 sub index_prepare ($$) {
314 my ($opt, $cfg) = @_;
316 if ($opt->{compact}) {
317 require PublicInbox::Xapcmd;
318 PublicInbox::Xapcmd::check_compact();
319 $opt->{compact_opt} = { -coarse_lock => 1, compact => 1 };
320 if (defined(my $jobs = $opt->{jobs})) {
321 $opt->{compact_opt}->{jobs} = $jobs;
324 for my $k (qw(max_size batch_size)) {
325 my $git_key = "publicInbox.index".ucfirst($k);
326 $git_key =~ s/_([a-z])/\U$1/g;
327 defined(my $v = $opt->{$k} // $cfg->{lc($git_key)}) or next;
328 parse_unsigned(\$v) or die "`$git_key=$v' not parsed\n";
329 $v > 0 or die "`$git_key=$v' must be positive\n";
333 # out-of-the-box builds of Xapian 1.4.x are still limited to 32-bit
334 # https://getting-started-with-xapian.readthedocs.io/en/latest/concepts/indexing/limitations.html
335 $opt->{batch_size} and
336 $env = { XAPIAN_FLUSH_THRESHOLD => '4294967295' };
338 for my $k (qw(sequential_shard)) {
339 my $git_key = "publicInbox.index".ucfirst($k);
340 $git_key =~ s/_([a-z])/\U$1/g;
341 defined(my $s = $opt->{$k} // $cfg->{lc($git_key)}) or next;
342 defined(my $v = $cfg->git_bool($s))
343 or die "`$git_key=$s' not boolean\n";