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(quiet|q blocksize|b=s no-full|n fuller|F);
18 sub commit_changes ($$$) {
19 my ($ibx, $tmp, $opt) = @_;
21 my $reindex = $opt->{reindex};
22 my $im = $ibx->importer(0);
23 $im->lock_acquire if !$opt->{-coarse_lock};
25 while (my ($old, $new) = each %$tmp) {
26 my @st = stat($old) or die "failed to stat($old): $!\n";
28 my $over = "$old/over.sqlite3";
29 if (-f $over) { # only for v1, v2 over is untouched
30 $over = PublicInbox::Over->new($over);
31 my $tmp_over = "$new/over.sqlite3";
32 $over->connect->sqlite_backup_to_file($tmp_over);
35 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
37 # Xtmpdir->DESTROY won't remove $new after this:
38 rename($old, "$new/old") or die "rename $old => $new/old: $!\n";
39 rename($new, $old) or die "rename $new => $old: $!\n";
40 my $prev = "$old/old";
41 remove_tree($prev) or die "failed to remove $prev: $!\n";
44 if (!$opt->{-coarse_lock}) {
45 $opt->{-skip_lock} = 1;
46 PublicInbox::Admin::index_inbox($ibx, $opt);
47 # implicit lock_release
54 my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
55 defined(my $pid = fork) or die "fork: $!";
56 return $pid if $pid > 0;
57 eval { $cb->($args, $opt) };
62 sub runnable_or_die ($) {
64 which($exe) or die "$exe not found in PATH\n";
67 sub prepare_reindex ($$) {
68 my ($ibx, $reindex) = @_;
69 if ($ibx->{version} == 1) {
70 my $dir = $ibx->search->xdir(1);
71 my $xdb = Search::Xapian::Database->new($dir);
72 if (my $lc = $xdb->get_metadata('last_commit')) {
73 $reindex->{from} = $lc;
76 my $v2w = $ibx->importer(0);
78 $v2w->git_dir_latest(\$max) or return;
79 my $from = $reindex->{from};
81 my $v = PublicInbox::Search::SCHEMA_VERSION();
82 foreach my $i (0..$max) {
83 $from->[$i] = $mm->last_commit_xap($v, $i);
88 sub progress_prepare ($) {
91 open my $null, '>', '/dev/null' or
92 die "failed to open /dev/null: $!\n";
93 $opt->{1} = fileno($null);
94 $opt->{-dev_null} = $null;
96 $opt->{-progress} = sub { print STDERR @_ };
100 sub same_fs_or_die ($$) {
102 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
103 die "$x and $y reside on different filesystems\n";
107 my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
108 my $cb = \&${\"PublicInbox::Xapcmd::$task"};
109 progress_prepare($opt ||= {});
110 my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
111 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
112 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
113 my $from; # per-epoch ranges
115 if (!$opt->{-coarse_lock}) {
116 $reindex = $opt->{reindex} = {};
117 $from = $reindex->{from} = [];
118 require Search::Xapian::WritableDatabase;
122 my $old = $ibx->search->xdir(1);
123 -d $old or die "$old does not exist\n";
125 my $tmp = PublicInbox::Xtmpdirs->new;
126 my $v = $ibx->{version} ||= 1;
129 # we want temporary directories to be as deep as possible,
130 # so v2 partitions can keep "xap$SCHEMA_VERSION" on a separate FS.
132 my $old_parent = dirname($old);
133 same_fs_or_die($old_parent, $old);
134 $tmp->{$old} = tempdir('xapcmd-XXXXXXXX', DIR => $old_parent);
135 push @q, [ $old, $tmp->{$old} ];
137 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
138 while (defined(my $dn = readdir($dh))) {
139 if ($dn =~ /\A\d+\z/) {
140 my $tmpl = "$dn-XXXXXXXX";
141 my $dst = tempdir($tmpl, DIR => $old);
142 same_fs_or_die($old, $dst);
143 my $cur = "$old/$dn";
144 push @q, [ $cur, $dst ];
146 } elsif ($dn eq '.' || $dn eq '..') {
147 } elsif ($dn =~ /\Aover\.sqlite3/) {
149 warn "W: skipping unknown dir: $old/$dn\n"
152 die "No Xapian parts found in $old\n" unless @q;
154 my $im = $ibx->importer(0);
155 my $max = $opt->{jobs} || scalar(@q);
156 $ibx->with_umask(sub {
159 # fine-grained locking if we prepare for reindex
160 if (!$opt->{-coarse_lock}) {
161 prepare_reindex($ibx, $reindex);
165 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
168 while (scalar(keys(%pids)) < $max && scalar(@q)) {
170 $pids{cb_spawn($cb, $args, $opt)} = $args;
173 while (scalar keys %pids) {
174 my $pid = waitpid(-1, 0);
175 my $args = delete $pids{$pid};
176 die join(' ', @$args)." failed: $?\n" if $?;
179 commit_changes($ibx, $tmp, $opt);
183 sub cpdb_retryable ($$) {
184 my ($src, $pfx) = @_;
185 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
186 warn "$pfx Xapian DB modified, reopening and retrying\n";
191 warn "$pfx E: ", ref($@), "\n";
197 sub progress_pfx ($) {
198 my @p = split('/', $_[0]);
200 # return "xap15/0" for v2, or "xapian15" for v1:
201 ($p[-1] =~ /\A\d+\z/) ? "$p[-2]/$p[-1]" : $p[-1];
204 # xapian-compact wrapper
206 my ($args, $opt) = @_;
207 my ($src, $dst) = @$args;
209 my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
210 my $pr = $opt->{-progress};
213 foreach my $fd (0..2) {
214 defined(my $dfd = $opt->{$fd}) or next;
217 $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
219 # we rely on --no-renumber to keep docids synched to NNTP
220 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
221 for my $sw (qw(no-full fuller)) {
222 push @$cmd, "--$sw" if $opt->{$sw};
224 for my $sw (qw(blocksize)) {
225 defined(my $v = $opt->{$sw}) or next;
226 push @$cmd, "--$sw", $v;
228 $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
229 push @$cmd, $src, $dst;
230 my $pid = spawn($cmd, undef, $rdr);
232 close $w or die "close: \$w: $!";
238 my $rp = waitpid($pid, 0);
239 if ($? || $rp != $pid) {
240 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
244 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
245 # to the overhead of Perl.
247 my ($args, $opt) = @_;
248 my ($old, $new) = @$args;
249 my $src = Search::Xapian::Database->new($old);
251 if ($opt->{compact}) {
252 my $newdir = dirname($new);
253 same_fs_or_die($newdir, $new);
254 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
255 $xtmp = PublicInbox::Xtmpdirs->new;
256 $xtmp->{$new} = $tmp;
261 # like copydatabase(1), be sure we don't overwrite anything in case
263 my $creat = Search::Xapian::DB_CREATE();
264 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
266 my ($nr, $tot, $fmt); # progress output
267 my $pr = $opt->{-progress};
268 my $pfx = $opt->{-progress_pfx} = progress_pfx($old);
272 # update the only metadata key for v1:
273 my $lc = $src->get_metadata('last_commit');
274 $dst->set_metadata('last_commit', $lc) if $lc;
276 $it = $src->postlist_begin('');
277 $end = $src->postlist_end('');
280 $tot = $src->get_doccount;
281 $fmt = "$pfx % ".length($tot)."u/$tot\n";
282 $pr->("$pfx copying $tot documents\n");
285 } while (cpdb_retryable($src, $pfx));
289 while ($it != $end) {
290 my $docid = $it->get_docid;
291 my $doc = $src->get_document($docid);
292 $dst->replace_document($docid, $doc);
294 if ($pr && !(++$nr & 1023)) {
295 $pr->(sprintf($fmt, $nr));
299 # unlike copydatabase(1), we don't copy spelling
300 # and synonym data (or other user metadata) since
301 # the Perl APIs don't expose iterators for them
302 # (and public-inbox does not use those features)
304 } while (cpdb_retryable($src, $pfx));
306 $pr->(sprintf($fmt, $nr)) if $pr;
309 $src = $dst = undef; # flushes and closes
311 # this is probably the best place to do xapian-compact
312 # since $dst isn't readable by HTTP or NNTP clients, yet:
313 compact([ $tmp, $new ], $opt);
314 remove_tree($tmp) or die "failed to remove $tmp: $!\n";
318 # slightly easier-to-manage manage than END{} blocks
319 package PublicInbox::Xtmpdirs;
322 use File::Path qw(remove_tree);
326 # http://www.tldp.org/LDP/abs/html/exitcodes.html
327 $SIG{INT} = sub { exit(130) };
328 $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
329 my $self = bless {}, $_[0]; # old partition => new (tmp) partition
330 $owner{"$self"} = $$;
336 delete $owner{"$self"};
337 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
343 my $owner_pid = delete $owner{"$self"} or return;
344 return if $owner_pid != $$;
345 foreach my $new (values %$self) {
346 remove_tree($new) unless -d "$new/old";
348 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';