]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Admin.pm
update copyrights for 2021
[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 *rel2abs_collapsed = \&PublicInbox::Config::rel2abs_collapsed;
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 sub resolve_inboxdir {
31         my ($cd, $ver) = @_;
32         my $try = $cd // '.';
33         my $root_dev_ino;
34         while (1) { # favor v2, first
35                 if (-f "$try/inbox.lock") {
36                         $$ver = 2 if $ver;
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                         last 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         # 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";
55         chomp $dir;
56         $$ver = 1 if $ver;
57         rel2abs_collapsed($dir eq '.' ? ($cd // $dir) : $dir);
58 }
59
60 # for unconfigured inboxes
61 sub detect_indexlevel ($) {
62         my ($ibx) = @_;
63
64         my $over = $ibx->over;
65         my $srch = $ibx->search;
66         delete @$ibx{qw(over search)}; # don't leave open FDs lying around
67
68         # brand new or never before indexed inboxes default to full
69         return 'full' unless $over;
70         my $l = 'basic';
71         return $l unless $srch;
72         if (my $xdb = $srch->xdb) {
73                 $l = 'full';
74                 my $m = $xdb->get_metadata('indexlevel');
75                 if ($m eq 'medium') {
76                         $l = $m;
77                 } elsif ($m ne '') {
78                         warn <<"";
79 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
80
81                 }
82                 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
83         }
84         $l;
85 }
86
87 sub unconfigured_ibx ($$) {
88         my ($dir, $i) = @_;
89         my $name = "unconfigured-$i";
90         PublicInbox::Inbox->new({
91                 name => $name,
92                 address => [ "$name\@example.com" ],
93                 inboxdir => $dir,
94                 # consumers (-convert) warn on this:
95                 -unconfigured => 1,
96         });
97 }
98
99 sub resolve_inboxes ($;$$) {
100         my ($argv, $opt, $cfg) = @_;
101         $opt ||= {};
102
103         $cfg //= PublicInbox::Config->new;
104         if ($opt->{all}) {
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";
108         }
109
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
113         my (@old, @ibxs);
114         if ($opt->{all}) {
115                 $cfg->each_inbox(sub {
116                         my ($ibx) = @_;
117                         if (-e $ibx->{inboxdir}) {
118                                 push(@ibxs, $ibx) if $ibx->version >= $min_ver;
119                         } else {
120                                 warn "W: $ibx->{name} $ibx->{inboxdir}: $!\n";
121                         }
122                 });
123         } else { # directories specified on the command-line
124                 my @dirs = @$argv;
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++) {
128                         my $dir = $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;
133                         } else {
134                                 push @old, $dir;
135                         }
136                 }
137                 my $done = \'done';
138                 eval {
139                         $cfg->each_inbox(sub {
140                                 my ($ibx) = @_;
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]"})
145                                                 // return;
146                                         $ibxs[$i] = $ibx;
147                                         die $done if !keys(%s2i);
148                                 } else {
149                                         warn "W: $ibx->{name} $dir: $!\n";
150                                 }
151                         });
152                 };
153                 die $@ if $@ && $@ ne $done;
154                 for my $i (sort { $a <=> $b } values %s2i) {
155                         $ibxs[$i] = unconfigured_ibx($dirs[$i], $i);
156                 }
157                 @ibxs = grep { defined } @ibxs; # duplicates are undef
158         }
159         if (@old) {
160                 die "-V$min_ver inboxes not supported by $0\n\t",
161                     join("\n\t", @old), "\n";
162         }
163         @ibxs;
164 }
165
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);
169 my %mod_groups = (
170         -index => [ @base_mod, @over_mod ],
171         -base => \@base_mod,
172         -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
173 );
174
175 sub scan_ibx_modules ($$) {
176         my ($mods, $ibx) = @_;
177         if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
178                 $mods->{'Search::Xapian'} = 1;
179         } else {
180                 $mods->{$_} = 1 foreach @over_mod;
181         }
182 }
183
184 sub check_require {
185         my (@mods) = @_;
186         my $err = {};
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'} = $@;
194                 } else {
195                         eval "require $mod";
196                         $err->{$mod} = $@ if $@;
197                 }
198         }
199         scalar keys %$err ? $err : undef;
200 }
201
202 sub missing_mod_msg {
203         my ($err) = @_;
204         my @mods = map { "`$_'" } sort keys %$err;
205         my $last = pop @mods;
206         @mods ? (join(', ', @mods)."' and $last") : $last
207 }
208
209 sub require_or_die {
210         my $err = check_require(@_) or return;
211         die missing_mod_msg($err)." required for $0\n";
212 }
213
214 sub indexlevel_ok_or_die ($) {
215         my ($indexlevel) = @_;
216         my $req;
217         if ($indexlevel eq 'basic') {
218                 $req = '-index';
219         } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
220                 $req = '-search';
221         } else {
222                 die <<"";
223 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
224
225         }
226         my $err = check_require($req) or return;
227         die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
228 }
229
230 sub index_terminate {
231         my (undef, $ibx) = @_; # $_[0] = signal name
232         $ibx->git->cleanup;
233 }
234
235 sub index_inbox {
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");
241         }
242         local %SIG = %SIG;
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}, ': ', @_);
250         };
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);
256                 if (defined $jobs) {
257                         if ($jobs == 0) {
258                                 $v2w->{parallel} = 0;
259                         } else {
260                                 my $n = $v2w->{shards};
261                                 if ($jobs < ($n + 1) && !$opt->{reshard}) {
262                                         warn <<EOM;
263 Unable to respect --jobs=$jobs on index, inbox was created with $n shards
264 EOM
265                                 }
266                         }
267                 }
268                 $idx = $v2w;
269         } else {
270                 require PublicInbox::SearchIdx;
271                 $idx = PublicInbox::SearchIdx->new($ibx, 1);
272         }
273         $idx->index_sync($opt);
274         $idx->{nidx} // 0; # returns number processed
275 }
276
277 sub progress_prepare ($) {
278         my ($opt) = @_;
279
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};
283         }
284         if ($opt->{quiet}) {
285                 open my $null, '>', '/dev/null' or
286                         die "failed to open /dev/null: $!\n";
287                 $opt->{1} = $null; # suitable for spawn() redirect
288         } else {
289                 $opt->{verbose} ||= 1;
290                 $opt->{-progress} = sub { print STDERR @_ };
291         }
292 }
293
294 # same unit factors as git:
295 sub parse_unsigned ($) {
296         my ($val) = @_;
297
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);
302         1;
303 }
304
305 sub index_prepare ($$) {
306         my ($opt, $cfg) = @_;
307         my $env;
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;
314                 }
315         }
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";
322                 $opt->{$k} = $v;
323         }
324
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' };
329
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";
336                 $opt->{$k} = $v;
337         }
338         $env;
339 }
340
341 1;