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