]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Admin.pm
admin: improve minimum version text
[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 use Cwd qw(abs_path);
10 use POSIX ();
11 our @EXPORT_OK = qw(resolve_repo_dir setup_signals);
12 use PublicInbox::Config;
13 use PublicInbox::Inbox;
14 use PublicInbox::Spawn qw(popen_rd);
15
16 sub setup_signals {
17         my ($cb, $arg) = @_; # optional
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_repo_dir {
31         my ($cd, $ver) = @_;
32         my $prefix = defined $cd ? $cd : './';
33         if (-d $prefix && -f "$prefix/inbox.lock") { # v2
34                 $$ver = 2 if $ver;
35                 return abs_path($prefix);
36         }
37         my $cmd = [ qw(git rev-parse --git-dir) ];
38         my $fh = popen_rd($cmd, undef, {-C => $cd});
39         my $dir = do { local $/; <$fh> };
40         close $fh or die "error in ".join(' ', @$cmd)." (cwd:$cd): $!\n";
41         chomp $dir;
42         $$ver = 1 if $ver;
43         return abs_path($cd) if ($dir eq '.' && defined $cd);
44         abs_path($dir);
45 }
46
47 # for unconfigured inboxes
48 sub detect_indexlevel ($) {
49         my ($ibx) = @_;
50
51         my $over = $ibx->over;
52         my $srch = $ibx->search;
53         delete @$ibx{qw(over search)}; # don't leave open FDs lying around
54
55         # brand new or never before indexed inboxes default to full
56         return 'full' unless $over;
57         my $l = 'basic';
58         return $l unless $srch;
59         if (my $xdb = $srch->xdb) {
60                 $l = 'full';
61                 my $m = $xdb->get_metadata('indexlevel');
62                 if ($m eq 'medium') {
63                         $l = $m;
64                 } elsif ($m ne '') {
65                         warn <<"";
66 $ibx->{inboxdir} has unexpected indexlevel in Xapian: $m
67
68                 }
69                 $ibx->{-skip_docdata} = 1 if $xdb->get_metadata('skip_docdata');
70         }
71         $l;
72 }
73
74 sub unconfigured_ibx ($$) {
75         my ($dir, $i) = @_;
76         my $name = "unconfigured-$i";
77         PublicInbox::Inbox->new({
78                 name => $name,
79                 address => [ "$name\@example.com" ],
80                 inboxdir => $dir,
81                 # TODO: consumers may want to warn on this:
82                 #-unconfigured => 1,
83         });
84 }
85
86 sub resolve_inboxes ($;$$) {
87         my ($argv, $opt, $cfg) = @_;
88         $opt ||= {};
89
90         $cfg //= PublicInbox::Config->new;
91         if ($opt->{all}) {
92                 my $cfgfile = PublicInbox::Config::default_file();
93                 $cfg or die "--all specified, but $cfgfile not readable\n";
94                 @$argv and die "--all specified, but directories specified\n";
95         }
96
97         my $min_ver = $opt->{-min_inbox_version} || 0;
98         my (@old, @ibxs);
99         my %dir2ibx;
100         if ($cfg) {
101                 $cfg->each_inbox(sub {
102                         my ($ibx) = @_;
103                         my $path = abs_path($ibx->{inboxdir});
104                         if (defined($path)) {
105                                 $dir2ibx{$path} = $ibx;
106                         } else {
107                                 warn <<EOF;
108 W: $ibx->{name} $ibx->{inboxdir}: $!
109 EOF
110                         }
111                 });
112         }
113         if ($opt->{all}) {
114                 my @all = values %dir2ibx;
115                 @all = grep { $_->version >= $min_ver } @all;
116                 push @ibxs, @all;
117         } else { # directories specified on the command-line
118                 my $i = 0;
119                 my @dirs = @$argv;
120                 push @dirs, '.' unless @dirs;
121                 foreach (@dirs) {
122                         my $v;
123                         my $dir = resolve_repo_dir($_, \$v);
124                         if ($v < $min_ver) {
125                                 push @old, $dir;
126                                 next;
127                         }
128                         my $ibx = $dir2ibx{$dir} ||= unconfigured_ibx($dir, $i);
129                         $i++;
130                         push @ibxs, $ibx;
131                 }
132         }
133         if (@old) {
134                 die "-V$min_ver inboxes not supported by $0\n\t",
135                     join("\n\t", @old), "\n";
136         }
137         @ibxs;
138 }
139
140 # TODO: make Devel::Peek optional, only used for daemon
141 my @base_mod = qw(Devel::Peek);
142 my @over_mod = qw(DBD::SQLite DBI);
143 my %mod_groups = (
144         -index => [ @base_mod, @over_mod ],
145         -base => \@base_mod,
146         -search => [ @base_mod, @over_mod, 'Search::Xapian' ],
147 );
148
149 sub scan_ibx_modules ($$) {
150         my ($mods, $ibx) = @_;
151         if (!$ibx->{indexlevel} || $ibx->{indexlevel} ne 'basic') {
152                 $mods->{'Search::Xapian'} = 1;
153         } else {
154                 $mods->{$_} = 1 foreach @over_mod;
155         }
156 }
157
158 sub check_require {
159         my (@mods) = @_;
160         my $err = {};
161         while (my $mod = shift @mods) {
162                 if (my $groups = $mod_groups{$mod}) {
163                         push @mods, @$groups;
164                 } elsif ($mod eq 'Search::Xapian') {
165                         require PublicInbox::Search;
166                         PublicInbox::Search::load_xapian() or
167                                 $err->{'Search::Xapian || Xapian'} = $@;
168                 } else {
169                         eval "require $mod";
170                         $err->{$mod} = $@ if $@;
171                 }
172         }
173         scalar keys %$err ? $err : undef;
174 }
175
176 sub missing_mod_msg {
177         my ($err) = @_;
178         my @mods = map { "`$_'" } sort keys %$err;
179         my $last = pop @mods;
180         @mods ? (join(', ', @mods)."' and $last") : $last
181 }
182
183 sub require_or_die {
184         my $err = check_require(@_) or return;
185         die missing_mod_msg($err)." required for $0\n";
186 }
187
188 sub indexlevel_ok_or_die ($) {
189         my ($indexlevel) = @_;
190         my $req;
191         if ($indexlevel eq 'basic') {
192                 $req = '-index';
193         } elsif ($indexlevel =~ /\A(?:medium|full)\z/) {
194                 $req = '-search';
195         } else {
196                 die <<"";
197 invalid indexlevel=$indexlevel (must be `basic', `medium', or `full')
198
199         }
200         my $err = check_require($req) or return;
201         die missing_mod_msg($err) ." required for indexlevel=$indexlevel\n";
202 }
203
204 sub index_terminate {
205         my (undef, $ibx) = @_; # $_[0] = signal name
206         $ibx->git->cleanup;
207 }
208
209 sub index_inbox {
210         my ($ibx, $im, $opt) = @_;
211         my $jobs = delete $opt->{jobs} if $opt;
212         if (my $pr = $opt->{-progress}) {
213                 $pr->("indexing $ibx->{inboxdir} ...\n");
214         }
215         local %SIG = %SIG;
216         setup_signals(\&index_terminate, $ibx);
217         if (ref($ibx) && $ibx->version == 2) {
218                 eval { require PublicInbox::V2Writable };
219                 die "v2 requirements not met: $@\n" if $@;
220                 $ibx->{-creat_opt}->{nproc} = $jobs;
221                 my $v2w = $im // $ibx->importer($opt->{reindex} // $jobs);
222                 if (defined $jobs) {
223                         if ($jobs == 0) {
224                                 $v2w->{parallel} = 0;
225                         } else {
226                                 my $n = $v2w->{shards};
227                                 if ($jobs < ($n + 1) && !$opt->{reshard}) {
228                                         warn
229 "Unable to respect --jobs=$jobs on index, inbox was created with $n shards\n";
230                                 }
231                         }
232                 }
233                 my $warn_cb = $SIG{__WARN__} || sub { print STDERR @_ };
234                 local $SIG{__WARN__} = sub {
235                         $warn_cb->($v2w->{current_info}, ': ', @_);
236                 };
237                 $v2w->index_sync($opt);
238         } else {
239                 require PublicInbox::SearchIdx;
240                 my $s = PublicInbox::SearchIdx->new($ibx, 1);
241                 $s->index_sync($opt);
242         }
243 }
244
245 sub progress_prepare ($) {
246         my ($opt) = @_;
247
248         # public-inbox-index defaults to quiet, -xcpdb and -compact do not
249         if (defined($opt->{quiet}) && $opt->{quiet} < 0) {
250                 $opt->{quiet} = !$opt->{verbose};
251         }
252         if ($opt->{quiet}) {
253                 open my $null, '>', '/dev/null' or
254                         die "failed to open /dev/null: $!\n";
255                 $opt->{1} = $null; # suitable for spawn() redirect
256         } else {
257                 $opt->{verbose} ||= 1;
258                 $opt->{-progress} = sub { print STDERR @_ };
259         }
260 }
261
262 # same unit factors as git:
263 sub parse_unsigned ($) {
264         my ($val) = @_;
265
266         $$val =~ /\A([0-9]+)([kmg])?\z/i or return;
267         my ($n, $unit_factor) = ($1, $2 // '');
268         my %u = ( k => 1024, m => 1024**2, g => 1024**3 );
269         $$val = $n * ($u{lc($unit_factor)} // 1);
270         1;
271 }
272
273 sub index_prepare ($$) {
274         my ($opt, $cfg) = @_;
275         my $env;
276         if ($opt->{compact}) {
277                 require PublicInbox::Xapcmd;
278                 PublicInbox::Xapcmd::check_compact();
279                 $opt->{compact_opt} = { -coarse_lock => 1, compact => 1 };
280                 if (defined(my $jobs = $opt->{jobs})) {
281                         $opt->{compact_opt}->{jobs} = $jobs;
282                 }
283         }
284         for my $k (qw(max_size batch_size)) {
285                 my $git_key = "publicInbox.index".ucfirst($k);
286                 $git_key =~ s/_([a-z])/\U$1/g;
287                 defined(my $v = $opt->{$k} // $cfg->{lc($git_key)}) or next;
288                 parse_unsigned(\$v) or die "`$git_key=$v' not parsed\n";
289                 $v > 0 or die "`$git_key=$v' must be positive\n";
290                 $opt->{$k} = $v;
291         }
292
293         # out-of-the-box builds of Xapian 1.4.x are still limited to 32-bit
294         # https://getting-started-with-xapian.readthedocs.io/en/latest/concepts/indexing/limitations.html
295         $opt->{batch_size} and
296                 $env = { XAPIAN_FLUSH_THRESHOLD => '4294967295' };
297
298         for my $k (qw(sequential_shard)) {
299                 my $git_key = "publicInbox.index".ucfirst($k);
300                 $git_key =~ s/_([a-z])/\U$1/g;
301                 defined(my $s = $opt->{$k} // $cfg->{lc($git_key)}) or next;
302                 defined(my $v = $cfg->git_bool($s))
303                                         or die "`$git_key=$s' not boolean\n";
304                 $opt->{$k} = $v;
305         }
306         $env;
307 }
308
309 1;