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