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