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