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