]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
xcpdb: wire up new index options and --help
[public-inbox.git] / lib / PublicInbox / Xapcmd.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::Xapcmd;
4 use strict;
5 use PublicInbox::Spawn qw(which popen_rd nodatacow_dir);
6 use PublicInbox::Admin qw(setup_signals);
7 use PublicInbox::Over;
8 use PublicInbox::SearchIdx;
9 use File::Temp 0.19 (); # ->newdir
10 use File::Path qw(remove_tree);
11 use File::Basename qw(dirname);
12 use POSIX qw(WNOHANG);
13
14 # support testing with dev versions of Xapian which installs
15 # commands with a version number suffix (e.g. "xapian-compact-1.5")
16 our $XAPIAN_COMPACT = $ENV{XAPIAN_COMPACT} || 'xapian-compact';
17 our @COMPACT_OPT = qw(jobs|j=i quiet|q blocksize|b=s no-full|n fuller|F);
18
19 sub commit_changes ($$$$) {
20         my ($ibx, $im, $tmp, $opt) = @_;
21         my $reshard = $opt->{reshard};
22         my $reindex = $opt->{reindex};
23
24         $SIG{INT} or die 'BUG: $SIG{INT} not handled';
25         my @old_shard;
26         my $over_chg;
27
28         while (my ($old, $newdir) = each %$tmp) {
29                 next if $old eq ''; # no invalid paths
30                 my @st = stat($old);
31                 if (!@st && !defined($opt->{reshard})) {
32                         die "failed to stat($old): $!";
33                 }
34
35                 my $new = $newdir->dirname if defined($newdir);
36                 my $over = "$old/over.sqlite3";
37                 if (-f $over) { # only for v1, v2 over is untouched
38                         defined $new or die "BUG: $over exists when culling v2";
39                         $over = PublicInbox::Over->new($over);
40                         my $tmp_over = "$new/over.sqlite3";
41                         $over->connect->sqlite_backup_to_file($tmp_over);
42                         $over = undef;
43                         $over_chg = 1;
44                 }
45
46                 if (!defined($new)) { # culled shard
47                         push @old_shard, $old;
48                         next;
49                 }
50
51                 if (@st) {
52                         chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
53                         rename($old, "$new/old") or
54                                         die "rename $old => $new/old: $!\n";
55                 }
56                 rename($new, $old) or die "rename $new => $old: $!\n";
57                 if (@st) {
58                         my $prev = "$old/old";
59                         remove_tree($prev) or
60                                 die "failed to remove $prev: $!\n";
61                 }
62         }
63
64         # trigger ->check_inodes in read-only daemons
65         syswrite($im->{lockfh}, '.') if $over_chg;
66
67         remove_tree(@old_shard);
68         $tmp = undef;
69         if (!$opt->{-coarse_lock}) {
70                 $opt->{-skip_lock} = 1;
71
72                 if ($im->can('count_shards')) {
73                         my $pr = $opt->{-progress};
74                         my $n = $im->count_shards;
75                         if (defined $reshard && $n != $reshard) {
76                                 die
77 "BUG: counted $n shards after resharding to $reshard";
78                         }
79                         my $prev = $im->{shards};
80                         if ($pr && $prev != $n) {
81                                 $pr->("shard count changed: $prev => $n\n");
82                                 $im->{shards} = $n;
83                         }
84                 }
85                 my $env = $opt->{-idx_env};
86                 local %ENV = (%ENV, %$env) if $env;
87                 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
88         }
89 }
90
91 sub cb_spawn {
92         my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
93         defined(my $pid = fork) or die "fork: $!";
94         return $pid if $pid > 0;
95         $cb->($args, $opt);
96         POSIX::_exit(0);
97 }
98
99 sub runnable_or_die ($) {
100         my ($exe) = @_;
101         which($exe) or die "$exe not found in PATH\n";
102 }
103
104 sub prepare_reindex ($$$) {
105         my ($ibx, $im, $reindex) = @_;
106         if ($ibx->version == 1) {
107                 my $dir = $ibx->search->xdir(1);
108                 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
109                 if (my $lc = $xdb->get_metadata('last_commit')) {
110                         $reindex->{from} = $lc;
111                 }
112         } else { # v2
113                 my $max;
114                 $im->git_dir_latest(\$max) or return;
115                 my $from = $reindex->{from};
116                 my $mm = $ibx->mm;
117                 my $v = PublicInbox::Search::SCHEMA_VERSION();
118                 foreach my $i (0..$max) {
119                         $from->[$i] = $mm->last_commit_xap($v, $i);
120                 }
121         }
122 }
123
124 sub same_fs_or_die ($$) {
125         my ($x, $y) = @_;
126         return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
127         die "$x and $y reside on different filesystems\n";
128 }
129
130 sub kill_pids {
131         my ($sig, $pids) = @_;
132         kill($sig, keys %$pids); # pids may be empty
133 }
134
135 sub process_queue {
136         my ($queue, $cb, $opt) = @_;
137         my $max = $opt->{jobs} // scalar(@$queue);
138         if ($max <= 1) {
139                 while (defined(my $args = shift @$queue)) {
140                         $cb->($args, $opt);
141                 }
142                 return;
143         }
144
145         # run in parallel:
146         my %pids;
147         local %SIG = %SIG;
148         setup_signals(\&kill_pids, \%pids);
149         while (@$queue) {
150                 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
151                         my $args = shift @$queue;
152                         $pids{cb_spawn($cb, $args, $opt)} = $args;
153                 }
154
155                 my $flags = 0;
156                 while (scalar keys %pids) {
157                         my $pid = waitpid(-1, $flags) or last;
158                         last if $pid < 0;
159                         my $args = delete $pids{$pid};
160                         if ($args) {
161                                 die join(' ', @$args)." failed: $?\n" if $?;
162                         } else {
163                                 warn "unknown PID($pid) reaped: $?\n";
164                         }
165                         $flags = WNOHANG if scalar(@$queue);
166                 }
167         }
168 }
169
170 sub prepare_run {
171         my ($ibx, $opt) = @_;
172         my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
173         my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
174         my $old;
175         if (my $srch = $ibx->search) {
176                 $old = $srch->xdir(1);
177                 -d $old or die "$old does not exist\n";
178         }
179         my $reshard = $opt->{reshard};
180         if (defined $reshard && $reshard <= 0) {
181                 die "--reshard must be a positive number\n";
182         }
183
184         # we want temporary directories to be as deep as possible,
185         # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
186         if ($old && $ibx->version == 1) {
187                 if (defined $reshard) {
188                         warn
189 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
190                 }
191                 my $dir = dirname($old);
192                 same_fs_or_die($dir, $old);
193                 my $v = PublicInbox::Search::SCHEMA_VERSION();
194                 my $wip = File::Temp->newdir("xapian$v-XXXXXXXX", DIR => $dir);
195                 $tmp->{$old} = $wip;
196                 nodatacow_dir($wip->dirname);
197                 push @queue, [ $old, $wip ];
198         } elsif ($old) {
199                 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
200                 my @old_shards;
201                 while (defined(my $dn = readdir($dh))) {
202                         if ($dn =~ /\A[0-9]+\z/) {
203                                 push @old_shards, $dn;
204                         } elsif ($dn eq '.' || $dn eq '..') {
205                         } elsif ($dn =~ /\Aover\.sqlite3/) {
206                         } else {
207                                 warn "W: skipping unknown dir: $old/$dn\n"
208                         }
209                 }
210                 die "No Xapian shards found in $old\n" unless @old_shards;
211
212                 my ($src, $max_shard);
213                 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
214                         # 1:1 copy
215                         $max_shard = scalar(@old_shards) - 1;
216                 } else {
217                         # M:N copy
218                         $max_shard = $reshard - 1;
219                         $src = [ map { "$old/$_" } @old_shards ];
220                 }
221                 foreach my $dn (0..$max_shard) {
222                         my $tmpl = "$dn-XXXXXXXX";
223                         my $wip = File::Temp->newdir($tmpl, DIR => $old);
224                         same_fs_or_die($old, $wip->dirname);
225                         my $cur = "$old/$dn";
226                         push @queue, [ $src // $cur , $wip ];
227                         nodatacow_dir($wip->dirname);
228                         $tmp->{$cur} = $wip;
229                 }
230                 # mark old shards to be unlinked
231                 if ($src) {
232                         $tmp->{$_} ||= undef for @$src;
233                 }
234         }
235         ($tmp, \@queue);
236 }
237
238 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
239
240 sub _run {
241         my ($ibx, $cb, $opt, $reindex) = @_;
242         my $im = $ibx->importer(0);
243         $im->lock_acquire;
244         my ($tmp, $queue) = prepare_run($ibx, $opt);
245
246         # fine-grained locking if we prepare for reindex
247         if (!$opt->{-coarse_lock}) {
248                 prepare_reindex($ibx, $im, $reindex);
249                 $im->lock_release;
250         }
251
252         $ibx->cleanup;
253         process_queue($queue, $cb, $opt);
254         $im->lock_acquire if !$opt->{-coarse_lock};
255         commit_changes($ibx, $im, $tmp, $opt);
256 }
257
258 sub run {
259         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
260         my $cb = \&$task;
261         PublicInbox::Admin::progress_prepare($opt ||= {});
262         defined(my $dir = $ibx->{inboxdir}) or die "no inboxdir defined\n";
263         -d $dir or die "inboxdir=$dir does not exist\n";
264         check_compact() if $opt->{compact} && $ibx->search;
265         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
266
267         if (!$opt->{-coarse_lock}) {
268                 $reindex = $opt->{reindex} = { # per-epoch ranges for v2
269                         from => $ibx->version == 1 ? '' : [],
270                 };
271                 PublicInbox::SearchIdx::load_xapian_writable();
272         }
273
274         local %SIG = %SIG;
275         setup_signals();
276         $ibx->umask_prepare;
277         $ibx->with_umask(\&_run, $ibx, $cb, $opt, $reindex);
278 }
279
280 sub cpdb_retryable ($$) {
281         my ($src, $pfx) = @_;
282         if (ref($@) =~ /\bDatabaseModifiedError\b/) {
283                 warn "$pfx Xapian DB modified, reopening and retrying\n";
284                 $src->reopen;
285                 return 1;
286         }
287         if ($@) {
288                 warn "$pfx E: ", ref($@), "\n";
289                 die;
290         }
291         0;
292 }
293
294 sub progress_pfx ($) {
295         my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
296         my @p = split('/', $wip);
297
298         # return "xap15/0" for v2, or "xapian15" for v1:
299         ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
300 }
301
302 sub kill_compact { # setup_signals callback
303         my ($sig, $pidref) = @_;
304         kill($sig, $$pidref) if defined($$pidref);
305 }
306
307 # xapian-compact wrapper
308 sub compact ($$) {
309         my ($args, $opt) = @_;
310         my ($src, $newdir) = @$args;
311         my $dst = ref($newdir) ? $newdir->dirname : $newdir;
312         my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
313         my $pr = $opt->{-progress};
314         my $rdr = {};
315
316         foreach my $fd (0..2) {
317                 defined(my $dfd = $opt->{$fd}) or next;
318                 $rdr->{$fd} = $dfd;
319         }
320
321         # we rely on --no-renumber to keep docids synched to NNTP
322         my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
323         for my $sw (qw(no-full fuller)) {
324                 push @$cmd, "--$sw" if $opt->{$sw};
325         }
326         for my $sw (qw(blocksize)) {
327                 defined(my $v = $opt->{$sw}) or next;
328                 push @$cmd, "--$sw", $v;
329         }
330         $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
331         push @$cmd, $src, $dst;
332         my ($rd, $pid);
333         local %SIG = %SIG;
334         setup_signals(\&kill_compact, \$pid);
335         ($rd, $pid) = popen_rd($cmd, undef, $rdr);
336         while (<$rd>) {
337                 if ($pr) {
338                         s/\r/\r$pfx /g;
339                         $pr->("$pfx $_");
340                 }
341         }
342         waitpid($pid, 0);
343         die "@$cmd failed: \$?=$?\n" if $?;
344 }
345
346 sub cpdb_loop ($$$;$$) {
347         my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
348         my ($pr, $fmt, $nr, $pfx);
349         if ($pr_data) {
350                 $pr = $pr_data->{pr};
351                 $fmt = $pr_data->{fmt};
352                 $nr = \($pr_data->{nr});
353                 $pfx = $pr_data->{pfx};
354         }
355
356         my ($it, $end);
357         do {
358                 eval {
359                         $it = $src->postlist_begin('');
360                         $end = $src->postlist_end('');
361                 };
362         } while (cpdb_retryable($src, $pfx));
363
364         do {
365                 eval {
366                         for (; $it != $end; $it++) {
367                                 my $docid = $it->get_docid;
368                                 if (defined $reshard) {
369                                         my $dst_shard = $docid % $reshard;
370                                         next if $dst_shard != $cur_shard;
371                                 }
372                                 my $doc = $src->get_document($docid);
373                                 $dst->replace_document($docid, $doc);
374                                 if ($pr_data && !(++$$nr  & 1023)) {
375                                         $pr->(sprintf($fmt, $$nr));
376                                 }
377                         }
378
379                         # unlike copydatabase(1), we don't copy spelling
380                         # and synonym data (or other user metadata) since
381                         # the Perl APIs don't expose iterators for them
382                         # (and public-inbox does not use those features)
383                 };
384         } while (cpdb_retryable($src, $pfx));
385 }
386
387 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
388 # to the overhead of Perl.
389 sub cpdb ($$) {
390         my ($args, $opt) = @_;
391         my ($old, $newdir) = @$args;
392         my $new = $newdir->dirname;
393         my ($src, $cur_shard);
394         my $reshard;
395         PublicInbox::SearchIdx::load_xapian_writable() or die;
396         my $XapianDatabase = $PublicInbox::Search::X{Database};
397         if (ref($old) eq 'ARRAY') {
398                 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
399                 defined $cur_shard or
400                         die "BUG: could not extract shard # from $new";
401                 $reshard = $opt->{reshard};
402                 defined $reshard or die 'BUG: got array src w/o --reshard';
403
404                 # resharding, M:N copy means have full read access
405                 foreach (@$old) {
406                         if ($src) {
407                                 my $sub = $XapianDatabase->new($_);
408                                 $src->add_database($sub);
409                         } else {
410                                 $src = $XapianDatabase->new($_);
411                         }
412                 }
413         } else {
414                 $src = $XapianDatabase->new($old);
415         }
416
417         my ($tmp, $ft);
418         local %SIG = %SIG;
419         if ($opt->{compact}) {
420                 my $dir = dirname($new);
421                 same_fs_or_die($dir, $new);
422                 $ft = File::Temp->newdir("$new.compact-XXXXXX", DIR => $dir);
423                 setup_signals();
424                 $tmp = $ft->dirname;
425                 nodatacow_dir($tmp);
426         } else {
427                 $tmp = $new;
428         }
429
430         # like copydatabase(1), be sure we don't overwrite anything in case
431         # of other bugs:
432         my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
433         die if $@;
434         my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
435         $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
436         my $dst = $XapianWritableDatabase->new($tmp, $flag);
437         my $pr = $opt->{-progress};
438         my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
439         my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
440
441         do {
442                 eval {
443                         # update the only metadata key for v1:
444                         my $lc = $src->get_metadata('last_commit');
445                         $dst->set_metadata('last_commit', $lc) if $lc;
446
447                         # only the first xapian shard (0) gets 'indexlevel'
448                         if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
449                                 my $l = $src->get_metadata('indexlevel');
450                                 if ($l eq 'medium') {
451                                         $dst->set_metadata('indexlevel', $l);
452                                 }
453                         }
454                         if ($pr_data) {
455                                 my $tot = $src->get_doccount;
456
457                                 # we can only estimate when resharding,
458                                 # because removed spam causes slight imbalance
459                                 my $est = '';
460                                 if (defined $cur_shard && $reshard > 1) {
461                                         $tot = int($tot/$reshard);
462                                         $est = 'around ';
463                                 }
464                                 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
465                                 $pr->("$pfx copying $est$tot documents\n");
466                                 $pr_data->{fmt} = $fmt;
467                                 $pr_data->{total} = $tot;
468                         }
469                 };
470         } while (cpdb_retryable($src, $pfx));
471
472         if (defined $reshard) {
473                 # we rely on document IDs matching NNTP article number,
474                 # so we can't have the Xapian sharding DB support rewriting
475                 # document IDs.  Thus we iterate through each shard
476                 # individually.
477                 $src = undef;
478                 foreach (@$old) {
479                         my $old = $XapianDatabase->new($_);
480                         cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
481                 }
482         } else {
483                 cpdb_loop($src, $dst, $pr_data);
484         }
485
486         $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
487         return unless $opt->{compact};
488
489         $src = $dst = undef; # flushes and closes
490
491         # this is probably the best place to do xapian-compact
492         # since $dst isn't readable by HTTP or NNTP clients, yet:
493         compact([ $tmp, $new ], $opt);
494         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
495 }
496
497 1;