]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Admin.pm
3b38a5a337d7f1dae23ce1165e320a6d69ba0670
[public-inbox.git] / lib / PublicInbox / Admin.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 # common stuff for administrative command-line tools
5 # Unstable internal API
6 package PublicInbox::Admin;
7 use strict;
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 use PublicInbox::Eml;
14 *rel2abs_collapsed = \&PublicInbox::Config::rel2abs_collapsed;
15
16 sub setup_signals {
17         my ($cb, $arg) = @_; # optional
18         require POSIX;
19
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 {
23                 my ($sig) = @_;
24                 # https://www.tldp.org/LDP/abs/html/exitcodes.html
25                 eval { $cb->($sig, $arg) } if $cb;
26                 $sig = 'SIG'.$sig;
27                 exit(128 + POSIX->$sig);
28         };
29 }
30
31 sub resolve_inboxdir {
32         my ($cd, $ver) = @_;
33         my $try = $cd // '.';
34         my $root_dev_ino;
35         while (1) { # favor v2, first
36                 if (-f "$try/inbox.lock") {
37                         $$ver = 2 if $ver;
38                         return rel2abs_collapsed($try);
39                 } elsif (-d $try) {
40                         my @try = stat _;
41                         $root_dev_ino //= do {
42                                 my @root = stat('/') or die "stat /: $!\n";
43                                 "$root[0]\0$root[1]";
44                         };
45                         last if "$try[0]\0$try[1]" eq $root_dev_ino;
46                         $try .= '/..'; # continue, cd up
47                 } else {
48                         die "`$try' is not a directory\n";
49                 }
50         }
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";
56         chomp $dir;
57         $$ver = 1 if $ver;
58         rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
59 }
60
61 # for unconfigured inboxes
62 sub detect_indexlevel ($) {
63         my ($ibx) = @_;
64
65         my $over = $ibx->over;
66         my $srch = $ibx->search;
67         delete @$ibx{qw(over search)}; # don't leave open FDs lying around
68
69         # brand new or never before indexed inboxes default to full
70         return 'full' unless $over;
71         my $l = 'basic';
72         return $l unless $srch;
73         if (my $xdb = $srch->xdb) {
74                 $l = 'full';
75                 my $m = $xdb->get_metadata('indexlevel');
76                 if ($m eq 'medium') {
77                         $l = $m;
78                 } elsif ($m ne '') {
79                         warn <<"";
80 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
81
82                 }
83                 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
84         }
85         $l;
86 }
87
88 sub unconfigured_ibx ($$) {
89         my ($dir, $i) = @_;
90         my $name = "unconfigured-$i";
91         PublicInbox::Inbox->new({
92                 name => $name,
93                 address => [ "$name\@example.com" ],
94                 inboxdir => $dir,
95                 # consumers (-convert) warn on this:
96                 -unconfigured => 1,
97         });
98 }
99
100 sub resolve_inboxes ($;$$) {
101         my ($argv, $opt, $cfg) = @_;
102         $opt ||= {};
103
104         $cfg //= PublicInbox::Config->new;
105         if ($opt->{all}) {
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";
109         }
110
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
114         my (@old, @ibxs);
115         if ($opt->{all}) {
116                 $cfg->each_inbox(sub {
117                         my ($ibx) = @_;
118                         if (-e $ibx->{inboxdir}) {
119                                 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
120                         } else {
121                                 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
122                         }
123                 });
124         } else { # directories specified on the command-line
125                 my @dirs = @$argv;
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++) {
129                         my $dir = $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;
134                         } else {
135                                 push @old, $dir;
136                         }
137                 }
138                 my $done = \'done';
139                 eval {
140                         $cfg->each_inbox(sub {
141                                 my ($ibx) = @_;
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]"})
146                                                 // return;
147                                         $ibxs[$i] = $ibx;
148                                         die $done if !keys(%s2i);
149                                 } else {
150                                         warn "W: $ibx->{name} $dir: $!\n";
151                                 }
152                         });
153                 };
154                 die $@ if $@ && $@ ne $done;
155                 for my $i (sort { $a <=> $b } values %s2i) {
156                         $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
157                 }
158                 @ibxs = grep { defined } @ibxs; # duplicates are undef
159         }
160         if (@old) {
161                 die "-V$min_ver inboxes not supported by $0\n\t",
162                     join("\n\t", @old), "\n";
163         }
164         @ibxs;
165 }
166
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);
170 my %mod_groups = (
171         -index => [ @base_mod, @over_mod ],
172         -base => \@base_mod,
173         -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
174 );
175
176 sub scan_ibx_modules ($$) {
177         my ($mods, $ibx) = @_;
178         if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
179                 $mods->{'Search::Xapian'} = 1;
180         } else {
181                 $mods->{$_} = 1 foreach @over_mod;
182         }
183 }
184
185 sub check_require {
186         my (@mods) = @_;
187         my $err = {};
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'} = $@;
195                 } else {
196                         eval "require $mod";
197                         $err->{$mod} = $@ if $@;
198                 }
199         }
200         scalar keys %$err ? $err : undef;
201 }
202
203 sub missing_mod_msg {
204         my ($err) = @_;
205         my @mods = map { "`$_'" } sort keys %$err;
206         my $last = pop @mods;
207         @mods ? (join(', ', @mods)."' and $last") : $last
208 }
209
210 sub require_or_die {
211         my $err = check_require(@_) or return;
212         die missing_mod_msg($err)." required for $0\n";
213 }
214
215 sub indexlevel_ok_or_die ($) {
216         my ($indexlevel) = @_;
217         my $req;
218         if ($indexlevel eq 'basic') {
219                 $req = '-index';
220         } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
221                 $req = '-search';
222         } else {
223                 die <<"";
224 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
225
226         }
227         my $err = check_require($req) or return;
228         die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
229 }
230
231 sub index_terminate {
232         my (undef, $ibx) = @_; # $_[0] = signal name
233         $ibx->git->cleanup;
234 }
235
236 sub index_inbox {
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");
242         }
243         local %SIG = %SIG;
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}, ': ', @_);
249         };
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);
255                 if (defined $jobs) {
256                         if ($jobs == 0) {
257                                 $v2w->{parallel} = 0;
258                         } else {
259                                 my $n = $v2w->{shards};
260                                 if ($jobs < ($n + 1) && !$opt->{reshard}) {
261                                         warn <<EOM;
262 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
263 EOM
264                                 }
265                         }
266                 }
267                 $idx = $v2w;
268         } else {
269                 require PublicInbox::SearchIdx;
270                 $idx = PublicInbox::SearchIdx->new($ibx, 1);
271         }
272         $idx->index_sync($opt);
273         $idx->{nidx} // 0; # returns number processed
274 }
275
276 sub progress_prepare ($) {
277         my ($opt) = @_;
278
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};
282         }
283         if ($opt->{quiet}) {
284                 open my $null, '>', '/dev/null' or
285                         die "failed to open /dev/null: $!\n";
286                 $opt->{1} = $null; # suitable for spawn() redirect
287         } else {
288                 $opt->{verbose} ||= 1;
289                 $opt->{-progress} = sub { print STDERR @_ };
290         }
291 }
292
293 # same unit factors as git:
294 sub parse_unsigned ($) {
295         my ($val) = @_;
296
297         $$val =~ /\A([0-9]+)([kmg])?\z/i or return;
298         my ($n, $unit_factor) = ($1, $2 // '');
299         my %u = ( k => 1024, m => 1024**2, g => 1024**3 );
300         $$val = $n * ($u{lc($unit_factor)} // 1);
301         1;
302 }
303
304 sub index_prepare ($$) {
305         my ($opt, $cfg) = @_;
306         my $env;
307         if ($opt->{compact}) {
308                 require PublicInbox::Xapcmd;
309                 PublicInbox::Xapcmd::check_compact();
310                 $opt->{compact_opt} = { -coarse_lock => 1, compact => 1 };
311                 if (defined(my $jobs = $opt->{jobs})) {
312                         $opt->{compact_opt}->{jobs} = $jobs;
313                 }
314         }
315         for my $k (qw(max_size batch_size)) {
316                 my $git_key = "publicInbox.index".ucfirst($k);
317                 $git_key =~ s/_([a-z])/\U$1/g;
318                 defined(my $v = $opt->{$k} // $cfg->{lc($git_key)}) or next;
319                 parse_unsigned(\$v) or die "`$git_key=$v' not parsed\n";
320                 $v > 0 or die "`$git_key=$v' must be positive\n";
321                 $opt->{$k} = $v;
322         }
323
324         # out-of-the-box builds of Xapian 1.4.x are still limited to 32-bit
325         # https://getting-started-with-xapian.readthedocs.io/en/latest/concepts/indexing/limitations.html
326         $opt->{batch_size} and
327                 $env = { XAPIAN_FLUSH_THRESHOLD => '4294967295' };
328
329         for my $k (qw(sequential_shard)) {
330                 my $git_key = "publicInbox.index".ucfirst($k);
331                 $git_key =~ s/_([a-z])/\U$1/g;
332                 defined(my $s = $opt->{$k} // $cfg->{lc($git_key)}) or next;
333                 defined(my $v = $cfg->git_bool($s))
334                                         or die "`$git_key=$s' not boolean\n";
335                 $opt->{$k} = $v;
336         }
337         $env;
338 }
339
340 1;