]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
488c6165c3d03af5323f3b8383ff47b1844c8970
[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 !$opt->{-coarse_lock};
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                 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
35
36                 # Xtmpdir->DESTROY won't remove $new after this:
37                 rename($old, "$new/old") or die "rename $old => $new/old: $!\n";
38                 rename($new, $old) or die "rename $new => $old: $!\n";
39                 my $prev = "$old/old";
40                 remove_tree($prev) or die "failed to remove $prev: $!\n";
41         }
42         $tmp->done;
43         if (!$opt->{-coarse_lock}) {
44                 $opt->{-skip_lock} = 1;
45                 PublicInbox::Admin::index_inbox($ibx, $opt);
46                 # implicit lock_release
47         } else {
48                 $im->lock_release;
49         }
50 }
51
52 sub cb_spawn {
53         my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
54         defined(my $pid = fork) or die "fork: $!";
55         return $pid if $pid > 0;
56         eval { $cb->($args, $opt) };
57         die $@ if $@;
58         exit 0;
59 }
60
61 sub runnable_or_die ($) {
62         my ($exe) = @_;
63         which($exe) or die "$exe not found in PATH\n";
64 }
65
66 sub prepare_reindex ($$) {
67         my ($ibx, $reindex) = @_;
68         if ($ibx->{version} == 1) {
69                 my $dir = $ibx->search->xdir(1);
70                 my $xdb = Search::Xapian::Database->new($dir);
71                 if (my $lc = $xdb->get_metadata('last_commit')) {
72                         $reindex->{from} = $lc;
73                 }
74         } else { # v2
75                 my $v2w = $ibx->importer(0);
76                 my $max;
77                 $v2w->git_dir_latest(\$max) or return;
78                 my $from = $reindex->{from};
79                 my $mm = $ibx->mm;
80                 my $v = PublicInbox::Search::SCHEMA_VERSION();
81                 foreach my $i (0..$max) {
82                         $from->[$i] = $mm->last_commit_xap($v, $i);
83                 }
84         }
85 }
86
87 sub progress_prepare ($) {
88         my ($opt) = @_;
89         if ($opt->{quiet}) {
90                 open my $null, '>', '/dev/null' or
91                         die "failed to open /dev/null: $!\n";
92                 $opt->{1} = fileno($null);
93                 $opt->{-dev_null} = $null;
94         } else {
95                 $opt->{-progress} = sub { print STDERR @_ };
96         }
97 }
98
99 sub same_fs_or_die ($$) {
100         my ($x, $y) = @_;
101         return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
102         die "$x and $y reside on different filesystems\n";
103 }
104
105 sub run {
106         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
107         my $cb = \&${\"PublicInbox::Xapcmd::$task"};
108         progress_prepare($opt ||= {});
109         my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
110         runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
111         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
112         my $from; # per-epoch ranges
113
114         if (!$opt->{-coarse_lock}) {
115                 $reindex = $opt->{reindex} = {};
116                 $from = $reindex->{from} = [];
117                 require Search::Xapian::WritableDatabase;
118         }
119
120         $ibx->umask_prepare;
121         my $old = $ibx->search->xdir(1);
122         -d $old or die "$old does not exist\n";
123
124         my $tmp = PublicInbox::Xtmpdirs->new;
125         my $v = $ibx->{version} ||= 1;
126         my @q;
127
128         # we want temporary directories to be as deep as possible,
129         # so v2 partitions can keep "xap$SCHEMA_VERSION" on a separate FS.
130         if ($v == 1) {
131                 my $old_parent = dirname($old);
132                 same_fs_or_die($old_parent, $old);
133                 $tmp->{$old} = tempdir('xapcmd-XXXXXXXX', DIR => $old_parent);
134                 push @q, [ $old, $tmp->{$old} ];
135         } else {
136                 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
137                 while (defined(my $dn = readdir($dh))) {
138                         if ($dn =~ /\A\d+\z/) {
139                                 my $tmpl = "$dn-XXXXXXXX";
140                                 my $dst = tempdir($tmpl, DIR => $old);
141                                 same_fs_or_die($old, $dst);
142                                 my $cur = "$old/$dn";
143                                 push @q, [ $cur, $dst ];
144                                 $tmp->{$cur} = $dst;
145                         } elsif ($dn eq '.' || $dn eq '..') {
146                         } elsif ($dn =~ /\Aover\.sqlite3/) {
147                         } else {
148                                 warn "W: skipping unknown dir: $old/$dn\n"
149                         }
150                 }
151                 die "No Xapian parts found in $old\n" unless @q;
152         }
153         my $im = $ibx->importer(0);
154         my $max = $opt->{jobs} || scalar(@q);
155         $ibx->with_umask(sub {
156                 $im->lock_acquire;
157
158                 # fine-grained locking if we prepare for reindex
159                 if (!$opt->{-coarse_lock}) {
160                         prepare_reindex($ibx, $reindex);
161                         $im->lock_release;
162                 }
163
164                 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
165                 my %pids;
166                 while (@q) {
167                         while (scalar(keys(%pids)) < $max && scalar(@q)) {
168                                 my $args = shift @q;
169                                 $pids{cb_spawn($cb, $args, $opt)} = $args;
170                         }
171
172                         while (scalar keys %pids) {
173                                 my $pid = waitpid(-1, 0);
174                                 my $args = delete $pids{$pid};
175                                 die join(' ', @$args)." failed: $?\n" if $?;
176                         }
177                 }
178                 commit_changes($ibx, $tmp, $opt);
179         });
180 }
181
182 sub cpdb_retryable ($$) {
183         my ($src, $pfx) = @_;
184         if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
185                 warn "$pfx Xapian DB modified, reopening and retrying\n";
186                 $src->reopen;
187                 return 1;
188         }
189         if ($@) {
190                 warn "$pfx E: ", ref($@), "\n";
191                 die;
192         }
193         0;
194 }
195
196 sub progress_pfx ($) {
197         my @p = split('/', $_[0]);
198
199         # return "xap15/0" for v2, or "xapian15" for v1:
200         ($p[-1] =~ /\A\d+\z/) ? "$p[-2]/$p[-1]" : $p[-1];
201 }
202
203 # xapian-compact wrapper
204 sub compact ($$) {
205         my ($args, $opt) = @_;
206         my ($src, $dst) = @$args;
207         my ($r, $w);
208         my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
209         my $pr = $opt->{-progress};
210         my $rdr = {};
211
212         foreach my $fd (0..2) {
213                 defined(my $dfd = $opt->{$fd}) or next;
214                 $rdr->{$fd} = $dfd;
215         }
216         if ($pr) {
217                 $pr->("$pfx compacting...\n");
218                 $rdr->{1} = fileno($w) if pipe($r, $w);
219         }
220
221         # we rely on --no-renumber to keep docids synched to NNTP
222         my $cmd = [ $XAPIAN_COMPACT, '--no-renumber', $src, $dst ];
223         my $pid = spawn($cmd, undef, $rdr);
224         if ($pr) {
225                 close $w or die "close: \$w: $!";
226                 foreach (<$r>) {
227                         s/\r/\r$pfx /g;
228                         $pr->("$pfx $_");
229                 }
230         }
231         my $rp = waitpid($pid, 0);
232         if ($? || $rp != $pid) {
233                 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
234         }
235 }
236
237 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
238 # to the overhead of Perl.
239 sub cpdb ($$) {
240         my ($args, $opt) = @_;
241         my ($old, $new) = @$args;
242         my $src = Search::Xapian::Database->new($old);
243         my $tmp = $opt->{compact} ? "$new.compact" : $new;
244
245         # like copydatabase(1), be sure we don't overwrite anything in case
246         # of other bugs:
247         my $creat = Search::Xapian::DB_CREATE();
248         my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
249         my ($it, $end);
250         my ($nr, $tot, $fmt); # progress output
251         my $pr = $opt->{-progress};
252         my $pfx = $opt->{-progress_pfx} = progress_pfx($old);
253
254         do {
255                 eval {
256                         # update the only metadata key for v1:
257                         my $lc = $src->get_metadata('last_commit');
258                         $dst->set_metadata('last_commit', $lc) if $lc;
259
260                         $it = $src->postlist_begin('');
261                         $end = $src->postlist_end('');
262                         if ($pr) {
263                                 $nr = 0;
264                                 $tot = $src->get_doccount;
265                                 $fmt = "$pfx % ".length($tot)."u/$tot\n";
266                                 $pr->("$pfx copying $tot documents\n");
267                         }
268                 };
269         } while (cpdb_retryable($src, $pfx));
270
271         do {
272                 eval {
273                         while ($it != $end) {
274                                 my $docid = $it->get_docid;
275                                 my $doc = $src->get_document($docid);
276                                 $dst->replace_document($docid, $doc);
277                                 $it->inc;
278                                 if ($pr && !(++$nr & 1023)) {
279                                         $pr->(sprintf($fmt, $nr));
280                                 }
281                         }
282
283                         # unlike copydatabase(1), we don't copy spelling
284                         # and synonym data (or other user metadata) since
285                         # the Perl APIs don't expose iterators for them
286                         # (and public-inbox does not use those features)
287                 };
288         } while (cpdb_retryable($src, $pfx));
289
290         $pr->(sprintf($fmt, $nr)) if $pr;
291         return unless $opt->{compact};
292
293         $src = $dst = undef; # flushes and closes
294
295         # this is probably the best place to do xapian-compact
296         # since $dst isn't readable by HTTP or NNTP clients, yet:
297         compact([ $tmp, $new ], $opt);
298         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
299 }
300
301 # slightly easier-to-manage manage than END{} blocks
302 package PublicInbox::Xtmpdirs;
303 use strict;
304 use warnings;
305 use File::Path qw(remove_tree);
306 my %owner;
307
308 sub new {
309         # http://www.tldp.org/LDP/abs/html/exitcodes.html
310         $SIG{INT} = sub { exit(130) };
311         $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
312         my $self = bless {}, $_[0]; # old partition => new (tmp) partition
313         $owner{"$self"} = $$;
314         $self;
315 }
316
317 sub done {
318         my ($self) = @_;
319         delete $owner{"$self"};
320         $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
321         %$self = ();
322 }
323
324 sub DESTROY {
325         my ($self) = @_;
326         my $owner_pid = delete $owner{"$self"} or return;
327         return if $owner_pid != $$;
328         foreach my $new (values %$self) {
329                 remove_tree($new) unless -d "$new/old";
330         }
331         $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
332 }
333
334 1;