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