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