]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
819d7829d37dbd95398fcaebb2163365f29d74a2
[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         my $reshard = $opt->{reshard};
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         my @old_shard;
27
28         while (my ($old, $new) = each %$tmp) {
29                 my @st = stat($old);
30                 if (!@st && !defined($opt->{reshard})) {
31                         die "failed to stat($old): $!";
32                 }
33
34                 my $over = "$old/over.sqlite3";
35                 if (-f $over) { # only for v1, v2 over is untouched
36                         defined $new or die "BUG: $over exists when culling v2";
37                         $over = PublicInbox::Over->new($over);
38                         my $tmp_over = "$new/over.sqlite3";
39                         $over->connect->sqlite_backup_to_file($tmp_over);
40                         $over = undef;
41                 }
42
43                 if (!defined($new)) { # culled shard
44                         push @old_shard, $old;
45                         next;
46                 }
47
48                 if (@st) {
49                         chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
50                         rename($old, "$new/old") or
51                                         die "rename $old => $new/old: $!\n";
52                 }
53                 # Xtmpdir->DESTROY won't remove $new after this:
54                 rename($new, $old) or die "rename $new => $old: $!\n";
55                 if (@st) {
56                         my $prev = "$old/old";
57                         remove_tree($prev) or
58                                 die "failed to remove $prev: $!\n";
59                 }
60         }
61         remove_tree(@old_shard);
62         $tmp->done;
63         if (!$opt->{-coarse_lock}) {
64                 $opt->{-skip_lock} = 1;
65
66                 if ($im->can('count_shards')) {
67                         my $pr = $opt->{-progress};
68                         my $n = $im->count_shards;
69                         if (defined $reshard && $n != $reshard) {
70                                 die
71 "BUG: counted $n shards after resharding to $reshard";
72                         }
73                         my $prev = $im->{shards};
74                         if ($pr && $prev != $n) {
75                                 $pr->("shard count changed: $prev => $n\n");
76                                 $im->{shards} = $n;
77                         }
78                 }
79
80                 PublicInbox::Admin::index_inbox($ibx, $opt);
81                 # implicit lock_release
82         } else {
83                 $im->lock_release;
84         }
85 }
86
87 sub cb_spawn {
88         my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
89         defined(my $pid = fork) or die "fork: $!";
90         return $pid if $pid > 0;
91         $cb->($args, $opt);
92         exit 0;
93 }
94
95 sub runnable_or_die ($) {
96         my ($exe) = @_;
97         which($exe) or die "$exe not found in PATH\n";
98 }
99
100 sub prepare_reindex ($$) {
101         my ($ibx, $reindex) = @_;
102         if ($ibx->{version} == 1) {
103                 my $dir = $ibx->search->xdir(1);
104                 my $xdb = Search::Xapian::Database->new($dir);
105                 if (my $lc = $xdb->get_metadata('last_commit')) {
106                         $reindex->{from} = $lc;
107                 }
108         } else { # v2
109                 my $v2w = $ibx->importer(0);
110                 my $max;
111                 $v2w->git_dir_latest(\$max) or return;
112                 my $from = $reindex->{from};
113                 my $mm = $ibx->mm;
114                 my $v = PublicInbox::Search::SCHEMA_VERSION();
115                 foreach my $i (0..$max) {
116                         $from->[$i] = $mm->last_commit_xap($v, $i);
117                 }
118         }
119 }
120
121 sub same_fs_or_die ($$) {
122         my ($x, $y) = @_;
123         return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
124         die "$x and $y reside on different filesystems\n";
125 }
126
127 sub process_queue {
128         my ($queue, $cb, $max, $opt) = @_;
129         if ($max <= 1) {
130                 while (defined(my $args = shift @$queue)) {
131                         $cb->($args, $opt);
132                 }
133                 return;
134         }
135
136         # run in parallel:
137         my %pids;
138         while (@$queue) {
139                 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
140                         my $args = shift @$queue;
141                         $pids{cb_spawn($cb, $args, $opt)} = $args;
142                 }
143
144                 while (scalar keys %pids) {
145                         my $pid = waitpid(-1, 0);
146                         my $args = delete $pids{$pid};
147                         die join(' ', @$args)." failed: $?\n" if $?;
148                 }
149         }
150 }
151
152 sub run {
153         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
154         my $cb = \&${\"PublicInbox::Xapcmd::$task"};
155         PublicInbox::Admin::progress_prepare($opt ||= {});
156         my $dir = $ibx->{mainrepo} or die "no mainrepo in inbox\n";
157         runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
158         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
159         my $from; # per-epoch ranges
160
161         if (!$opt->{-coarse_lock}) {
162                 $reindex = $opt->{reindex} = {};
163                 $from = $reindex->{from} = [];
164                 require Search::Xapian::WritableDatabase;
165         }
166
167         $ibx->umask_prepare;
168         my $old = $ibx->search->xdir(1);
169         -d $old or die "$old does not exist\n";
170
171         my $tmp = PublicInbox::Xtmpdirs->new;
172         my $v = $ibx->{version} ||= 1;
173         my @q;
174         my $reshard = $opt->{reshard};
175         if (defined $reshard && $reshard <= 0) {
176                 die "--reshard must be a positive number\n";
177         }
178
179         # we want temporary directories to be as deep as possible,
180         # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
181         if ($v == 1) {
182                 if (defined $reshard) {
183                         warn
184 "--reshard=$reshard ignored for v1 $ibx->{mainrepo}\n";
185                 }
186                 my $old_parent = dirname($old);
187                 same_fs_or_die($old_parent, $old);
188                 my $v = PublicInbox::Search::SCHEMA_VERSION();
189                 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
190                 $tmp->{$old} = $wip;
191                 push @q, [ $old, $wip ];
192         } else {
193                 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
194                 my @old_shards;
195                 while (defined(my $dn = readdir($dh))) {
196                         if ($dn =~ /\A[0-9]+\z/) {
197                                 push @old_shards, $dn;
198                         } elsif ($dn eq '.' || $dn eq '..') {
199                         } elsif ($dn =~ /\Aover\.sqlite3/) {
200                         } else {
201                                 warn "W: skipping unknown dir: $old/$dn\n"
202                         }
203                 }
204                 die "No Xapian shards found in $old\n" unless @old_shards;
205
206                 my ($src, $max_shard);
207                 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
208                         # 1:1 copy
209                         $max_shard = scalar(@old_shards) - 1;
210                 } else {
211                         # M:N copy
212                         $max_shard = $reshard - 1;
213                         $src = [ map { "$old/$_" } @old_shards ];
214                 }
215                 foreach my $dn (0..$max_shard) {
216                         my $tmpl = "$dn-XXXXXXXX";
217                         my $wip = tempdir($tmpl, DIR => $old);
218                         same_fs_or_die($old, $wip);
219                         my $cur = "$old/$dn";
220                         push @q, [ $src // $cur , $wip ];
221                         $tmp->{$cur} = $wip;
222                 }
223                 # mark old shards to be unlinked
224                 if ($src) {
225                         $tmp->{$_} ||= undef for @$src;
226                 }
227         }
228         my $im = $ibx->importer(0);
229         my $max = $opt->{jobs} || scalar(@q);
230         $ibx->with_umask(sub {
231                 $im->lock_acquire;
232
233                 # fine-grained locking if we prepare for reindex
234                 if (!$opt->{-coarse_lock}) {
235                         prepare_reindex($ibx, $reindex);
236                         $im->lock_release;
237                 }
238
239                 delete($ibx->{$_}) for (qw(mm over search)); # cleanup
240                 process_queue(\@q, $cb, $max, $opt);
241                 commit_changes($ibx, $tmp, $opt);
242         });
243 }
244
245 sub cpdb_retryable ($$) {
246         my ($src, $pfx) = @_;
247         if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
248                 warn "$pfx Xapian DB modified, reopening and retrying\n";
249                 $src->reopen;
250                 return 1;
251         }
252         if ($@) {
253                 warn "$pfx E: ", ref($@), "\n";
254                 die;
255         }
256         0;
257 }
258
259 sub progress_pfx ($) {
260         my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
261         my @p = split('/', $wip);
262
263         # return "xap15/0" for v2, or "xapian15" for v1:
264         ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
265 }
266
267 # xapian-compact wrapper
268 sub compact ($$) {
269         my ($args, $opt) = @_;
270         my ($src, $dst) = @$args;
271         my ($r, $w);
272         my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
273         my $pr = $opt->{-progress};
274         my $rdr = {};
275
276         foreach my $fd (0..2) {
277                 defined(my $dfd = $opt->{$fd}) or next;
278                 $rdr->{$fd} = $dfd;
279         }
280         $rdr->{1} = fileno($w) if $pr && pipe($r, $w);
281
282         # we rely on --no-renumber to keep docids synched to NNTP
283         my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
284         for my $sw (qw(no-full fuller)) {
285                 push @$cmd, "--$sw" if $opt->{$sw};
286         }
287         for my $sw (qw(blocksize)) {
288                 defined(my $v = $opt->{$sw}) or next;
289                 push @$cmd, "--$sw", $v;
290         }
291         $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
292         push @$cmd, $src, $dst;
293         my $pid = spawn($cmd, undef, $rdr);
294         if ($pr) {
295                 close $w or die "close: \$w: $!";
296                 foreach (<$r>) {
297                         s/\r/\r$pfx /g;
298                         $pr->("$pfx $_");
299                 }
300         }
301         my $rp = waitpid($pid, 0);
302         if ($? || $rp != $pid) {
303                 die join(' ', @$cmd)." failed: $? (pid=$pid, reaped=$rp)\n";
304         }
305 }
306
307 sub cpdb_loop ($$$;$$) {
308         my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
309         my ($pr, $fmt, $nr, $pfx);
310         if ($pr_data) {
311                 $pr = $pr_data->{pr};
312                 $fmt = $pr_data->{fmt};
313                 $nr = \($pr_data->{nr});
314                 $pfx = $pr_data->{pfx};
315         }
316
317         my ($it, $end);
318         do {
319                 eval {
320                         $it = $src->postlist_begin('');
321                         $end = $src->postlist_end('');
322                 };
323         } while (cpdb_retryable($src, $pfx));
324
325         do {
326                 eval {
327                         for (; $it != $end; $it++) {
328                                 my $docid = $it->get_docid;
329                                 if (defined $reshard) {
330                                         my $dst_shard = $docid % $reshard;
331                                         next if $dst_shard != $cur_shard;
332                                 }
333                                 my $doc = $src->get_document($docid);
334                                 $dst->replace_document($docid, $doc);
335                                 if ($pr_data && !(++$$nr  & 1023)) {
336                                         $pr->(sprintf($fmt, $$nr));
337                                 }
338                         }
339
340                         # unlike copydatabase(1), we don't copy spelling
341                         # and synonym data (or other user metadata) since
342                         # the Perl APIs don't expose iterators for them
343                         # (and public-inbox does not use those features)
344                 };
345         } while (cpdb_retryable($src, $pfx));
346 }
347
348 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
349 # to the overhead of Perl.
350 sub cpdb ($$) {
351         my ($args, $opt) = @_;
352         my ($old, $new) = @$args;
353         my ($src, $cur_shard);
354         my $reshard;
355         if (ref($old) eq 'ARRAY') {
356                 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
357                 defined $cur_shard or
358                         die "BUG: could not extract shard # from $new";
359                 $reshard = $opt->{reshard};
360                 defined $reshard or die 'BUG: got array src w/o --reshard';
361
362                 # resharding, M:N copy means have full read access
363                 foreach (@$old) {
364                         if ($src) {
365                                 my $sub = Search::Xapian::Database->new($_);
366                                 $src->add_database($sub);
367                         } else {
368                                 $src = Search::Xapian::Database->new($_);
369                         }
370                 }
371         } else {
372                 $src = Search::Xapian::Database->new($old);
373         }
374
375         my ($xtmp, $tmp);
376         if ($opt->{compact}) {
377                 my $newdir = dirname($new);
378                 same_fs_or_die($newdir, $new);
379                 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
380                 $xtmp = PublicInbox::Xtmpdirs->new;
381                 $xtmp->{$new} = $tmp;
382         } else {
383                 $tmp = $new;
384         }
385
386         # like copydatabase(1), be sure we don't overwrite anything in case
387         # of other bugs:
388         my $creat = Search::Xapian::DB_CREATE();
389         my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
390         my $pr = $opt->{-progress};
391         my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
392         my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
393
394         do {
395                 eval {
396                         # update the only metadata key for v1:
397                         my $lc = $src->get_metadata('last_commit');
398                         $dst->set_metadata('last_commit', $lc) if $lc;
399
400                         # only the first xapian shard (0) gets 'indexlevel'
401                         if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
402                                 my $l = $src->get_metadata('indexlevel');
403                                 if ($l eq 'medium') {
404                                         $dst->set_metadata('indexlevel', $l);
405                                 }
406                         }
407                         if ($pr_data) {
408                                 my $tot = $src->get_doccount;
409
410                                 # we can only estimate when resharding,
411                                 # because removed spam causes slight imbalance
412                                 my $est = '';
413                                 if (defined $cur_shard && $reshard > 1) {
414                                         $tot = int($tot/$reshard);
415                                         $est = 'around ';
416                                 }
417                                 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
418                                 $pr->("$pfx copying $est$tot documents\n");
419                                 $pr_data->{fmt} = $fmt;
420                                 $pr_data->{total} = $tot;
421                         }
422                 };
423         } while (cpdb_retryable($src, $pfx));
424
425         if (defined $reshard) {
426                 # we rely on document IDs matching NNTP article number,
427                 # so we can't have the Xapian sharding DB support rewriting
428                 # document IDs.  Thus we iterate through each shard
429                 # individually.
430                 $src = undef;
431                 foreach (@$old) {
432                         my $old = Search::Xapian::Database->new($_);
433                         cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
434                 }
435         } else {
436                 cpdb_loop($src, $dst, $pr_data);
437         }
438
439         $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
440         return unless $xtmp;
441
442         $src = $dst = undef; # flushes and closes
443
444         # this is probably the best place to do xapian-compact
445         # since $dst isn't readable by HTTP or NNTP clients, yet:
446         compact([ $tmp, $new ], $opt);
447         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
448         $xtmp->done;
449 }
450
451 # slightly easier-to-manage manage than END{} blocks
452 package PublicInbox::Xtmpdirs;
453 use strict;
454 use warnings;
455 use File::Path qw(remove_tree);
456 my %owner;
457
458 sub new {
459         # http://www.tldp.org/LDP/abs/html/exitcodes.html
460         $SIG{INT} = sub { exit(130) };
461         $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
462         my $self = bless {}, $_[0]; # old shard => new (WIP) shard
463         $owner{"$self"} = $$;
464         $self;
465 }
466
467 sub done {
468         my ($self) = @_;
469         delete $owner{"$self"};
470
471         my %known_pids;
472         $known_pids{$_}++ foreach values %owner;
473         if (!$known_pids{$$}) {
474                 $SIG{INT} = $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = 'DEFAULT';
475         }
476         %$self = ();
477 }
478
479 sub DESTROY {
480         my ($self) = @_;
481         my $owner_pid = delete $owner{"$self"} or return;
482         return if $owner_pid != $$;
483         foreach my $new (values %$self) {
484                 defined $new or next; # may be undef if resharding
485                 remove_tree($new) unless -d "$new/old";
486         }
487         done($self);
488 }
489
490 1;