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