1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::Xapcmd;
6 use PublicInbox::Spawn qw(which popen_rd);
8 use PublicInbox::SearchIdx qw(nodatacow_dir);
9 use File::Temp 0.19 (); # ->newdir
10 use File::Path qw(remove_tree);
11 use File::Basename qw(dirname);
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};
22 my $reindex = $opt->{reindex};
24 $SIG{INT} or die 'BUG: $SIG{INT} not handled';
28 while (my ($old, $newdir) = each %$tmp) {
29 next if $old eq ''; # no invalid paths
31 if (!@st && !defined($opt->{reshard})) {
32 die "failed to stat($old): $!";
35 my $new = $newdir->dirname if defined($newdir);
36 my $over = "$old/over.sqlite3";
37 if (-f $over) { # only for v1, v2 over is untouched
38 defined $new or die "BUG: $over exists when culling v2";
39 $over = PublicInbox::Over->new($over);
40 my $tmp_over = "$new/over.sqlite3";
41 $over->connect->sqlite_backup_to_file($tmp_over);
46 if (!defined($new)) { # culled shard
47 push @old_shard, $old;
52 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
53 rename($old, "$new/old") or
54 die "rename $old => $new/old: $!\n";
56 # Xtmpdir->DESTROY won't remove $new after this:
57 rename($new, $old) or die "rename $new => $old: $!\n";
59 my $prev = "$old/old";
61 die "failed to remove $prev: $!\n";
65 # trigger ->check_inodes in read-only daemons
66 syswrite($im->{lockfh}, '.') if $over_chg;
68 remove_tree(@old_shard);
70 if (!$opt->{-coarse_lock}) {
71 $opt->{-skip_lock} = 1;
73 if ($im->can('count_shards')) {
74 my $pr = $opt->{-progress};
75 my $n = $im->count_shards;
76 if (defined $reshard && $n != $reshard) {
78 "BUG: counted $n shards after resharding to $reshard";
80 my $prev = $im->{shards};
81 if ($pr && $prev != $n) {
82 $pr->("shard count changed: $prev => $n\n");
87 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
92 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
93 defined(my $pid = fork) or die "fork: $!";
94 return $pid if $pid > 0;
99 sub runnable_or_die ($) {
101 which($exe) or die "$exe not found in PATH\n";
104 sub prepare_reindex ($$$) {
105 my ($ibx, $im, $reindex) = @_;
106 if ($ibx->version == 1) {
107 my $dir = $ibx->search->xdir(1);
108 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
109 if (my $lc = $xdb->get_metadata('last_commit')) {
110 $reindex->{from} = $lc;
114 $im->git_dir_latest(\$max) or return;
115 my $from = $reindex->{from};
117 my $v = PublicInbox::Search::SCHEMA_VERSION();
118 foreach my $i (0..$max) {
119 $from->[$i] = $mm->last_commit_xap($v, $i);
124 sub same_fs_or_die ($$) {
126 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
127 die "$x and $y reside on different filesystems\n";
131 my ($queue, $cb, $opt) = @_;
132 my $max = $opt->{jobs} // scalar(@$queue);
134 while (defined(my $args = shift @$queue)) {
143 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
144 my $args = shift @$queue;
145 $pids{cb_spawn($cb, $args, $opt)} = $args;
148 while (scalar keys %pids) {
149 my $pid = waitpid(-1, 0);
150 my $args = delete $pids{$pid};
152 die join(' ', @$args)." failed: $?\n" if $?;
154 warn "unknown PID($pid) reaped: $?\n";
160 sub setup_signals () {
161 # http://www.tldp.org/LDP/abs/html/exitcodes.html
162 $SIG{INT} = sub { exit(130) };
163 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
167 my ($ibx, $opt) = @_;
168 my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
169 my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
171 if (my $srch = $ibx->search) {
172 $old = $srch->xdir(1);
173 -d $old or die "$old does not exist\n";
175 my $reshard = $opt->{reshard};
176 if (defined $reshard && $reshard <= 0) {
177 die "--reshard must be a positive number\n";
180 # we want temporary directories to be as deep as possible,
181 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
182 if ($old && $ibx->version == 1) {
183 if (defined $reshard) {
185 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
187 my $dir = dirname($old);
188 same_fs_or_die($dir, $old);
189 my $v = PublicInbox::Search::SCHEMA_VERSION();
190 my $wip = File::Temp->newdir("xapian$v-XXXXXXXX", DIR => $dir);
192 nodatacow_dir($wip->dirname);
193 push @queue, [ $old, $wip ];
195 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
197 while (defined(my $dn = readdir($dh))) {
198 if ($dn =~ /\A[0-9]+\z/) {
199 push @old_shards, $dn;
200 } elsif ($dn eq '.' || $dn eq '..') {
201 } elsif ($dn =~ /\Aover\.sqlite3/) {
203 warn "W: skipping unknown dir: $old/$dn\n"
206 die "No Xapian shards found in $old\n" unless @old_shards;
208 my ($src, $max_shard);
209 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
211 $max_shard = scalar(@old_shards) - 1;
214 $max_shard = $reshard - 1;
215 $src = [ map { "$old/$_" } @old_shards ];
217 foreach my $dn (0..$max_shard) {
218 my $tmpl = "$dn-XXXXXXXX";
219 my $wip = File::Temp->newdir($tmpl, DIR => $old);
220 same_fs_or_die($old, $wip->dirname);
221 my $cur = "$old/$dn";
222 push @queue, [ $src // $cur , $wip ];
223 nodatacow_dir($wip->dirname);
226 # mark old shards to be unlinked
228 $tmp->{$_} ||= undef for @$src;
234 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
237 my ($ibx, $cb, $opt, $reindex) = @_;
238 my $im = $ibx->importer(0);
240 my ($tmp, $queue) = prepare_run($ibx, $opt);
242 # fine-grained locking if we prepare for reindex
243 if (!$opt->{-coarse_lock}) {
244 prepare_reindex($ibx, $im, $reindex);
249 process_queue($queue, $cb, $opt);
250 $im->lock_acquire if !$opt->{-coarse_lock};
251 commit_changes($ibx, $im, $tmp, $opt);
255 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
256 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
257 PublicInbox::Admin::progress_prepare($opt ||= {});
258 defined(my $dir = $ibx->{inboxdir}) or die "no inboxdir defined\n";
259 -d $dir or die "inboxdir=$dir does not exist\n";
260 check_compact() if $opt->{compact} && $ibx->search;
261 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
263 if (!$opt->{-coarse_lock}) {
264 $reindex = $opt->{reindex} = { # per-epoch ranges for v2
265 from => $ibx->version == 1 ? '' : [],
267 require PublicInbox::SearchIdx;
268 PublicInbox::SearchIdx::load_xapian_writable();
274 $ibx->with_umask(\&_run, $ibx, $cb, $opt, $reindex);
277 sub cpdb_retryable ($$) {
278 my ($src, $pfx) = @_;
279 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
280 warn "$pfx Xapian DB modified, reopening and retrying\n";
285 warn "$pfx E: ", ref($@), "\n";
291 sub progress_pfx ($) {
292 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
293 my @p = split('/', $wip);
295 # return "xap15/0" for v2, or "xapian15" for v1:
296 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
299 # xapian-compact wrapper
301 my ($args, $opt) = @_;
302 my ($src, $newdir) = @$args;
303 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
304 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
305 my $pr = $opt->{-progress};
308 foreach my $fd (0..2) {
309 defined(my $dfd = $opt->{$fd}) or next;
313 # we rely on --no-renumber to keep docids synched to NNTP
314 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
315 for my $sw (qw(no-full fuller)) {
316 push @$cmd, "--$sw" if $opt->{$sw};
318 for my $sw (qw(blocksize)) {
319 defined(my $v = $opt->{$sw}) or next;
320 push @$cmd, "--$sw", $v;
322 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
323 push @$cmd, $src, $dst;
324 my $rd = popen_rd($cmd, undef, $rdr);
331 close $rd or die join(' ', @$cmd)." failed: $?n";
334 sub cpdb_loop ($$$;$$) {
335 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
336 my ($pr, $fmt, $nr, $pfx);
338 $pr = $pr_data->{pr};
339 $fmt = $pr_data->{fmt};
340 $nr = \($pr_data->{nr});
341 $pfx = $pr_data->{pfx};
347 $it = $src->postlist_begin('');
348 $end = $src->postlist_end('');
350 } while (cpdb_retryable($src, $pfx));
354 for (; $it != $end; $it++) {
355 my $docid = $it->get_docid;
356 if (defined $reshard) {
357 my $dst_shard = $docid % $reshard;
358 next if $dst_shard != $cur_shard;
360 my $doc = $src->get_document($docid);
361 $dst->replace_document($docid, $doc);
362 if ($pr_data && !(++$$nr & 1023)) {
363 $pr->(sprintf($fmt, $$nr));
367 # unlike copydatabase(1), we don't copy spelling
368 # and synonym data (or other user metadata) since
369 # the Perl APIs don't expose iterators for them
370 # (and public-inbox does not use those features)
372 } while (cpdb_retryable($src, $pfx));
375 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
376 # to the overhead of Perl.
378 my ($args, $opt) = @_;
379 my ($old, $newdir) = @$args;
380 my $new = $newdir->dirname;
381 my ($src, $cur_shard);
383 PublicInbox::SearchIdx::load_xapian_writable() or die;
384 my $XapianDatabase = $PublicInbox::Search::X{Database};
385 if (ref($old) eq 'ARRAY') {
386 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
387 defined $cur_shard or
388 die "BUG: could not extract shard # from $new";
389 $reshard = $opt->{reshard};
390 defined $reshard or die 'BUG: got array src w/o --reshard';
392 # resharding, M:N copy means have full read access
395 my $sub = $XapianDatabase->new($_);
396 $src->add_database($sub);
398 $src = $XapianDatabase->new($_);
402 $src = $XapianDatabase->new($old);
407 if ($opt->{compact}) {
408 my $dir = dirname($new);
409 same_fs_or_die($dir, $new);
410 $ft = File::Temp->newdir("$new.compact-XXXXXX", DIR => $dir);
418 # like copydatabase(1), be sure we don't overwrite anything in case
420 my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
422 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
423 $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{sync};
424 my $dst = $XapianWritableDatabase->new($tmp, $flag);
425 my $pr = $opt->{-progress};
426 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
427 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
431 # update the only metadata key for v1:
432 my $lc = $src->get_metadata('last_commit');
433 $dst->set_metadata('last_commit', $lc) if $lc;
435 # only the first xapian shard (0) gets 'indexlevel'
436 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
437 my $l = $src->get_metadata('indexlevel');
438 if ($l eq 'medium') {
439 $dst->set_metadata('indexlevel', $l);
443 my $tot = $src->get_doccount;
445 # we can only estimate when resharding,
446 # because removed spam causes slight imbalance
448 if (defined $cur_shard && $reshard > 1) {
449 $tot = int($tot/$reshard);
452 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
453 $pr->("$pfx copying $est$tot documents\n");
454 $pr_data->{fmt} = $fmt;
455 $pr_data->{total} = $tot;
458 } while (cpdb_retryable($src, $pfx));
460 if (defined $reshard) {
461 # we rely on document IDs matching NNTP article number,
462 # so we can't have the Xapian sharding DB support rewriting
463 # document IDs. Thus we iterate through each shard
467 my $old = $XapianDatabase->new($_);
468 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
471 cpdb_loop($src, $dst, $pr_data);
474 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
475 return unless $opt->{compact};
477 $src = $dst = undef; # flushes and closes
479 # this is probably the best place to do xapian-compact
480 # since $dst isn't readable by HTTP or NNTP clients, yet:
481 compact([ $tmp, $new ], $opt);
482 remove_tree($tmp) or die "failed to remove $tmp: $!\n";