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