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