1 # Copyright (C) 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);
6 use PublicInbox::Syscall;
7 use PublicInbox::Admin qw(setup_signals);
9 use PublicInbox::SearchIdx;
10 use File::Temp 0.19 (); # ->newdir
11 use File::Path qw(remove_tree);
12 use POSIX qw(WNOHANG _exit);
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);
19 sub commit_changes ($$$$) {
20 my ($ibx, $im, $tmp, $opt) = @_;
21 my $reshard = $opt->{reshard};
23 $SIG{INT} or die 'BUG: $SIG{INT} not handled';
24 my (@old_shard, $over_chg);
26 # Sort shards highest-to-lowest, since ->xdb_shards_flat
27 # determines the number of shards to load based on the max;
28 # and we'd rather xdb_shards_flat to momentarily fail rather
29 # than load out-of-date shards
31 my ($x) = ($a =~ m!/([0-9]+)/*\z!);
32 my ($y) = ($b =~ m!/([0-9]+)/*\z!);
33 ($y // -1) <=> ($x // -1) # we may have non-shards
36 my ($dname) = ($order[0] =~ m!(.*/)[^/]+/*\z!);
37 my $mode = (stat($dname))[2];
38 for my $old (@order) {
39 next if $old eq ''; # no invalid paths
40 my $newdir = $tmp->{$old};
41 my $have_old = -e $old;
42 if (!$have_old && !defined($opt->{reshard})) {
43 die "failed to stat($old): $!";
46 my $new = $newdir->dirname if defined($newdir);
47 my $over = "$old/over.sqlite3";
48 if (-f $over) { # only for v1, v2 over is untouched
49 defined $new or die "BUG: $over exists when culling v2";
50 $over = PublicInbox::Over->new($over);
51 my $tmp_over = "$new/over.sqlite3";
52 $over->dbh->sqlite_backup_to_file($tmp_over);
57 if (!defined($new)) { # culled shard
58 push @old_shard, $old;
62 chmod($mode & 07777, $new) or die "chmod($new): $!\n";
64 rename($old, "$new/old") or
65 die "rename $old => $new/old: $!\n";
67 rename($new, $old) or die "rename $new => $old: $!\n";
68 push @old_shard, "$old/old" if $have_old;
71 # trigger ->check_inodes in read-only daemons
72 syswrite($im->{lockfh}, '.') if $over_chg && $im;
74 remove_tree(@old_shard);
76 if (!$opt->{-coarse_lock}) {
77 $opt->{-skip_lock} = 1;
78 $im //= $ibx if $ibx->can('eidx_sync');
79 if ($im->can('count_shards')) { # v2w or eidx
80 my $pr = $opt->{-progress};
81 my $n = $im->count_shards;
82 if (defined $reshard && $n != $reshard) {
84 "BUG: counted $n shards after resharding to $reshard";
86 my $prev = $im->{shards};
87 if ($pr && $prev != $n) {
88 $pr->("shard count changed: $prev => $n\n");
92 my $env = $opt->{-idx_env};
93 local %ENV = (%ENV, %$env) if $env;
94 if ($ibx->can('eidx_sync')) {
95 $ibx->eidx_sync($opt);
97 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
103 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
104 my $seed = rand(0xffffffff);
105 my $pid = fork // die "fork: $!";
106 return $pid if $pid > 0;
108 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
113 sub runnable_or_die ($) {
115 which($exe) or die "$exe not found in PATH\n";
118 sub prepare_reindex ($$) {
119 my ($ibx, $opt) = @_;
120 if ($ibx->can('eidx_sync')) { # no prep needed for ExtSearchIdx
121 } elsif ($ibx->version == 1) {
122 my $dir = $ibx->search->xdir(1);
123 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
124 if (my $lc = $xdb->get_metadata('last_commit')) {
125 $opt->{reindex}->{from} = $lc;
128 my $max = $ibx->max_git_epoch // return;
129 my $from = $opt->{reindex}->{from};
131 my $v = PublicInbox::Search::SCHEMA_VERSION();
132 foreach my $i (0..$max) {
133 $from->[$i] = $mm->last_commit_xap($v, $i);
138 sub same_fs_or_die ($$) {
140 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
141 die "$x and $y reside on different filesystems\n";
145 my ($sig, $pids) = @_;
146 kill($sig, keys %$pids); # pids may be empty
150 my ($queue, $cb, $opt) = @_;
151 my $max = $opt->{jobs} // scalar(@$queue);
153 while (defined(my $args = shift @$queue)) {
161 local @SIG{keys %SIG} = values %SIG;
162 setup_signals(\&kill_pids, \%pids);
164 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
165 my $args = shift @$queue;
166 $pids{cb_spawn($cb, $args, $opt)} = $args;
170 while (scalar keys %pids) {
171 my $pid = waitpid(-1, $flags) or last;
173 my $args = delete $pids{$pid};
175 die join(' ', @$args)." failed: $?\n" if $?;
177 warn "unknown PID($pid) reaped: $?\n";
179 $flags = WNOHANG if scalar(@$queue);
185 my ($ibx, $opt) = @_;
186 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
187 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
189 if ($ibx->can('eidx_sync')) {
191 $old = $ibx->xdir(1);
192 } elsif (my $srch = $ibx->search) {
193 $old = $srch->xdir(1);
196 -d $old or die "$old does not exist\n";
198 my $reshard = $opt->{reshard};
199 if (defined $reshard && $reshard <= 0) {
200 die "--reshard must be a positive number\n";
203 # we want temporary directories to be as deep as possible,
204 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
205 if (defined($old) && $ibx->can('version') && $ibx->version == 1) {
206 if (defined $reshard) {
208 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
210 my ($dir) = ($old =~ m!(.*?/)[^/]+/*\z!);
211 same_fs_or_die($dir, $old);
212 my $v = PublicInbox::Search::SCHEMA_VERSION();
213 my $wip = File::Temp->newdir("xapian$v-XXXX", DIR => $dir);
215 PublicInbox::Syscall::nodatacow_dir($wip->dirname);
216 push @queue, [ $old, $wip ];
217 } elsif (defined $old) {
218 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
220 while (defined(my $dn = readdir($dh))) {
221 if ($dn =~ /\A[0-9]+\z/) {
222 push @old_shards, $dn;
223 } elsif ($dn eq '.' || $dn eq '..') {
224 } elsif ($dn =~ /\Aover\.sqlite3/) {
225 } elsif ($dn eq 'misc' && $misc_ok) {
227 warn "W: skipping unknown dir: $old/$dn\n"
230 die "No Xapian shards found in $old\n" unless @old_shards;
232 my ($src, $max_shard);
233 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
235 $max_shard = scalar(@old_shards) - 1;
238 $max_shard = $reshard - 1;
239 $src = [ map { "$old/$_" } @old_shards ];
241 foreach my $dn (0..$max_shard) {
242 my $wip = File::Temp->newdir("$dn-XXXX", DIR => $old);
243 same_fs_or_die($old, $wip->dirname);
244 my $cur = "$old/$dn";
245 push @queue, [ $src // $cur , $wip ];
246 PublicInbox::Syscall::nodatacow_dir($wip->dirname);
249 # mark old shards to be unlinked
251 $tmp->{$_} ||= undef for @$src;
257 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
259 sub _run { # with_umask callback
260 my ($ibx, $cb, $opt) = @_;
261 my $im = $ibx->can('importer') ? $ibx->importer(0) : undef;
262 ($im // $ibx)->lock_acquire;
263 my ($tmp, $queue) = prepare_run($ibx, $opt);
265 # fine-grained locking if we prepare for reindex
266 if (!$opt->{-coarse_lock}) {
267 prepare_reindex($ibx, $opt);
268 ($im // $ibx)->lock_release;
271 $ibx->cleanup if $ibx->can('cleanup');
272 process_queue($queue, $cb, $opt);
273 ($im // $ibx)->lock_acquire if !$opt->{-coarse_lock};
274 commit_changes($ibx, $im, $tmp, $opt);
278 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
280 PublicInbox::Admin::progress_prepare($opt ||= {});
282 for my $fld (qw(inboxdir topdir)) {
283 my $d = $ibx->{$fld} // next;
284 -d $d or die "$fld=$d does not exist\n";
288 check_compact() if $opt->{compact} && $ibx->search;
290 if (!$ibx->can('eidx_sync') && !$opt->{-coarse_lock}) {
291 # per-epoch ranges for v2
292 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
293 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
294 PublicInbox::SearchIdx::load_xapian_writable();
297 local @SIG{keys %SIG} = values %SIG;
299 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
302 sub cpdb_retryable ($$) {
303 my ($src, $pfx) = @_;
304 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
305 warn "$pfx Xapian DB modified, reopening and retrying\n";
310 warn "$pfx E: ", ref($@), "\n";
316 sub progress_pfx ($) {
317 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXX
318 my @p = split('/', $wip);
320 # return "xap15/0" for v2, or "xapian15" for v1:
321 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
324 sub kill_compact { # setup_signals callback
325 my ($sig, $pidref) = @_;
326 kill($sig, $$pidref) if defined($$pidref);
329 # xapian-compact wrapper
330 sub compact ($$) { # cb_spawn callback
331 my ($args, $opt) = @_;
332 my ($src, $newdir) = @$args;
333 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
334 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
335 my $pr = $opt->{-progress};
338 foreach my $fd (0..2) {
339 defined(my $dfd = $opt->{$fd}) or next;
343 # we rely on --no-renumber to keep docids synched to NNTP
344 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
345 for my $sw (qw(no-full fuller)) {
346 push @$cmd, "--$sw" if $opt->{$sw};
348 for my $sw (qw(blocksize)) {
349 defined(my $v = $opt->{$sw}) or next;
350 push @$cmd, "--$sw", $v;
352 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
353 push @$cmd, $src, $dst;
355 local @SIG{keys %SIG} = values %SIG;
356 setup_signals(\&kill_compact, \$pid);
357 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
365 die "@$cmd failed: \$?=$?\n" if $?;
368 sub cpdb_loop ($$$;$$) {
369 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
370 my ($pr, $fmt, $nr, $pfx);
372 $pr = $pr_data->{pr};
373 $fmt = $pr_data->{fmt};
374 $nr = \($pr_data->{nr});
375 $pfx = $pr_data->{pfx};
381 $it = $src->postlist_begin('');
382 $end = $src->postlist_end('');
384 } while (cpdb_retryable($src, $pfx));
388 for (; $it != $end; $it++) {
389 my $docid = $it->get_docid;
390 if (defined $reshard) {
391 my $dst_shard = $docid % $reshard;
392 next if $dst_shard != $cur_shard;
394 my $doc = $src->get_document($docid);
395 $dst->replace_document($docid, $doc);
396 if ($pr_data && !(++$$nr & 1023)) {
397 $pr->(sprintf($fmt, $$nr));
401 # unlike copydatabase(1), we don't copy spelling
402 # and synonym data (or other user metadata) since
403 # the Perl APIs don't expose iterators for them
404 # (and public-inbox does not use those features)
406 } while (cpdb_retryable($src, $pfx));
409 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
410 # to the overhead of Perl.
411 sub cpdb ($$) { # cb_spawn callback
412 my ($args, $opt) = @_;
413 my ($old, $newdir) = @$args;
414 my $new = $newdir->dirname;
415 my ($src, $cur_shard);
417 PublicInbox::SearchIdx::load_xapian_writable();
418 my $XapianDatabase = $PublicInbox::Search::X{Database};
419 if (ref($old) eq 'ARRAY') {
420 ($cur_shard) = ($new =~ m!(?:xap|ei)[0-9]+/([0-9]+)\b!);
421 defined $cur_shard or
422 die "BUG: could not extract shard # from $new";
423 $reshard = $opt->{reshard};
424 defined $reshard or die 'BUG: got array src w/o --reshard';
426 # resharding, M:N copy means have full read access
429 my $sub = $XapianDatabase->new($_);
430 $src->add_database($sub);
432 $src = $XapianDatabase->new($_);
436 $src = $XapianDatabase->new($old);
440 local @SIG{keys %SIG} = values %SIG;
441 if ($opt->{compact}) {
442 my ($dir) = ($new =~ m!(.*?/)[^/]+/*\z!);
443 same_fs_or_die($dir, $new);
444 $ft = File::Temp->newdir("$new.compact-XXXX", DIR => $dir);
447 PublicInbox::Syscall::nodatacow_dir($tmp);
452 # like copydatabase(1), be sure we don't overwrite anything in case
454 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
456 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
457 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
458 my $dst = $XapianWritableDatabase->new($tmp, $flag);
459 my $pr = $opt->{-progress};
460 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
461 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
465 # update the only metadata key for v1:
466 my $lc = $src->get_metadata('last_commit');
467 $dst->set_metadata('last_commit', $lc) if $lc;
469 # only the first xapian shard (0) gets 'indexlevel'
470 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
471 my $l = $src->get_metadata('indexlevel');
472 if ($l eq 'medium') {
473 $dst->set_metadata('indexlevel', $l);
477 my $tot = $src->get_doccount;
479 # we can only estimate when resharding,
480 # because removed spam causes slight imbalance
482 if (defined $cur_shard && $reshard > 1) {
483 $tot = int($tot/$reshard);
486 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
487 $pr->("$pfx copying $est$tot documents\n");
488 $pr_data->{fmt} = $fmt;
489 $pr_data->{total} = $tot;
492 } while (cpdb_retryable($src, $pfx));
494 if (defined $reshard) {
495 # we rely on document IDs matching NNTP article number,
496 # so we can't have the Xapian sharding DB support rewriting
497 # document IDs. Thus we iterate through each shard
501 my $old = $XapianDatabase->new($_);
502 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
505 cpdb_loop($src, $dst, $pr_data);
508 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
509 return unless $opt->{compact};
511 $src = $dst = undef; # flushes and closes
513 # this is probably the best place to do xapian-compact
514 # since $dst isn't readable by HTTP or NNTP clients, yet:
515 compact([ $tmp, $new ], $opt);
516 remove_tree($tmp) or die "failed to remove $tmp: $!\n";