]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
xapcmd: avoid EXDEV when finalizing changes
[public-inbox.git] / lib / PublicInbox / Xapcmd.pm
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;
4 use strict;
5 use warnings;
6 use PublicInbox::Spawn qw(which spawn);
7 use PublicInbox::Over;
8 use PublicInbox::Search;
9 use File::Temp qw(tempdir);
10 use File::Path qw(remove_tree);
11 use File::Basename qw(dirname);
12
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
17 sub commit_changes ($$$) {
18         my ($ibx, $tmp, $opt) = @_;
19
20         my $reindex = $opt->{reindex};
21         my $im = $ibx->importer(0);
22         $im->lock_acquire if $reindex;
23
24         while (my ($old, $new) = each %$tmp) {
25                 my @st = stat($old) or die "failed to stat($old): $!\n";
26
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);
32                         $over = undef;
33                 }
34
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";
40         }
41         if ($reindex) {
42                 $opt->{-skip_lock} = 1;
43                 PublicInbox::Admin::index_inbox($ibx, $opt);
44                 # implicit lock_release
45         } else {
46                 $im->lock_release;
47         }
48 }
49
50 sub xspawn {
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) };
57                 die $@ if $@;
58                 exit 0;
59         } else {
60                 spawn($cmd, $env, $opt);
61         }
62 }
63
64 sub runnable_or_die ($) {
65         my ($exe) = @_;
66         which($exe) or die "$exe not found in PATH\n";
67 }
68
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;
76                 }
77         } else { # v2
78                 my $v2w = $ibx->importer(0);
79                 my $max;
80                 $v2w->git_dir_latest(\$max) or return;
81                 my $from = $reindex->{from};
82                 my $mm = $ibx->mm;
83                 my $v = PublicInbox::Search::SCHEMA_VERSION();
84                 foreach my $i (0..$max) {
85                         $from->[$i] = $mm->last_commit_xap($v, $i);
86                 }
87         }
88 }
89
90 sub progress_prepare ($) {
91         my ($opt) = @_;
92         if ($opt->{quiet}) {
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;
97         } else {
98                 $opt->{-progress} = 1;
99         }
100 }
101
102 sub same_fs_or_die ($$) {
103         my ($x, $y) = @_;
104         return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
105         die "$x and $y reside on different filesystems\n";
106 }
107
108 sub run {
109         my ($ibx, $cmd, $env, $opt) = @_;
110         progress_prepare($opt ||= {});
111         my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
112         my $exe = $cmd->[0];
113         runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
114
115         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
116         my $from; # per-epoch ranges
117
118         if (ref($exe) eq 'CODE') {
119                 $reindex = $opt->{reindex} = {};
120                 $from = $reindex->{from} = [];
121                 require Search::Xapian::WritableDatabase;
122         } else {
123                 runnable_or_die($exe);
124         }
125         $ibx->umask_prepare;
126         my $old = $ibx->search->xdir(1);
127         -d $old or die "$old does not exist\n";
128
129         my $tmp = {}; # old partition => new (tmp) partition
130         my $v = $ibx->{version} ||= 1;
131         my @cmds;
132
133         # we want temporary directories to be as deep as possible,
134         # so v2 partitions can keep "xap$SCHEMA_VERSION" on a separate FS.
135         if ($v == 1) {
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} ];
140         } else {
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 ];
149                                 $tmp->{$cur} = $dst;
150                         } elsif ($dn eq '.' || $dn eq '..') {
151                         } elsif ($dn =~ /\Aover\.sqlite3/) {
152                         } else {
153                                 warn "W: skipping unknown dir: $old/$dn\n"
154                         }
155                 }
156                 die "No Xapian parts found in $old\n" unless @cmds;
157         }
158         my $im = $ibx->importer(0);
159         my $max = $opt->{jobs} || scalar(@cmds);
160         $ibx->with_umask(sub {
161                 $im->lock_acquire;
162
163                 # fine-grained locking if we prepare for reindex
164                 if ($reindex) {
165                         prepare_reindex($ibx, $reindex);
166                         $im->lock_release;
167                 }
168                 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
169                 my %pids;
170                 while (@cmds) {
171                         while (scalar(keys(%pids)) < $max && scalar(@cmds)) {
172                                 my $x = shift @cmds;
173                                 $pids{xspawn($x, $env, $opt)} = $x;
174                         }
175
176                         while (scalar keys %pids) {
177                                 my $pid = waitpid(-1, 0);
178                                 my $x = delete $pids{$pid};
179                                 die join(' ', @$x)." failed: $?\n" if $?;
180                         }
181                 }
182                 commit_changes($ibx, $tmp, $opt);
183         });
184 }
185
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";
190                 $src->reopen;
191                 return 1;
192         }
193         if ($@) {
194                 warn "$pfx E: ", ref($@), "\n";
195                 die;
196         }
197         0;
198 }
199
200 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
201 # to the overhead of Perl.
202 sub cpdb {
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;
207
208         # like copydatabase(1), be sure we don't overwrite anything in case
209         # of other bugs:
210         my $creat = Search::Xapian::DB_CREATE();
211         my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
212         my ($it, $end);
213         my $pfx = '';
214         my ($nr, $tot, $fmt); # progress output
215
216         do {
217                 eval {
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;
221
222                         $it = $src->postlist_begin('');
223                         $end = $src->postlist_end('');
224                         $pfx = (split('/', $old))[-1].':';
225                         if ($opt->{-progress}) {
226                                 $nr = 0;
227                                 $tot = $src->get_doccount;
228                                 $fmt = "$pfx % ".length($tot)."u/$tot\n";
229                                 warn "$pfx copying $tot documents\n";
230                         }
231                 };
232         } while (cpdb_retryable($src, $pfx));
233
234         do {
235                 eval {
236                         while ($it != $end) {
237                                 my $docid = $it->get_docid;
238                                 my $doc = $src->get_document($docid);
239                                 $dst->replace_document($docid, $doc);
240                                 $it->inc;
241                                 if ($fmt && !(++$nr & 1023)) {
242                                         warn(sprintf($fmt, $nr));
243                                 }
244                         }
245
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)
250                 };
251         } while (cpdb_retryable($src, $pfx));
252
253         warn(sprintf($fmt, $nr)) if $fmt;
254         return unless $opt->{compact};
255
256         $src = $dst = undef; # flushes and closes
257         $pfx = undef unless $fmt;
258
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 ];
263         my $rdr = {};
264         foreach my $fd (0..2) {
265                 defined(my $dst = $opt->{$fd}) or next;
266                 $rdr->{$fd} = $dst;
267         }
268
269         my ($r, $w);
270         if ($pfx && pipe($r, $w)) {
271                 $rdr->{1} = fileno($w);
272         }
273         my $pid = spawn($cmd, $env, $rdr);
274         if ($pfx) {
275                 close $w or die "close: \$w: $!";
276                 foreach (<$r>) {
277                         s/\r/\r$pfx /g;
278                         warn "$pfx $_";
279                 }
280         }
281         my $rp = waitpid($pid, 0);
282         if ($? || $rp != $pid) {
283                 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
284         }
285         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
286 }
287
288 1;