]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Admin.pm
20964f9cf7ac97dc7428c0a3cbee58d5e0050bb9
[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_eidxdir {
32         my ($cd) = @_;
33         my $try = $cd // '.';
34         my $root_dev_ino;
35         while (1) { # favor v2, first
36                 if (-f "$try/ei.lock") {
37                         return rel2abs_collapsed($try);
38                 } elsif (-d $try) {
39                         my @try = stat _;
40                         $root_dev_ino //= do {
41                                 my @root = stat('/') or die "stat /: $!\n";
42                                 "$root[0]\0$root[1]";
43                         };
44                         return undef if "$try[0]\0$try[1]" eq $root_dev_ino;
45                         $try .= '/..'; # continue, cd up
46                 } else {
47                         die "`$try' is not a directory\n";
48                 }
49         }
50 }
51
52 sub resolve_inboxdir {
53         my ($cd, $ver) = @_;
54         my $try = $cd // '.';
55         my $root_dev_ino;
56         while (1) { # favor v2, first
57                 if (-f "$try/inbox.lock") {
58                         $$ver = 2 if $ver;
59                         return rel2abs_collapsed($try);
60                 } elsif (-d $try) {
61                         my @try = stat _;
62                         $root_dev_ino //= do {
63                                 my @root = stat('/') or die "stat /: $!\n";
64                                 "$root[0]\0$root[1]";
65                         };
66                         last if "$try[0]\0$try[1]" eq $root_dev_ino;
67                         $try .= '/..'; # continue, cd up
68                 } else {
69                         die "`$try' is not a directory\n";
70                 }
71         }
72         # try v1 bare git dirs
73         my $cmd = [ qw(git rev-parse --git-dir) ];
74         my $fh = popen_rd($cmd, undef, {-C => $cd});
75         my $dir = do { local $/; <$fh> };
76         close $fh or die "error in @$cmd (cwd:${\($cd // '.')}): $!\n";
77         chomp $dir;
78         $$ver = 1 if $ver;
79         rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
80 }
81
82 # for unconfigured inboxes
83 sub detect_indexlevel ($) {
84         my ($ibx) = @_;
85
86         my $over = $ibx->over;
87         my $srch = $ibx->search;
88         delete @$ibx{qw(over search)}; # don't leave open FDs lying around
89
90         # brand new or never before indexed inboxes default to full
91         return 'full' unless $over;
92         my $l = 'basic';
93         return $l unless $srch;
94         if (my $xdb = $srch->xdb) {
95                 $l = 'full';
96                 my $m = $xdb->get_metadata('indexlevel');
97                 if ($m eq 'medium') {
98                         $l = $m;
99                 } elsif ($m ne '') {
100                         warn <<"";
101 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
102
103                 }
104                 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
105         }
106         $l;
107 }
108
109 sub unconfigured_ibx ($$) {
110         my ($dir, $i) = @_;
111         my $name = "unconfigured-$i";
112         PublicInbox::Inbox->new({
113                 name => $name,
114                 address => [ "$name\@example.com" ],
115                 inboxdir => $dir,
116                 # consumers (-convert) warn on this:
117                 -unconfigured => 1,
118         });
119 }
120
121 sub resolve_inboxes ($;$$) {
122         my ($argv, $opt, $cfg) = @_;
123         $opt ||= {};
124
125         $cfg //= PublicInbox::Config->new;
126         if ($opt->{all}) {
127                 my $cfgfile = PublicInbox::Config::default_file();
128                 $cfg or die "--all specified, but $cfgfile not readable\n";
129                 @$argv and die "--all specified, but directories specified\n";
130         }
131         my (@old, @ibxs, @eidx);
132         if ($opt->{-eidx_ok}) {
133                 require PublicInbox::ExtSearchIdx;
134                 my $i = -1;
135                 @$argv = grep {
136                         $i++;
137                         if (defined(my $ei = resolve_eidxdir($_))) {
138                                 $ei = PublicInbox::ExtSearchIdx->new($ei, $opt);
139                                 push @eidx, $ei;
140                                 undef;
141                         } else {
142                                 1;
143                         }
144                 } @$argv;
145         }
146         my $min_ver = $opt->{-min_inbox_version} || 0;
147         # lookup inboxes by st_dev + st_ino instead of {inboxdir} pathnames,
148         # pathnames are not unique due to symlinks and bind mounts
149         if ($opt->{all}) {
150                 $cfg->each_inbox(sub {
151                         my ($ibx) = @_;
152                         if (-e $ibx->{inboxdir}) {
153                                 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
154                         } else {
155                                 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
156                         }
157                 });
158         } else { # directories specified on the command-line
159                 my @dirs = @$argv;
160                 push @dirs, '.' if !@dirs && $opt->{-use_cwd};
161                 my %s2i; # "st_dev\0st_ino" => array index
162                 for (my $i = 0; $i <= $#dirs; $i++) {
163                         my $dir = $dirs[$i];
164                         my @st = stat($dir) or die "stat($dir): $!\n";
165                         $dir = $dirs[$i] = resolve_inboxdir($dir, \(my $ver));
166                         if ($ver >= $min_ver) {
167                                 $s2i{"$st[0]\0$st[1]"} //= $i;
168                         } else {
169                                 push @old, $dir;
170                         }
171                 }
172                 my $done = \'done';
173                 eval {
174                         $cfg->each_inbox(sub {
175                                 my ($ibx) = @_;
176                                 return if $ibx->version < $min_ver;
177                                 my $dir = $ibx->{inboxdir};
178                                 if (my @s = stat $dir) {
179                                         my $i = delete($s2i{"$s[0]\0$s[1]"})
180                                                 // return;
181                                         $ibxs[$i] = $ibx;
182                                         die $done if !keys(%s2i);
183                                 } else {
184                                         warn "W: $ibx->{name} $dir: $!\n";
185                                 }
186                         });
187                 };
188                 die $@ if $@ && $@ ne $done;
189                 for my $i (sort { $a <=> $b } values %s2i) {
190                         $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
191                 }
192                 @ibxs = grep { defined } @ibxs; # duplicates are undef
193         }
194         if (@old) {
195                 die "-V$min_ver inboxes not supported by $0\n\t",
196                     join("\n\t", @old), "\n";
197         }
198         $opt->{-eidx_ok} ? (\@ibxs, \@eidx) : @ibxs;
199 }
200
201 # TODO: make Devel::Peek optional, only used for daemon
202 my @base_mod = qw(Devel::Peek);
203 my @over_mod = qw(DBD::SQLite DBI);
204 my %mod_groups = (
205         -index => [ @base_mod, @over_mod ],
206         -base => \@base_mod,
207         -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
208 );
209
210 sub scan_ibx_modules ($$) {
211         my ($mods, $ibx) = @_;
212         if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
213                 $mods->{'Search::Xapian'} = 1;
214         } else {
215                 $mods->{$_} = 1 foreach @over_mod;
216         }
217 }
218
219 sub check_require {
220         my (@mods) = @_;
221         my $err = {};
222         while (my $mod = shift @mods) {
223                 if (my $groups = $mod_groups{$mod}) {
224                         push @mods, @$groups;
225                 } elsif ($mod eq 'Search::Xapian') {
226                         require PublicInbox::Search;
227                         PublicInbox::Search::load_xapian() or
228                                 $err->{'Search::Xapian || Xapian'} = $@;
229                 } else {
230                         eval "require $mod";
231                         $err->{$mod} = $@ if $@;
232                 }
233         }
234         scalar keys %$err ? $err : undef;
235 }
236
237 sub missing_mod_msg {
238         my ($err) = @_;
239         my @mods = map { "`$_'" } sort keys %$err;
240         my $last = pop @mods;
241         @mods ? (join(', ', @mods)."' and $last") : $last
242 }
243
244 sub require_or_die {
245         my $err = check_require(@_) or return;
246         die missing_mod_msg($err)." required for $0\n";
247 }
248
249 sub indexlevel_ok_or_die ($) {
250         my ($indexlevel) = @_;
251         my $req;
252         if ($indexlevel eq 'basic') {
253                 $req = '-index';
254         } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
255                 $req = '-search';
256         } else {
257                 die <<"";
258 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
259
260         }
261         my $err = check_require($req) or return;
262         die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
263 }
264
265 sub index_terminate {
266         my (undef, $ibx) = @_; # $_[0] = signal name
267         $ibx->git->cleanup;
268 }
269
270 sub index_inbox {
271         my ($ibx, $im, $opt) = @_;
272         require PublicInbox::InboxWritable;
273         my $jobs = delete $opt->{jobs} if $opt;
274         if (my $pr = $opt->{-progress}) {
275                 $pr->("indexing $ibx->{inboxdir} ...\n");
276         }
277         local @SIG{keys %SIG} = values %SIG;
278         setup_signals(\&index_terminate, $ibx);
279         my $idx = { current_info => $ibx->{inboxdir} };
280         local $SIG{__WARN__} = sub {
281                 return if PublicInbox::Eml::warn_ignore(@_);
282                 warn($idx->{current_info}, ': ', @_);
283         };
284         if ($ibx->version == 2) {
285                 eval { require PublicInbox::V2Writable };
286                 die "v2 requirements not met: $@\n" if $@;
287                 $ibx->{-creat_opt}->{nproc} = $jobs;
288                 my $v2w = $im // $ibx->importer($opt->{reindex} // $jobs);
289                 if (defined $jobs) {
290                         if ($jobs == 0) {
291                                 $v2w->{parallel} = 0;
292                         } else {
293                                 my $n = $v2w->{shards};
294                                 if ($jobs < ($n + 1) && !$opt->{reshard}) {
295                                         warn <<EOM;
296 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
297 EOM
298                                 }
299                         }
300                 }
301                 $idx = $v2w;
302         } else {
303                 require PublicInbox::SearchIdx;
304                 $idx = PublicInbox::SearchIdx->new($ibx, 1);
305         }
306         $idx->index_sync($opt);
307         $idx->{nidx} // 0; # returns number processed
308 }
309
310 sub progress_prepare ($;$) {
311         my ($opt, $dst) = @_;
312
313         # public-inbox-index defaults to quiet, -xcpdb and -compact do not
314         if (defined($opt->{quiet}) && $opt->{quiet} < 0) {
315                 $opt->{quiet} = !$opt->{verbose};
316         }
317         if ($opt->{quiet}) {
318                 open my $null, '>', '/dev/null' or
319                         die "failed to open /dev/null: $!\n";
320                 $opt->{1} = $null; # suitable for spawn() redirect
321         } else {
322                 $opt->{verbose} ||= 1;
323                 $dst //= *STDERR{GLOB};
324                 $opt->{-progress} = sub { print $dst @_ };
325         }
326 }
327
328 # same unit factors as git:
329 sub parse_unsigned ($) {
330         my ($val) = @_;
331
332         $$val =~ /\A([0-9]+)([kmg])?\z/i or return;
333         my ($n, $unit_factor) = ($1, $2 // '');
334         my %u = ( k => 1024, m => 1024**2, g => 1024**3 );
335         $$val = $n * ($u{lc($unit_factor)} // 1);
336         1;
337 }
338
339 sub index_prepare ($$) {
340         my ($opt, $cfg) = @_;
341         my $env;
342         if ($opt->{compact}) {
343                 require PublicInbox::Xapcmd;
344                 PublicInbox::Xapcmd::check_compact();
345                 $opt->{compact_opt} = { -coarse_lock => 1, compact => 1 };
346                 if (defined(my $jobs = $opt->{jobs})) {
347                         $opt->{compact_opt}->{jobs} = $jobs;
348                 }
349         }
350         for my $k (qw(max_size batch_size)) {
351                 my $git_key = "publicInbox.index".ucfirst($k);
352                 $git_key =~ s/_([a-z])/\U$1/g;
353                 defined(my $v = $opt->{$k} // $cfg->{lc($git_key)}) or next;
354                 parse_unsigned(\$v) or die "`$git_key=$v' not parsed\n";
355                 $v > 0 or die "`$git_key=$v' must be positive\n";
356                 $opt->{$k} = $v;
357         }
358
359         # out-of-the-box builds of Xapian 1.4.x are still limited to 32-bit
360         # https://getting-started-with-xapian.readthedocs.io/en/latest/concepts/indexing/limitations.html
361         $opt->{batch_size} and
362                 $env = { XAPIAN_FLUSH_THRESHOLD => '4294967295' };
363
364         for my $k (qw(sequential-shard)) {
365                 my $git_key = "publicInbox.index".ucfirst($k);
366                 $git_key =~ s/-([a-z])/\U$1/g;
367                 defined(my $s = $opt->{$k} // $cfg->{lc($git_key)}) or next;
368                 defined(my $v = $cfg->git_bool($s))
369                                         or die "`$git_key=$s' not boolean\n";
370                 $opt->{$k} = $v;
371         }
372         $env;
373 }
374
375 sub do_chdir ($) {
376         my $chdir = $_[0] // return;
377         for my $d (@$chdir) {
378                 next if $d eq ''; # same as git(1)
379                 chdir $d or die "cd $d: $!";
380         }
381 }
382
383 1;