]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
clone|fetch|--mirror: cull manifest in partial mirrors
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::Config;
10 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
11 use IO::Compress::Gzip qw(gzip $GzipError);
12 use PublicInbox::Spawn qw(popen_rd spawn run_die);
13 use File::Temp ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15
16 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
17         my ($arg, $pid) = @_;
18         my ($mrr, $lei) = @$arg;
19         my $f = "$mrr->{dst}/mirror.done";
20         if ($?) {
21                 $lei->child_error($?);
22         } elsif (!unlink($f)) {
23                 $lei->err("unlink($f): $!") unless $!{ENOENT};
24         } else {
25                 if ($lei->{cmd} ne 'public-inbox-clone') {
26                         $lei->add_external_finish($mrr->{dst});
27                 }
28                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
29         }
30         $lei->dclose;
31 }
32
33 # for old installations without manifest.js.gz
34 sub try_scrape {
35         my ($self) = @_;
36         my $uri = URI->new($self->{src});
37         my $lei = $self->{lei};
38         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
39         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
40         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
41         my $fh = popen_rd($cmd, undef, $opt);
42         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
43         close($fh) or return $lei->child_error($?, "@$cmd failed");
44
45         # we grep with URL below, we don't want Subject/From headers
46         # making us clone random URLs
47         my @html = split(/<hr>/, $html);
48         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
49         my $url = $uri->as_string;
50         chop($url) eq '/' or die "BUG: $uri not canonicalized";
51
52         # since this is for old instances w/o manifest.js.gz, try v1 first
53         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
54         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
55                 my %v2_epochs = map {
56                         my ($n) = (m!/([0-9]+)\z!);
57                         $n => URI->new($_)
58                 } @v2_urls; # uniq
59                 return clone_v2($self, \%v2_epochs);
60         }
61
62         # filter out common URLs served by WWW (e.g /$MSGID/T/)
63         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
64                         grep(m!\A\Q$url\E/*\z!, @urls)) {
65                 die <<"";
66 E: confused by scraping <$uri>, did you mean <$url>?
67
68         }
69         @urls and die <<"";
70 E: confused by scraping <$uri>, got ambiguous results:
71 @urls
72
73         die "E: scraping <$uri> revealed nothing\n";
74 }
75
76 sub clone_cmd {
77         my ($lei, $opt) = @_;
78         my @cmd = qw(git);
79         $opt->{$_} = $lei->{$_} for (0..2);
80         # we support "-c $key=$val" for arbitrary git config options
81         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
82         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
83         push @cmd, qw(clone --mirror);
84         push @cmd, '-q' if $lei->{opt}->{quiet};
85         push @cmd, '-v' if $lei->{opt}->{verbose};
86         # XXX any other options to support?
87         # --reference is tricky with multiple epochs...
88         @cmd;
89 }
90
91 sub _get_txt { # non-fatal
92         my ($self, $endpoint, $file) = @_;
93         my $uri = URI->new($self->{src});
94         my $lei = $self->{lei};
95         my $path = $uri->path;
96         chop($path) eq '/' or die "BUG: $uri not canonicalized";
97         $uri->path("$path/$endpoint");
98         my $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
99         my $ce = "$self->{dst}/$file";
100         my $ft = File::Temp->new(TEMPLATE => "$file-XXXX",
101                                 UNLINK => 1, DIR => $self->{dst});
102         my $opt = { 0 => $lei->{0}, 1 => $ft, 2 => $lei->{2} };
103         my $cerr = run_reap($lei, $cmd, $opt);
104         return "$uri missing" if ($cerr >> 8) == 22;
105         return "# @$cmd failed (non-fatal)" if $cerr;
106         my $f = $ft->filename;
107         rename($f, $ce) or return "rename($f, $ce): $! (non-fatal)";
108         $ft->unlink_on_destroy(0);
109         undef; # success
110 }
111
112 # tries the relatively new /$INBOX/_/text/config/raw endpoint
113 sub _try_config {
114         my ($self) = @_;
115         my $dst = $self->{dst};
116         if (!-d $dst || !mkdir($dst)) {
117                 require File::Path;
118                 File::Path::mkpath($dst);
119                 -d $dst or die "mkpath($dst): $!\n";
120         }
121         my $err = _get_txt($self, qw(_/text/config/raw inbox.config.example));
122         return $self->{lei}->err($err) if $err;
123         my $f = "$self->{dst}/inbox.config.example";
124         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
125         my $ibx = $self->{ibx} = {};
126         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
127                 for (qw(address newsgroup nntpmirror)) {
128                         $ibx->{$_} = $cfg->{"$sec.$_"};
129                 }
130         }
131 }
132
133 sub set_description ($) {
134         my ($self) = @_;
135         my $f = "$self->{dst}/description";
136         open my $fh, '+>>', $f or die "open($f): $!";
137         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
138         chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
139         if ($d eq '($INBOX_DIR/description missing)' ||
140                         $d =~ /^Unnamed repository/ || $d !~ /\S/) {
141                 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
142                 truncate($fh, 0) or die "truncate($f): $!";
143                 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
144                 close $fh or die "close($f): $!";
145         }
146 }
147
148 sub index_cloned_inbox {
149         my ($self, $iv) = @_;
150         my $lei = $self->{lei};
151         my $err = _get_txt($self, qw(description description));
152         $lei->err($err) if $err; # non fatal
153         eval { set_description($self) };
154         warn $@ if $@;
155
156         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
157         # lei is useless without Xapian + SQLite
158         if ($lei->{cmd} ne 'public-inbox-clone') {
159                 my $ibx = delete($self->{ibx}) // {
160                         address => [ 'lei@example.com' ],
161                         version => $iv,
162                 };
163                 $ibx->{inboxdir} = $self->{dst};
164                 PublicInbox::Inbox->new($ibx);
165                 PublicInbox::InboxWritable->new($ibx);
166                 my $opt = {};
167                 for my $sw ($lei->index_opt) {
168                         my ($k) = ($sw =~ /\A([\w-]+)/);
169                         $opt->{$k} = $lei->{opt}->{$k};
170                 }
171                 # force synchronous dwaitpid for v2:
172                 local $PublicInbox::DS::in_loop = 0;
173                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
174                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
175                 local %ENV = (%ENV, %$env) if $env;
176                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
177                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
178         }
179         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
180 }
181
182 sub run_reap {
183         my ($lei, $cmd, $opt) = @_;
184         $lei->qerr("# @$cmd");
185         $opt->{pgid} = 0 if $lei->{sock};
186         my $pid = spawn($cmd, undef, $opt);
187         my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
188         waitpid($pid, 0) == $pid or die "waitpid @$cmd: $!";
189         @$reap = (); # cancel reap
190         my $ret = $?;
191         $? = 0; # don't let it influence normal exit
192         $ret;
193 }
194
195 sub clone_v1 {
196         my ($self) = @_;
197         my $lei = $self->{lei};
198         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
199         my $uri = URI->new($self->{src});
200         defined($lei->{opt}->{epoch}) and
201                 die "$uri is a v1 inbox, --epoch is not supported\n";
202         my $pfx = $curl->torsocks($lei, $uri) or return;
203         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
204                         $uri->as_string, $self->{dst} ];
205         my $cerr = run_reap($lei, $cmd, $opt);
206         return $lei->child_error($cerr, "@$cmd failed") if $cerr;
207         _try_config($self);
208         write_makefile($self->{dst}, 1);
209         index_cloned_inbox($self, 1);
210 }
211
212 sub parse_epochs ($$) {
213         my ($opt_epochs, $v2_epochs) = @_; # $epcohs "LOW..HIGH"
214         $opt_epochs // return; # undef => all epochs
215         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
216         undef($lo) if ($lo // '') eq '';
217         my $re = qr/\A~?[0-9]+\z/;
218         if (@extra || (($lo // '0') !~ $re) ||
219                         (($hi // '0') !~ $re) ||
220                         !(grep(defined, $lo, $hi))) {
221                 die <<EOM;
222 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
223 EOM
224         }
225         my @n = sort { $a <=> $b } keys %$v2_epochs;
226         for (grep(defined, $lo, $hi)) {
227                 if (/\A[0-9]+\z/) {
228                         $_ > $n[-1] and die
229 "`$_' exceeds maximum available epoch ($n[-1])\n";
230                         $_ < $n[0] and die
231 "`$_' is lower than minimum available epoch ($n[0])\n";
232                 } elsif (/\A~([0-9]+)/) {
233                         my $off = -$1 - 1;
234                         $n[$off] // die "`$_' is out of range\n";
235                         $_ = $n[$off];
236                 } else { die "`$_' not understood\n" }
237         }
238         defined($lo) && defined($hi) && $lo > $hi and die
239 "low value (`$lo') exceeds high (`$hi')\n";
240         $lo //= $n[0] if $dotdot;
241         $hi //= $n[-1] if $dotdot;
242         $hi //= $lo;
243         my $want = {};
244         for ($lo..$hi) {
245                 if (defined $v2_epochs->{$_}) {
246                         $want->{$_} = 1;
247                 } else {
248                         warn
249 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
250                 }
251         }
252         $want
253 }
254
255 sub init_placeholder ($$) {
256         my ($src, $edst) = @_;
257         PublicInbox::Import::init_bare($edst);
258         my $f = "$edst/config";
259         open my $fh, '>>', $f or die "open($f): $!";
260         print $fh <<EOM or die "print($f): $!";
261 [remote "origin"]
262         url = $src
263         fetch = +refs/*:refs/*
264         mirror = true
265
266 ; This git epoch was created read-only and "public-inbox-fetch"
267 ; will not fetch updates for it unless write permission is added.
268 EOM
269         close $fh or die "close:($f): $!";
270 }
271
272 sub clone_v2 ($$;$) {
273         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
274         my $lei = $self->{lei};
275         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
276         my $pfx = $curl->torsocks($lei, (values %$v2_epochs)[0]) or return;
277         my $dst = $self->{dst};
278         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
279         my (@src_edst, @read_only, @skip_nr);
280         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
281                 my $uri = $v2_epochs->{$nr};
282                 my $src = $uri->as_string;
283                 my $edst = $dst;
284                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
285 failed to extract epoch number from $src
286
287                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
288                 $edst .= "/git/$nr.git";
289                 if (!$want || $want->{$nr}) {
290                         push @src_edst, $src, $edst;
291                 } else { # create a placeholder so users only need to chmod +w
292                         init_placeholder($src, $edst);
293                         push @read_only, $edst;
294                         push @skip_nr, $nr;
295                 }
296         }
297         if (@skip_nr) { # filter out the epochs we skipped
298                 my $re = join('|', @skip_nr);
299                 my @del = grep(m!/git/$re\.git\z!, keys %$m);
300                 delete @$m{@del};
301                 $self->{-culled_manifest} = 1;
302         }
303         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
304         _try_config($self);
305         my $on_destroy = $lk->lock_for_scope($$);
306         my @cmd = clone_cmd($lei, my $opt = {});
307         while (my ($src, $edst) = splice(@src_edst, 0, 2)) {
308                 my $cmd = [ @$pfx, @cmd, $src, $edst ];
309                 my $cerr = run_reap($lei, $cmd, $opt);
310                 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
311         }
312         require PublicInbox::MultiGit;
313         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
314         $mg->fill_alternates;
315         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
316         for my $edst (@read_only) {
317                 my @st = stat($edst) or die "stat($edst): $!";
318                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
319         }
320         write_makefile($self->{dst}, 2);
321         undef $on_destroy; # unlock
322         index_cloned_inbox($self, 2);
323 }
324
325 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
326 sub deduce_epochs ($$) {
327         my ($m, $path) = @_;
328         my ($v1_ent, @v2_epochs);
329         my $path_pfx = '';
330         $path =~ s!/+\z!!;
331         do {
332                 $v1_ent = $m->{$path};
333                 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
334         } while (!defined($v1_ent) && !@v2_epochs &&
335                 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
336         ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
337 }
338
339 sub decode_manifest ($$$) {
340         my ($fh, $fn, $uri) = @_;
341         my $js;
342         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
343         gunzip(\$gz => \$js, MultiStream => 1) or
344                 die "gunzip($uri): $GunzipError\n";
345         my $m = eval { PublicInbox::Config->json->decode($js) };
346         die "$uri: error decoding `$js': $@\n" if $@;
347         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
348         $m;
349 }
350
351 sub try_manifest {
352         my ($self) = @_;
353         my $uri = URI->new($self->{src});
354         my $lei = $self->{lei};
355         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
356         my $path = $uri->path;
357         chop($path) eq '/' or die "BUG: $uri not canonicalized";
358         $uri->path($path . '/manifest.js.gz');
359         my $pdir = $lei->rel2abs($self->{dst});
360         $pdir =~ s!/[^/]+/?\z!!;
361         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
362                                 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
363         my $fn = $ft->filename;
364         my ($bn) = ($fn =~ m!/([^/]+)\z!);
365         my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
366         my $opt = { -C => $pdir };
367         $opt->{$_} = $lei->{$_} for (0..2);
368         my $cerr = run_reap($lei, $cmd, $opt);
369         if ($cerr) {
370                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
371                 return $lei->child_error($cerr, "@$cmd failed");
372         }
373         my $m = eval { decode_manifest($ft, $fn, $uri) };
374         if ($@) {
375                 warn $@;
376                 return try_scrape($self);
377         }
378         my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
379         if (@v2_epochs) {
380                 # It may be possible to have v1 + v2 in parallel someday:
381                 $lei->err(<<EOM) if defined $v1_path;
382 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
383 # @v2_epochs
384 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
385 EOM
386                 my %v2_epochs = map {
387                         $uri->path($path_pfx.$_);
388                         my ($n) = ("$uri" =~ m!/([0-9]+)\.git\z!);
389                         $n => $uri->clone
390                 } @v2_epochs;
391                 clone_v2($self, \%v2_epochs, $m);
392         } elsif (defined $v1_path) {
393                 clone_v1($self);
394         } else {
395                 die "E: confused by <$uri>, possible matches:\n\t",
396                         join(', ', sort keys %$m), "\n";
397         }
398         if (delete $self->{-culled_manifest}) { # set by clone_v2
399                 # write the smaller manifest if epochs were skipped so
400                 # users won't have to delete manifest if they +w an
401                 # epoch they no longer want to skip
402                 my $json = PublicInbox::Config->json->encode($m);
403                 gzip(\$json => $fn) or die "gzip: $GzipError";
404         }
405         my $fin = "$self->{dst}/manifest.js.gz";
406         rename($fn, $fin) or die "E: rename($fn, $fin): $!";
407         $ft->unlink_on_destroy(0);
408 }
409
410 sub start_clone_url {
411         my ($self) = @_;
412         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
413         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
414 }
415
416 sub do_mirror { # via wq_io_do
417         my ($self) = @_;
418         my $lei = $self->{lei};
419         eval {
420                 my $iv = $lei->{opt}->{'inbox-version'};
421                 if (defined $iv) {
422                         return clone_v1($self) if $iv == 1;
423                         return try_scrape($self) if $iv == 2;
424                         die "bad --inbox-version=$iv\n";
425                 }
426                 return start_clone_url($self) if $self->{src} =~ m!://!;
427                 die "TODO: cloning local directories not supported, yet";
428         };
429         $lei->fail($@) if $@;
430 }
431
432 sub start {
433         my ($cls, $lei, $src, $dst) = @_;
434         my $self = bless { src => $src, dst => $dst }, $cls;
435         if ($src =~ m!https?://!) {
436                 require URI;
437                 require PublicInbox::LeiCurl;
438         }
439         require PublicInbox::Lock;
440         require PublicInbox::Inbox;
441         require PublicInbox::Admin;
442         require PublicInbox::InboxWritable;
443         my ($op_c, $ops) = $lei->workers_start($self, 1);
444         $lei->{wq1} = $self;
445         $self->wq_io_do('do_mirror', []);
446         $self->wq_close(1);
447         $lei->wait_wq_events($op_c, $ops);
448 }
449
450 sub ipc_atfork_child {
451         my ($self) = @_;
452         $self->{lei}->_lei_atfork_child;
453         $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
454         $self->SUPER::ipc_atfork_child;
455 }
456
457 sub write_makefile {
458         my ($dir, $ibx_ver) = @_;
459         my $f = "$dir/Makefile";
460         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
461                 print $fh <<EOM or die "print($f) $!";
462 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
463 # manpage for more information on the format.  This Makefile is
464 # intended as a familiar wrapper for users unfamiliar with
465 # public-inbox-* commands.
466 #
467 # See the respective manpages for public-inbox-fetch(1),
468 # public-inbox-index(1), etc for more information on
469 # some of the commands used by this Makefile.
470 #
471 # This Makefile will not be modified nor read by public-inbox,
472 # so you may edit it freely with your own convenience targets
473 # and notes.  public-inbox-fetch will recreate it if removed.
474 EOM
475                 print $fh <<'EOM' or die "print($f): $!";
476 # the default target:
477 help :
478         @echo Common targets:
479         @echo '    make fetch        - fetch from remote git repostorie(s)'
480         @echo '    make update       - fetch and update index '
481         @echo
482         @echo Rarely needed targets:
483         @echo '    make reindex      - may be needed for new features/bugfixes'
484         @echo '    make compact      - rewrite Xapian storage to save space'
485
486 fetch :
487         public-inbox-fetch
488 update :
489         @if ! public-inbox-fetch --exit-code; \
490         then \
491                 c=$$?; \
492                 test $$c -eq 127 && exit 0; \
493                 exit $$c; \
494         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
495         then \
496                 public-inbox-index; \
497         else \
498                 echo 'public-inbox index not initialized'; \
499                 echo 'see public-inbox-index(1) man page'; \
500         fi
501 reindex :
502         public-inbox-index --reindex
503 compact :
504         public-inbox-compact
505
506 .PHONY : help fetch update reindex compact
507 EOM
508                 close $fh or die "close($f): $!";
509         } else {
510                 die "open($f): $!" unless $!{EEXIST};
511         }
512 }
513
514 1;