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