]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Admin.pm
script/public-inbox-*: favor caller-provided pathnames
[public-inbox.git] / lib / PublicInbox / Admin.pm
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>
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 File::Spec ();
14
15 sub setup_signals {
16         my ($cb, $arg) = @_; # optional
17         require POSIX;
18
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 {
22                 my ($sig) = @_;
23                 # https://www.tldp.org/LDP/abs/html/exitcodes.html
24                 eval { $cb->($sig, $arg) } if $cb;
25                 $sig = 'SIG'.$sig;
26                 exit(128 + POSIX->$sig);
27         };
28 }
29
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
35         require Cwd;
36         Cwd::abs_path($p);
37 }
38
39 sub resolve_inboxdir {
40         my ($cd, $ver) = @_;
41         my $try = $cd // '.';
42         my $root_dev_ino;
43         while (1) { # favor v2, first
44                 if (-f "$try/inbox.lock") {
45                         $$ver = 2 if $ver;
46                         return rel2abs_collapsed($try);
47                 } elsif (-d $try) {
48                         my @try = stat _;
49                         $root_dev_ino //= do {
50                                 my @root = stat('/') or die "stat /: $!\n";
51                                 "$root[0]\0$root[1]";
52                         };
53                         last if "$try[0]\0$try[1]" eq $root_dev_ino;
54                         $try .= '/..'; # continue, cd up
55                 } else {
56                         die "`$try' is not a directory\n";
57                 }
58         }
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";
64         chomp $dir;
65         $$ver = 1 if $ver;
66         rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
67 }
68
69 # for unconfigured inboxes
70 sub detect_indexlevel ($) {
71         my ($ibx) = @_;
72
73         my $over = $ibx->over;
74         my $srch = $ibx->search;
75         delete @$ibx{qw(over search)}; # don't leave open FDs lying around
76
77         # brand new or never before indexed inboxes default to full
78         return 'full' unless $over;
79         my $l = 'basic';
80         return $l unless $srch;
81         if (my $xdb = $srch->xdb) {
82                 $l = 'full';
83                 my $m = $xdb->get_metadata('indexlevel');
84                 if ($m eq 'medium') {
85                         $l = $m;
86                 } elsif ($m ne '') {
87                         warn <<"";
88 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
89
90                 }
91                 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
92         }
93         $l;
94 }
95
96 sub unconfigured_ibx ($$) {
97         my ($dir, $i) = @_;
98         my $name = "unconfigured-$i";
99         PublicInbox::Inbox->new({
100                 name => $name,
101                 address => [ "$name\@example.com" ],
102                 inboxdir => $dir,
103                 # consumers (-convert) warn on this:
104                 -unconfigured => 1,
105         });
106 }
107
108 sub resolve_inboxes ($;$$) {
109         my ($argv, $opt, $cfg) = @_;
110         $opt ||= {};
111
112         $cfg //= PublicInbox::Config->new;
113         if ($opt->{all}) {
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";
117         }
118
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
122         my (@old, @ibxs);
123         if ($opt->{all}) {
124                 $cfg->each_inbox(sub {
125                         my ($ibx) = @_;
126                         if (-e $ibx->{inboxdir}) {
127                                 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
128                         } else {
129                                 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
130                         }
131                 });
132         } else { # directories specified on the command-line
133                 my @dirs = @$argv;
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++) {
137                         my $dir = $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;
142                         } else {
143                                 push @old, $dir;
144                         }
145                 }
146                 my $done = \'done';
147                 eval {
148                         $cfg->each_inbox(sub {
149                                 my ($ibx) = @_;
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]"})
154                                                 // return;
155                                         $ibxs[$i] = $ibx;
156                                         die $done if !keys(%s2i);
157                                 } else {
158                                         warn "W: $ibx->{name} $dir: $!\n";
159                                 }
160                         });
161                 };
162                 die $@ if $@ && $@ ne $done;
163                 for my $i (sort { $a <=> $b } values %s2i) {
164                         $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
165                 }
166                 @ibxs = grep { defined } @ibxs; # duplicates are undef
167         }
168         if (@old) {
169                 die "-V$min_ver inboxes not supported by $0\n\t",
170                     join("\n\t", @old), "\n";
171         }
172         @ibxs;
173 }
174
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);
178 my %mod_groups = (
179         -index => [ @base_mod, @over_mod ],
180         -base => \@base_mod,
181         -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
182 );
183
184 sub scan_ibx_modules ($$) {
185         my ($mods, $ibx) = @_;
186         if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
187                 $mods->{'Search::Xapian'} = 1;
188         } else {
189                 $mods->{$_} = 1 foreach @over_mod;
190         }
191 }
192
193 sub check_require {
194         my (@mods) = @_;
195         my $err = {};
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'} = $@;
203                 } else {
204                         eval "require $mod";
205                         $err->{$mod} = $@ if $@;
206                 }
207         }
208         scalar keys %$err ? $err : undef;
209 }
210
211 sub missing_mod_msg {
212         my ($err) = @_;
213         my @mods = map { "`$_'" } sort keys %$err;
214         my $last = pop @mods;
215         @mods ? (join(', ', @mods)."' and $last") : $last
216 }
217
218 sub require_or_die {
219         my $err = check_require(@_) or return;
220         die missing_mod_msg($err)." required for $0\n";
221 }
222
223 sub indexlevel_ok_or_die ($) {
224         my ($indexlevel) = @_;
225         my $req;
226         if ($indexlevel eq 'basic') {
227                 $req = '-index';
228         } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
229                 $req = '-search';
230         } else {
231                 die <<"";
232 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
233
234         }
235         my $err = check_require($req) or return;
236         die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
237 }
238
239 sub index_terminate {
240         my (undef, $ibx) = @_; # $_[0] = signal name
241         $ibx->git->cleanup;
242 }
243
244 sub index_inbox {
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");
250         }
251         local %SIG = %SIG;
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}, ': ', @_);
259         };
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);
265                 if (defined $jobs) {
266                         if ($jobs == 0) {
267                                 $v2w->{parallel} = 0;
268                         } else {
269                                 my $n = $v2w->{shards};
270                                 if ($jobs < ($n + 1) && !$opt->{reshard}) {
271                                         warn <<EOM;
272 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
273 EOM
274                                 }
275                         }
276                 }
277                 $idx = $v2w;
278         } else {
279                 require PublicInbox::SearchIdx;
280                 $idx = PublicInbox::SearchIdx->new($ibx, 1);
281         }
282         $idx->index_sync($opt);
283 }
284
285 sub progress_prepare ($) {
286         my ($opt) = @_;
287
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};
291         }
292         if ($opt->{quiet}) {
293                 open my $null, '>', '/dev/null' or
294                         die "failed to open /dev/null: $!\n";
295                 $opt->{1} = $null; # suitable for spawn() redirect
296         } else {
297                 $opt->{verbose} ||= 1;
298                 $opt->{-progress} = sub { print STDERR @_ };
299         }
300 }
301
302 # same unit factors as git:
303 sub parse_unsigned ($) {
304         my ($val) = @_;
305
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);
310         1;
311 }
312
313 sub index_prepare ($$) {
314         my ($opt, $cfg) = @_;
315         my $env;
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;
322                 }
323         }
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";
330                 $opt->{$k} = $v;
331         }
332
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' };
337
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";
344                 $opt->{$k} = $v;
345         }
346         $env;
347 }
348
349 1;