1 # Copyright (C) 2021 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 IO::Uncompress::Gunzip qw(gunzip $GunzipError);
11 use IO::Compress::Gzip qw(gzip $GzipError);
12 use PublicInbox::Spawn qw(popen_rd spawn run_die);
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
16 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
18 my ($mrr, $lei) = @$arg;
19 my $f = "$mrr->{dst}/mirror.done";
21 $lei->child_error($?);
22 } elsif (!unlink($f)) {
23 $lei->err("unlink($f): $!") unless $!{ENOENT};
25 if ($lei->{cmd} ne 'public-inbox-clone') {
26 $lei->lazy_cb('add-external', '_finish_'
27 )->($lei, $mrr->{dst});
29 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
34 # for old installations without manifest.js.gz
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");
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";
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)) {
57 my ($n) = (m!/([0-9]+)\z!);
60 return clone_v2($self, \%v2_epochs);
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)) {
67 E: confused by scraping <$uri>, did you mean <$url>?
71 E: confused by scraping <$uri>, got ambiguous results:
74 die "E: scraping <$uri> revealed nothing\n";
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...
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 $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
100 my $ce = "$self->{dst}/$file";
101 my $ft = File::Temp->new(TEMPLATE => "$file-XXXX",
102 UNLINK => 1, DIR => $self->{dst});
103 my $opt = { 0 => $lei->{0}, 1 => $ft, 2 => $lei->{2} };
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 $f = $ft->filename;
108 rename($f, $ce) or return "rename($f, $ce): $! (non-fatal)";
109 $ft->unlink_on_destroy(0);
113 # tries the relatively new /$INBOX/_/text/config/raw endpoint
116 my $dst = $self->{dst};
117 if (!-d $dst || !mkdir($dst)) {
119 File::Path::mkpath($dst);
120 -d $dst or die "mkpath($dst): $!\n";
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 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
126 my $ibx = $self->{ibx} = {};
127 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
128 for (qw(address newsgroup nntpmirror)) {
129 $ibx->{$_} = $cfg->{"$sec.$_"};
134 sub set_description ($) {
136 my $f = "$self->{dst}/description";
137 open my $fh, '+>>', $f or die "open($f): $!";
138 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
139 chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
140 if ($d eq '($INBOX_DIR/description missing)' ||
141 $d =~ /^Unnamed repository/ || $d !~ /\S/) {
142 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
143 truncate($fh, 0) or die "truncate($f): $!";
144 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
145 close $fh or die "close($f): $!";
149 sub index_cloned_inbox {
150 my ($self, $iv) = @_;
151 my $lei = $self->{lei};
152 my $err = _get_txt($self, qw(description description));
153 $lei->err($err) if $err; # non fatal
154 eval { set_description($self) };
157 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
158 # lei is useless without Xapian + SQLite
159 if ($lei->{cmd} ne 'public-inbox-clone') {
160 my $ibx = delete($self->{ibx}) // {
161 address => [ 'lei@example.com' ],
164 $ibx->{inboxdir} = $self->{dst};
165 PublicInbox::Inbox->new($ibx);
166 PublicInbox::InboxWritable->new($ibx);
168 for my $sw ($lei->index_opt) {
169 my ($k) = ($sw =~ /\A([\w-]+)/);
170 $opt->{$k} = $lei->{opt}->{$k};
172 # force synchronous dwaitpid for v2:
173 local $PublicInbox::DS::in_loop = 0;
174 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
175 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
176 local %ENV = (%ENV, %$env) if $env;
177 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
178 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
180 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
184 my ($lei, $cmd, $opt) = @_;
185 $lei->qerr("# @$cmd");
186 $opt->{pgid} = 0 if $lei->{sock};
187 my $pid = spawn($cmd, undef, $opt);
188 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
189 waitpid($pid, 0) == $pid or die "waitpid @$cmd: $!";
190 @$reap = (); # cancel reap
192 $? = 0; # don't let it influence normal exit
198 my $lei = $self->{lei};
199 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
200 my $uri = URI->new($self->{src});
201 defined($lei->{opt}->{epoch}) and
202 die "$uri is a v1 inbox, --epoch is not supported\n";
203 my $pfx = $curl->torsocks($lei, $uri) or return;
204 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
205 $uri->as_string, $self->{dst} ];
206 my $cerr = run_reap($lei, $cmd, $opt);
207 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
209 write_makefile($self->{dst}, 1);
210 index_cloned_inbox($self, 1);
213 sub parse_epochs ($$) {
214 my ($opt_epochs, $v2_epochs) = @_; # $epcohs "LOW..HIGH"
215 $opt_epochs // return; # undef => all epochs
216 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
217 undef($lo) if ($lo // '') eq '';
218 my $re = qr/\A~?[0-9]+\z/;
219 if (@extra || (($lo // '0') !~ $re) ||
220 (($hi // '0') !~ $re) ||
221 !(grep(defined, $lo, $hi))) {
223 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
226 my @n = sort { $a <=> $b } keys %$v2_epochs;
227 for (grep(defined, $lo, $hi)) {
230 "`$_' exceeds maximum available epoch ($n[-1])\n";
232 "`$_' is lower than minimum available epoch ($n[0])\n";
233 } elsif (/\A~([0-9]+)/) {
235 $n[$off] // die "`$_' is out of range\n";
237 } else { die "`$_' not understood\n" }
239 defined($lo) && defined($hi) && $lo > $hi and die
240 "low value (`$lo') exceeds high (`$hi')\n";
241 $lo //= $n[0] if $dotdot;
242 $hi //= $n[-1] if $dotdot;
246 if (defined $v2_epochs->{$_}) {
250 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
256 sub init_placeholder ($$) {
257 my ($src, $edst) = @_;
258 PublicInbox::Import::init_bare($edst);
259 my $f = "$edst/config";
260 open my $fh, '>>', $f or die "open($f): $!";
261 print $fh <<EOM or die "print($f): $!";
264 fetch = +refs/*:refs/*
267 ; This git epoch was created read-only and "public-inbox-fetch"
268 ; will not fetch updates for it unless write permission is added.
270 close $fh or die "close:($f): $!";
273 sub clone_v2 ($$;$) {
274 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
275 my $lei = $self->{lei};
276 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
277 my $pfx = $curl->torsocks($lei, (values %$v2_epochs)[0]) or return;
278 my $dst = $self->{dst};
279 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
280 my (@src_edst, @read_only, @skip_nr);
281 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
282 my $uri = $v2_epochs->{$nr};
283 my $src = $uri->as_string;
285 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
286 failed to extract epoch number from $src
288 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
289 $edst .= "/git/$nr.git";
290 if (!$want || $want->{$nr}) {
291 push @src_edst, $src, $edst;
292 } else { # create a placeholder so users only need to chmod +w
293 init_placeholder($src, $edst);
294 push @read_only, $edst;
298 if (@skip_nr) { # filter out the epochs we skipped
299 my $re = join('|', @skip_nr);
300 my @del = grep(m!/git/$re\.git\z!, keys %$m);
302 $self->{-culled_manifest} = 1;
304 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
306 my $on_destroy = $lk->lock_for_scope($$);
307 my @cmd = clone_cmd($lei, my $opt = {});
308 while (my ($src, $edst) = splice(@src_edst, 0, 2)) {
309 my $cmd = [ @$pfx, @cmd, $src, $edst ];
310 my $cerr = run_reap($lei, $cmd, $opt);
311 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
313 require PublicInbox::MultiGit;
314 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
315 $mg->fill_alternates;
316 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
317 for my $edst (@read_only) {
318 my @st = stat($edst) or die "stat($edst): $!";
319 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
321 write_makefile($self->{dst}, 2);
322 undef $on_destroy; # unlock
323 index_cloned_inbox($self, 2);
326 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
327 sub deduce_epochs ($$) {
329 my ($v1_ent, @v2_epochs);
333 $v1_ent = $m->{$path};
334 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
335 } while (!defined($v1_ent) && !@v2_epochs &&
336 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
337 ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
340 sub decode_manifest ($$$) {
341 my ($fh, $fn, $uri) = @_;
343 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
344 gunzip(\$gz => \$js, MultiStream => 1) or
345 die "gunzip($uri): $GunzipError\n";
346 my $m = eval { PublicInbox::Config->json->decode($js) };
347 die "$uri: error decoding `$js': $@\n" if $@;
348 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
354 my $uri = URI->new($self->{src});
355 my $lei = $self->{lei};
356 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
357 my $path = $uri->path;
358 chop($path) eq '/' or die "BUG: $uri not canonicalized";
359 $uri->path($path . '/manifest.js.gz');
360 my $pdir = $lei->rel2abs($self->{dst});
361 $pdir =~ s!/[^/]+/?\z!!;
362 my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
363 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
364 my $fn = $ft->filename;
365 my ($bn) = ($fn =~ m!/([^/]+)\z!);
366 my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
367 my $opt = { -C => $pdir };
368 $opt->{$_} = $lei->{$_} for (0..2);
369 my $cerr = run_reap($lei, $cmd, $opt);
371 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
372 return $lei->child_error($cerr, "@$cmd failed");
374 my $m = eval { decode_manifest($ft, $fn, $uri) };
377 return try_scrape($self);
379 my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
381 # It may be possible to have v1 + v2 in parallel someday:
382 $lei->err(<<EOM) if defined $v1_path;
383 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
385 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
387 my %v2_epochs = map {
388 $uri->path($path_pfx.$_);
389 my ($n) = ("$uri" =~ m!/([0-9]+)\.git\z!);
392 clone_v2($self, \%v2_epochs, $m);
393 } elsif (defined $v1_path) {
396 die "E: confused by <$uri>, possible matches:\n\t",
397 join(', ', sort keys %$m), "\n";
399 if (delete $self->{-culled_manifest}) { # set by clone_v2
400 # write the smaller manifest if epochs were skipped so
401 # users won't have to delete manifest if they +w an
402 # epoch they no longer want to skip
403 my $json = PublicInbox::Config->json->encode($m);
404 gzip(\$json => $fn) or die "gzip: $GzipError";
406 my $fin = "$self->{dst}/manifest.js.gz";
407 rename($fn, $fin) or die "E: rename($fn, $fin): $!";
408 $ft->unlink_on_destroy(0);
411 sub start_clone_url {
413 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
414 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
417 sub do_mirror { # via wq_io_do
419 my $lei = $self->{lei};
421 my $iv = $lei->{opt}->{'inbox-version'};
423 return clone_v1($self) if $iv == 1;
424 return try_scrape($self) if $iv == 2;
425 die "bad --inbox-version=$iv\n";
427 return start_clone_url($self) if $self->{src} =~ m!://!;
428 die "TODO: cloning local directories not supported, yet";
430 $lei->fail($@) if $@;
434 my ($cls, $lei, $src, $dst) = @_;
435 my $self = bless { src => $src, dst => $dst }, $cls;
436 if ($src =~ m!https?://!) {
438 require PublicInbox::LeiCurl;
440 require PublicInbox::Lock;
441 require PublicInbox::Inbox;
442 require PublicInbox::Admin;
443 require PublicInbox::InboxWritable;
444 my ($op_c, $ops) = $lei->workers_start($self, 1);
446 $self->wq_io_do('do_mirror', []);
448 $lei->wait_wq_events($op_c, $ops);
451 sub ipc_atfork_child {
453 $self->{lei}->_lei_atfork_child;
454 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
455 $self->SUPER::ipc_atfork_child;
459 my ($dir, $ibx_ver) = @_;
460 my $f = "$dir/Makefile";
461 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
462 print $fh <<EOM or die "print($f) $!";
463 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
464 # manpage for more information on the format. This Makefile is
465 # intended as a familiar wrapper for users unfamiliar with
466 # public-inbox-* commands.
468 # See the respective manpages for public-inbox-fetch(1),
469 # public-inbox-index(1), etc for more information on
470 # some of the commands used by this Makefile.
472 # This Makefile will not be modified nor read by public-inbox,
473 # so you may edit it freely with your own convenience targets
474 # and notes. public-inbox-fetch will recreate it if removed.
476 print $fh <<'EOM' or die "print($f): $!";
477 # the default target:
479 @echo Common targets:
480 @echo ' make fetch - fetch from remote git repostorie(s)'
481 @echo ' make update - fetch and update index '
483 @echo Rarely needed targets:
484 @echo ' make reindex - may be needed for new features/bugfixes'
485 @echo ' make compact - rewrite Xapian storage to save space'
490 @if ! public-inbox-fetch --exit-code; \
493 test $$c -eq 127 && exit 0; \
495 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
497 public-inbox-index; \
499 echo 'public-inbox index not initialized'; \
500 echo 'see public-inbox-index(1) man page'; \
503 public-inbox-index --reindex
507 .PHONY : help fetch update reindex compact
509 close $fh or die "close($f): $!";
511 die "open($f): $!" unless $!{EEXIST};