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