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 File::Basename qw(dirname);
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';
27 while (my ($old, $newdir) = each %$tmp) {
28 next if $old eq ''; # no invalid paths
30 if (!@st && !defined($opt->{reshard})) {
31 die "failed to stat($old): $!";
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);
45 if (!defined($new)) { # culled shard
46 push @old_shard, $old;
51 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
52 rename($old, "$new/old") or
53 die "rename $old => $new/old: $!\n";
55 rename($new, $old) or die "rename $new => $old: $!\n";
57 my $prev = "$old/old";
59 die "failed to remove $prev: $!\n";
63 # trigger ->check_inodes in read-only daemons
64 syswrite($im->{lockfh}, '.') if $over_chg;
66 remove_tree(@old_shard);
68 if (!$opt->{-coarse_lock}) {
69 $opt->{-skip_lock} = 1;
71 if ($im->can('count_shards')) {
72 my $pr = $opt->{-progress};
73 my $n = $im->count_shards;
74 if (defined $reshard && $n != $reshard) {
76 "BUG: counted $n shards after resharding to $reshard";
78 my $prev = $im->{shards};
79 if ($pr && $prev != $n) {
80 $pr->("shard count changed: $prev => $n\n");
84 my $env = $opt->{-idx_env};
85 local %ENV = (%ENV, %$env) if $env;
86 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
91 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
92 my $seed = rand(0xffffffff);
93 my $pid = fork // die "fork: $!";
94 return $pid if $pid > 0;
96 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
101 sub runnable_or_die ($) {
103 which($exe) or die "$exe not found in PATH\n";
106 sub prepare_reindex ($$$) {
107 my ($ibx, $im, $opt) = @_;
108 if ($ibx->version == 1) {
109 my $dir = $ibx->search->xdir(1);
110 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
111 if (my $lc = $xdb->get_metadata('last_commit')) {
112 $opt->{reindex}->{from} = $lc;
115 my $max = $ibx->max_git_epoch // return;
116 my $from = $opt->{reindex}->{from};
118 my $v = PublicInbox::Search::SCHEMA_VERSION();
119 foreach my $i (0..$max) {
120 $from->[$i] = $mm->last_commit_xap($v, $i);
125 sub same_fs_or_die ($$) {
127 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
128 die "$x and $y reside on different filesystems\n";
132 my ($sig, $pids) = @_;
133 kill($sig, keys %$pids); # pids may be empty
137 my ($queue, $cb, $opt) = @_;
138 my $max = $opt->{jobs} // scalar(@$queue);
140 while (defined(my $args = shift @$queue)) {
149 setup_signals(\&kill_pids, \%pids);
151 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
152 my $args = shift @$queue;
153 $pids{cb_spawn($cb, $args, $opt)} = $args;
157 while (scalar keys %pids) {
158 my $pid = waitpid(-1, $flags) or last;
160 my $args = delete $pids{$pid};
162 die join(' ', @$args)." failed: $?\n" if $?;
164 warn "unknown PID($pid) reaped: $?\n";
166 $flags = WNOHANG if scalar(@$queue);
172 my ($ibx, $opt) = @_;
173 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
174 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
176 if (my $srch = $ibx->search) {
177 $old = $srch->xdir(1);
178 -d $old or die "$old does not exist\n";
180 my $reshard = $opt->{reshard};
181 if (defined $reshard && $reshard <= 0) {
182 die "--reshard must be a positive number\n";
185 # we want temporary directories to be as deep as possible,
186 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
187 if ($old && $ibx->version == 1) {
188 if (defined $reshard) {
190 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
192 my $dir = dirname($old);
193 same_fs_or_die($dir, $old);
194 my $v = PublicInbox::Search::SCHEMA_VERSION();
195 my $wip = File::Temp->newdir("xapian$v-XXXXXXXX", DIR => $dir);
197 nodatacow_dir($wip->dirname);
198 push @queue, [ $old, $wip ];
200 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
202 while (defined(my $dn = readdir($dh))) {
203 if ($dn =~ /\A[0-9]+\z/) {
204 push @old_shards, $dn;
205 } elsif ($dn eq '.' || $dn eq '..') {
206 } elsif ($dn =~ /\Aover\.sqlite3/) {
208 warn "W: skipping unknown dir: $old/$dn\n"
211 die "No Xapian shards found in $old\n" unless @old_shards;
213 my ($src, $max_shard);
214 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
216 $max_shard = scalar(@old_shards) - 1;
219 $max_shard = $reshard - 1;
220 $src = [ map { "$old/$_" } @old_shards ];
222 foreach my $dn (0..$max_shard) {
223 my $tmpl = "$dn-XXXXXXXX";
224 my $wip = File::Temp->newdir($tmpl, DIR => $old);
225 same_fs_or_die($old, $wip->dirname);
226 my $cur = "$old/$dn";
227 push @queue, [ $src // $cur , $wip ];
228 nodatacow_dir($wip->dirname);
231 # mark old shards to be unlinked
233 $tmp->{$_} ||= undef for @$src;
239 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
241 sub _run { # with_umask callback
242 my ($ibx, $cb, $opt) = @_;
243 my $im = $ibx->importer(0);
245 my ($tmp, $queue) = prepare_run($ibx, $opt);
247 # fine-grained locking if we prepare for reindex
248 if (!$opt->{-coarse_lock}) {
249 prepare_reindex($ibx, $im, $opt);
254 process_queue($queue, $cb, $opt);
255 $im->lock_acquire if !$opt->{-coarse_lock};
256 commit_changes($ibx, $im, $tmp, $opt);
260 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
262 PublicInbox::Admin::progress_prepare($opt ||= {});
263 defined(my $dir = $ibx->{inboxdir}) or die "no inboxdir defined\n";
264 -d $dir or die "inboxdir=$dir does not exist\n";
265 check_compact() if $opt->{compact} && $ibx->search;
267 if (!$opt->{-coarse_lock}) {
268 # per-epoch ranges for v2
269 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
270 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
271 PublicInbox::SearchIdx::load_xapian_writable();
276 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
279 sub cpdb_retryable ($$) {
280 my ($src, $pfx) = @_;
281 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
282 warn "$pfx Xapian DB modified, reopening and retrying\n";
287 warn "$pfx E: ", ref($@), "\n";
293 sub progress_pfx ($) {
294 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
295 my @p = split('/', $wip);
297 # return "xap15/0" for v2, or "xapian15" for v1:
298 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
301 sub kill_compact { # setup_signals callback
302 my ($sig, $pidref) = @_;
303 kill($sig, $$pidref) if defined($$pidref);
306 # xapian-compact wrapper
307 sub compact ($$) { # cb_spawn callback
308 my ($args, $opt) = @_;
309 my ($src, $newdir) = @$args;
310 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
311 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
312 my $pr = $opt->{-progress};
315 foreach my $fd (0..2) {
316 defined(my $dfd = $opt->{$fd}) or next;
320 # we rely on --no-renumber to keep docids synched to NNTP
321 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
322 for my $sw (qw(no-full fuller)) {
323 push @$cmd, "--$sw" if $opt->{$sw};
325 for my $sw (qw(blocksize)) {
326 defined(my $v = $opt->{$sw}) or next;
327 push @$cmd, "--$sw", $v;
329 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
330 push @$cmd, $src, $dst;
333 setup_signals(\&kill_compact, \$pid);
334 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
342 die "@$cmd failed: \$?=$?\n" if $?;
345 sub cpdb_loop ($$$;$$) {
346 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
347 my ($pr, $fmt, $nr, $pfx);
349 $pr = $pr_data->{pr};
350 $fmt = $pr_data->{fmt};
351 $nr = \($pr_data->{nr});
352 $pfx = $pr_data->{pfx};
358 $it = $src->postlist_begin('');
359 $end = $src->postlist_end('');
361 } while (cpdb_retryable($src, $pfx));
365 for (; $it != $end; $it++) {
366 my $docid = $it->get_docid;
367 if (defined $reshard) {
368 my $dst_shard = $docid % $reshard;
369 next if $dst_shard != $cur_shard;
371 my $doc = $src->get_document($docid);
372 $dst->replace_document($docid, $doc);
373 if ($pr_data && !(++$$nr & 1023)) {
374 $pr->(sprintf($fmt, $$nr));
378 # unlike copydatabase(1), we don't copy spelling
379 # and synonym data (or other user metadata) since
380 # the Perl APIs don't expose iterators for them
381 # (and public-inbox does not use those features)
383 } while (cpdb_retryable($src, $pfx));
386 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
387 # to the overhead of Perl.
388 sub cpdb ($$) { # cb_spawn callback
389 my ($args, $opt) = @_;
390 my ($old, $newdir) = @$args;
391 my $new = $newdir->dirname;
392 my ($src, $cur_shard);
394 PublicInbox::SearchIdx::load_xapian_writable() or die;
395 my $XapianDatabase = $PublicInbox::Search::X{Database};
396 if (ref($old) eq 'ARRAY') {
397 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
398 defined $cur_shard or
399 die "BUG: could not extract shard # from $new";
400 $reshard = $opt->{reshard};
401 defined $reshard or die 'BUG: got array src w/o --reshard';
403 # resharding, M:N copy means have full read access
406 my $sub = $XapianDatabase->new($_);
407 $src->add_database($sub);
409 $src = $XapianDatabase->new($_);
413 $src = $XapianDatabase->new($old);
418 if ($opt->{compact}) {
419 my $dir = dirname($new);
420 same_fs_or_die($dir, $new);
421 $ft = File::Temp->newdir("$new.compact-XXXXXX", DIR => $dir);
429 # like copydatabase(1), be sure we don't overwrite anything in case
431 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
433 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
434 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
435 my $dst = $XapianWritableDatabase->new($tmp, $flag);
436 my $pr = $opt->{-progress};
437 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
438 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
442 # update the only metadata key for v1:
443 my $lc = $src->get_metadata('last_commit');
444 $dst->set_metadata('last_commit', $lc) if $lc;
446 # only the first xapian shard (0) gets 'indexlevel'
447 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
448 my $l = $src->get_metadata('indexlevel');
449 if ($l eq 'medium') {
450 $dst->set_metadata('indexlevel', $l);
454 my $tot = $src->get_doccount;
456 # we can only estimate when resharding,
457 # because removed spam causes slight imbalance
459 if (defined $cur_shard && $reshard > 1) {
460 $tot = int($tot/$reshard);
463 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
464 $pr->("$pfx copying $est$tot documents\n");
465 $pr_data->{fmt} = $fmt;
466 $pr_data->{total} = $tot;
469 } while (cpdb_retryable($src, $pfx));
471 if (defined $reshard) {
472 # we rely on document IDs matching NNTP article number,
473 # so we can't have the Xapian sharding DB support rewriting
474 # document IDs. Thus we iterate through each shard
478 my $old = $XapianDatabase->new($_);
479 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
482 cpdb_loop($src, $dst, $pr_data);
485 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
486 return unless $opt->{compact};
488 $src = $dst = undef; # flushes and closes
490 # this is probably the best place to do xapian-compact
491 # since $dst isn't readable by HTTP or NNTP clients, yet:
492 compact([ $tmp, $new ], $opt);
493 remove_tree($tmp) or die "failed to remove $tmp: $!\n";