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