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