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, $im, $tmp, $opt) = @_;
20 my $reshard = $opt->{reshard};
21 my $reindex = $opt->{reindex};
23 $SIG{INT} or die 'BUG: $SIG{INT} not handled';
26 while (my ($old, $new) = each %$tmp) {
27 next if $old eq ''; # no invalid paths
29 if (!@st && !defined($opt->{reshard})) {
30 die "failed to stat($old): $!";
33 my $over = "$old/over.sqlite3";
34 if (-f $over) { # only for v1, v2 over is untouched
35 defined $new or die "BUG: $over exists when culling v2";
36 $over = PublicInbox::Over->new($over);
37 my $tmp_over = "$new/over.sqlite3";
38 $over->connect->sqlite_backup_to_file($tmp_over);
42 if (!defined($new)) { # culled shard
43 push @old_shard, $old;
48 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
49 rename($old, "$new/old") or
50 die "rename $old => $new/old: $!\n";
52 # Xtmpdir->DESTROY won't remove $new after this:
53 rename($new, $old) or die "rename $new => $old: $!\n";
55 my $prev = "$old/old";
57 die "failed to remove $prev: $!\n";
60 remove_tree(@old_shard);
62 if (!$opt->{-coarse_lock}) {
63 $opt->{-skip_lock} = 1;
65 if ($im->can('count_shards')) {
66 my $pr = $opt->{-progress};
67 my $n = $im->count_shards;
68 if (defined $reshard && $n != $reshard) {
70 "BUG: counted $n shards after resharding to $reshard";
72 my $prev = $im->{shards};
73 if ($pr && $prev != $n) {
74 $pr->("shard count changed: $prev => $n\n");
79 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
84 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
85 defined(my $pid = fork) or die "fork: $!";
86 return $pid if $pid > 0;
91 sub runnable_or_die ($) {
93 which($exe) or die "$exe not found in PATH\n";
96 sub prepare_reindex ($$$) {
97 my ($ibx, $im, $reindex) = @_;
98 if ($ibx->{version} == 1) {
99 my $dir = $ibx->search->xdir(1);
100 my $xdb = Search::Xapian::Database->new($dir);
101 if (my $lc = $xdb->get_metadata('last_commit')) {
102 $reindex->{from} = $lc;
106 $im->git_dir_latest(\$max) or return;
107 my $from = $reindex->{from};
109 my $v = PublicInbox::Search::SCHEMA_VERSION();
110 foreach my $i (0..$max) {
111 $from->[$i] = $mm->last_commit_xap($v, $i);
116 sub same_fs_or_die ($$) {
118 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
119 die "$x and $y reside on different filesystems\n";
123 my ($queue, $cb, $max, $opt) = @_;
125 while (defined(my $args = shift @$queue)) {
134 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
135 my $args = shift @$queue;
136 $pids{cb_spawn($cb, $args, $opt)} = $args;
139 while (scalar keys %pids) {
140 my $pid = waitpid(-1, 0);
141 my $args = delete $pids{$pid};
142 die join(' ', @$args)." failed: $?\n" if $?;
148 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
149 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
150 PublicInbox::Admin::progress_prepare($opt ||= {});
151 my $dir = $ibx->{inboxdir} or die "no inboxdir in inbox\n";
152 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
153 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
154 my $from; # per-epoch ranges
156 if (!$opt->{-coarse_lock}) {
157 $reindex = $opt->{reindex} = {};
158 $from = $reindex->{from} = [];
159 require Search::Xapian::WritableDatabase;
163 my $old = $ibx->search->xdir(1);
164 -d $old or die "$old does not exist\n";
166 my $tmp = PublicInbox::Xtmpdirs->new;
167 my $v = $ibx->{version} ||= 1;
169 my $reshard = $opt->{reshard};
170 if (defined $reshard && $reshard <= 0) {
171 die "--reshard must be a positive number\n";
177 # we want temporary directories to be as deep as possible,
178 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
180 if (defined $reshard) {
182 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
184 my $old_parent = dirname($old);
185 same_fs_or_die($old_parent, $old);
186 my $v = PublicInbox::Search::SCHEMA_VERSION();
187 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
189 push @q, [ $old, $wip ];
191 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
193 while (defined(my $dn = readdir($dh))) {
194 if ($dn =~ /\A[0-9]+\z/) {
195 push @old_shards, $dn;
196 } elsif ($dn eq '.' || $dn eq '..') {
197 } elsif ($dn =~ /\Aover\.sqlite3/) {
199 warn "W: skipping unknown dir: $old/$dn\n"
202 die "No Xapian shards found in $old\n" unless @old_shards;
204 my ($src, $max_shard);
205 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
207 $max_shard = scalar(@old_shards) - 1;
210 $max_shard = $reshard - 1;
211 $src = [ map { "$old/$_" } @old_shards ];
213 foreach my $dn (0..$max_shard) {
214 my $tmpl = "$dn-XXXXXXXX";
215 my $wip = tempdir($tmpl, DIR => $old);
216 same_fs_or_die($old, $wip);
217 my $cur = "$old/$dn";
218 push @q, [ $src // $cur , $wip ];
221 # mark old shards to be unlinked
223 $tmp->{$_} ||= undef for @$src;
226 my $max = $opt->{jobs} || scalar(@q);
227 $ibx->with_umask(sub {
228 my $im = $ibx->importer(0);
231 # fine-grained locking if we prepare for reindex
232 if (!$opt->{-coarse_lock}) {
233 prepare_reindex($ibx, $im, $reindex);
237 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
238 process_queue(\@q, $cb, $max, $opt);
239 $im->lock_acquire if !$opt->{-coarse_lock};
240 commit_changes($ibx, $im, $tmp, $opt);
244 sub cpdb_retryable ($$) {
245 my ($src, $pfx) = @_;
246 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
247 warn "$pfx Xapian DB modified, reopening and retrying\n";
252 warn "$pfx E: ", ref($@), "\n";
258 sub progress_pfx ($) {
259 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
260 my @p = split('/', $wip);
262 # return "xap15/0" for v2, or "xapian15" for v1:
263 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
266 # xapian-compact wrapper
268 my ($args, $opt) = @_;
269 my ($src, $dst) = @$args;
271 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
272 my $pr = $opt->{-progress};
275 foreach my $fd (0..2) {
276 defined(my $dfd = $opt->{$fd}) or next;
279 $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
281 # we rely on --no-renumber to keep docids synched to NNTP
282 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
283 for my $sw (qw(no-full fuller)) {
284 push @$cmd, "--$sw" if $opt->{$sw};
286 for my $sw (qw(blocksize)) {
287 defined(my $v = $opt->{$sw}) or next;
288 push @$cmd, "--$sw", $v;
290 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
291 push @$cmd, $src, $dst;
292 my $pid = spawn($cmd, undef, $rdr);
294 close $w or die "close: \$w: $!";
300 my $rp = waitpid($pid, 0);
301 if ($? || $rp != $pid) {
302 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
306 sub cpdb_loop ($$$;$$) {
307 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
308 my ($pr, $fmt, $nr, $pfx);
310 $pr = $pr_data->{pr};
311 $fmt = $pr_data->{fmt};
312 $nr = \($pr_data->{nr});
313 $pfx = $pr_data->{pfx};
319 $it = $src->postlist_begin('');
320 $end = $src->postlist_end('');
322 } while (cpdb_retryable($src, $pfx));
326 for (; $it != $end; $it++) {
327 my $docid = $it->get_docid;
328 if (defined $reshard) {
329 my $dst_shard = $docid % $reshard;
330 next if $dst_shard != $cur_shard;
332 my $doc = $src->get_document($docid);
333 $dst->replace_document($docid, $doc);
334 if ($pr_data && !(++$$nr & 1023)) {
335 $pr->(sprintf($fmt, $$nr));
339 # unlike copydatabase(1), we don't copy spelling
340 # and synonym data (or other user metadata) since
341 # the Perl APIs don't expose iterators for them
342 # (and public-inbox does not use those features)
344 } while (cpdb_retryable($src, $pfx));
347 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
348 # to the overhead of Perl.
350 my ($args, $opt) = @_;
351 my ($old, $new) = @$args;
352 my ($src, $cur_shard);
354 if (ref($old) eq 'ARRAY') {
355 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
356 defined $cur_shard or
357 die "BUG: could not extract shard # from $new";
358 $reshard = $opt->{reshard};
359 defined $reshard or die 'BUG: got array src w/o --reshard';
361 # resharding, M:N copy means have full read access
364 my $sub = Search::Xapian::Database->new($_);
365 $src->add_database($sub);
367 $src = Search::Xapian::Database->new($_);
371 $src = Search::Xapian::Database->new($old);
376 if ($opt->{compact}) {
377 my $newdir = dirname($new);
378 same_fs_or_die($newdir, $new);
379 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
380 $xtmp = PublicInbox::Xtmpdirs->new;
381 $xtmp->setup_signals;
382 $xtmp->{$new} = $tmp;
387 # like copydatabase(1), be sure we don't overwrite anything in case
389 my $creat = Search::Xapian::DB_CREATE();
390 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
391 my $pr = $opt->{-progress};
392 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
393 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
397 # update the only metadata key for v1:
398 my $lc = $src->get_metadata('last_commit');
399 $dst->set_metadata('last_commit', $lc) if $lc;
401 # only the first xapian shard (0) gets 'indexlevel'
402 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
403 my $l = $src->get_metadata('indexlevel');
404 if ($l eq 'medium') {
405 $dst->set_metadata('indexlevel', $l);
409 my $tot = $src->get_doccount;
411 # we can only estimate when resharding,
412 # because removed spam causes slight imbalance
414 if (defined $cur_shard && $reshard > 1) {
415 $tot = int($tot/$reshard);
418 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
419 $pr->("$pfx copying $est$tot documents\n");
420 $pr_data->{fmt} = $fmt;
421 $pr_data->{total} = $tot;
424 } while (cpdb_retryable($src, $pfx));
426 if (defined $reshard) {
427 # we rely on document IDs matching NNTP article number,
428 # so we can't have the Xapian sharding DB support rewriting
429 # document IDs. Thus we iterate through each shard
433 my $old = Search::Xapian::Database->new($_);
434 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
437 cpdb_loop($src, $dst, $pr_data);
440 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
443 $src = $dst = undef; # flushes and closes
445 # this is probably the best place to do xapian-compact
446 # since $dst isn't readable by HTTP or NNTP clients, yet:
447 compact([ $tmp, $new ], $opt);
448 remove_tree($tmp) or die "failed to remove $tmp: $!\n";
452 # slightly easier-to-manage manage than END{} blocks
453 package PublicInbox::Xtmpdirs;
456 use File::Path qw(remove_tree);
458 sub setup_signals () {
459 # http://www.tldp.org/LDP/abs/html/exitcodes.html
460 $SIG{INT} = sub { exit(130) };
461 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
465 bless { '' => $$ }, $_[0]; # old shard => new (WIP) shard
470 my $owner_pid = delete($self->{''}) or return;
471 return if $owner_pid != $$;
472 foreach my $new (values %$self) {
473 defined $new or next; # may be undef if resharding
474 remove_tree($new) unless -d "$new/old";