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);
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';
27 while (my ($old, $new) = each %$tmp) {
28 next if $old eq ''; # no invalid paths
30 if (!@st && !defined($opt->{reshard})) {
31 die "failed to stat($old): $!";
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->connect->sqlite_backup_to_file($tmp_over);
43 if (!defined($new)) { # culled shard
44 push @old_shard, $old;
49 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
50 rename($old, "$new/old") or
51 die "rename $old => $new/old: $!\n";
53 # Xtmpdir->DESTROY won't remove $new after this:
54 rename($new, $old) or die "rename $new => $old: $!\n";
56 my $prev = "$old/old";
58 die "failed to remove $prev: $!\n";
61 remove_tree(@old_shard);
63 if (!$opt->{-coarse_lock}) {
64 $opt->{-skip_lock} = 1;
66 if ($im->can('count_shards')) {
67 my $pr = $opt->{-progress};
68 my $n = $im->count_shards;
69 if (defined $reshard && $n != $reshard) {
71 "BUG: counted $n shards after resharding to $reshard";
73 my $prev = $im->{shards};
74 if ($pr && $prev != $n) {
75 $pr->("shard count changed: $prev => $n\n");
80 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
85 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
86 defined(my $pid = fork) or die "fork: $!";
87 return $pid if $pid > 0;
92 sub runnable_or_die ($) {
94 which($exe) or die "$exe not found in PATH\n";
97 sub prepare_reindex ($$$) {
98 my ($ibx, $im, $reindex) = @_;
99 if ($ibx->{version} == 1) {
100 my $dir = $ibx->search->xdir(1);
101 my $xdb = Search::Xapian::Database->new($dir);
102 if (my $lc = $xdb->get_metadata('last_commit')) {
103 $reindex->{from} = $lc;
107 $im->git_dir_latest(\$max) or return;
108 my $from = $reindex->{from};
110 my $v = PublicInbox::Search::SCHEMA_VERSION();
111 foreach my $i (0..$max) {
112 $from->[$i] = $mm->last_commit_xap($v, $i);
117 sub same_fs_or_die ($$) {
119 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
120 die "$x and $y reside on different filesystems\n";
124 my ($queue, $cb, $max, $opt) = @_;
126 while (defined(my $args = shift @$queue)) {
135 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
136 my $args = shift @$queue;
137 $pids{cb_spawn($cb, $args, $opt)} = $args;
140 while (scalar keys %pids) {
141 my $pid = waitpid(-1, 0);
142 my $args = delete $pids{$pid};
143 die join(' ', @$args)." failed: $?\n" if $?;
149 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
150 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
151 PublicInbox::Admin::progress_prepare($opt ||= {});
152 my $dir = $ibx->{inboxdir} or die "no inboxdir in inbox\n";
153 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
154 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
155 my $from; # per-epoch ranges
157 if (!$opt->{-coarse_lock}) {
158 $reindex = $opt->{reindex} = {};
159 $from = $reindex->{from} = [];
160 require Search::Xapian::WritableDatabase;
164 my $old = $ibx->search->xdir(1);
165 -d $old or die "$old does not exist\n";
167 my $tmp = PublicInbox::Xtmpdirs->new;
168 my $v = $ibx->{version} ||= 1;
170 my $reshard = $opt->{reshard};
171 if (defined $reshard && $reshard <= 0) {
172 die "--reshard must be a positive number\n";
178 # we want temporary directories to be as deep as possible,
179 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
181 if (defined $reshard) {
183 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
185 my $old_parent = dirname($old);
186 same_fs_or_die($old_parent, $old);
187 my $v = PublicInbox::Search::SCHEMA_VERSION();
188 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
190 push @q, [ $old, $wip ];
192 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
194 while (defined(my $dn = readdir($dh))) {
195 if ($dn =~ /\A[0-9]+\z/) {
196 push @old_shards, $dn;
197 } elsif ($dn eq '.' || $dn eq '..') {
198 } elsif ($dn =~ /\Aover\.sqlite3/) {
200 warn "W: skipping unknown dir: $old/$dn\n"
203 die "No Xapian shards found in $old\n" unless @old_shards;
205 my ($src, $max_shard);
206 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
208 $max_shard = scalar(@old_shards) - 1;
211 $max_shard = $reshard - 1;
212 $src = [ map { "$old/$_" } @old_shards ];
214 foreach my $dn (0..$max_shard) {
215 my $tmpl = "$dn-XXXXXXXX";
216 my $wip = tempdir($tmpl, DIR => $old);
217 same_fs_or_die($old, $wip);
218 my $cur = "$old/$dn";
219 push @q, [ $src // $cur , $wip ];
222 # mark old shards to be unlinked
224 $tmp->{$_} ||= undef for @$src;
227 my $max = $opt->{jobs} || scalar(@q);
228 $ibx->with_umask(sub {
229 my $im = $ibx->importer(0);
232 # fine-grained locking if we prepare for reindex
233 if (!$opt->{-coarse_lock}) {
234 prepare_reindex($ibx, $im, $reindex);
239 process_queue(\@q, $cb, $max, $opt);
240 $im->lock_acquire if !$opt->{-coarse_lock};
241 commit_changes($ibx, $im, $tmp, $opt);
245 sub cpdb_retryable ($$) {
246 my ($src, $pfx) = @_;
247 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
248 warn "$pfx Xapian DB modified, reopening and retrying\n";
253 warn "$pfx E: ", ref($@), "\n";
259 sub progress_pfx ($) {
260 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
261 my @p = split('/', $wip);
263 # return "xap15/0" for v2, or "xapian15" for v1:
264 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
267 # xapian-compact wrapper
269 my ($args, $opt) = @_;
270 my ($src, $dst) = @$args;
272 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
273 my $pr = $opt->{-progress};
276 foreach my $fd (0..2) {
277 defined(my $dfd = $opt->{$fd}) or next;
280 $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
282 # we rely on --no-renumber to keep docids synched to NNTP
283 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
284 for my $sw (qw(no-full fuller)) {
285 push @$cmd, "--$sw" if $opt->{$sw};
287 for my $sw (qw(blocksize)) {
288 defined(my $v = $opt->{$sw}) or next;
289 push @$cmd, "--$sw", $v;
291 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
292 push @$cmd, $src, $dst;
293 my $pid = spawn($cmd, undef, $rdr);
295 close $w or die "close: \$w: $!";
301 my $rp = waitpid($pid, 0);
302 if ($? || $rp != $pid) {
303 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
307 sub cpdb_loop ($$$;$$) {
308 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
309 my ($pr, $fmt, $nr, $pfx);
311 $pr = $pr_data->{pr};
312 $fmt = $pr_data->{fmt};
313 $nr = \($pr_data->{nr});
314 $pfx = $pr_data->{pfx};
320 $it = $src->postlist_begin('');
321 $end = $src->postlist_end('');
323 } while (cpdb_retryable($src, $pfx));
327 for (; $it != $end; $it++) {
328 my $docid = $it->get_docid;
329 if (defined $reshard) {
330 my $dst_shard = $docid % $reshard;
331 next if $dst_shard != $cur_shard;
333 my $doc = $src->get_document($docid);
334 $dst->replace_document($docid, $doc);
335 if ($pr_data && !(++$$nr & 1023)) {
336 $pr->(sprintf($fmt, $$nr));
340 # unlike copydatabase(1), we don't copy spelling
341 # and synonym data (or other user metadata) since
342 # the Perl APIs don't expose iterators for them
343 # (and public-inbox does not use those features)
345 } while (cpdb_retryable($src, $pfx));
348 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
349 # to the overhead of Perl.
351 my ($args, $opt) = @_;
352 my ($old, $new) = @$args;
353 my ($src, $cur_shard);
355 if (ref($old) eq 'ARRAY') {
356 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
357 defined $cur_shard or
358 die "BUG: could not extract shard # from $new";
359 $reshard = $opt->{reshard};
360 defined $reshard or die 'BUG: got array src w/o --reshard';
362 # resharding, M:N copy means have full read access
365 my $sub = Search::Xapian::Database->new($_);
366 $src->add_database($sub);
368 $src = Search::Xapian::Database->new($_);
372 $src = Search::Xapian::Database->new($old);
377 if ($opt->{compact}) {
378 my $newdir = dirname($new);
379 same_fs_or_die($newdir, $new);
380 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
381 $xtmp = PublicInbox::Xtmpdirs->new;
382 $xtmp->setup_signals;
383 $xtmp->{$new} = $tmp;
388 # like copydatabase(1), be sure we don't overwrite anything in case
390 my $creat = Search::Xapian::DB_CREATE();
391 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
392 my $pr = $opt->{-progress};
393 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
394 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
398 # update the only metadata key for v1:
399 my $lc = $src->get_metadata('last_commit');
400 $dst->set_metadata('last_commit', $lc) if $lc;
402 # only the first xapian shard (0) gets 'indexlevel'
403 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
404 my $l = $src->get_metadata('indexlevel');
405 if ($l eq 'medium') {
406 $dst->set_metadata('indexlevel', $l);
410 my $tot = $src->get_doccount;
412 # we can only estimate when resharding,
413 # because removed spam causes slight imbalance
415 if (defined $cur_shard && $reshard > 1) {
416 $tot = int($tot/$reshard);
419 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
420 $pr->("$pfx copying $est$tot documents\n");
421 $pr_data->{fmt} = $fmt;
422 $pr_data->{total} = $tot;
425 } while (cpdb_retryable($src, $pfx));
427 if (defined $reshard) {
428 # we rely on document IDs matching NNTP article number,
429 # so we can't have the Xapian sharding DB support rewriting
430 # document IDs. Thus we iterate through each shard
434 my $old = Search::Xapian::Database->new($_);
435 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
438 cpdb_loop($src, $dst, $pr_data);
441 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
444 $src = $dst = undef; # flushes and closes
446 # this is probably the best place to do xapian-compact
447 # since $dst isn't readable by HTTP or NNTP clients, yet:
448 compact([ $tmp, $new ], $opt);
449 remove_tree($tmp) or die "failed to remove $tmp: $!\n";
453 # slightly easier-to-manage manage than END{} blocks
454 package PublicInbox::Xtmpdirs;
457 use File::Path qw(remove_tree);
459 sub setup_signals () {
460 # http://www.tldp.org/LDP/abs/html/exitcodes.html
461 $SIG{INT} = sub { exit(130) };
462 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
466 bless { '' => $$ }, $_[0]; # old shard => new (WIP) shard
471 my $owner_pid = delete($self->{''}) or return;
472 return if $owner_pid != $$;
473 foreach my $new (values %$self) {
474 defined $new or next; # may be undef if resharding
475 remove_tree($new) unless -d "$new/old";