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';
26 while (my ($old, $newdir) = each %$tmp) {
27 next if $old eq ''; # no invalid paths
29 if (!@st && !defined($opt->{reshard})) {
30 die "failed to stat($old): $!";
33 my $new = $newdir->dirname if defined($newdir);
34 my $over = "$old/over.sqlite3";
35 if (-f $over) { # only for v1, v2 over is untouched
36 defined $new or die "BUG: $over exists when culling v2";
37 $over = PublicInbox::Over->new($over);
38 my $tmp_over = "$new/over.sqlite3";
39 $over->dbh->sqlite_backup_to_file($tmp_over);
44 if (!defined($new)) { # culled shard
45 push @old_shard, $old;
50 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
51 rename($old, "$new/old") or
52 die "rename $old => $new/old: $!\n";
54 rename($new, $old) or die "rename $new => $old: $!\n";
56 my $prev = "$old/old";
58 die "failed to remove $prev: $!\n";
62 # trigger ->check_inodes in read-only daemons
63 syswrite($im->{lockfh}, '.') if $over_chg && $im;
65 remove_tree(@old_shard);
67 if (!$opt->{-coarse_lock}) {
68 $opt->{-skip_lock} = 1;
69 $im //= $ibx if $ibx->can('eidx_sync');
70 if ($im->can('count_shards')) { # v2w or eidx
71 my $pr = $opt->{-progress};
72 my $n = $im->count_shards;
73 if (defined $reshard && $n != $reshard) {
75 "BUG: counted $n shards after resharding to $reshard";
77 my $prev = $im->{shards};
78 if ($pr && $prev != $n) {
79 $pr->("shard count changed: $prev => $n\n");
83 my $env = $opt->{-idx_env};
84 local %ENV = (%ENV, %$env) if $env;
85 if ($ibx->can('eidx_sync')) {
86 $ibx->eidx_sync($opt);
88 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
94 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
95 my $seed = rand(0xffffffff);
96 my $pid = fork // die "fork: $!";
97 return $pid if $pid > 0;
99 $SIG{__DIE__} = sub { warn @_; _exit(1) }; # don't jump up stack
104 sub runnable_or_die ($) {
106 which($exe) or die "$exe not found in PATH\n";
109 sub prepare_reindex ($$) {
110 my ($ibx, $opt) = @_;
111 if ($ibx->can('eidx_sync')) { # no prep needed for ExtSearchIdx
112 } elsif ($ibx->version == 1) {
113 my $dir = $ibx->search->xdir(1);
114 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
115 if (my $lc = $xdb->get_metadata('last_commit')) {
116 $opt->{reindex}->{from} = $lc;
119 my $max = $ibx->max_git_epoch // return;
120 my $from = $opt->{reindex}->{from};
122 my $v = PublicInbox::Search::SCHEMA_VERSION();
123 foreach my $i (0..$max) {
124 $from->[$i] = $mm->last_commit_xap($v, $i);
129 sub same_fs_or_die ($$) {
131 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
132 die "$x and $y reside on different filesystems\n";
136 my ($sig, $pids) = @_;
137 kill($sig, keys %$pids); # pids may be empty
141 my ($queue, $cb, $opt) = @_;
142 my $max = $opt->{jobs} // scalar(@$queue);
144 while (defined(my $args = shift @$queue)) {
153 setup_signals(\&kill_pids, \%pids);
155 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
156 my $args = shift @$queue;
157 $pids{cb_spawn($cb, $args, $opt)} = $args;
161 while (scalar keys %pids) {
162 my $pid = waitpid(-1, $flags) or last;
164 my $args = delete $pids{$pid};
166 die join(' ', @$args)." failed: $?\n" if $?;
168 warn "unknown PID($pid) reaped: $?\n";
170 $flags = WNOHANG if scalar(@$queue);
176 my ($ibx, $opt) = @_;
177 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
178 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
180 if ($ibx->can('eidx_sync')) {
182 $old = $ibx->xdir(1);
183 } elsif (my $srch = $ibx->search) {
184 $old = $srch->xdir(1);
187 -d $old or die "$old does not exist\n";
189 my $reshard = $opt->{reshard};
190 if (defined $reshard && $reshard <= 0) {
191 die "--reshard must be a positive number\n";
194 # we want temporary directories to be as deep as possible,
195 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
196 if (defined($old) && $ibx->can('version') && $ibx->version == 1) {
197 if (defined $reshard) {
199 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
201 my ($dir) = ($old =~ m!(.*?/)[^/]+/*\z!);
202 same_fs_or_die($dir, $old);
203 my $v = PublicInbox::Search::SCHEMA_VERSION();
204 my $wip = File::Temp->newdir("xapian$v-XXXX", DIR => $dir);
206 nodatacow_dir($wip->dirname);
207 push @queue, [ $old, $wip ];
208 } elsif (defined $old) {
209 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
211 while (defined(my $dn = readdir($dh))) {
212 if ($dn =~ /\A[0-9]+\z/) {
213 push @old_shards, $dn;
214 } elsif ($dn eq '.' || $dn eq '..') {
215 } elsif ($dn =~ /\Aover\.sqlite3/) {
216 } elsif ($dn eq 'misc' && $misc_ok) {
218 warn "W: skipping unknown dir: $old/$dn\n"
221 die "No Xapian shards found in $old\n" unless @old_shards;
223 my ($src, $max_shard);
224 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
226 $max_shard = scalar(@old_shards) - 1;
229 $max_shard = $reshard - 1;
230 $src = [ map { "$old/$_" } @old_shards ];
232 foreach my $dn (0..$max_shard) {
233 my $wip = File::Temp->newdir("$dn-XXXX", DIR => $old);
234 same_fs_or_die($old, $wip->dirname);
235 my $cur = "$old/$dn";
236 push @queue, [ $src // $cur , $wip ];
237 nodatacow_dir($wip->dirname);
240 # mark old shards to be unlinked
242 $tmp->{$_} ||= undef for @$src;
248 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
250 sub _run { # with_umask callback
251 my ($ibx, $cb, $opt) = @_;
252 my $im = $ibx->can('importer') ? $ibx->importer(0) : undef;
253 ($im // $ibx)->lock_acquire;
254 my ($tmp, $queue) = prepare_run($ibx, $opt);
256 # fine-grained locking if we prepare for reindex
257 if (!$opt->{-coarse_lock}) {
258 prepare_reindex($ibx, $opt);
259 ($im // $ibx)->lock_release;
262 $ibx->cleanup if $ibx->can('cleanup');
263 process_queue($queue, $cb, $opt);
264 ($im // $ibx)->lock_acquire if !$opt->{-coarse_lock};
265 commit_changes($ibx, $im, $tmp, $opt);
269 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
271 PublicInbox::Admin::progress_prepare($opt ||= {});
273 for my $fld (qw(inboxdir topdir)) {
274 my $d = $ibx->{$fld} // next;
275 -d $d or die "$fld=$d does not exist\n";
279 check_compact() if $opt->{compact} && $ibx->search;
281 if (!$ibx->can('eidx_sync') && !$opt->{-coarse_lock}) {
282 # per-epoch ranges for v2
283 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
284 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
285 PublicInbox::SearchIdx::load_xapian_writable();
290 $ibx->with_umask(\&_run, $ibx, $cb, $opt);
293 sub cpdb_retryable ($$) {
294 my ($src, $pfx) = @_;
295 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
296 warn "$pfx Xapian DB modified, reopening and retrying\n";
301 warn "$pfx E: ", ref($@), "\n";
307 sub progress_pfx ($) {
308 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXX
309 my @p = split('/', $wip);
311 # return "xap15/0" for v2, or "xapian15" for v1:
312 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
315 sub kill_compact { # setup_signals callback
316 my ($sig, $pidref) = @_;
317 kill($sig, $$pidref) if defined($$pidref);
320 # xapian-compact wrapper
321 sub compact ($$) { # cb_spawn callback
322 my ($args, $opt) = @_;
323 my ($src, $newdir) = @$args;
324 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
325 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
326 my $pr = $opt->{-progress};
329 foreach my $fd (0..2) {
330 defined(my $dfd = $opt->{$fd}) or next;
334 # we rely on --no-renumber to keep docids synched to NNTP
335 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
336 for my $sw (qw(no-full fuller)) {
337 push @$cmd, "--$sw" if $opt->{$sw};
339 for my $sw (qw(blocksize)) {
340 defined(my $v = $opt->{$sw}) or next;
341 push @$cmd, "--$sw", $v;
343 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
344 push @$cmd, $src, $dst;
347 setup_signals(\&kill_compact, \$pid);
348 ($rd, $pid) = popen_rd($cmd, undef, $rdr);
356 die "@$cmd failed: \$?=$?\n" if $?;
359 sub cpdb_loop ($$$;$$) {
360 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
361 my ($pr, $fmt, $nr, $pfx);
363 $pr = $pr_data->{pr};
364 $fmt = $pr_data->{fmt};
365 $nr = \($pr_data->{nr});
366 $pfx = $pr_data->{pfx};
372 $it = $src->postlist_begin('');
373 $end = $src->postlist_end('');
375 } while (cpdb_retryable($src, $pfx));
379 for (; $it != $end; $it++) {
380 my $docid = $it->get_docid;
381 if (defined $reshard) {
382 my $dst_shard = $docid % $reshard;
383 next if $dst_shard != $cur_shard;
385 my $doc = $src->get_document($docid);
386 $dst->replace_document($docid, $doc);
387 if ($pr_data && !(++$$nr & 1023)) {
388 $pr->(sprintf($fmt, $$nr));
392 # unlike copydatabase(1), we don't copy spelling
393 # and synonym data (or other user metadata) since
394 # the Perl APIs don't expose iterators for them
395 # (and public-inbox does not use those features)
397 } while (cpdb_retryable($src, $pfx));
400 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
401 # to the overhead of Perl.
402 sub cpdb ($$) { # cb_spawn callback
403 my ($args, $opt) = @_;
404 my ($old, $newdir) = @$args;
405 my $new = $newdir->dirname;
406 my ($src, $cur_shard);
408 PublicInbox::SearchIdx::load_xapian_writable();
409 my $XapianDatabase = $PublicInbox::Search::X{Database};
410 if (ref($old) eq 'ARRAY') {
411 ($cur_shard) = ($new =~ m!(?:xap|ei)[0-9]+/([0-9]+)\b!);
412 defined $cur_shard or
413 die "BUG: could not extract shard # from $new";
414 $reshard = $opt->{reshard};
415 defined $reshard or die 'BUG: got array src w/o --reshard';
417 # resharding, M:N copy means have full read access
420 my $sub = $XapianDatabase->new($_);
421 $src->add_database($sub);
423 $src = $XapianDatabase->new($_);
427 $src = $XapianDatabase->new($old);
432 if ($opt->{compact}) {
433 my ($dir) = ($new =~ m!(.*?/)[^/]+/*\z!);
434 same_fs_or_die($dir, $new);
435 $ft = File::Temp->newdir("$new.compact-XXXX", DIR => $dir);
443 # like copydatabase(1), be sure we don't overwrite anything in case
445 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
447 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
448 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
449 my $dst = $XapianWritableDatabase->new($tmp, $flag);
450 my $pr = $opt->{-progress};
451 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
452 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
456 # update the only metadata key for v1:
457 my $lc = $src->get_metadata('last_commit');
458 $dst->set_metadata('last_commit', $lc) if $lc;
460 # only the first xapian shard (0) gets 'indexlevel'
461 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
462 my $l = $src->get_metadata('indexlevel');
463 if ($l eq 'medium') {
464 $dst->set_metadata('indexlevel', $l);
468 my $tot = $src->get_doccount;
470 # we can only estimate when resharding,
471 # because removed spam causes slight imbalance
473 if (defined $cur_shard && $reshard > 1) {
474 $tot = int($tot/$reshard);
477 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
478 $pr->("$pfx copying $est$tot documents\n");
479 $pr_data->{fmt} = $fmt;
480 $pr_data->{total} = $tot;
483 } while (cpdb_retryable($src, $pfx));
485 if (defined $reshard) {
486 # we rely on document IDs matching NNTP article number,
487 # so we can't have the Xapian sharding DB support rewriting
488 # document IDs. Thus we iterate through each shard
492 my $old = $XapianDatabase->new($_);
493 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
496 cpdb_loop($src, $dst, $pr_data);
499 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
500 return unless $opt->{compact};
502 $src = $dst = undef; # flushes and closes
504 # this is probably the best place to do xapian-compact
505 # since $dst isn't readable by HTTP or NNTP clients, yet:
506 compact([ $tmp, $new ], $opt);
507 remove_tree($tmp) or die "failed to remove $tmp: $!\n";