1 # Copyright (C) 2018-2019 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 spawn);
8 use PublicInbox::Search;
9 use File::Temp qw(tempdir);
10 use File::Path qw(remove_tree);
11 use File::Basename qw(dirname);
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, $tmp, $opt) = @_;
20 my $reshard = $opt->{reshard};
21 my $reindex = $opt->{reindex};
22 my $im = $ibx->importer(0);
23 $im->lock_acquire if !$opt->{-coarse_lock};
25 $SIG{INT} or die 'BUG: $SIG{INT} not handled';
28 while (my ($old, $new) = each %$tmp) {
29 next if $old eq ''; # no invalid paths
31 if (!@st && !defined($opt->{reshard})) {
32 die "failed to stat($old): $!";
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->connect->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 # Xtmpdir->DESTROY won't remove $new after this:
55 rename($new, $old) or die "rename $new => $old: $!\n";
57 my $prev = "$old/old";
59 die "failed to remove $prev: $!\n";
62 remove_tree(@old_shard);
64 if (!$opt->{-coarse_lock}) {
65 $opt->{-skip_lock} = 1;
67 if ($im->can('count_shards')) {
68 my $pr = $opt->{-progress};
69 my $n = $im->count_shards;
70 if (defined $reshard && $n != $reshard) {
72 "BUG: counted $n shards after resharding to $reshard";
74 my $prev = $im->{shards};
75 if ($pr && $prev != $n) {
76 $pr->("shard count changed: $prev => $n\n");
81 PublicInbox::Admin::index_inbox($ibx, $opt);
82 # implicit lock_release
89 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
90 defined(my $pid = fork) or die "fork: $!";
91 return $pid if $pid > 0;
96 sub runnable_or_die ($) {
98 which($exe) or die "$exe not found in PATH\n";
101 sub prepare_reindex ($$) {
102 my ($ibx, $reindex) = @_;
103 if ($ibx->{version} == 1) {
104 my $dir = $ibx->search->xdir(1);
105 my $xdb = Search::Xapian::Database->new($dir);
106 if (my $lc = $xdb->get_metadata('last_commit')) {
107 $reindex->{from} = $lc;
110 my $v2w = $ibx->importer(0);
112 $v2w->git_dir_latest(\$max) or return;
113 my $from = $reindex->{from};
115 my $v = PublicInbox::Search::SCHEMA_VERSION();
116 foreach my $i (0..$max) {
117 $from->[$i] = $mm->last_commit_xap($v, $i);
122 sub same_fs_or_die ($$) {
124 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
125 die "$x and $y reside on different filesystems\n";
129 my ($queue, $cb, $max, $opt) = @_;
131 while (defined(my $args = shift @$queue)) {
140 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
141 my $args = shift @$queue;
142 $pids{cb_spawn($cb, $args, $opt)} = $args;
145 while (scalar keys %pids) {
146 my $pid = waitpid(-1, 0);
147 my $args = delete $pids{$pid};
148 die join(' ', @$args)." failed: $?\n" if $?;
154 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
155 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
156 PublicInbox::Admin::progress_prepare($opt ||= {});
157 my $dir = $ibx->{inboxdir} or die "no inboxdir in inbox\n";
158 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
159 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
160 my $from; # per-epoch ranges
162 if (!$opt->{-coarse_lock}) {
163 $reindex = $opt->{reindex} = {};
164 $from = $reindex->{from} = [];
165 require Search::Xapian::WritableDatabase;
169 my $old = $ibx->search->xdir(1);
170 -d $old or die "$old does not exist\n";
172 my $tmp = PublicInbox::Xtmpdirs->new;
173 my $v = $ibx->{version} ||= 1;
175 my $reshard = $opt->{reshard};
176 if (defined $reshard && $reshard <= 0) {
177 die "--reshard must be a positive number\n";
183 # we want temporary directories to be as deep as possible,
184 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
186 if (defined $reshard) {
188 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
190 my $old_parent = dirname($old);
191 same_fs_or_die($old_parent, $old);
192 my $v = PublicInbox::Search::SCHEMA_VERSION();
193 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
195 push @q, [ $old, $wip ];
197 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
199 while (defined(my $dn = readdir($dh))) {
200 if ($dn =~ /\A[0-9]+\z/) {
201 push @old_shards, $dn;
202 } elsif ($dn eq '.' || $dn eq '..') {
203 } elsif ($dn =~ /\Aover\.sqlite3/) {
205 warn "W: skipping unknown dir: $old/$dn\n"
208 die "No Xapian shards found in $old\n" unless @old_shards;
210 my ($src, $max_shard);
211 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
213 $max_shard = scalar(@old_shards) - 1;
216 $max_shard = $reshard - 1;
217 $src = [ map { "$old/$_" } @old_shards ];
219 foreach my $dn (0..$max_shard) {
220 my $tmpl = "$dn-XXXXXXXX";
221 my $wip = tempdir($tmpl, DIR => $old);
222 same_fs_or_die($old, $wip);
223 my $cur = "$old/$dn";
224 push @q, [ $src // $cur , $wip ];
227 # mark old shards to be unlinked
229 $tmp->{$_} ||= undef for @$src;
232 my $im = $ibx->importer(0);
233 my $max = $opt->{jobs} || scalar(@q);
234 $ibx->with_umask(sub {
237 # fine-grained locking if we prepare for reindex
238 if (!$opt->{-coarse_lock}) {
239 prepare_reindex($ibx, $reindex);
243 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
244 process_queue(\@q, $cb, $max, $opt);
245 commit_changes($ibx, $tmp, $opt);
249 sub cpdb_retryable ($$) {
250 my ($src, $pfx) = @_;
251 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
252 warn "$pfx Xapian DB modified, reopening and retrying\n";
257 warn "$pfx E: ", ref($@), "\n";
263 sub progress_pfx ($) {
264 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
265 my @p = split('/', $wip);
267 # return "xap15/0" for v2, or "xapian15" for v1:
268 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
271 # xapian-compact wrapper
273 my ($args, $opt) = @_;
274 my ($src, $dst) = @$args;
276 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
277 my $pr = $opt->{-progress};
280 foreach my $fd (0..2) {
281 defined(my $dfd = $opt->{$fd}) or next;
284 $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
286 # we rely on --no-renumber to keep docids synched to NNTP
287 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
288 for my $sw (qw(no-full fuller)) {
289 push @$cmd, "--$sw" if $opt->{$sw};
291 for my $sw (qw(blocksize)) {
292 defined(my $v = $opt->{$sw}) or next;
293 push @$cmd, "--$sw", $v;
295 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
296 push @$cmd, $src, $dst;
297 my $pid = spawn($cmd, undef, $rdr);
299 close $w or die "close: \$w: $!";
305 my $rp = waitpid($pid, 0);
306 if ($? || $rp != $pid) {
307 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
311 sub cpdb_loop ($$$;$$) {
312 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
313 my ($pr, $fmt, $nr, $pfx);
315 $pr = $pr_data->{pr};
316 $fmt = $pr_data->{fmt};
317 $nr = \($pr_data->{nr});
318 $pfx = $pr_data->{pfx};
324 $it = $src->postlist_begin('');
325 $end = $src->postlist_end('');
327 } while (cpdb_retryable($src, $pfx));
331 for (; $it != $end; $it++) {
332 my $docid = $it->get_docid;
333 if (defined $reshard) {
334 my $dst_shard = $docid % $reshard;
335 next if $dst_shard != $cur_shard;
337 my $doc = $src->get_document($docid);
338 $dst->replace_document($docid, $doc);
339 if ($pr_data && !(++$$nr & 1023)) {
340 $pr->(sprintf($fmt, $$nr));
344 # unlike copydatabase(1), we don't copy spelling
345 # and synonym data (or other user metadata) since
346 # the Perl APIs don't expose iterators for them
347 # (and public-inbox does not use those features)
349 } while (cpdb_retryable($src, $pfx));
352 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
353 # to the overhead of Perl.
355 my ($args, $opt) = @_;
356 my ($old, $new) = @$args;
357 my ($src, $cur_shard);
359 if (ref($old) eq 'ARRAY') {
360 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
361 defined $cur_shard or
362 die "BUG: could not extract shard # from $new";
363 $reshard = $opt->{reshard};
364 defined $reshard or die 'BUG: got array src w/o --reshard';
366 # resharding, M:N copy means have full read access
369 my $sub = Search::Xapian::Database->new($_);
370 $src->add_database($sub);
372 $src = Search::Xapian::Database->new($_);
376 $src = Search::Xapian::Database->new($old);
381 if ($opt->{compact}) {
382 my $newdir = dirname($new);
383 same_fs_or_die($newdir, $new);
384 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
385 $xtmp = PublicInbox::Xtmpdirs->new;
386 $xtmp->setup_signals;
387 $xtmp->{$new} = $tmp;
392 # like copydatabase(1), be sure we don't overwrite anything in case
394 my $creat = Search::Xapian::DB_CREATE();
395 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
396 my $pr = $opt->{-progress};
397 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
398 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
402 # update the only metadata key for v1:
403 my $lc = $src->get_metadata('last_commit');
404 $dst->set_metadata('last_commit', $lc) if $lc;
406 # only the first xapian shard (0) gets 'indexlevel'
407 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
408 my $l = $src->get_metadata('indexlevel');
409 if ($l eq 'medium') {
410 $dst->set_metadata('indexlevel', $l);
414 my $tot = $src->get_doccount;
416 # we can only estimate when resharding,
417 # because removed spam causes slight imbalance
419 if (defined $cur_shard && $reshard > 1) {
420 $tot = int($tot/$reshard);
423 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
424 $pr->("$pfx copying $est$tot documents\n");
425 $pr_data->{fmt} = $fmt;
426 $pr_data->{total} = $tot;
429 } while (cpdb_retryable($src, $pfx));
431 if (defined $reshard) {
432 # we rely on document IDs matching NNTP article number,
433 # so we can't have the Xapian sharding DB support rewriting
434 # document IDs. Thus we iterate through each shard
438 my $old = Search::Xapian::Database->new($_);
439 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
442 cpdb_loop($src, $dst, $pr_data);
445 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
448 $src = $dst = undef; # flushes and closes
450 # this is probably the best place to do xapian-compact
451 # since $dst isn't readable by HTTP or NNTP clients, yet:
452 compact([ $tmp, $new ], $opt);
453 remove_tree($tmp) or die "failed to remove $tmp: $!\n";
457 # slightly easier-to-manage manage than END{} blocks
458 package PublicInbox::Xtmpdirs;
461 use File::Path qw(remove_tree);
463 sub setup_signals () {
464 # http://www.tldp.org/LDP/abs/html/exitcodes.html
465 $SIG{INT} = sub { exit(130) };
466 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
470 bless { '' => $$ }, $_[0]; # old shard => new (WIP) shard
475 my $owner_pid = delete($self->{''}) or return;
476 return if $owner_pid != $$;
477 foreach my $new (values %$self) {
478 defined $new or next; # may be undef if resharding
479 remove_tree($new) unless -d "$new/old";