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