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