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