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;
5 use PublicInbox::Spawn qw(which popen_rd nodatacow_dir);
6 use PublicInbox::Admin qw(setup_signals);
8 use PublicInbox::SearchIdx;
9 use File::Temp 0.19 (); # ->newdir
10 use File::Path qw(remove_tree);
11 use POSIX qw(WNOHANG _exit);
13 # support testing with dev versions of Xapian which installs
14 # commands with a version number suffix (e.g. "xapian-compact-1.5")
15 our $XAPIAN_COMPACT = $ENV{XAPIAN_COMPACT} || 'xapian-compact';
16 our @COMPACT_OPT = qw(jobs|j=i quiet|q blocksize|b=s no-full|n fuller|F);
18 sub commit_changes ($$$$) {
19 my ($ibx, $im, $tmp, $opt) = @_;
20 my $reshard = $opt->{reshard};
22 $SIG{INT} or die 'BUG: $SIG{INT} not handled';
23 my (@old_shard, $over_chg);
25 # Sort shards highest-to-lowest, since ->xdb_shards_flat
26 # determines the number of shards to load based on the max;
27 # and we'd rather xdb_shards_flat to momentarily fail rather
28 # than load out-of-date shards
30 my ($x) = ($a =~ m!/([0-9]+)/*\z!);
31 my ($y) = ($b =~ m!/([0-9]+)/*\z!);
32 ($y // -1) <=> ($x // -1) # we may have non-shards
35 my ($dname) = ($order[0] =~ m!(.*/)[^/]+/*\z!);
36 my $mode = (stat($dname))[2];
37 for my $old (@order) {
38 next if $old eq ''; # no invalid paths
39 my $newdir = $tmp->{$old};
40 my $have_old = -e $old;
41 if (!$have_old && !defined($opt->{reshard})) {
42 die "failed to stat($old): $!";
45 my $new = $newdir->dirname if defined($newdir);
46 my $over = "$old/over.sqlite3";
47 if (-f $over) { # only for v1, v2 over is untouched
48 defined $new or die "BUG: $over exists when culling v2";
49 $over = PublicInbox::Over->new($over);
50 my $tmp_over = "$new/over.sqlite3";
51 $over->dbh->sqlite_backup_to_file($tmp_over);
56 if (!defined($new)) { # culled shard
57 push @old_shard, $old;
61 chmod($mode & 07777, $new) or die "chmod($new): $!\n";
63 rename($old, "$new/old") or
64 die "rename $old => $new/old: $!\n";
66 rename($new, $old) or die "rename $new => $old: $!\n";
67 push @old_shard, "$old/old" if $have_old;
70 # trigger ->check_inodes in read-only daemons
71 syswrite($im->{lockfh}, '.') if $over_chg && $im;
73 remove_tree(@old_shard);
75 if (!$opt->{-coarse_lock}) {
76 $opt->{-skip_lock} = 1;
77 $im //= $ibx if $ibx->can('eidx_sync');
78 if ($im->can('count_shards')) { # v2w or eidx
79 my $pr = $opt->{-progress};
80 my $n = $im->count_shards;
81 if (defined $reshard && $n != $reshard) {
83 "BUG: counted $n shards after resharding to $reshard";
85 my $prev = $im->{shards};
86 if ($pr && $prev != $n) {
87 $pr->("shard count changed: $prev => $n\n");
91 my $env = $opt->{-idx_env};
92 local %ENV = (%ENV, %$env) if $env;
93 if ($ibx->can('eidx_sync')) {
94 $ibx->eidx_sync($opt);
96 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
102 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
103 my $seed = rand(0xffffffff);
104 my $pid = fork // die "fork: $!";
105 return $pid if $pid > 0;
107 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
112 sub runnable_or_die ($) {
114 which($exe) or die "$exe not found in PATH\n";
117 sub prepare_reindex ($$) {
118 my ($ibx, $opt) = @_;
119 if ($ibx->can('eidx_sync')) { # no prep needed for ExtSearchIdx
120 } elsif ($ibx->version == 1) {
121 my $dir = $ibx->search->xdir(1);
122 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
123 if (my $lc = $xdb->get_metadata('last_commit')) {
124 $opt->{reindex}->{from} = $lc;
127 my $max = $ibx->max_git_epoch // return;
128 my $from = $opt->{reindex}->{from};
130 my $v = PublicInbox::Search::SCHEMA_VERSION();
131 foreach my $i (0..$max) {
132 $from->[$i] = $mm->last_commit_xap($v, $i);
137 sub same_fs_or_die ($$) {
139 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
140 die "$x and $y reside on different filesystems\n";
144 my ($sig, $pids) = @_;
145 kill($sig, keys %$pids); # pids may be empty
149 my ($queue, $cb, $opt) = @_;
150 my $max = $opt->{jobs} // scalar(@$queue);
152 while (defined(my $args = shift @$queue)) {
160 local @SIG{keys %SIG} = values %SIG;
161 setup_signals(\&kill_pids, \%pids);
163 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
164 my $args = shift @$queue;
165 $pids{cb_spawn($cb, $args, $opt)} = $args;
169 while (scalar keys %pids) {
170 my $pid = waitpid(-1, $flags) or last;
172 my $args = delete $pids{$pid};
174 die join(' ', @$args)." failed: $?\n" if $?;
176 warn "unknown PID($pid) reaped: $?\n";
178 $flags = WNOHANG if scalar(@$queue);
184 my ($ibx, $opt) = @_;
185 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
186 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
188 if ($ibx->can('eidx_sync')) {
190 $old = $ibx->xdir(1);
191 } elsif (my $srch = $ibx->search) {
192 $old = $srch->xdir(1);
195 -d $old or die "$old does not exist\n";
197 my $reshard = $opt->{reshard};
198 if (defined $reshard && $reshard <= 0) {
199 die "--reshard must be a positive number\n";
202 # we want temporary directories to be as deep as possible,
203 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
204 if (defined($old) && $ibx->can('version') && $ibx->version == 1) {
205 if (defined $reshard) {
207 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
209 my ($dir) = ($old =~ m!(.*?/)[^/]+/*\z!);
210 same_fs_or_die($dir, $old);
211 my $v = PublicInbox::Search::SCHEMA_VERSION();
212 my $wip = File::Temp->newdir("xapian$v-XXXX", DIR => $dir);
214 nodatacow_dir($wip->dirname);
215 push @queue, [ $old, $wip ];
216 } elsif (defined $old) {
217 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
219 while (defined(my $dn = readdir($dh))) {
220 if ($dn =~ /\A[0-9]+\z/) {
221 push @old_shards, $dn;
222 } elsif ($dn eq '.' || $dn eq '..') {
223 } elsif ($dn =~ /\Aover\.sqlite3/) {
224 } elsif ($dn eq 'misc' && $misc_ok) {
226 warn "W: skipping unknown dir: $old/$dn\n"
229 die "No Xapian shards found in $old\n" unless @old_shards;
231 my ($src, $max_shard);
232 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
234 $max_shard = scalar(@old_shards) - 1;
237 $max_shard = $reshard - 1;
238 $src = [ map { "$old/$_" } @old_shards ];
240 foreach my $dn (0..$max_shard) {
241 my $wip = File::Temp->newdir("$dn-XXXX", DIR => $old);
242 same_fs_or_die($old, $wip->dirname);
243 my $cur = "$old/$dn";
244 push @queue, [ $src // $cur , $wip ];
245 nodatacow_dir($wip->dirname);
248 # mark old shards to be unlinked
250 $tmp->{$_} ||= undef for @$src;
256 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
258 sub _run { # with_umask callback
259 my ($ibx, $cb, $opt) = @_;
260 my $im = $ibx->can('importer') ? $ibx->importer(0) : undef;
261 ($im // $ibx)->lock_acquire;
262 my ($tmp, $queue) = prepare_run($ibx, $opt);
264 # fine-grained locking if we prepare for reindex
265 if (!$opt->{-coarse_lock}) {
266 prepare_reindex($ibx, $opt);
267 ($im // $ibx)->lock_release;
270 $ibx->cleanup if $ibx->can('cleanup');
271 process_queue($queue, $cb, $opt);
272 ($im // $ibx)->lock_acquire if !$opt->{-coarse_lock};
273 commit_changes($ibx, $im, $tmp, $opt);
277 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
279 PublicInbox::Admin::progress_prepare($opt ||= {});
281 for my $fld (qw(inboxdir topdir)) {
282 my $d = $ibx->{$fld} // next;
283 -d $d or die "$fld=$d does not exist\n";
287 check_compact() if $opt->{compact} && $ibx->search;
289 if (!$ibx->can('eidx_sync') && !$opt->{-coarse_lock}) {
290 # per-epoch ranges for v2
291 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
292 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
293 PublicInbox::SearchIdx::load_xapian_writable();
296 local @SIG{keys %SIG} = values %SIG;
298 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
301 sub cpdb_retryable ($$) {
302 my ($src, $pfx) = @_;
303 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
304 warn "$pfx Xapian DB modified, reopening and retrying\n";
309 warn "$pfx E: ", ref($@), "\n";
315 sub progress_pfx ($) {
316 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXX
317 my @p = split('/', $wip);
319 # return "xap15/0" for v2, or "xapian15" for v1:
320 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
323 sub kill_compact { # setup_signals callback
324 my ($sig, $pidref) = @_;
325 kill($sig, $$pidref) if defined($$pidref);
328 # xapian-compact wrapper
329 sub compact ($$) { # cb_spawn callback
330 my ($args, $opt) = @_;
331 my ($src, $newdir) = @$args;
332 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
333 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
334 my $pr = $opt->{-progress};
337 foreach my $fd (0..2) {
338 defined(my $dfd = $opt->{$fd}) or next;
342 # we rely on --no-renumber to keep docids synched to NNTP
343 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
344 for my $sw (qw(no-full fuller)) {
345 push @$cmd, "--$sw" if $opt->{$sw};
347 for my $sw (qw(blocksize)) {
348 defined(my $v = $opt->{$sw}) or next;
349 push @$cmd, "--$sw", $v;
351 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
352 push @$cmd, $src, $dst;
354 local @SIG{keys %SIG} = values %SIG;
355 setup_signals(\&kill_compact, \$pid);
356 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
364 die "@$cmd failed: \$?=$?\n" if $?;
367 sub cpdb_loop ($$$;$$) {
368 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
369 my ($pr, $fmt, $nr, $pfx);
371 $pr = $pr_data->{pr};
372 $fmt = $pr_data->{fmt};
373 $nr = \($pr_data->{nr});
374 $pfx = $pr_data->{pfx};
380 $it = $src->postlist_begin('');
381 $end = $src->postlist_end('');
383 } while (cpdb_retryable($src, $pfx));
387 for (; $it != $end; $it++) {
388 my $docid = $it->get_docid;
389 if (defined $reshard) {
390 my $dst_shard = $docid % $reshard;
391 next if $dst_shard != $cur_shard;
393 my $doc = $src->get_document($docid);
394 $dst->replace_document($docid, $doc);
395 if ($pr_data && !(++$$nr & 1023)) {
396 $pr->(sprintf($fmt, $$nr));
400 # unlike copydatabase(1), we don't copy spelling
401 # and synonym data (or other user metadata) since
402 # the Perl APIs don't expose iterators for them
403 # (and public-inbox does not use those features)
405 } while (cpdb_retryable($src, $pfx));
408 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
409 # to the overhead of Perl.
410 sub cpdb ($$) { # cb_spawn callback
411 my ($args, $opt) = @_;
412 my ($old, $newdir) = @$args;
413 my $new = $newdir->dirname;
414 my ($src, $cur_shard);
416 PublicInbox::SearchIdx::load_xapian_writable();
417 my $XapianDatabase = $PublicInbox::Search::X{Database};
418 if (ref($old) eq 'ARRAY') {
419 ($cur_shard) = ($new =~ m!(?:xap|ei)[0-9]+/([0-9]+)\b!);
420 defined $cur_shard or
421 die "BUG: could not extract shard # from $new";
422 $reshard = $opt->{reshard};
423 defined $reshard or die 'BUG: got array src w/o --reshard';
425 # resharding, M:N copy means have full read access
428 my $sub = $XapianDatabase->new($_);
429 $src->add_database($sub);
431 $src = $XapianDatabase->new($_);
435 $src = $XapianDatabase->new($old);
439 local @SIG{keys %SIG} = values %SIG;
440 if ($opt->{compact}) {
441 my ($dir) = ($new =~ m!(.*?/)[^/]+/*\z!);
442 same_fs_or_die($dir, $new);
443 $ft = File::Temp->newdir("$new.compact-XXXX", DIR => $dir);
451 # like copydatabase(1), be sure we don't overwrite anything in case
453 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
455 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
456 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
457 my $dst = $XapianWritableDatabase->new($tmp, $flag);
458 my $pr = $opt->{-progress};
459 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
460 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
464 # update the only metadata key for v1:
465 my $lc = $src->get_metadata('last_commit');
466 $dst->set_metadata('last_commit', $lc) if $lc;
468 # only the first xapian shard (0) gets 'indexlevel'
469 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
470 my $l = $src->get_metadata('indexlevel');
471 if ($l eq 'medium') {
472 $dst->set_metadata('indexlevel', $l);
476 my $tot = $src->get_doccount;
478 # we can only estimate when resharding,
479 # because removed spam causes slight imbalance
481 if (defined $cur_shard && $reshard > 1) {
482 $tot = int($tot/$reshard);
485 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
486 $pr->("$pfx copying $est$tot documents\n");
487 $pr_data->{fmt} = $fmt;
488 $pr_data->{total} = $tot;
491 } while (cpdb_retryable($src, $pfx));
493 if (defined $reshard) {
494 # we rely on document IDs matching NNTP article number,
495 # so we can't have the Xapian sharding DB support rewriting
496 # document IDs. Thus we iterate through each shard
500 my $old = $XapianDatabase->new($_);
501 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
504 cpdb_loop($src, $dst, $pr_data);
507 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
508 return unless $opt->{compact};
510 $src = $dst = undef; # flushes and closes
512 # this is probably the best place to do xapian-compact
513 # since $dst isn't readable by HTTP or NNTP clients, yet:
514 compact([ $tmp, $new ], $opt);
515 remove_tree($tmp) or die "failed to remove $tmp: $!\n";