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