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) {
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, $opt);
81 # implicit lock_release
88 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
89 defined(my $pid = fork) or die "fork: $!";
90 return $pid if $pid > 0;
95 sub runnable_or_die ($) {
97 which($exe) or die "$exe not found in PATH\n";
100 sub prepare_reindex ($$) {
101 my ($ibx, $reindex) = @_;
102 if ($ibx->{version} == 1) {
103 my $dir = $ibx->search->xdir(1);
104 my $xdb = Search::Xapian::Database->new($dir);
105 if (my $lc = $xdb->get_metadata('last_commit')) {
106 $reindex->{from} = $lc;
109 my $v2w = $ibx->importer(0);
111 $v2w->git_dir_latest(\$max) or return;
112 my $from = $reindex->{from};
114 my $v = PublicInbox::Search::SCHEMA_VERSION();
115 foreach my $i (0..$max) {
116 $from->[$i] = $mm->last_commit_xap($v, $i);
121 sub same_fs_or_die ($$) {
123 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
124 die "$x and $y reside on different filesystems\n";
128 my ($queue, $cb, $max, $opt) = @_;
130 while (defined(my $args = shift @$queue)) {
139 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
140 my $args = shift @$queue;
141 $pids{cb_spawn($cb, $args, $opt)} = $args;
144 while (scalar keys %pids) {
145 my $pid = waitpid(-1, 0);
146 my $args = delete $pids{$pid};
147 die join(' ', @$args)." failed: $?\n" if $?;
153 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
154 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
155 PublicInbox::Admin::progress_prepare($opt ||= {});
156 my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
157 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
158 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
159 my $from; # per-epoch ranges
161 if (!$opt->{-coarse_lock}) {
162 $reindex = $opt->{reindex} = {};
163 $from = $reindex->{from} = [];
164 require Search::Xapian::WritableDatabase;
168 my $old = $ibx->search->xdir(1);
169 -d $old or die "$old does not exist\n";
171 my $tmp = PublicInbox::Xtmpdirs->new;
172 my $v = $ibx->{version} ||= 1;
174 my $reshard = $opt->{reshard};
175 if (defined $reshard && $reshard <= 0) {
176 die "--reshard must be a positive number\n";
179 # we want temporary directories to be as deep as possible,
180 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
182 if (defined $reshard) {
184 "--reshard=$reshard ignored for v1 $ibx->{mainrepo}\n";
186 my $old_parent = dirname($old);
187 same_fs_or_die($old_parent, $old);
188 my $v = PublicInbox::Search::SCHEMA_VERSION();
189 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
191 push @q, [ $old, $wip ];
193 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
195 while (defined(my $dn = readdir($dh))) {
196 if ($dn =~ /\A[0-9]+\z/) {
197 push @old_shards, $dn;
198 } elsif ($dn eq '.' || $dn eq '..') {
199 } elsif ($dn =~ /\Aover\.sqlite3/) {
201 warn "W: skipping unknown dir: $old/$dn\n"
204 die "No Xapian shards found in $old\n" unless @old_shards;
206 my ($src, $max_shard);
207 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
209 $max_shard = scalar(@old_shards) - 1;
212 $max_shard = $reshard - 1;
213 $src = [ map { "$old/$_" } @old_shards ];
215 foreach my $dn (0..$max_shard) {
216 my $tmpl = "$dn-XXXXXXXX";
217 my $wip = tempdir($tmpl, DIR => $old);
218 same_fs_or_die($old, $wip);
219 my $cur = "$old/$dn";
220 push @q, [ $src // $cur , $wip ];
223 # mark old shards to be unlinked
225 $tmp->{$_} ||= undef for @$src;
228 my $im = $ibx->importer(0);
229 my $max = $opt->{jobs} || scalar(@q);
230 $ibx->with_umask(sub {
233 # fine-grained locking if we prepare for reindex
234 if (!$opt->{-coarse_lock}) {
235 prepare_reindex($ibx, $reindex);
239 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
240 process_queue(\@q, $cb, $max, $opt);
241 commit_changes($ibx, $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);
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->{$new} = $tmp;
386 # like copydatabase(1), be sure we don't overwrite anything in case
388 my $creat = Search::Xapian::DB_CREATE();
389 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
390 my $pr = $opt->{-progress};
391 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
392 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
396 # update the only metadata key for v1:
397 my $lc = $src->get_metadata('last_commit');
398 $dst->set_metadata('last_commit', $lc) if $lc;
400 # only the first xapian shard (0) gets 'indexlevel'
401 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
402 my $l = $src->get_metadata('indexlevel');
403 if ($l eq 'medium') {
404 $dst->set_metadata('indexlevel', $l);
408 my $tot = $src->get_doccount;
410 # we can only estimate when resharding,
411 # because removed spam causes slight imbalance
413 if (defined $cur_shard && $reshard > 1) {
414 $tot = int($tot/$reshard);
417 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
418 $pr->("$pfx copying $est$tot documents\n");
419 $pr_data->{fmt} = $fmt;
420 $pr_data->{total} = $tot;
423 } while (cpdb_retryable($src, $pfx));
425 if (defined $reshard) {
426 # we rely on document IDs matching NNTP article number,
427 # so we can't have the Xapian sharding DB support rewriting
428 # document IDs. Thus we iterate through each shard
432 my $old = Search::Xapian::Database->new($_);
433 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
436 cpdb_loop($src, $dst, $pr_data);
439 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
442 $src = $dst = undef; # flushes and closes
444 # this is probably the best place to do xapian-compact
445 # since $dst isn't readable by HTTP or NNTP clients, yet:
446 compact([ $tmp, $new ], $opt);
447 remove_tree($tmp) or die "failed to remove $tmp: $!\n";
451 # slightly easier-to-manage manage than END{} blocks
452 package PublicInbox::Xtmpdirs;
455 use File::Path qw(remove_tree);
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) };
462 my $self = bless {}, $_[0]; # old shard => new (WIP) shard
463 $owner{"$self"} = $$;
469 delete $owner{"$self"};
472 $known_pids{$_}++ foreach values %owner;
473 if (!$known_pids{$$}) {
474 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
481 my $owner_pid = delete $owner{"$self"} or return;
482 return if $owner_pid != $$;
483 foreach my $new (values %$self) {
484 defined $new or next; # may be undef if resharding
485 remove_tree($new) unless -d "$new/old";