]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
xapcmd: do not fire END and DESTROY handlers in child
[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 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, $new) = 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 $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 = undef;
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, $im, $opt);
81         }
82 }
83
84 sub cb_spawn {
85         my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
86         defined(my $pid = fork) or die "fork: $!";
87         return $pid if $pid > 0;
88         $cb->($args, $opt);
89         POSIX::_exit(0);
90 }
91
92 sub runnable_or_die ($) {
93         my ($exe) = @_;
94         which($exe) or die "$exe not found in PATH\n";
95 }
96
97 sub prepare_reindex ($$$) {
98         my ($ibx, $im, $reindex) = @_;
99         if ($ibx->{version} == 1) {
100                 my $dir = $ibx->search->xdir(1);
101                 my $xdb = Search::Xapian::Database->new($dir);
102                 if (my $lc = $xdb->get_metadata('last_commit')) {
103                         $reindex->{from} = $lc;
104                 }
105         } else { # v2
106                 my $max;
107                 $im->git_dir_latest(\$max) or return;
108                 my $from = $reindex->{from};
109                 my $mm = $ibx->mm;
110                 my $v = PublicInbox::Search::SCHEMA_VERSION();
111                 foreach my $i (0..$max) {
112                         $from->[$i] = $mm->last_commit_xap($v, $i);
113                 }
114         }
115 }
116
117 sub same_fs_or_die ($$) {
118         my ($x, $y) = @_;
119         return if ((stat($x))[0] == (stat($y))[0]); # 0 - st_dev
120         die "$x and $y reside on different filesystems\n";
121 }
122
123 sub process_queue {
124         my ($queue, $cb, $max, $opt) = @_;
125         if ($max <= 1) {
126                 while (defined(my $args = shift @$queue)) {
127                         $cb->($args, $opt);
128                 }
129                 return;
130         }
131
132         # run in parallel:
133         my %pids;
134         while (@$queue) {
135                 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
136                         my $args = shift @$queue;
137                         $pids{cb_spawn($cb, $args, $opt)} = $args;
138                 }
139
140                 while (scalar keys %pids) {
141                         my $pid = waitpid(-1, 0);
142                         my $args = delete $pids{$pid};
143                         die join(' ', @$args)." failed: $?\n" if $?;
144                 }
145         }
146 }
147
148 sub run {
149         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
150         my $cb = \&${\"PublicInbox::Xapcmd::$task"};
151         PublicInbox::Admin::progress_prepare($opt ||= {});
152         my $dir = $ibx->{inboxdir} or die "no inboxdir in inbox\n";
153         runnable_or_die($XAPIAN_COMPACT) if $opt->{compact};
154         my $reindex; # v1:{ from => $x40 }, v2:{ from => [ $x40, $x40, .. ] } }
155         my $from; # per-epoch ranges
156
157         if (!$opt->{-coarse_lock}) {
158                 $reindex = $opt->{reindex} = {};
159                 $from = $reindex->{from} = [];
160                 require Search::Xapian::WritableDatabase;
161         }
162
163         $ibx->umask_prepare;
164         my $old = $ibx->search->xdir(1);
165         -d $old or die "$old does not exist\n";
166
167         my $tmp = PublicInbox::Xtmpdirs->new;
168         my $v = $ibx->{version} ||= 1;
169         my @q;
170         my $reshard = $opt->{reshard};
171         if (defined $reshard && $reshard <= 0) {
172                 die "--reshard must be a positive number\n";
173         }
174
175         local %SIG = %SIG;
176         $tmp->setup_signals;
177
178         # we want temporary directories to be as deep as possible,
179         # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
180         if ($v == 1) {
181                 if (defined $reshard) {
182                         warn
183 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
184                 }
185                 my $old_parent = dirname($old);
186                 same_fs_or_die($old_parent, $old);
187                 my $v = PublicInbox::Search::SCHEMA_VERSION();
188                 my $wip = tempdir("xapian$v-XXXXXXXX", DIR => $old_parent);
189                 $tmp->{$old} = $wip;
190                 push @q, [ $old, $wip ];
191         } else {
192                 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
193                 my @old_shards;
194                 while (defined(my $dn = readdir($dh))) {
195                         if ($dn =~ /\A[0-9]+\z/) {
196                                 push @old_shards, $dn;
197                         } elsif ($dn eq '.' || $dn eq '..') {
198                         } elsif ($dn =~ /\Aover\.sqlite3/) {
199                         } else {
200                                 warn "W: skipping unknown dir: $old/$dn\n"
201                         }
202                 }
203                 die "No Xapian shards found in $old\n" unless @old_shards;
204
205                 my ($src, $max_shard);
206                 if (!defined($reshard) || $reshard == scalar(@old_shards)) {
207                         # 1:1 copy
208                         $max_shard = scalar(@old_shards) - 1;
209                 } else {
210                         # M:N copy
211                         $max_shard = $reshard - 1;
212                         $src = [ map { "$old/$_" } @old_shards ];
213                 }
214                 foreach my $dn (0..$max_shard) {
215                         my $tmpl = "$dn-XXXXXXXX";
216                         my $wip = tempdir($tmpl, DIR => $old);
217                         same_fs_or_die($old, $wip);
218                         my $cur = "$old/$dn";
219                         push @q, [ $src // $cur , $wip ];
220                         $tmp->{$cur} = $wip;
221                 }
222                 # mark old shards to be unlinked
223                 if ($src) {
224                         $tmp->{$_} ||= undef for @$src;
225                 }
226         }
227         my $max = $opt->{jobs} || scalar(@q);
228         $ibx->with_umask(sub {
229                 my $im = $ibx->importer(0);
230                 $im->lock_acquire;
231
232                 # fine-grained locking if we prepare for reindex
233                 if (!$opt->{-coarse_lock}) {
234                         prepare_reindex($ibx, $im, $reindex);
235                         $im->lock_release;
236                 }
237
238                 $ibx->cleanup;
239                 process_queue(\@q, $cb, $max, $opt);
240                 $im->lock_acquire if !$opt->{-coarse_lock};
241                 commit_changes($ibx, $im, $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         local %SIG = %SIG;
377         if ($opt->{compact}) {
378                 my $newdir = dirname($new);
379                 same_fs_or_die($newdir, $new);
380                 $tmp = tempdir("$new.compact-XXXXXX", DIR => $newdir);
381                 $xtmp = PublicInbox::Xtmpdirs->new;
382                 $xtmp->setup_signals;
383                 $xtmp->{$new} = $tmp;
384         } else {
385                 $tmp = $new;
386         }
387
388         # like copydatabase(1), be sure we don't overwrite anything in case
389         # of other bugs:
390         my $creat = Search::Xapian::DB_CREATE();
391         my $dst = Search::Xapian::WritableDatabase->new($tmp, $creat);
392         my $pr = $opt->{-progress};
393         my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
394         my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
395
396         do {
397                 eval {
398                         # update the only metadata key for v1:
399                         my $lc = $src->get_metadata('last_commit');
400                         $dst->set_metadata('last_commit', $lc) if $lc;
401
402                         # only the first xapian shard (0) gets 'indexlevel'
403                         if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
404                                 my $l = $src->get_metadata('indexlevel');
405                                 if ($l eq 'medium') {
406                                         $dst->set_metadata('indexlevel', $l);
407                                 }
408                         }
409                         if ($pr_data) {
410                                 my $tot = $src->get_doccount;
411
412                                 # we can only estimate when resharding,
413                                 # because removed spam causes slight imbalance
414                                 my $est = '';
415                                 if (defined $cur_shard && $reshard > 1) {
416                                         $tot = int($tot/$reshard);
417                                         $est = 'around ';
418                                 }
419                                 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
420                                 $pr->("$pfx copying $est$tot documents\n");
421                                 $pr_data->{fmt} = $fmt;
422                                 $pr_data->{total} = $tot;
423                         }
424                 };
425         } while (cpdb_retryable($src, $pfx));
426
427         if (defined $reshard) {
428                 # we rely on document IDs matching NNTP article number,
429                 # so we can't have the Xapian sharding DB support rewriting
430                 # document IDs.  Thus we iterate through each shard
431                 # individually.
432                 $src = undef;
433                 foreach (@$old) {
434                         my $old = Search::Xapian::Database->new($_);
435                         cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
436                 }
437         } else {
438                 cpdb_loop($src, $dst, $pr_data);
439         }
440
441         $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
442         return unless $xtmp;
443
444         $src = $dst = undef; # flushes and closes
445
446         # this is probably the best place to do xapian-compact
447         # since $dst isn't readable by HTTP or NNTP clients, yet:
448         compact([ $tmp, $new ], $opt);
449         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
450         $xtmp = undef;
451 }
452
453 # slightly easier-to-manage manage than END{} blocks
454 package PublicInbox::Xtmpdirs;
455 use strict;
456 use warnings;
457 use File::Path qw(remove_tree);
458
459 sub setup_signals () {
460         # http://www.tldp.org/LDP/abs/html/exitcodes.html
461         $SIG{INT} = sub { exit(130) };
462         $SIG{HUP} = $SIG{PIPE} = $SIG{TERM} = sub { exit(1) };
463 }
464
465 sub new {
466         bless { '' => $$ }, $_[0]; # old shard => new (WIP) shard
467 }
468
469 sub DESTROY {
470         my ($self) = @_;
471         my $owner_pid = delete($self->{''}) or return;
472         return if $owner_pid != $$;
473         foreach my $new (values %$self) {
474                 defined $new or next; # may be undef if resharding
475                 remove_tree($new) unless -d "$new/old";
476         }
477 }
478
479 1;