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';
27 while (my ($old, $newdir) = each %$tmp) {
28 next if $old eq ''; # no invalid paths
30 my ($dname) = ($old =~ m!(.*/)[^/]+/*\z!);
33 my $have_old = -e $old;
34 if (!$have_old && !defined($opt->{reshard})) {
35 die "failed to stat($old): $!";
38 my $new = $newdir->dirname if defined($newdir);
39 my $over = "$old/over.sqlite3";
40 if (-f $over) { # only for v1, v2 over is untouched
41 defined $new or die "BUG: $over exists when culling v2";
42 $over = PublicInbox::Over->new($over);
43 my $tmp_over = "$new/over.sqlite3";
44 $over->dbh->sqlite_backup_to_file($tmp_over);
49 if (!defined($new)) { # culled shard
50 push @old_shard, $old;
54 chmod($mode & 07777, $new) or die "chmod($new): $!\n";
56 rename($old, "$new/old") or
57 die "rename $old => $new/old: $!\n";
59 rename($new, $old) or die "rename $new => $old: $!\n";
61 my $prev = "$old/old";
63 die "failed to remove $prev: $!\n";
67 # trigger ->check_inodes in read-only daemons
68 syswrite($im->{lockfh}, '.') if $over_chg && $im;
70 remove_tree(@old_shard);
72 if (!$opt->{-coarse_lock}) {
73 $opt->{-skip_lock} = 1;
74 $im //= $ibx if $ibx->can('eidx_sync');
75 if ($im->can('count_shards')) { # v2w or eidx
76 my $pr = $opt->{-progress};
77 my $n = $im->count_shards;
78 if (defined $reshard && $n != $reshard) {
80 "BUG: counted $n shards after resharding to $reshard";
82 my $prev = $im->{shards};
83 if ($pr && $prev != $n) {
84 $pr->("shard count changed: $prev => $n\n");
88 my $env = $opt->{-idx_env};
89 local %ENV = (%ENV, %$env) if $env;
90 if ($ibx->can('eidx_sync')) {
91 $ibx->eidx_sync($opt);
93 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
99 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
100 my $seed = rand(0xffffffff);
101 my $pid = fork // die "fork: $!";
102 return $pid if $pid > 0;
104 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
109 sub runnable_or_die ($) {
111 which($exe) or die "$exe not found in PATH\n";
114 sub prepare_reindex ($$) {
115 my ($ibx, $opt) = @_;
116 if ($ibx->can('eidx_sync')) { # no prep needed for ExtSearchIdx
117 } elsif ($ibx->version == 1) {
118 my $dir = $ibx->search->xdir(1);
119 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
120 if (my $lc = $xdb->get_metadata('last_commit')) {
121 $opt->{reindex}->{from} = $lc;
124 my $max = $ibx->max_git_epoch // return;
125 my $from = $opt->{reindex}->{from};
127 my $v = PublicInbox::Search::SCHEMA_VERSION();
128 foreach my $i (0..$max) {
129 $from->[$i] = $mm->last_commit_xap($v, $i);
134 sub same_fs_or_die ($$) {
136 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
137 die "$x and $y reside on different filesystems\n";
141 my ($sig, $pids) = @_;
142 kill($sig, keys %$pids); # pids may be empty
146 my ($queue, $cb, $opt) = @_;
147 my $max = $opt->{jobs} // scalar(@$queue);
149 while (defined(my $args = shift @$queue)) {
157 local @SIG{keys %SIG} = values %SIG;
158 setup_signals(\&kill_pids, \%pids);
160 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
161 my $args = shift @$queue;
162 $pids{cb_spawn($cb, $args, $opt)} = $args;
166 while (scalar keys %pids) {
167 my $pid = waitpid(-1, $flags) or last;
169 my $args = delete $pids{$pid};
171 die join(' ', @$args)." failed: $?\n" if $?;
173 warn "unknown PID($pid) reaped: $?\n";
175 $flags = WNOHANG if scalar(@$queue);
181 my ($ibx, $opt) = @_;
182 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
183 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
185 if ($ibx->can('eidx_sync')) {
187 $old = $ibx->xdir(1);
188 } elsif (my $srch = $ibx->search) {
189 $old = $srch->xdir(1);
192 -d $old or die "$old does not exist\n";
194 my $reshard = $opt->{reshard};
195 if (defined $reshard && $reshard <= 0) {
196 die "--reshard must be a positive number\n";
199 # we want temporary directories to be as deep as possible,
200 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
201 if (defined($old) && $ibx->can('version') && $ibx->version == 1) {
202 if (defined $reshard) {
204 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
206 my ($dir) = ($old =~ m!(.*?/)[^/]+/*\z!);
207 same_fs_or_die($dir, $old);
208 my $v = PublicInbox::Search::SCHEMA_VERSION();
209 my $wip = File::Temp->newdir("xapian$v-XXXX", DIR => $dir);
211 nodatacow_dir($wip->dirname);
212 push @queue, [ $old, $wip ];
213 } elsif (defined $old) {
214 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
216 while (defined(my $dn = readdir($dh))) {
217 if ($dn =~ /\A[0-9]+\z/) {
218 push @old_shards, $dn;
219 } elsif ($dn eq '.' || $dn eq '..') {
220 } elsif ($dn =~ /\Aover\.sqlite3/) {
221 } elsif ($dn eq 'misc' && $misc_ok) {
223 warn "W: skipping unknown dir: $old/$dn\n"
226 die "No Xapian shards found in $old\n" unless @old_shards;
228 my ($src, $max_shard);
229 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
231 $max_shard = scalar(@old_shards) - 1;
234 $max_shard = $reshard - 1;
235 $src = [ map { "$old/$_" } @old_shards ];
237 foreach my $dn (0..$max_shard) {
238 my $wip = File::Temp->newdir("$dn-XXXX", DIR => $old);
239 same_fs_or_die($old, $wip->dirname);
240 my $cur = "$old/$dn";
241 push @queue, [ $src // $cur , $wip ];
242 nodatacow_dir($wip->dirname);
245 # mark old shards to be unlinked
247 $tmp->{$_} ||= undef for @$src;
253 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
255 sub _run { # with_umask callback
256 my ($ibx, $cb, $opt) = @_;
257 my $im = $ibx->can('importer') ? $ibx->importer(0) : undef;
258 ($im // $ibx)->lock_acquire;
259 my ($tmp, $queue) = prepare_run($ibx, $opt);
261 # fine-grained locking if we prepare for reindex
262 if (!$opt->{-coarse_lock}) {
263 prepare_reindex($ibx, $opt);
264 ($im // $ibx)->lock_release;
267 $ibx->cleanup if $ibx->can('cleanup');
268 process_queue($queue, $cb, $opt);
269 ($im // $ibx)->lock_acquire if !$opt->{-coarse_lock};
270 commit_changes($ibx, $im, $tmp, $opt);
274 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
276 PublicInbox::Admin::progress_prepare($opt ||= {});
278 for my $fld (qw(inboxdir topdir)) {
279 my $d = $ibx->{$fld} // next;
280 -d $d or die "$fld=$d does not exist\n";
284 check_compact() if $opt->{compact} && $ibx->search;
286 if (!$ibx->can('eidx_sync') && !$opt->{-coarse_lock}) {
287 # per-epoch ranges for v2
288 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
289 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
290 PublicInbox::SearchIdx::load_xapian_writable();
293 local @SIG{keys %SIG} = values %SIG;
295 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
298 sub cpdb_retryable ($$) {
299 my ($src, $pfx) = @_;
300 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
301 warn "$pfx Xapian DB modified, reopening and retrying\n";
306 warn "$pfx E: ", ref($@), "\n";
312 sub progress_pfx ($) {
313 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXX
314 my @p = split('/', $wip);
316 # return "xap15/0" for v2, or "xapian15" for v1:
317 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
320 sub kill_compact { # setup_signals callback
321 my ($sig, $pidref) = @_;
322 kill($sig, $$pidref) if defined($$pidref);
325 # xapian-compact wrapper
326 sub compact ($$) { # cb_spawn callback
327 my ($args, $opt) = @_;
328 my ($src, $newdir) = @$args;
329 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
330 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
331 my $pr = $opt->{-progress};
334 foreach my $fd (0..2) {
335 defined(my $dfd = $opt->{$fd}) or next;
339 # we rely on --no-renumber to keep docids synched to NNTP
340 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
341 for my $sw (qw(no-full fuller)) {
342 push @$cmd, "--$sw" if $opt->{$sw};
344 for my $sw (qw(blocksize)) {
345 defined(my $v = $opt->{$sw}) or next;
346 push @$cmd, "--$sw", $v;
348 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
349 push @$cmd, $src, $dst;
351 local @SIG{keys %SIG} = values %SIG;
352 setup_signals(\&kill_compact, \$pid);
353 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
361 die "@$cmd failed: \$?=$?\n" if $?;
364 sub cpdb_loop ($$$;$$) {
365 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
366 my ($pr, $fmt, $nr, $pfx);
368 $pr = $pr_data->{pr};
369 $fmt = $pr_data->{fmt};
370 $nr = \($pr_data->{nr});
371 $pfx = $pr_data->{pfx};
377 $it = $src->postlist_begin('');
378 $end = $src->postlist_end('');
380 } while (cpdb_retryable($src, $pfx));
384 for (; $it != $end; $it++) {
385 my $docid = $it->get_docid;
386 if (defined $reshard) {
387 my $dst_shard = $docid % $reshard;
388 next if $dst_shard != $cur_shard;
390 my $doc = $src->get_document($docid);
391 $dst->replace_document($docid, $doc);
392 if ($pr_data && !(++$$nr & 1023)) {
393 $pr->(sprintf($fmt, $$nr));
397 # unlike copydatabase(1), we don't copy spelling
398 # and synonym data (or other user metadata) since
399 # the Perl APIs don't expose iterators for them
400 # (and public-inbox does not use those features)
402 } while (cpdb_retryable($src, $pfx));
405 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
406 # to the overhead of Perl.
407 sub cpdb ($$) { # cb_spawn callback
408 my ($args, $opt) = @_;
409 my ($old, $newdir) = @$args;
410 my $new = $newdir->dirname;
411 my ($src, $cur_shard);
413 PublicInbox::SearchIdx::load_xapian_writable();
414 my $XapianDatabase = $PublicInbox::Search::X{Database};
415 if (ref($old) eq 'ARRAY') {
416 ($cur_shard) = ($new =~ m!(?:xap|ei)[0-9]+/([0-9]+)\b!);
417 defined $cur_shard or
418 die "BUG: could not extract shard # from $new";
419 $reshard = $opt->{reshard};
420 defined $reshard or die 'BUG: got array src w/o --reshard';
422 # resharding, M:N copy means have full read access
425 my $sub = $XapianDatabase->new($_);
426 $src->add_database($sub);
428 $src = $XapianDatabase->new($_);
432 $src = $XapianDatabase->new($old);
436 local @SIG{keys %SIG} = values %SIG;
437 if ($opt->{compact}) {
438 my ($dir) = ($new =~ m!(.*?/)[^/]+/*\z!);
439 same_fs_or_die($dir, $new);
440 $ft = File::Temp->newdir("$new.compact-XXXX", DIR => $dir);
448 # like copydatabase(1), be sure we don't overwrite anything in case
450 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
452 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
453 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
454 my $dst = $XapianWritableDatabase->new($tmp, $flag);
455 my $pr = $opt->{-progress};
456 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
457 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
461 # update the only metadata key for v1:
462 my $lc = $src->get_metadata('last_commit');
463 $dst->set_metadata('last_commit', $lc) if $lc;
465 # only the first xapian shard (0) gets 'indexlevel'
466 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
467 my $l = $src->get_metadata('indexlevel');
468 if ($l eq 'medium') {
469 $dst->set_metadata('indexlevel', $l);
473 my $tot = $src->get_doccount;
475 # we can only estimate when resharding,
476 # because removed spam causes slight imbalance
478 if (defined $cur_shard && $reshard > 1) {
479 $tot = int($tot/$reshard);
482 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
483 $pr->("$pfx copying $est$tot documents\n");
484 $pr_data->{fmt} = $fmt;
485 $pr_data->{total} = $tot;
488 } while (cpdb_retryable($src, $pfx));
490 if (defined $reshard) {
491 # we rely on document IDs matching NNTP article number,
492 # so we can't have the Xapian sharding DB support rewriting
493 # document IDs. Thus we iterate through each shard
497 my $old = $XapianDatabase->new($_);
498 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
501 cpdb_loop($src, $dst, $pr_data);
504 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
505 return unless $opt->{compact};
507 $src = $dst = undef; # flushes and closes
509 # this is probably the best place to do xapian-compact
510 # since $dst isn't readable by HTTP or NNTP clients, yet:
511 compact([ $tmp, $new ], $opt);
512 remove_tree($tmp) or die "failed to remove $tmp: $!\n";