1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
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);
15 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
17 use POSIX qw(WNOHANG);
19 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
21 my ($mrr, $lei) = @$arg;
22 my $f = "$mrr->{dst}/mirror.done";
24 $lei->child_error($?);
25 } elsif (!unlink($f)) {
26 warn("unlink($f): $!\n") unless $!{ENOENT};
28 if ($lei->{cmd} ne 'public-inbox-clone') {
29 # calls _finish_add_external
30 $lei->lazy_cb('add-external', '_finish_'
31 )->($lei, $mrr->{dst});
33 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
38 # for old installations without manifest.js.gz
41 my $uri = URI->new($self->{src});
42 my $lei = $self->{lei};
43 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
44 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
45 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
46 my $fh = popen_rd($cmd, undef, $opt);
47 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
48 close($fh) or return $lei->child_error($?, "@$cmd failed");
50 # we grep with URL below, we don't want Subject/From headers
51 # making us clone random URLs
52 my @html = split(/<hr>/, $html);
53 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
54 my $url = $uri->as_string;
55 chop($url) eq '/' or die "BUG: $uri not canonicalized";
57 # since this is for old instances w/o manifest.js.gz, try v1 first
58 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
59 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
61 my ($n) = (m!/([0-9]+)\z!);
62 $n => [ URI->new($_), '' ]
64 return clone_v2($self, \%v2_epochs);
67 # filter out common URLs served by WWW (e.g /$MSGID/T/)
68 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
69 grep(m!\A\Q$url\E/*\z!, @urls)) {
71 E: confused by scraping <$uri>, did you mean <$url>?
75 E: confused by scraping <$uri>, got ambiguous results:
78 die "E: scraping <$uri> revealed nothing\n";
84 $opt->{$_} = $lei->{$_} for (0..2);
85 # we support "-c $key=$val" for arbitrary git config options
86 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
87 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
88 push @cmd, qw(clone --mirror);
89 push @cmd, '-q' if $lei->{opt}->{quiet};
90 push @cmd, '-v' if $lei->{opt}->{verbose};
91 # XXX any other options to support?
92 # --reference is tricky with multiple epochs...
97 my ($ft, $dst, $open_mode) = @_;
98 my $fn = $ft->filename;
100 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
101 chmod($mode, $ft) or croak "E: chmod $fn: $!";
102 rename($fn, $dst) or croak "E: rename($fn => $ft): $!";
103 $ft->unlink_on_destroy(0);
106 sub _get_txt { # non-fatal
107 my ($self, $endpoint, $file, $mode) = @_;
108 my $uri = URI->new($self->{cur_src} // $self->{src});
109 my $lei = $self->{lei};
110 my $path = $uri->path;
111 chop($path) eq '/' or die "BUG: $uri not canonicalized";
112 $uri->path("$path/$endpoint");
113 my $dst = $self->{cur_dst} // $self->{dst};
114 my $ft = File::Temp->new(TEMPLATE => "$file-XXXX", DIR => $dst);
115 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
116 my $cmd = $self->{curl}->for_uri($lei, $uri,
117 qw(--compressed -R -o), $ft->filename);
118 my $cerr = run_reap($lei, $cmd, $opt);
119 return "$uri missing" if ($cerr >> 8) == 22;
120 return "# @$cmd failed (non-fatal)" if $cerr;
121 ft_rename($ft, "$dst/$file", $mode);
125 # tries the relatively new /$INBOX/_/text/config/raw endpoint
128 my $dst = $self->{cur_dst} // $self->{dst};
129 if (!-d $dst || !mkdir($dst)) {
131 File::Path::mkpath($dst);
132 -d $dst or die "mkpath($dst): $!\n";
134 my $err = _get_txt($self,
135 qw(_/text/config/raw inbox.config.example), 0444);
136 return warn($err, "\n") if $err;
137 my $f = "$dst/inbox.config.example";
138 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
139 my $ibx = $self->{ibx} = {};
140 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
141 for (qw(address newsgroup nntpmirror)) {
142 $ibx->{$_} = $cfg->{"$sec.$_"};
147 sub set_description ($) {
149 my $dst = $self->{cur_dst} // $self->{dst};
150 my $f = "$dst/description";
151 open my $fh, '+>>', $f or die "open($f): $!";
152 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
153 chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
154 if ($d eq '($INBOX_DIR/description missing)' ||
155 $d =~ /^Unnamed repository/ || $d !~ /\S/) {
156 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
157 truncate($fh, 0) or die "truncate($f): $!";
158 my $src = $self->{cur_src} // $self->{src};
159 print $fh "mirror of $src\n" or die "print($f): $!";
160 close $fh or die "close($f): $!";
164 sub index_cloned_inbox {
165 my ($self, $iv) = @_;
166 my $lei = $self->{lei};
167 my $err = _get_txt($self, qw(description description), 0666);
168 warn($err, "\n") if $err; # non fatal
169 eval { set_description($self) };
172 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
173 # lei is useless without Xapian + SQLite
174 if ($lei->{cmd} ne 'public-inbox-clone') {
175 my $ibx = delete($self->{ibx}) // {
176 address => [ 'lei@example.com' ],
179 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
180 PublicInbox::Inbox->new($ibx);
181 PublicInbox::InboxWritable->new($ibx);
183 for my $sw ($lei->index_opt) {
184 my ($k) = ($sw =~ /\A([\w-]+)/);
185 $opt->{$k} = $lei->{opt}->{$k};
187 # force synchronous dwaitpid for v2:
188 local $PublicInbox::DS::in_loop = 0;
189 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
190 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
191 local %ENV = (%ENV, %$env) if $env;
192 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
193 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
195 return if defined $self->{cur_dst};
196 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
200 my ($lei, $cmd, $opt) = @_;
201 $lei->qerr("# @$cmd");
202 my $ar = PublicInbox::AutoReap->new(spawn($cmd, undef, $opt));
205 $? = 0; # don't let it influence normal exit
211 my $lei = $self->{lei};
212 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
213 my $uri = URI->new($self->{cur_src} // $self->{src});
214 defined($lei->{opt}->{epoch}) and
215 die "$uri is a v1 inbox, --epoch is not supported\n";
216 my $pfx = $curl->torsocks($lei, $uri) or return;
217 my $dst = $self->{cur_dst} // $self->{dst};
218 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
219 $uri->as_string, $dst ];
220 my $cerr = run_reap($lei, $cmd, $opt);
221 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
223 write_makefile($dst, 1);
224 index_cloned_inbox($self, 1);
227 sub parse_epochs ($$) {
228 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
229 $opt_epochs // return; # undef => all epochs
230 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
231 undef($lo) if ($lo // '') eq '';
232 my $re = qr/\A~?[0-9]+\z/;
233 if (@extra || (($lo // '0') !~ $re) ||
234 (($hi // '0') !~ $re) ||
235 !(grep(defined, $lo, $hi))) {
237 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
240 my @n = sort { $a <=> $b } keys %$v2_epochs;
241 for (grep(defined, $lo, $hi)) {
244 "`$_' exceeds maximum available epoch ($n[-1])\n";
246 "`$_' is lower than minimum available epoch ($n[0])\n";
247 } elsif (/\A~([0-9]+)/) {
249 $n[$off] // die "`$_' is out of range\n";
251 } else { die "`$_' not understood\n" }
253 defined($lo) && defined($hi) && $lo > $hi and die
254 "low value (`$lo') exceeds high (`$hi')\n";
255 $lo //= $n[0] if $dotdot;
256 $hi //= $n[-1] if $dotdot;
260 if (defined $v2_epochs->{$_}) {
264 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
270 sub init_placeholder ($$) {
271 my ($src, $edst) = @_;
272 PublicInbox::Import::init_bare($edst);
273 my $f = "$edst/config";
274 open my $fh, '>>', $f or die "open($f): $!";
275 print $fh <<EOM or die "print($f): $!";
278 fetch = +refs/*:refs/*
281 ; This git epoch was created read-only and "public-inbox-fetch"
282 ; will not fetch updates for it unless write permission is added.
284 close $fh or die "close:($f): $!";
287 sub reap_clone { # async, called via SIGCHLD
288 my ($lei, $cmd, $live) = @_;
290 $? = 0; # don't let it influence normal exit
292 kill('TERM', keys %$live);
293 $lei->child_error($cerr, "@$cmd failed");
297 sub clone_v2 ($$;$) {
298 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
299 my $lei = $self->{lei};
300 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
301 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
302 my $pfx = $curl->torsocks($lei, $first_uri) or return;
303 my $dst = $self->{cur_dst} // $self->{dst};
304 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
305 my (@src_edst, @read_only, @skip);
306 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
307 my ($uri, $key) = @{$v2_epochs->{$nr}};
308 my $src = $uri->as_string;
310 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
311 failed to extract epoch number from $src
313 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
314 $edst .= "/git/$nr.git";
315 if (!$want || $want->{$nr}) {
316 push @src_edst, $src, $edst;
317 } else { # create a placeholder so users only need to chmod +w
318 init_placeholder($src, $edst);
319 push @read_only, $edst;
323 # filter out the epochs we skipped
324 $self->{-culled_manifest} = 1 if delete(@$m{@skip});
325 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
326 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
329 my $on_destroy = $lk->lock_for_scope($$);
330 my @cmd = clone_cmd($lei, my $opt = {});
331 my $jobs = $self->{lei}->{opt}->{jobs} // 2;
335 my $flags = $sig ? WNOHANG : 0;
337 my $pid = waitpid(-1, $flags) or return;
339 if (my $x = delete $live{$pid}) {
343 warn "reaped unknown PID=$pid ($?)\n";
348 $sigchld->(0) while keys(%live) >= $jobs;
349 local $SIG{CHLD} = $sigchld;
350 while (keys(%live) < $jobs && @src_edst &&
351 !$lei->{child_error}) {
352 my $cmd = [ @$pfx, @cmd, splice(@src_edst, 0, 2) ];
353 $lei->qerr("# @$cmd");
354 my $pid = spawn($cmd, undef, $opt);
355 $live{$pid} = [ \&reap_clone, $lei, $cmd ];
357 } while (@src_edst && !$lei->{child_error});
358 $sigchld->(0) while keys(%live);
359 return if $lei->{child_error};
361 require PublicInbox::MultiGit;
362 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
363 $mg->fill_alternates;
364 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
365 for my $edst (@read_only) {
366 my @st = stat($edst) or die "stat($edst): $!";
367 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
369 write_makefile($dst, 2);
370 undef $on_destroy; # unlock
371 index_cloned_inbox($task, 2);
374 sub decode_manifest ($$$) {
375 my ($fh, $fn, $uri) = @_;
377 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
378 gunzip(\$gz => \$js, MultiStream => 1) or
379 die "gunzip($uri): $GunzipError\n";
380 my $m = eval { PublicInbox::Config->json->decode($js) };
381 die "$uri: error decoding `$js': $@\n" if $@;
382 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
386 sub multi_inbox ($$$) {
387 my ($self, $path, $m) = @_;
388 my $incl = $self->{lei}->{opt}->{include};
389 my $excl = $self->{lei}->{opt}->{exclude};
391 # assuming everything not v2 is v1, for now
392 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
393 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
397 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
398 push @{$v2->{$1}}, $_;
400 my $n = scalar(keys %$v2) + scalar(@v1);
401 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
403 my $re = '(?:'.join('|', map {
404 $self->{lei}->glob2re($_) // qr/\A\Q$_\E\z/
406 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
407 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
408 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
409 @v1 = grep(/$re/, @v1);
412 my $re = '(?:'.join('|', map {
413 $self->{lei}->glob2re($_) // qr/\A\Q$_\E\z/
415 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
416 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
417 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
418 @v1 = grep(!/$re/, @v1);
420 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
421 $ret->{v1} = \@v1 if @v1;
422 $ret->{v2} = $v2 if keys %$v2;
423 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
424 join("\n\t", sort @orig)
425 : "Nothing available to clone\n";
428 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
430 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
431 @v2_epochs) == @v2_epochs) {
432 $$path =~ s!\A(/[^/]+)/!/! or last;
436 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
440 ($path_pfx, $n, $ret);
443 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
446 my $uri = URI->new($self->{src});
447 my $lei = $self->{lei};
448 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
449 my $path = $uri->path;
450 chop($path) eq '/' or die "BUG: $uri not canonicalized";
451 $uri->path($path . '/manifest.js.gz');
452 my $pdir = $lei->rel2abs($self->{dst});
453 $pdir =~ s!/[^/]+/?\z!!;
454 my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
455 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
456 my $fn = $ft->filename;
457 my ($bn) = ($fn =~ m!/([^/]+)\z!);
458 my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
459 my $opt = { -C => $pdir };
460 $opt->{$_} = $lei->{$_} for (0..2);
461 my $cerr = run_reap($lei, $cmd, $opt);
463 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
464 return $lei->child_error($cerr, "@$cmd failed");
466 my $m = eval { decode_manifest($ft, $fn, $uri) };
469 return try_scrape($self);
471 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
472 return $lei->child_error(1, $multi) if !ref($multi);
473 if (my $v2 = delete $multi->{v2}) {
474 for my $name (sort keys %$v2) {
475 my $epochs = delete $v2->{$name};
476 my %v2_epochs = map {
477 $uri->path($n > 1 ? $path_pfx.$path.$_
479 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
480 $e // die "no [0-9]+\.git in `$uri'";
481 $e => [ $uri->clone, $_ ];
483 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
484 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
485 local $self->{cur_src} = $1;
486 local $self->{cur_dst} = $self->{dst};
487 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
488 git/[0-9]+\.git\z!x) {
489 $self->{cur_dst} .= "/$1";
491 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
492 E: `$self->{cur_dst}' must not contain newline
494 clone_v2($self, \%v2_epochs, $m);
497 if (my $v1 = delete $multi->{v1}) {
498 my $p = $path_pfx.$path;
499 chop($p) if substr($p, -1, 1) eq '/';
501 for my $name (@$v1) {
502 local $self->{cur_src} = "$uri";
503 local $self->{cur_dst} = $self->{dst};
505 $self->{cur_dst} .= $name;
506 $self->{cur_src} .= $name;
508 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
509 E: `$self->{cur_dst}' must not contain newline
511 $self->{cur_src} .= '/';
515 if (delete $self->{-culled_manifest}) { # set by clone_v2/-I/--exclude
516 # write the smaller manifest if epochs were skipped so
517 # users won't have to delete manifest if they +w an
518 # epoch they no longer want to skip
519 my $json = PublicInbox::Config->json->encode($m);
520 my $mtime = (stat($fn))[9];
521 gzip(\$json => $fn) or die "gzip: $GzipError";
522 utime($mtime, $mtime, $fn) or die "utime(..., $fn): $!";
524 ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
525 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
528 sub start_clone_url {
530 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
531 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
534 sub do_mirror { # via wq_io_do
536 my $lei = $self->{lei};
537 umask($lei->{client_umask}) if defined $lei->{client_umask};
539 my $iv = $lei->{opt}->{'inbox-version'};
541 return clone_v1($self) if $iv == 1;
542 return try_scrape($self) if $iv == 2;
543 die "bad --inbox-version=$iv\n";
545 return start_clone_url($self) if $self->{src} =~ m!://!;
546 die "TODO: cloning local directories not supported, yet";
548 $lei->fail($@) if $@;
552 my ($cls, $lei, $src, $dst) = @_;
553 my $self = bless { src => $src, dst => $dst }, $cls;
554 if ($src =~ m!https?://!) {
556 require PublicInbox::LeiCurl;
558 require PublicInbox::Lock;
559 require PublicInbox::Inbox;
560 require PublicInbox::Admin;
561 require PublicInbox::InboxWritable;
563 my ($op_c, $ops) = $lei->workers_start($self, 1);
565 $self->wq_io_do('do_mirror', []);
567 $lei->wait_wq_events($op_c, $ops);
570 sub ipc_atfork_child {
572 $self->{lei}->_lei_atfork_child;
573 $self->SUPER::ipc_atfork_child;
577 my ($dir, $ibx_ver) = @_;
578 my $f = "$dir/Makefile";
579 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
580 print $fh <<EOM or die "print($f) $!";
581 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
582 # manpage for more information on the format. This Makefile is
583 # intended as a familiar wrapper for users unfamiliar with
584 # public-inbox-* commands.
586 # See the respective manpages for public-inbox-fetch(1),
587 # public-inbox-index(1), etc for more information on
588 # some of the commands used by this Makefile.
590 # This Makefile will not be modified nor read by public-inbox,
591 # so you may edit it freely with your own convenience targets
592 # and notes. public-inbox-fetch will recreate it if removed.
594 print $fh <<'EOM' or die "print($f): $!";
595 # the default target:
597 @echo Common targets:
598 @echo ' make fetch - fetch from remote git repostorie(s)'
599 @echo ' make update - fetch and update index '
601 @echo Rarely needed targets:
602 @echo ' make reindex - may be needed for new features/bugfixes'
603 @echo ' make compact - rewrite Xapian storage to save space'
608 @if ! public-inbox-fetch --exit-code; \
611 test $$c -eq 127 && exit 0; \
613 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
615 public-inbox-index; \
617 echo 'public-inbox index not initialized'; \
618 echo 'see public-inbox-index(1) man page'; \
621 public-inbox-index --reindex
625 .PHONY : help fetch update reindex compact
627 close $fh or die "close($f): $!";
629 die "open($f): $!" unless $!{EEXIST};