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::SearchIdx;
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, $newdir) = each %$tmp) {
28 next if $old eq ''; # no invalid paths
30 if (!@st && !defined($opt->{reshard})) {
31 die "failed to stat($old): $!";
34 my $new = $newdir->dirname if defined($newdir);
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, $im, $opt);
86 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
87 defined(my $pid = fork) or die "fork: $!";
88 return $pid if $pid > 0;
93 sub runnable_or_die ($) {
95 which($exe) or die "$exe not found in PATH\n";
98 sub prepare_reindex ($$$) {
99 my ($ibx, $im, $reindex) = @_;
100 if ($ibx->{version} == 1) {
101 my $dir = $ibx->search->xdir(1);
102 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
103 if (my $lc = $xdb->get_metadata('last_commit')) {
104 $reindex->{from} = $lc;
108 $im->git_dir_latest(\$max) or return;
109 my $from = $reindex->{from};
111 my $v = PublicInbox::Search::SCHEMA_VERSION();
112 foreach my $i (0..$max) {
113 $from->[$i] = $mm->last_commit_xap($v, $i);
118 sub same_fs_or_die ($$) {
120 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
121 die "$x and $y reside on different filesystems\n";
125 my ($queue, $cb, $max, $opt) = @_;
127 while (defined(my $args = shift @$queue)) {
136 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
137 my $args = shift @$queue;
138 $pids{cb_spawn($cb, $args, $opt)} = $args;
141 while (scalar keys %pids) {
142 my $pid = waitpid(-1, 0);
143 my $args = delete $pids{$pid};
144 die join(' ', @$args)." failed: $?\n" if $?;
149 sub setup_signals () {
150 # http://www.tldp.org/LDP/abs/html/exitcodes.html
151 $SIG{INT} = sub { exit(130) };
152 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
156 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
157 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
158 PublicInbox::Admin::progress_prepare($opt ||= {});
159 my $dir = $ibx->{inboxdir} or die "no inboxdir in inbox\n";
160 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
161 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
162 my $from; # per-epoch ranges
164 if (!$opt->{-coarse_lock}) {
165 $reindex = $opt->{reindex} = {};
166 $from = $reindex->{from} = [];
167 require PublicInbox::SearchIdx;
168 PublicInbox::SearchIdx::load_xapian_writable();
172 my $old = $ibx->search->xdir(1);
173 -d $old or die "$old does not exist\n";
176 my $v = $ibx->{version} ||= 1;
178 my $reshard = $opt->{reshard};
179 if (defined $reshard && $reshard <= 0) {
180 die "--reshard must be a positive number\n";
186 # we want temporary directories to be as deep as possible,
187 # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
189 if (defined $reshard) {
191 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
193 my $dir = dirname($old);
194 same_fs_or_die($dir, $old);
195 my $v = PublicInbox::Search::SCHEMA_VERSION();
196 my $wip = File::Temp->newdir("xapian$v-XXXXXXXX", DIR => $dir);
198 push @q, [ $old, $wip ];
200 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
202 while (defined(my $dn = readdir($dh))) {
203 if ($dn =~ /\A[0-9]+\z/) {
204 push @old_shards, $dn;
205 } elsif ($dn eq '.' || $dn eq '..') {
206 } elsif ($dn =~ /\Aover\.sqlite3/) {
208 warn "W: skipping unknown dir: $old/$dn\n"
211 die "No Xapian shards found in $old\n" unless @old_shards;
213 my ($src, $max_shard);
214 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
216 $max_shard = scalar(@old_shards) - 1;
219 $max_shard = $reshard - 1;
220 $src = [ map { "$old/$_" } @old_shards ];
222 foreach my $dn (0..$max_shard) {
223 my $tmpl = "$dn-XXXXXXXX";
224 my $wip = File::Temp->newdir($tmpl, DIR => $old);
225 same_fs_or_die($old, $wip->dirname);
226 my $cur = "$old/$dn";
227 push @q, [ $src // $cur , $wip ];
230 # mark old shards to be unlinked
232 $tmp->{$_} ||= undef for @$src;
235 my $max = $opt->{jobs} || scalar(@q);
236 $ibx->with_umask(sub {
237 my $im = $ibx->importer(0);
240 # fine-grained locking if we prepare for reindex
241 if (!$opt->{-coarse_lock}) {
242 prepare_reindex($ibx, $im, $reindex);
247 process_queue(\@q, $cb, $max, $opt);
248 $im->lock_acquire if !$opt->{-coarse_lock};
249 commit_changes($ibx, $im, $tmp, $opt);
253 sub cpdb_retryable ($$) {
254 my ($src, $pfx) = @_;
255 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
256 warn "$pfx Xapian DB modified, reopening and retrying\n";
261 warn "$pfx E: ", ref($@), "\n";
267 sub progress_pfx ($) {
268 my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
269 my @p = split('/', $wip);
271 # return "xap15/0" for v2, or "xapian15" for v1:
272 ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
275 # xapian-compact wrapper
277 my ($args, $opt) = @_;
278 my ($src, $newdir) = @$args;
279 my $dst = ref($newdir) ? $newdir->dirname : $newdir;
281 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
282 my $pr = $opt->{-progress};
285 foreach my $fd (0..2) {
286 defined(my $dfd = $opt->{$fd}) or next;
289 $rdr->{1} = $w if $pr && pipe($r, $w);
291 # we rely on --no-renumber to keep docids synched to NNTP
292 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
293 for my $sw (qw(no-full fuller)) {
294 push @$cmd, "--$sw" if $opt->{$sw};
296 for my $sw (qw(blocksize)) {
297 defined(my $v = $opt->{$sw}) or next;
298 push @$cmd, "--$sw", $v;
300 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
301 push @$cmd, $src, $dst;
302 my $pid = spawn($cmd, undef, $rdr);
304 close $w or die "close: \$w: $!";
310 my $rp = waitpid($pid, 0);
311 if ($? || $rp != $pid) {
312 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
316 sub cpdb_loop ($$$;$$) {
317 my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
318 my ($pr, $fmt, $nr, $pfx);
320 $pr = $pr_data->{pr};
321 $fmt = $pr_data->{fmt};
322 $nr = \($pr_data->{nr});
323 $pfx = $pr_data->{pfx};
329 $it = $src->postlist_begin('');
330 $end = $src->postlist_end('');
332 } while (cpdb_retryable($src, $pfx));
336 for (; $it != $end; $it++) {
337 my $docid = $it->get_docid;
338 if (defined $reshard) {
339 my $dst_shard = $docid % $reshard;
340 next if $dst_shard != $cur_shard;
342 my $doc = $src->get_document($docid);
343 $dst->replace_document($docid, $doc);
344 if ($pr_data && !(++$$nr & 1023)) {
345 $pr->(sprintf($fmt, $$nr));
349 # unlike copydatabase(1), we don't copy spelling
350 # and synonym data (or other user metadata) since
351 # the Perl APIs don't expose iterators for them
352 # (and public-inbox does not use those features)
354 } while (cpdb_retryable($src, $pfx));
357 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
358 # to the overhead of Perl.
360 my ($args, $opt) = @_;
361 my ($old, $newdir) = @$args;
362 my $new = $newdir->dirname;
363 my ($src, $cur_shard);
365 PublicInbox::SearchIdx::load_xapian_writable() or die;
366 my $XapianDatabase = $PublicInbox::Search::X{Database};
367 if (ref($old) eq 'ARRAY') {
368 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
369 defined $cur_shard or
370 die "BUG: could not extract shard # from $new";
371 $reshard = $opt->{reshard};
372 defined $reshard or die 'BUG: got array src w/o --reshard';
374 # resharding, M:N copy means have full read access
377 my $sub = $XapianDatabase->new($_);
378 $src->add_database($sub);
380 $src = $XapianDatabase->new($_);
384 $src = $XapianDatabase->new($old);
389 if ($opt->{compact}) {
390 my $dir = dirname($new);
391 same_fs_or_die($dir, $new);
392 $ft = File::Temp->newdir("$new.compact-XXXXXX", DIR => $dir);
399 # like copydatabase(1), be sure we don't overwrite anything in case
401 my $creat = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
403 my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
404 my $dst = $XapianWritableDatabase->new($tmp, $creat);
405 my $pr = $opt->{-progress};
406 my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
407 my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
411 # update the only metadata key for v1:
412 my $lc = $src->get_metadata('last_commit');
413 $dst->set_metadata('last_commit', $lc) if $lc;
415 # only the first xapian shard (0) gets 'indexlevel'
416 if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
417 my $l = $src->get_metadata('indexlevel');
418 if ($l eq 'medium') {
419 $dst->set_metadata('indexlevel', $l);
423 my $tot = $src->get_doccount;
425 # we can only estimate when resharding,
426 # because removed spam causes slight imbalance
428 if (defined $cur_shard && $reshard > 1) {
429 $tot = int($tot/$reshard);
432 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
433 $pr->("$pfx copying $est$tot documents\n");
434 $pr_data->{fmt} = $fmt;
435 $pr_data->{total} = $tot;
438 } while (cpdb_retryable($src, $pfx));
440 if (defined $reshard) {
441 # we rely on document IDs matching NNTP article number,
442 # so we can't have the Xapian sharding DB support rewriting
443 # document IDs. Thus we iterate through each shard
447 my $old = $XapianDatabase->new($_);
448 cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
451 cpdb_loop($src, $dst, $pr_data);
454 $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
455 return unless $opt->{compact};
457 $src = $dst = undef; # flushes and closes
459 # this is probably the best place to do xapian-compact
460 # since $dst isn't readable by HTTP or NNTP clients, yet:
461 compact([ $tmp, $new ], $opt);
462 remove_tree($tmp) or die "failed to remove $tmp: $!\n";