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