]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Xapcmd.pm
ca2345f764386b9438e81c3666a8de5d259e1549
[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 PublicInbox::Spawn qw(which popen_rd nodatacow_dir);
6 use PublicInbox::Admin qw(setup_signals);
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 qw(WNOHANG);
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
23         $SIG{INT} or die 'BUG: $SIG{INT} not handled';
24         my @old_shard;
25         my $over_chg;
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->dbh->sqlite_backup_to_file($tmp_over);
41                         $over = undef;
42                         $over_chg = 1;
43                 }
44
45                 if (!defined($new)) { # culled shard
46                         push @old_shard, $old;
47                         next;
48                 }
49
50                 if (@st) {
51                         chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
52                         rename($old, "$new/old") or
53                                         die "rename $old => $new/old: $!\n";
54                 }
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
63         # trigger ->check_inodes in read-only daemons
64         syswrite($im->{lockfh}, '.') if $over_chg;
65
66         remove_tree(@old_shard);
67         $tmp = undef;
68         if (!$opt->{-coarse_lock}) {
69                 $opt->{-skip_lock} = 1;
70
71                 if ($im->can('count_shards')) {
72                         my $pr = $opt->{-progress};
73                         my $n = $im->count_shards;
74                         if (defined $reshard && $n != $reshard) {
75                                 die
76 "BUG: counted $n shards after resharding to $reshard";
77                         }
78                         my $prev = $im->{shards};
79                         if ($pr && $prev != $n) {
80                                 $pr->("shard count changed: $prev => $n\n");
81                                 $im->{shards} = $n;
82                         }
83                 }
84                 my $env = $opt->{-idx_env};
85                 local %ENV = (%ENV, %$env) if $env;
86                 PublicInbox::Admin::index_inbox($ibx, $im, $opt);
87         }
88 }
89
90 sub cb_spawn {
91         my ($cb, $args, $opt) = @_; # $cb = cpdb() or compact()
92         defined(my $pid = fork) or die "fork: $!";
93         return $pid if $pid > 0;
94         $cb->($args, $opt);
95         POSIX::_exit(0);
96 }
97
98 sub runnable_or_die ($) {
99         my ($exe) = @_;
100         which($exe) or die "$exe not found in PATH\n";
101 }
102
103 sub prepare_reindex ($$$) {
104         my ($ibx, $im, $opt) = @_;
105         if ($ibx->version == 1) {
106                 my $dir = $ibx->search->xdir(1);
107                 my $xdb = $PublicInbox::Search::X{Database}->new($dir);
108                 if (my $lc = $xdb->get_metadata('last_commit')) {
109                         $opt->{reindex}->{from} = $lc;
110                 }
111         } else { # v2
112                 my $max = $ibx->max_git_epoch // return;
113                 my $from = $opt->{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 kill_pids {
129         my ($sig, $pids) = @_;
130         kill($sig, keys %$pids); # pids may be empty
131 }
132
133 sub process_queue {
134         my ($queue, $cb, $opt) = @_;
135         my $max = $opt->{jobs} // scalar(@$queue);
136         if ($max <= 1) {
137                 while (defined(my $args = shift @$queue)) {
138                         $cb->($args, $opt);
139                 }
140                 return;
141         }
142
143         # run in parallel:
144         my %pids;
145         local %SIG = %SIG;
146         setup_signals(\&kill_pids, \%pids);
147         while (@$queue) {
148                 while (scalar(keys(%pids)) < $max && scalar(@$queue)) {
149                         my $args = shift @$queue;
150                         $pids{cb_spawn($cb, $args, $opt)} = $args;
151                 }
152
153                 my $flags = 0;
154                 while (scalar keys %pids) {
155                         my $pid = waitpid(-1, $flags) or last;
156                         last if $pid < 0;
157                         my $args = delete $pids{$pid};
158                         if ($args) {
159                                 die join(' ', @$args)." failed: $?\n" if $?;
160                         } else {
161                                 warn "unknown PID($pid) reaped: $?\n";
162                         }
163                         $flags = WNOHANG if scalar(@$queue);
164                 }
165         }
166 }
167
168 sub prepare_run {
169         my ($ibx, $opt) = @_;
170         my $tmp = {}; # old shard dir => File::Temp->newdir object or undef
171         my @queue; # ([old//src,newdir]) - list of args for cpdb() or compact()
172         my $old;
173         if (my $srch = $ibx->search) {
174                 $old = $srch->xdir(1);
175                 -d $old or die "$old does not exist\n";
176         }
177         my $reshard = $opt->{reshard};
178         if (defined $reshard && $reshard <= 0) {
179                 die "--reshard must be a positive number\n";
180         }
181
182         # we want temporary directories to be as deep as possible,
183         # so v2 shards can keep "xap$SCHEMA_VERSION" on a separate FS.
184         if ($old && $ibx->version == 1) {
185                 if (defined $reshard) {
186                         warn
187 "--reshard=$reshard ignored for v1 $ibx->{inboxdir}\n";
188                 }
189                 my $dir = dirname($old);
190                 same_fs_or_die($dir, $old);
191                 my $v = PublicInbox::Search::SCHEMA_VERSION();
192                 my $wip = File::Temp->newdir("xapian$v-XXXXXXXX", DIR => $dir);
193                 $tmp->{$old} = $wip;
194                 nodatacow_dir($wip->dirname);
195                 push @queue, [ $old, $wip ];
196         } elsif ($old) {
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 = File::Temp->newdir($tmpl, DIR => $old);
222                         same_fs_or_die($old, $wip->dirname);
223                         my $cur = "$old/$dn";
224                         push @queue, [ $src // $cur , $wip ];
225                         nodatacow_dir($wip->dirname);
226                         $tmp->{$cur} = $wip;
227                 }
228                 # mark old shards to be unlinked
229                 if ($src) {
230                         $tmp->{$_} ||= undef for @$src;
231                 }
232         }
233         ($tmp, \@queue);
234 }
235
236 sub check_compact () { runnable_or_die($XAPIAN_COMPACT) }
237
238 sub _run {
239         my ($ibx, $cb, $opt) = @_;
240         my $im = $ibx->importer(0);
241         $im->lock_acquire;
242         my ($tmp, $queue) = prepare_run($ibx, $opt);
243
244         # fine-grained locking if we prepare for reindex
245         if (!$opt->{-coarse_lock}) {
246                 prepare_reindex($ibx, $im, $opt);
247                 $im->lock_release;
248         }
249
250         $ibx->cleanup;
251         process_queue($queue, $cb, $opt);
252         $im->lock_acquire if !$opt->{-coarse_lock};
253         commit_changes($ibx, $im, $tmp, $opt);
254 }
255
256 sub run {
257         my ($ibx, $task, $opt) = @_; # task = 'cpdb' or 'compact'
258         my $cb = \&$task;
259         PublicInbox::Admin::progress_prepare($opt ||= {});
260         defined(my $dir = $ibx->{inboxdir}) or die "no inboxdir defined\n";
261         -d $dir or die "inboxdir=$dir does not exist\n";
262         check_compact() if $opt->{compact} && $ibx->search;
263
264         if (!$opt->{-coarse_lock}) {
265                 # per-epoch ranges for v2
266                 # v1:{ from => $OID }, v2:{ from => [ $OID, $OID, $OID ] } }
267                 $opt->{reindex} = { from => $ibx->version == 1 ? '' : [] };
268                 PublicInbox::SearchIdx::load_xapian_writable();
269         }
270
271         local %SIG = %SIG;
272         setup_signals();
273         $ibx->with_umask(\&_run, $ibx, $cb, $opt);
274 }
275
276 sub cpdb_retryable ($$) {
277         my ($src, $pfx) = @_;
278         if (ref($@) =~ /\bDatabaseModifiedError\b/) {
279                 warn "$pfx Xapian DB modified, reopening and retrying\n";
280                 $src->reopen;
281                 return 1;
282         }
283         if ($@) {
284                 warn "$pfx E: ", ref($@), "\n";
285                 die;
286         }
287         0;
288 }
289
290 sub progress_pfx ($) {
291         my ($wip) = @_; # tempdir v2: ([0-9])+-XXXXXXXX
292         my @p = split('/', $wip);
293
294         # return "xap15/0" for v2, or "xapian15" for v1:
295         ($p[-1] =~ /\A([0-9]+)/) ? "$p[-2]/$1" : $p[-1];
296 }
297
298 sub kill_compact { # setup_signals callback
299         my ($sig, $pidref) = @_;
300         kill($sig, $$pidref) if defined($$pidref);
301 }
302
303 # xapian-compact wrapper
304 sub compact ($$) {
305         my ($args, $opt) = @_;
306         my ($src, $newdir) = @$args;
307         my $dst = ref($newdir) ? $newdir->dirname : $newdir;
308         my $pfx = $opt->{-progress_pfx} ||= progress_pfx($src);
309         my $pr = $opt->{-progress};
310         my $rdr = {};
311
312         foreach my $fd (0..2) {
313                 defined(my $dfd = $opt->{$fd}) or next;
314                 $rdr->{$fd} = $dfd;
315         }
316
317         # we rely on --no-renumber to keep docids synched to NNTP
318         my $cmd = [ $XAPIAN_COMPACT, '--no-renumber' ];
319         for my $sw (qw(no-full fuller)) {
320                 push @$cmd, "--$sw" if $opt->{$sw};
321         }
322         for my $sw (qw(blocksize)) {
323                 defined(my $v = $opt->{$sw}) or next;
324                 push @$cmd, "--$sw", $v;
325         }
326         $pr->("$pfx `".join(' ', @$cmd)."'\n") if $pr;
327         push @$cmd, $src, $dst;
328         my ($rd, $pid);
329         local %SIG = %SIG;
330         setup_signals(\&kill_compact, \$pid);
331         ($rd, $pid) = popen_rd($cmd, undef, $rdr);
332         while (<$rd>) {
333                 if ($pr) {
334                         s/\r/\r$pfx /g;
335                         $pr->("$pfx $_");
336                 }
337         }
338         waitpid($pid, 0);
339         die "@$cmd failed: \$?=$?\n" if $?;
340 }
341
342 sub cpdb_loop ($$$;$$) {
343         my ($src, $dst, $pr_data, $cur_shard, $reshard) = @_;
344         my ($pr, $fmt, $nr, $pfx);
345         if ($pr_data) {
346                 $pr = $pr_data->{pr};
347                 $fmt = $pr_data->{fmt};
348                 $nr = \($pr_data->{nr});
349                 $pfx = $pr_data->{pfx};
350         }
351
352         my ($it, $end);
353         do {
354                 eval {
355                         $it = $src->postlist_begin('');
356                         $end = $src->postlist_end('');
357                 };
358         } while (cpdb_retryable($src, $pfx));
359
360         do {
361                 eval {
362                         for (; $it != $end; $it++) {
363                                 my $docid = $it->get_docid;
364                                 if (defined $reshard) {
365                                         my $dst_shard = $docid % $reshard;
366                                         next if $dst_shard != $cur_shard;
367                                 }
368                                 my $doc = $src->get_document($docid);
369                                 $dst->replace_document($docid, $doc);
370                                 if ($pr_data && !(++$$nr  & 1023)) {
371                                         $pr->(sprintf($fmt, $$nr));
372                                 }
373                         }
374
375                         # unlike copydatabase(1), we don't copy spelling
376                         # and synonym data (or other user metadata) since
377                         # the Perl APIs don't expose iterators for them
378                         # (and public-inbox does not use those features)
379                 };
380         } while (cpdb_retryable($src, $pfx));
381 }
382
383 # Like copydatabase(1), this is horribly slow; and it doesn't seem due
384 # to the overhead of Perl.
385 sub cpdb ($$) {
386         my ($args, $opt) = @_;
387         my ($old, $newdir) = @$args;
388         my $new = $newdir->dirname;
389         my ($src, $cur_shard);
390         my $reshard;
391         PublicInbox::SearchIdx::load_xapian_writable() or die;
392         my $XapianDatabase = $PublicInbox::Search::X{Database};
393         if (ref($old) eq 'ARRAY') {
394                 ($cur_shard) = ($new =~ m!xap[0-9]+/([0-9]+)\b!);
395                 defined $cur_shard or
396                         die "BUG: could not extract shard # from $new";
397                 $reshard = $opt->{reshard};
398                 defined $reshard or die 'BUG: got array src w/o --reshard';
399
400                 # resharding, M:N copy means have full read access
401                 foreach (@$old) {
402                         if ($src) {
403                                 my $sub = $XapianDatabase->new($_);
404                                 $src->add_database($sub);
405                         } else {
406                                 $src = $XapianDatabase->new($_);
407                         }
408                 }
409         } else {
410                 $src = $XapianDatabase->new($old);
411         }
412
413         my ($tmp, $ft);
414         local %SIG = %SIG;
415         if ($opt->{compact}) {
416                 my $dir = dirname($new);
417                 same_fs_or_die($dir, $new);
418                 $ft = File::Temp->newdir("$new.compact-XXXXXX", DIR => $dir);
419                 setup_signals();
420                 $tmp = $ft->dirname;
421                 nodatacow_dir($tmp);
422         } else {
423                 $tmp = $new;
424         }
425
426         # like copydatabase(1), be sure we don't overwrite anything in case
427         # of other bugs:
428         my $flag = eval($PublicInbox::Search::Xap.'::DB_CREATE()');
429         die if $@;
430         my $XapianWritableDatabase = $PublicInbox::Search::X{WritableDatabase};
431         $flag |= $PublicInbox::SearchIdx::DB_NO_SYNC if !$opt->{fsync};
432         my $dst = $XapianWritableDatabase->new($tmp, $flag);
433         my $pr = $opt->{-progress};
434         my $pfx = $opt->{-progress_pfx} = progress_pfx($new);
435         my $pr_data = { pr => $pr, pfx => $pfx, nr => 0 } if $pr;
436
437         do {
438                 eval {
439                         # update the only metadata key for v1:
440                         my $lc = $src->get_metadata('last_commit');
441                         $dst->set_metadata('last_commit', $lc) if $lc;
442
443                         # only the first xapian shard (0) gets 'indexlevel'
444                         if ($new =~ m!(?:xapian[0-9]+|xap[0-9]+/0)\b!) {
445                                 my $l = $src->get_metadata('indexlevel');
446                                 if ($l eq 'medium') {
447                                         $dst->set_metadata('indexlevel', $l);
448                                 }
449                         }
450                         if ($pr_data) {
451                                 my $tot = $src->get_doccount;
452
453                                 # we can only estimate when resharding,
454                                 # because removed spam causes slight imbalance
455                                 my $est = '';
456                                 if (defined $cur_shard && $reshard > 1) {
457                                         $tot = int($tot/$reshard);
458                                         $est = 'around ';
459                                 }
460                                 my $fmt = "$pfx % ".length($tot)."u/$tot\n";
461                                 $pr->("$pfx copying $est$tot documents\n");
462                                 $pr_data->{fmt} = $fmt;
463                                 $pr_data->{total} = $tot;
464                         }
465                 };
466         } while (cpdb_retryable($src, $pfx));
467
468         if (defined $reshard) {
469                 # we rely on document IDs matching NNTP article number,
470                 # so we can't have the Xapian sharding DB support rewriting
471                 # document IDs.  Thus we iterate through each shard
472                 # individually.
473                 $src = undef;
474                 foreach (@$old) {
475                         my $old = $XapianDatabase->new($_);
476                         cpdb_loop($old, $dst, $pr_data, $cur_shard, $reshard);
477                 }
478         } else {
479                 cpdb_loop($src, $dst, $pr_data);
480         }
481
482         $pr->(sprintf($pr_data->{fmt}, $pr_data->{nr})) if $pr;
483         return unless $opt->{compact};
484
485         $src = $dst = undef; # flushes and closes
486
487         # this is probably the best place to do xapian-compact
488         # since $dst isn't readable by HTTP or NNTP clients, yet:
489         compact([ $tmp, $new ], $opt);
490         remove_tree($tmp) or die "failed to remove $tmp: $!\n";
491 }
492
493 1;