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