]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
xcpdb|compact: support --jobs/-j flag like gmake(1)
[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(jobs|j=i 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         $cb->($args, $opt);
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 process_queue {
106         my ($queue, $cb, $max, $opt) = @_;
107         if ($max <= 1) {
108                 while (defined(my $args = shift @$queue)) {
109                         $cb->($args, $opt);
110                 }
111                 return;
112         }
113
114         # run in parallel:
115         my %pids;
116         while (@$queue) {
117                 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
118                         my $args = shift @$queue;
119                         $pids{cb_spawn($cb, $args, $opt)} = $args;
120                 }
121
122                 while (scalar keys %pids) {
123                         my $pid = waitpid(-1, 0);
124                         my $args = delete $pids{$pid};
125                         die join(' ', @$args)." failed: $?\n" if $?;
126                 }
127         }
128 }
129
130 sub run {
131         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
132         my $cb = \&${\"PublicInbox::Xapcmd::$task"};
133         progress_prepare($opt ||= {});
134         my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
135         runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
136         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
137         my $from; # per-epoch ranges
138
139         if (!$opt->{-coarse_lock}) {
140                 $reindex = $opt->{reindex} = {};
141                 $from = $reindex->{from} = [];
142                 require Search::Xapian::WritableDatabase;
143         }
144
145         $ibx->umask_prepare;
146         my $old = $ibx->search->xdir(1);
147         -d $old or die "$old does not exist\n";
148
149         my $tmp = PublicInbox::Xtmpdirs->new;
150         my $v = $ibx->{version} ||= 1;
151         my @q;
152
153         # we want temporary directories to be as deep as possible,
154         # so v2 partitions can keep "xap$SCHEMA_VERSION" on a separate FS.
155         if ($v == 1) {
156                 my $old_parent = dirname($old);
157                 same_fs_or_die($old_parent, $old);
158                 $tmp->{$old} = tempdir('xapcmd-XXXXXXXX', DIR => $old_parent);
159                 push @q, [ $old, $tmp->{$old} ];
160         } else {
161                 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
162                 while (defined(my $dn = readdir($dh))) {
163                         if ($dn =~ /\A\d+\z/) {
164                                 my $tmpl = "$dn-XXXXXXXX";
165                                 my $dst = tempdir($tmpl, DIR => $old);
166                                 same_fs_or_die($old, $dst);
167                                 my $cur = "$old/$dn";
168                                 push @q, [ $cur, $dst ];
169                                 $tmp->{$cur} = $dst;
170                         } elsif ($dn eq '.' || $dn eq '..') {
171                         } elsif ($dn =~ /\Aover\.sqlite3/) {
172                         } else {
173                                 warn "W: skipping unknown dir: $old/$dn\n"
174                         }
175                 }
176                 die "No Xapian parts found in $old\n" unless @q;
177         }
178         my $im = $ibx->importer(0);
179         my $max = $opt->{jobs} || scalar(@q);
180         $ibx->with_umask(sub {
181                 $im->lock_acquire;
182
183                 # fine-grained locking if we prepare for reindex
184                 if (!$opt->{-coarse_lock}) {
185                         prepare_reindex($ibx, $reindex);
186                         $im->lock_release;
187                 }
188
189                 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
190                 process_queue(\@q, $cb, $max, $opt);
191                 commit_changes($ibx, $tmp, $opt);
192         });
193 }
194
195 sub cpdb_retryable ($$) {
196         my ($src, $pfx) = @_;
197         if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
198                 warn "$pfx Xapian DB modified, reopening and retrying\n";
199                 $src->reopen;
200                 return 1;
201         }
202         if ($@) {
203                 warn "$pfx E: ", ref($@), "\n";
204                 die;
205         }
206         0;
207 }
208
209 sub progress_pfx ($) {
210         my @p = split('/', $_[0]);
211
212         # return "xap15/0" for v2, or "xapian15" for v1:
213         ($p[-1] =~ /\A\d+\z/) ? "$p[-2]/$p[-1]" : $p[-1];
214 }
215
216 # xapian-compact wrapper
217 sub compact ($$) {
218         my ($args, $opt) = @_;
219         my ($src, $dst) = @$args;
220         my ($r, $w);
221         my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
222         my $pr = $opt->{-progress};
223         my $rdr = {};
224
225         foreach my $fd (0..2) {
226                 defined(my $dfd = $opt->{$fd}) or next;
227                 $rdr->{$fd} = $dfd;
228         }
229         $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
230
231         # we rely on --no-renumber to keep docids synched to NNTP
232         my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
233         for my $sw (qw(no-full fuller)) {
234                 push @$cmd, "--$sw" if $opt->{$sw};
235         }
236         for my $sw (qw(blocksize)) {
237                 defined(my $v = $opt->{$sw}) or next;
238                 push @$cmd, "--$sw", $v;
239         }
240         $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
241         push @$cmd, $src, $dst;
242         my $pid = spawn($cmd, undef, $rdr);
243         if ($pr) {
244                 close $w or die "close: \$w: $!";
245                 foreach (<$r>) {
246                         s/\r/\r$pfx /g;
247                         $pr->("$pfx $_");
248                 }
249         }
250         my $rp = waitpid($pid, 0);
251         if ($? || $rp != $pid) {
252                 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
253         }
254 }
255
256 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
257 # to the overhead of Perl.
258 sub cpdb ($$) {
259         my ($args, $opt) = @_;
260         my ($old, $new) = @$args;
261         my $src = Search::Xapian::Database->new($old);
262         my ($xtmp, $tmp);
263         if ($opt->{compact}) {
264                 my $newdir = dirname($new);
265                 same_fs_or_die($newdir, $new);
266                 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
267                 $xtmp = PublicInbox::Xtmpdirs->new;
268                 $xtmp->{$new} = $tmp;
269         } else {
270                 $tmp = $new;
271         }
272
273         # like copydatabase(1), be sure we don't overwrite anything in case
274         # of other bugs:
275         my $creat = Search::Xapian::DB_CREATE();
276         my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
277         my ($it, $end);
278         my ($nr, $tot, $fmt); # progress output
279         my $pr = $opt->{-progress};
280         my $pfx = $opt->{-progress_pfx} = progress_pfx($old);
281
282         do {
283                 eval {
284                         # update the only metadata key for v1:
285                         my $lc = $src->get_metadata('last_commit');
286                         $dst->set_metadata('last_commit', $lc) if $lc;
287
288                         $it = $src->postlist_begin('');
289                         $end = $src->postlist_end('');
290                         if ($pr) {
291                                 $nr = 0;
292                                 $tot = $src->get_doccount;
293                                 $fmt = "$pfx % ".length($tot)."u/$tot\n";
294                                 $pr->("$pfx copying $tot documents\n");
295                         }
296                 };
297         } while (cpdb_retryable($src, $pfx));
298
299         do {
300                 eval {
301                         while ($it != $end) {
302                                 my $docid = $it->get_docid;
303                                 my $doc = $src->get_document($docid);
304                                 $dst->replace_document($docid, $doc);
305                                 $it->inc;
306                                 if ($pr && !(++$nr & 1023)) {
307                                         $pr->(sprintf($fmt, $nr));
308                                 }
309                         }
310
311                         # unlike copydatabase(1), we don't copy spelling
312                         # and synonym data (or other user metadata) since
313                         # the Perl APIs don't expose iterators for them
314                         # (and public-inbox does not use those features)
315                 };
316         } while (cpdb_retryable($src, $pfx));
317
318         $pr->(sprintf($fmt, $nr)) if $pr;
319         return unless $xtmp;
320
321         $src = $dst = undef; # flushes and closes
322
323         # this is probably the best place to do xapian-compact
324         # since $dst isn't readable by HTTP or NNTP clients, yet:
325         compact([ $tmp, $new ], $opt);
326         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
327         $xtmp->done;
328 }
329
330 # slightly easier-to-manage manage than END{} blocks
331 package PublicInbox::Xtmpdirs;
332 use strict;
333 use warnings;
334 use File::Path qw(remove_tree);
335 my %owner;
336
337 sub new {
338         # http://www.tldp.org/LDP/abs/html/exitcodes.html
339         $SIG{INT} = sub { exit(130) };
340         $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
341         my $self = bless {}, $_[0]; # old partition => new (tmp) partition
342         $owner{"$self"} = $$;
343         $self;
344 }
345
346 sub done {
347         my ($self) = @_;
348         delete $owner{"$self"};
349         $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
350         %$self = ();
351 }
352
353 sub DESTROY {
354         my ($self) = @_;
355         my $owner_pid = delete $owner{"$self"} or return;
356         return if $owner_pid != $$;
357         foreach my $new (values %$self) {
358                 remove_tree($new) unless -d "$new/old";
359         }
360         $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
361 }
362
363 1;