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 && $im;
66 remove_tree(@old_shard);
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) {
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 if ($ibx->can('eidx_sync')) {
87 $ibx->eidx_sync($opt);
89 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
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;
100 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
105 sub runnable_or_die ($) {
107 which($exe) or die "$exe not found in PATH\n";
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;
120 my $max = $ibx->max_git_epoch // return;
121 my $from = $opt->{reindex}->{from};
123 my $v = PublicInbox::Search::SCHEMA_VERSION();
124 foreach my $i (0..$max) {
125 $from->[$i] = $mm->last_commit_xap($v, $i);
130 sub same_fs_or_die ($$) {
132 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
133 die "$x and $y reside on different filesystems\n";
137 my ($sig, $pids) = @_;
138 kill($sig, keys %$pids); # pids may be empty
142 my ($queue, $cb, $opt) = @_;
143 my $max = $opt->{jobs} // scalar(@$queue);
145 while (defined(my $args = shift @$queue)) {
154 setup_signals(\&kill_pids, \%pids);
156 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
157 my $args = shift @$queue;
158 $pids{cb_spawn($cb, $args, $opt)} = $args;
162 while (scalar keys %pids) {
163 my $pid = waitpid(-1, $flags) or last;
165 my $args = delete $pids{$pid};
167 die join(' ', @$args)." failed: $?\n" if $?;
169 warn "unknown PID($pid) reaped: $?\n";
171 $flags = WNOHANG if scalar(@$queue);
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()
181 if ($ibx->can('eidx_sync')) {
183 $old = $ibx->xdir(1);
184 } elsif (my $srch = $ibx->search) {
185 $old = $srch->xdir(1);
188 -d $old or die "$old does not exist\n";
190 my $reshard = $opt->{reshard};
191 if (defined $reshard && $reshard <= 0) {
192 die "--reshard must be a positive number\n";
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) {
200 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
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);
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";
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) {
219 warn "W: skipping unknown dir: $old/$dn\n"
222 die "No Xapian shards found in $old\n" unless @old_shards;
224 my ($src, $max_shard);
225 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
227 $max_shard = scalar(@old_shards) - 1;
230 $max_shard = $reshard - 1;
231 $src = [ map { "$old/$_" } @old_shards ];
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);
241 # mark old shards to be unlinked
243 $tmp->{$_} ||= undef for @$src;
249 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
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);
257 # fine-grained locking if we prepare for reindex
258 if (!$opt->{-coarse_lock}) {
259 prepare_reindex($ibx, $opt);
260 ($im // $ibx)->lock_release;
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);
270 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
272 PublicInbox::Admin::progress_prepare($opt ||= {});
274 for my $fld (qw(inboxdir topdir)) {
275 my $d = $ibx->{$fld} // next;
276 -d $d or die "$fld=$d does not exist\n";
280 check_compact() if $opt->{compact} && $ibx->search;
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();
291 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
294 sub cpdb_retryable ($$) {
295 my ($src, $pfx) = @_;
296 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
297 warn "$pfx Xapian DB modified, reopening and retrying\n";
302 warn "$pfx E: ", ref($@), "\n";
308 sub progress_pfx ($) {
309 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXX
310 my @p = split('/', $wip);
312 # return "xap15/0" for v2, or "xapian15" for v1:
313 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
316 sub kill_compact { # setup_signals callback
317 my ($sig, $pidref) = @_;
318 kill($sig, $$pidref) if defined($$pidref);
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};
330 foreach my $fd (0..2) {
331 defined(my $dfd = $opt->{$fd}) or next;
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};
340 for my $sw (qw(blocksize)) {
341 defined(my $v = $opt->{$sw}) or next;
342 push @$cmd, "--$sw", $v;
344 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
345 push @$cmd, $src, $dst;
348 setup_signals(\&kill_compact, \$pid);
349 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
357 die "@$cmd failed: \$?=$?\n" if $?;
360 sub cpdb_loop ($$$;$$) {
361 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
362 my ($pr, $fmt, $nr, $pfx);
364 $pr = $pr_data->{pr};
365 $fmt = $pr_data->{fmt};
366 $nr = \($pr_data->{nr});
367 $pfx = $pr_data->{pfx};
373 $it = $src->postlist_begin('');
374 $end = $src->postlist_end('');
376 } while (cpdb_retryable($src, $pfx));
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;
386 my $doc = $src->get_document($docid);
387 $dst->replace_document($docid, $doc);
388 if ($pr_data && !(++$$nr & 1023)) {
389 $pr->(sprintf($fmt, $$nr));
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)
398 } while (cpdb_retryable($src, $pfx));
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);
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';
418 # resharding, M:N copy means have full read access
421 my $sub = $XapianDatabase->new($_);
422 $src->add_database($sub);
424 $src = $XapianDatabase->new($_);
428 $src = $XapianDatabase->new($old);
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);
444 # like copydatabase(1), be sure we don't overwrite anything in case
446 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
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;
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;
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);
469 my $tot = $src->get_doccount;
471 # we can only estimate when resharding,
472 # because removed spam causes slight imbalance
474 if (defined $cur_shard && $reshard > 1) {
475 $tot = int($tot/$reshard);
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;
484 } while (cpdb_retryable($src, $pfx));
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
493 my $old = $XapianDatabase->new($_);
494 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
497 cpdb_loop($src, $dst, $pr_data);
500 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
501 return unless $opt->{compact};
503 $src = $dst = undef; # flushes and closes
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";