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';
17 sub commit_changes ($$$) {
18 my ($ibx, $tmp, $opt) = @_;
20 my $reindex = $opt->{reindex};
21 my $im = $ibx->importer(0);
22 $im->lock_acquire if $reindex;
24 while (my ($old, $new) = each %$tmp) {
25 my @st = stat($old) or die "failed to stat($old): $!\n";
27 my $over = "$old/over.sqlite3";
28 if (-f $over) { # only for v1, v2 over is untouched
29 $over = PublicInbox::Over->new($over);
30 my $tmp_over = "$new/over.sqlite3";
31 $over->connect->sqlite_backup_to_file($tmp_over);
35 rename($old, "$new/old") or die "rename $old => $new/old: $!\n";
36 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
37 rename($new, $old) or die "rename $new => $old: $!\n";
38 my $prev = "$old/old";
39 remove_tree($prev) or die "failed to remove $prev: $!\n";
42 $opt->{-skip_lock} = 1;
43 PublicInbox::Admin::index_inbox($ibx, $opt);
44 # implicit lock_release
51 my ($cmd, $env, $opt) = @_;
52 if (ref($cmd->[0]) eq 'CODE') {
53 my $cb = shift(@$cmd); # $cb = cpdb()
54 defined(my $pid = fork) or die "fork: $!";
55 return $pid if $pid > 0;
56 eval { $cb->($cmd, $env, $opt) };
60 spawn($cmd, $env, $opt);
64 sub runnable_or_die ($) {
66 which($exe) or die "$exe not found in PATH\n";
69 sub prepare_reindex ($$) {
70 my ($ibx, $reindex) = @_;
71 if ($ibx->{version} == 1) {
72 my $dir = $ibx->search->xdir(1);
73 my $xdb = Search::Xapian::Database->new($dir);
74 if (my $lc = $xdb->get_metadata('last_commit')) {
75 $reindex->{from} = $lc;
78 my $v2w = $ibx->importer(0);
80 $v2w->git_dir_latest(\$max) or return;
81 my $from = $reindex->{from};
83 my $v = PublicInbox::Search::SCHEMA_VERSION();
84 foreach my $i (0..$max) {
85 $from->[$i] = $mm->last_commit_xap($v, $i);
90 sub progress_prepare ($) {
93 open my $null, '>', '/dev/null' or
94 die "failed to open /dev/null: $!\n";
95 $opt->{1} = fileno($null);
96 $opt->{-dev_null} = $null;
98 $opt->{-progress} = 1;
102 sub same_fs_or_die ($$) {
104 return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
105 die "$x and $y reside on different filesystems\n";
109 my ($ibx, $cmd, $env, $opt) = @_;
110 progress_prepare($opt ||= {});
111 my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
113 runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
115 my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
116 my $from; # per-epoch ranges
118 if (ref($exe) eq 'CODE') {
119 $reindex = $opt->{reindex} = {};
120 $from = $reindex->{from} = [];
121 require Search::Xapian::WritableDatabase;
123 runnable_or_die($exe);
126 my $old = $ibx->search->xdir(1);
127 -d $old or die "$old does not exist\n";
129 my $tmp = {}; # old partition => new (tmp) partition
130 my $v = $ibx->{version} ||= 1;
133 # we want temporary directories to be as deep as possible,
134 # so v2 partitions can keep "xap$SCHEMA_VERSION" on a separate FS.
136 my $old_parent = dirname($old);
137 same_fs_or_die($old_parent, $old);
138 $tmp->{$old} = tempdir('xapcmd-XXXXXXXX', DIR => $old_parent);
139 push @cmds, [ @$cmd, $old, $tmp->{$old} ];
141 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
142 while (defined(my $dn = readdir($dh))) {
143 if ($dn =~ /\A\d+\z/) {
144 my $tmpl = "$dn-XXXXXXXX";
145 my $dst = tempdir($tmpl, DIR => $old);
146 same_fs_or_die($old, $dst);
147 my $cur = "$old/$dn";
148 push @cmds, [@$cmd, $cur, $dst ];
150 } elsif ($dn eq '.' || $dn eq '..') {
151 } elsif ($dn =~ /\Aover\.sqlite3/) {
153 warn "W: skipping unknown dir: $old/$dn\n"
156 die "No Xapian parts found in $old\n" unless @cmds;
158 my $im = $ibx->importer(0);
159 my $max = $opt->{jobs} || scalar(@cmds);
160 $ibx->with_umask(sub {
163 # fine-grained locking if we prepare for reindex
165 prepare_reindex($ibx, $reindex);
168 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
171 while (scalar(keys(%pids)) < $max && scalar(@cmds)) {
173 $pids{xspawn($x, $env, $opt)} = $x;
176 while (scalar keys %pids) {
177 my $pid = waitpid(-1, 0);
178 my $x = delete $pids{$pid};
179 die join(' ', @$x)." failed: $?\n" if $?;
182 commit_changes($ibx, $tmp, $opt);
186 sub cpdb_retryable ($$) {
187 my ($src, $pfx) = @_;
188 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
189 warn "$pfx Xapian DB modified, reopening and retrying\n";
194 warn "$pfx E: ", ref($@), "\n";
200 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
201 # to the overhead of Perl.
203 my ($args, $env, $opt) = @_;
204 my ($old, $new) = @$args;
205 my $src = Search::Xapian::Database->new($old);
206 my $tmp = $opt->{compact} ? "$new.compact" : $new;
208 # like copydatabase(1), be sure we don't overwrite anything in case
210 my $creat = Search::Xapian::DB_CREATE();
211 my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
214 my ($nr, $tot, $fmt); # progress output
218 # update the only metadata key for v1:
219 my $lc = $src->get_metadata('last_commit');
220 $dst->set_metadata('last_commit', $lc) if $lc;
222 $it = $src->postlist_begin('');
223 $end = $src->postlist_end('');
224 $pfx = (split('/', $old))[-1].':';
225 if ($opt->{-progress}) {
227 $tot = $src->get_doccount;
228 $fmt = "$pfx % ".length($tot)."u/$tot\n";
229 warn "$pfx copying $tot documents\n";
232 } while (cpdb_retryable($src, $pfx));
236 while ($it != $end) {
237 my $docid = $it->get_docid;
238 my $doc = $src->get_document($docid);
239 $dst->replace_document($docid, $doc);
241 if ($fmt && !(++$nr & 1023)) {
242 warn(sprintf($fmt, $nr));
246 # unlike copydatabase(1), we don't copy spelling
247 # and synonym data (or other user metadata) since
248 # the Perl APIs don't expose iterators for them
249 # (and public-inbox does not use those features)
251 } while (cpdb_retryable($src, $pfx));
253 warn(sprintf($fmt, $nr)) if $fmt;
254 return unless $opt->{compact};
256 $src = $dst = undef; # flushes and closes
257 $pfx = undef unless $fmt;
259 warn "$pfx compacting...\n" if $pfx;
260 # this is probably the best place to do xapian-compact
261 # since $dst isn't readable by HTTP or NNTP clients, yet:
262 my $cmd = [ $XAPIAN_COMPACT, '--no-renumber', $tmp, $new ];
264 foreach my $fd (0..2) {
265 defined(my $dst = $opt->{$fd}) or next;
270 if ($pfx && pipe($r, $w)) {
271 $rdr->{1} = fileno($w);
273 my $pid = spawn($cmd, $env, $rdr);
275 close $w or die "close: \$w: $!";
281 my $rp = waitpid($pid, 0);
282 if ($? || $rp != $pid) {
283 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
285 remove_tree($tmp) or die "failed to remove $tmp: $!\n";