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);
13 *rel2abs_collapsed = \&PublicInbox::Config::rel2abs_collapsed;
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 sub resolve_inboxdir {
34 while (1) { # favor v2, first
35 if (-f "$try/inbox.lock") {
37 return rel2abs_collapsed($try);
40 $root_dev_ino //= do {
41 my @root = stat('/') or die "stat /: $!\n";
44 last if "$try[0]\0$try[1]" eq $root_dev_ino;
45 $try .= '/..'; # continue, cd up
47 die "`$try' is not a directory\n";
50 # try v1 bare git dirs
51 my $cmd = [ qw(git rev-parse --git-dir) ];
52 my $fh = popen_rd($cmd, undef, {-C => $cd});
53 my $dir = do { local $/; <$fh> };
54 close $fh or die "error in @$cmd (cwd:${\($cd // '.')}): $!\n";
57 rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
60 # for unconfigured inboxes
61 sub detect_indexlevel ($) {
64 my $over = $ibx->over;
65 my $srch = $ibx->search;
66 delete @$ibx{qw(over search)}; # don't leave open FDs lying around
68 # brand new or never before indexed inboxes default to full
69 return 'full' unless $over;
71 return $l unless $srch;
72 if (my $xdb = $srch->xdb) {
74 my $m = $xdb->get_metadata('indexlevel');
79 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
82 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
87 sub unconfigured_ibx ($$) {
89 my $name = "unconfigured-$i";
90 PublicInbox::Inbox->new({
92 address => [ "$name\@example.com" ],
94 # consumers (-convert) warn on this:
99 sub resolve_inboxes ($;$$) {
100 my ($argv, $opt, $cfg) = @_;
103 $cfg //= PublicInbox::Config->new;
105 my $cfgfile = PublicInbox::Config::default_file();
106 $cfg or die "--all specified, but $cfgfile not readable\n";
107 @$argv and die "--all specified, but directories specified\n";
110 my $min_ver = $opt->{-min_inbox_version} || 0;
111 # lookup inboxes by st_dev + st_ino instead of {inboxdir} pathnames,
112 # pathnames are not unique due to symlinks and bind mounts
115 $cfg->each_inbox(sub {
117 if (-e $ibx->{inboxdir}) {
118 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
120 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
123 } else { # directories specified on the command-line
125 push @dirs, '.' if !@dirs && $opt->{-use_cwd};
126 my %s2i; # "st_dev\0st_ino" => array index
127 for (my $i = 0; $i <= $#dirs; $i++) {
129 my @st = stat($dir) or die "stat($dir): $!\n";
130 $dir = $dirs[$i] = resolve_inboxdir($dir, \(my $ver));
131 if ($ver >= $min_ver) {
132 $s2i{"$st[0]\0$st[1]"} //= $i;
139 $cfg->each_inbox(sub {
141 return if $ibx->version < $min_ver;
142 my $dir = $ibx->{inboxdir};
143 if (my @s = stat $dir) {
144 my $i = delete($s2i{"$s[0]\0$s[1]"})
147 die $done if !keys(%s2i);
149 warn "W: $ibx->{name} $dir: $!\n";
153 die $@ if $@ && $@ ne $done;
154 for my $i (sort { $a <=> $b } values %s2i) {
155 $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
157 @ibxs = grep { defined } @ibxs; # duplicates are undef
160 die "-V$min_ver inboxes not supported by $0\n\t",
161 join("\n\t", @old), "\n";
166 # TODO: make Devel::Peek optional, only used for daemon
167 my @base_mod = qw(Devel::Peek);
168 my @over_mod = qw(DBD::SQLite DBI);
170 -index => [ @base_mod, @over_mod ],
172 -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
175 sub scan_ibx_modules ($$) {
176 my ($mods, $ibx) = @_;
177 if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
178 $mods->{'Search::Xapian'} = 1;
180 $mods->{$_} = 1 foreach @over_mod;
187 while (my $mod = shift @mods) {
188 if (my $groups = $mod_groups{$mod}) {
189 push @mods, @$groups;
190 } elsif ($mod eq 'Search::Xapian') {
191 require PublicInbox::Search;
192 PublicInbox::Search::load_xapian() or
193 $err->{'Search::Xapian || Xapian'} = $@;
196 $err->{$mod} = $@ if $@;
199 scalar keys %$err ? $err : undef;
202 sub missing_mod_msg {
204 my @mods = map { "`$_'" } sort keys %$err;
205 my $last = pop @mods;
206 @mods ? (join(', ', @mods)."' and $last") : $last
210 my $err = check_require(@_) or return;
211 die missing_mod_msg($err)." required for $0\n";
214 sub indexlevel_ok_or_die ($) {
215 my ($indexlevel) = @_;
217 if ($indexlevel eq 'basic') {
219 } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
223 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
226 my $err = check_require($req) or return;
227 die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
230 sub index_terminate {
231 my (undef, $ibx) = @_; # $_[0] = signal name
236 my ($ibx, $im, $opt) = @_;
237 require PublicInbox::InboxWritable;
238 my $jobs = delete $opt->{jobs} if $opt;
239 if (my $pr = $opt->{-progress}) {
240 $pr->("indexing $ibx->{inboxdir} ...\n");
243 setup_signals(\&index_terminate, $ibx);
244 my $warn_cb = $SIG{__WARN__} // \&CORE::warn;
245 my $idx = { current_info => $ibx->{inboxdir} };
246 my $warn_ignore = PublicInbox::InboxWritable->can('warn_ignore');
247 local $SIG{__WARN__} = sub {
248 return if $warn_ignore->(@_);
249 $warn_cb->($idx->{current_info}, ': ', @_);
251 if (ref($ibx) && $ibx->version == 2) {
252 eval { require PublicInbox::V2Writable };
253 die "v2 requirements not met: $@\n" if $@;
254 $ibx->{-creat_opt}->{nproc} = $jobs;
255 my $v2w = $im // $ibx->importer($opt->{reindex} // $jobs);
258 $v2w->{parallel} = 0;
260 my $n = $v2w->{shards};
261 if ($jobs < ($n + 1) && !$opt->{reshard}) {
263 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
270 require PublicInbox::SearchIdx;
271 $idx = PublicInbox::SearchIdx->new($ibx, 1);
273 $idx->index_sync($opt);
274 $idx->{nidx} // 0; # returns number processed
277 sub progress_prepare ($) {
280 # public-inbox-index defaults to quiet, -xcpdb and -compact do not
281 if (defined($opt->{quiet}) && $opt->{quiet} < 0) {
282 $opt->{quiet} = !$opt->{verbose};
285 open my $null, '>', '/dev/null' or
286 die "failed to open /dev/null: $!\n";
287 $opt->{1} = $null; # suitable for spawn() redirect
289 $opt->{verbose} ||= 1;
290 $opt->{-progress} = sub { print STDERR @_ };
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";