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;
7 use parent qw(PublicInbox::IPC);
8 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
9 use IO::Compress::Gzip qw(gzip $GzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn run_die);
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use Digest::SHA qw(sha256_hex sha1_hex);
23 our $LIVE; # pid => callback
25 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
27 my ($mrr, $lei) = @$arg;
28 my $f = "$mrr->{dst}/mirror.done";
30 $lei->child_error($?);
31 } elsif (!$mrr->{dry_run} && !unlink($f)) {
32 warn("unlink($f): $!\n") unless $!{ENOENT};
34 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
35 require PublicInbox::LeiAddExternal;
36 PublicInbox::LeiAddExternal::_finish_add_external(
39 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
44 # for old installations without manifest.js.gz
46 my ($self, $fallback_manifest) = @_;
47 my $uri = URI->new($self->{src});
48 my $lei = $self->{lei};
49 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
50 my $cmd = $curl->for_uri($lei, $uri, qw(-f --compressed));
51 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
52 my $fh = popen_rd($cmd, undef, $opt);
53 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
54 close($fh) or return $lei->child_error($?, "@$cmd failed");
56 # we grep with URL below, we don't want Subject/From headers
57 # making us clone random URLs. This assumes remote instances
58 # prior to public-inbox 1.7.0
59 # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
60 my @html = split(/<hr>/, $html);
61 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
62 if (!@urls && $fallback_manifest) {
64 W: failed to extract URLs from $uri, trying manifest.js.gz...
66 return start_clone_url($self);
68 my $url = $uri->as_string;
69 chop($url) eq '/' or die "BUG: $uri not canonicalized";
71 # since this is for old instances w/o manifest.js.gz, try v1 first
72 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
73 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
75 my ($n) = (m!/([0-9]+)\z!);
76 $n => [ URI->new($_), '' ]
78 clone_v2_prep($self, \%v2_epochs);
79 delete local $lei->{opt}->{epoch};
84 # filter out common URLs served by WWW (e.g /$MSGID/T/)
85 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
86 grep(m!\A\Q$url\E/*\z!, @urls)) {
88 E: confused by scraping <$uri>, did you mean <$url>?
92 E: confused by scraping <$uri>, got ambiguous results:
95 die "E: scraping <$uri> revealed nothing\n";
101 $opt->{$_} = $lei->{$_} for (0..2);
102 # we support "-c $key=$val" for arbitrary git config options
103 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
104 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
105 push @cmd, qw(clone --mirror);
106 push @cmd, '-q' if $lei->{opt}->{quiet} ||
107 ($lei->{opt}->{jobs} // 1) > 1;
108 push @cmd, '-v' if $lei->{opt}->{verbose};
109 # XXX any other options to support?
110 # --reference is tricky with multiple epochs, but handled
111 # automatically if using manifest.js.gz
115 sub ft_rename ($$$;$) {
116 my ($ft, $dst, $open_mode, $fh) = @_;
117 my @st = stat($fh // $dst);
118 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
119 chmod($mode, $ft) or croak "E: chmod($ft): $!";
121 File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
122 $ft->unlink_on_destroy(0);
126 my ($self, $jobs) = @_;
127 $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
128 $jobs = 1 if $jobs < 1;
129 while (keys(%$LIVE) >= $jobs) {
130 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
131 if (my $x = delete $LIVE->{$pid}) {
135 warn "reaped unknown PID=$pid ($?)\n";
140 sub _get_txt_start { # non-fatal
141 my ($self, $endpoint, $fini) = @_;
142 my $uri = URI->new($self->{cur_src} // $self->{src});
143 my $lei = $self->{lei};
144 my $path = $uri->path;
145 chop($path) eq '/' or die "BUG: $uri not canonicalized";
146 $uri->path("$path/$endpoint");
147 my $f = (split(m!/!, $endpoint))[-1];
148 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
149 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
150 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(-f --compressed -R -o),
153 $lei->qerr("# @$cmd");
154 return if $self->{dry_run};
155 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
156 $LIVE->{spawn($cmd, undef, $opt)} =
157 [ \&_get_txt_done, $self, $endpoint, $fini ];
160 sub _get_txt_done { # returns true on error (non-fatal), undef on success
161 my ($self, $endpoint) = @_;
162 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
164 $? = 0; # don't influence normal lei exit
165 return warn("$uri missing\n") if ($cerr >> 8) == 22;
166 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
167 seek($fh, SEEK_SET, 0) or die "seek: $!";
168 $self->{"mtime.$endpoint"} = (stat($fh))[9];
170 $self->{"txt.$endpoint"} = <$fh>;
174 sub _write_inbox_config {
176 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
177 my $dst = $self->{cur_dst} // $self->{dst};
178 my $f = "$dst/inbox.config.example";
179 open my $fh, '>', $f or die "open($f): $!";
180 print $fh $buf or die "print: $!";
181 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
182 my $mtime = delete $self->{'mtime._/text/config/raw'};
183 $fh->flush or die "flush($f): $!";
184 if (defined $mtime) {
185 utime($mtime, $mtime, $fh) or die "utime($f): $!";
187 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
188 my $ibx = $self->{ibx} = {};
189 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
190 for (qw(address newsgroup nntpmirror)) {
191 $ibx->{$_} = $cfg->{"$sec.$_"};
196 sub set_description ($) {
198 my $dst = $self->{cur_dst} // $self->{dst};
199 my $f = "$dst/description";
200 open my $fh, '+>>', $f or die "open($f): $!";
201 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
202 my $d = do { local $/; <$fh> } // die "read($f): $!";
203 chomp(my $orig = $d);
204 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
205 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
206 $d = delete($self->{'txt.description'});
208 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
210 return if $d eq $orig;
211 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
212 truncate($fh, 0) or die "truncate($f): $!";
213 print $fh $d, "\n" or die "print($f): $!";
214 close $fh or die "close($f): $!";
217 sub index_cloned_inbox {
218 my ($self, $iv) = @_;
219 my $lei = $self->{lei};
221 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
222 # lei is useless without Xapian + SQLite
223 if ($lei->{cmd} ne 'public-inbox-clone') {
224 require PublicInbox::InboxWritable;
225 require PublicInbox::Admin;
226 my $ibx = delete($self->{ibx}) // {
227 address => [ 'lei@example.com' ],
230 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
231 PublicInbox::Inbox->new($ibx);
232 PublicInbox::InboxWritable->new($ibx);
234 for my $sw ($lei->index_opt) {
235 my ($k) = ($sw =~ /\A([\w-]+)/);
236 $opt->{$k} = $lei->{opt}->{$k};
238 # force synchronous dwaitpid for v2:
239 local $PublicInbox::DS::in_loop = 0;
240 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
241 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
242 local %ENV = (%ENV, %$env) if $env;
243 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
244 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
246 return if defined $self->{cur_dst}; # one of many repos to clone
247 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
251 my ($lei, $cmd, $opt) = @_;
252 $lei->qerr("# @$cmd");
253 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
255 $? = 0; # don't let it influence normal exit
260 my ($self, $cmd, $opt, $fini) = @_;
262 $self->{lei}->qerr("# @$cmd");
263 return if $self->{dry_run};
264 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
267 sub fetch_args ($$) {
268 my ($lei, $opt) = @_;
269 my @cmd; # (git --git-dir=...) to be added by caller
270 $opt->{$_} = $lei->{$_} for (0..2);
271 # we support "-c $key=$val" for arbitrary git config options
272 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
273 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
275 push @cmd, '-q' if $lei->{opt}->{quiet} ||
276 ($lei->{opt}->{jobs} // 1) > 1;
277 push @cmd, '-v' if $lei->{opt}->{verbose};
281 sub upr { # feed `git update-ref --stdin -z' verbosely
282 my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
283 $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
284 print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
289 my $srcfh = delete $fgrp->{srcfh} or return;
290 my $dstfh = delete $fgrp->{dstfh} or return;
291 seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
292 seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
293 my %src = map { chomp; split(/\0/) } (<$srcfh>);
295 my %dst = map { chomp; split(/\0/) } (<$dstfh>);
297 pipe(my ($r, $w)) or die "pipe: $!";
298 my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
299 qw(update-ref --stdin -z) ];
300 my $lei = $fgrp->{lei};
301 $lei->qerr("# @$cmd");
302 my $opt = { 0 => $r, 1 => $lei->{1}, 2 => $lei->{2} };
303 my $pid = spawn($cmd, undef, $opt);
304 close $r or die "close(r): $!";
305 for my $ref (keys %dst) {
306 my $new = delete $src{$ref};
307 my $old = $dst{$ref};
310 upr($lei, $w, 'update', $ref, $new, $old);
312 upr($lei, $w, 'delete', $ref, $old);
315 while (my ($ref, $oid) = each %src) {
316 upr($lei, $w, 'create', $ref, $oid);
318 close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
319 my $pack = PublicInbox::OnDestroy->new($$, \&pack_dst, $fgrp);
320 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd, $pack ];
323 sub pack_dst { # packs lightweight satellite repos
325 pack_refs($fgrp, $fgrp->{cur_dst});
329 my ($self, $git_dir) = @_;
331 my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
332 $self->{lei}->qerr("# @$cmd");
333 return if $self->{dry_run};
334 my $opt = { 1 => $self->{lei}->{1}, 2 => $self->{lei}->{2} };
335 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd ];
342 my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
343 pack_refs($first, $first->{-osdir}); # objstore refs always packed
344 for my $fgrp (@$fgrpv) {
345 my $rn = $fgrp->{-remote};
346 my %opt = map { $_ => $fgrp->{lei}->{$_} } (0..2);
348 my $update_ref = $fgrp->{dry_run} ? undef :
349 PublicInbox::OnDestroy->new($$, \&fgrp_update, $fgrp);
351 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
352 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
353 "refs/remotes/$rn/" ];
355 $fgrp->{lei}->qerr("# @$src >SRC");
357 open(my $fh, '+>', undef) or die "open(src): $!";
358 $pid = spawn($src, undef, { %opt, 1 => $fh });
359 $fgrp->{srcfh} = $fh;
360 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $src, $update_ref ]
362 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
363 '--format=%(refname)%00%(objectname)' ];
365 $fgrp->{lei}->qerr("# @$dst >DST");
367 open(my $fh, '+>', undef) or die "open(dst): $!";
368 $pid = spawn($dst, undef, { %opt, 1 => $fh });
369 $fgrp->{dstfh} = $fh;
370 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $dst, $update_ref ]
377 my $todo = delete $self->{fgrp_todo} or return;
378 keys(%$todo) or return;
380 # Rely on the fgrptmp remote groups in the config file rather
381 # than listing all remotes since the remote name list may exceed
382 # system argv limits:
385 my @git = (@{$self->{-torsocks}}, 'git');
386 my $j = $self->{lei}->{opt}->{jobs};
389 local $self->{lei}->{opt}->{jobs} = 1;
390 (fetch_args($self->{lei}, $opt),
391 qw(--no-tags --multiple));
393 push(@fetch, "-j$j") if $j;
395 while (my ($osdir, $fgrpv) = each %$todo) {
396 my $f = "$osdir/config";
398 # clobber group from previous run atomically
399 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
400 $f, '--unset-all', "remotes.$grp"];
401 $self->{lei}->qerr("# @$cmd");
402 if (!$self->{dry_run}) {
404 waitpid($pid, 0) // die "waitpid: $!";
405 die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
407 # update the config atomically via O_APPEND while
408 # respecting git-config locking
409 sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
410 or die "open($f.lock): $!";
411 open my $fh, '>>', $f or die "open(>>$f): $!";
413 my $buf = join('', "[remotes]\n",
414 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
415 print $fh $buf or die "print($f): $!";
416 close $fh or die "close($f): $!";
417 unlink("$f.lock") or die "unlink($f.lock): $!";
420 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
422 $self->{lei}->qerr("# @$cmd");
423 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
424 return if $self->{dry_run};
425 $pid = spawn($cmd, undef, $opt);
426 $LIVE->{$pid} = [ \&reap_cmd, $self, $cmd, $end ];
430 # keep this idempotent for future use by public-inbox-fetch
432 my ($self, $uri) = @_;
433 $self->{-ent} // return;
434 my $os = $self->{-objstore} // return;
435 my $fg = $self->{-ent}->{forkgroup} // return;
436 my $dir = "$os/$fg.git";
437 my @cmd = ('git', "--git-dir=$dir", 'config');
438 my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
439 if (!-d $dir && !$self->{dry_run}) {
440 PublicInbox::Import::init_bare($dir);
441 for ('repack.useDeltaIslands=true',
442 'pack.island=refs/remotes/([^/]+)/') {
443 run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
446 my $key = $self->{-key} // die 'BUG: no -key';
447 my $rn = substr(sha256_hex($key), 0, 16);
448 unless ($self->{dry_run}) {
449 # --no-tags is required to avoid conflicts
450 for ("url=$uri", "fetch=+refs/*:refs/remotes/$rn/*",
451 'tagopt=--no-tags') {
452 my @kv = split(/=/, $_, 2);
453 $kv[0] = "remote.$rn.$kv[0]";
454 run_die([@cmd, @kv], undef, $opt);
457 if (!-d $self->{cur_dst} && !$self->{dry_run}) {
458 my $alt = File::Spec->rel2abs("$dir/objects");
459 PublicInbox::Import::init_bare($self->{cur_dst});
460 my $o = "$self->{cur_dst}/objects";
461 my $f = "$o/info/alternates";
462 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
463 open my $fh, '+>>', $f or die "open($f): $!";
464 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
465 chomp(my @cur = <$fh>);
466 if (!grep(/\A\Q$l\E\z/, @cur)) {
467 say $fh $l or die "say($f): $!";
469 close $fh or die "close($f): $!";
470 $f = "$self->{cur_dst}/config";
471 open $fh, '+>>', $f or die "open:($f): $!";
472 print $fh <<EOM or die "print($f): $!";
473 ; rely on the "$rn" remote in the
474 ; $fg fork group for fetches
475 ; only uncomment the following iff you detach from fork groups
478 ; fetch = +refs/*:refs/*
481 close $fh or die "close($f): $!";
483 bless { %$self, -osdir => $dir, -remote => $rn }, __PACKAGE__;
487 my ($self, $go_fetch) = @_;
488 my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
489 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
490 $self->{-ent} // die 'BUG: no -ent';
491 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
492 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
493 return if $A ne $B; # $go_fetch->DESTROY fires
495 $self->{lei}->qerr("# $self->{-key} up-to-date");
499 my ($self, $go_fetch) = @_;
500 # $go_fetch is either resume_fetch or fgrp_enqueue
501 my $new = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
502 my $key = $self->{-key} // die 'BUG: no -key';
503 if (my $cur_ent = $self->{-local_manifest}->{$key}) {
504 # runs go_fetch->DESTROY run if eq
505 return $go_fetch->cancel if $cur_ent->{fingerprint} eq $new;
507 my $dst = $self->{cur_dst} // $self->{dst};
508 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
509 my $opt = { 2 => $self->{lei}->{2} };
510 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
511 $self->{-show_ref} = $opt->{1};
512 my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $go_fetch);
513 start_cmd($self, $cmd, $opt, $done);
516 sub resume_fetch_maybe {
517 my ($self, $uri, $fini) = @_;
518 my $go_fetch = PublicInbox::OnDestroy->new($$, \&resume_fetch, @_);
519 cmp_fp_fetch($self, $go_fetch) if $self->{-ent} &&
520 defined($self->{-ent}->{fingerprint});
524 my ($self, $uri, $fini) = @_;
525 my $dst = $self->{cur_dst} // $self->{dst};
526 my @git = ('git', "--git-dir=$dst");
527 my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
528 my $rn = 'origin'; # configurable?
529 for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
530 my @kv = split(/=/, $_, 2);
531 $kv[0] = "remote.$rn.$kv[0]";
532 next if $self->{dry_run};
533 run_die([@git, 'config', @kv], undef, $opt);
535 my $cmd = [ @{$self->{-torsocks}}, @git,
536 fetch_args($self->{lei}, $opt), $rn ];
537 start_cmd($self, $cmd, $opt, $fini);
540 sub fgrp_enqueue_maybe {
541 my ($self, $fgrp) = @_;
542 my $enq = PublicInbox::OnDestroy->new($$, \&fgrp_enqueue, $self, $fgrp);
543 cmp_fp_fetch($self, $enq) if $self->{-ent} &&
544 defined($self->{-ent}->{fingerprint});
545 # $enq->DESTROY calls fgrp_enqueue otherwise
549 my ($self, $fgrp) = @_;
550 push @{$self->{fgrp_todo}->{$fgrp->{-osdir}}}, $fgrp;
554 my ($self, $nohang) = @_;
555 my $lei = $self->{lei};
556 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
557 my $uri = URI->new($self->{cur_src} // $self->{src});
558 defined($lei->{opt}->{epoch}) and
559 die "$uri is a v1 inbox, --epoch is not supported\n";
560 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
561 my $dst = $self->{cur_dst} // $self->{dst};
562 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
563 my $resume = -d $dst;
564 if (my $fgrp = forkgroup_prep($self, $uri)) {
565 $fgrp->{-fini} = $fini;
566 $resume ? fgrp_enqueue_maybe($self, $fgrp) :
567 fgrp_enqueue($self, $fgrp);
569 resume_fetch_maybe($self, $uri, $fini);
570 } else { # normal clone
571 my $cmd = [ @{$self->{-torsocks}},
572 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
573 if (defined($self->{-ent})) {
574 if (defined(my $ref = $self->{-ent}->{reference})) {
575 -e "$self->{dst}$ref" and
576 push @$cmd, '--reference',
580 start_cmd($self, $cmd, $opt, $fini);
582 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
583 /\A(?:always|v1)\z/s) {
584 _get_txt_start($self, '_/text/config/raw', $fini);
587 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
588 $self->{'txt.description'} = $d if defined $d;
589 (!defined($d) && !$nohang) and
590 _get_txt_start($self, 'description', $fini);
592 $nohang or do_reap($self, 1); # for non-manifest clone
595 sub parse_epochs ($$) {
596 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
597 $opt_epochs // return; # undef => all epochs
598 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
599 undef($lo) if ($lo // '') eq '';
600 my $re = qr/\A~?[0-9]+\z/;
601 if (@extra || (($lo // '0') !~ $re) ||
602 (($hi // '0') !~ $re) ||
603 !(grep(defined, $lo, $hi))) {
605 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
608 my @n = sort { $a <=> $b } keys %$v2_epochs;
609 for (grep(defined, $lo, $hi)) {
612 "`$_' exceeds maximum available epoch ($n[-1])\n";
614 "`$_' is lower than minimum available epoch ($n[0])\n";
615 } elsif (/\A~([0-9]+)/) {
617 $n[$off] // die "`$_' is out of range\n";
619 } else { die "`$_' not understood\n" }
621 defined($lo) && defined($hi) && $lo > $hi and die
622 "low value (`$lo') exceeds high (`$hi')\n";
623 $lo //= $n[0] if $dotdot;
624 $hi //= $n[-1] if $dotdot;
628 if (defined $v2_epochs->{$_}) {
632 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
638 sub init_placeholder ($$$) {
639 my ($src, $edst, $ent) = @_;
640 PublicInbox::Import::init_bare($edst);
641 my $f = "$edst/config";
642 open my $fh, '>>', $f or die "open($f): $!";
643 print $fh <<EOM or die "print($f): $!";
646 fetch = +refs/*:refs/*
649 ; This git epoch was created read-only and "public-inbox-fetch"
650 ; will not fetch updates for it unless write permission is added.
651 ; Hint: chmod +w $edst
653 if (defined($ent->{owner})) {
654 print $fh <<EOM or die "print($f): $!";
656 owner = $ent->{owner}
659 close $fh or die "close($f): $!";
660 my %map = (head => 'HEAD', description => undef);
661 while (my ($key, $fn) = each %map) {
662 my $val = $ent->{$key} // next;
665 open $fh, '>', $fn or die "open($fn): $!";
666 print $fh $val, "\n" or die "print($fn): $!";
667 close $fh or die "close($fn): $!";
671 sub reap_cmd { # async, called via SIGCHLD
672 my ($self, $cmd) = @_;
674 $? = 0; # don't let it influence normal exit
676 kill('TERM', keys %$LIVE);
677 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)");
681 sub v1_done { # called via OnDestroy
683 return if $self->{dry_run} || !$LIVE;
684 _write_inbox_config($self);
685 my $dst = $self->{cur_dst} // $self->{dst};
686 if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
687 my $key = $self->{-key} // die 'BUG: no -key';
688 my $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
689 $cur eq $o or run_die([qw(git config -f),
690 "$dst/config", 'gitweb.owner', $o]);
692 my $o = "$dst/objects";
693 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
694 my $base = File::Spec->rel2abs($o);
699 $_ = File::Spec->abs2rel($_, $base);
700 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
704 print $ft @l or die "print($ft): $!";
705 $ft->flush or die "flush($ft): $!";
706 ft_rename($ft, $fn, 0666, $fh);
709 eval { set_description($self) };
711 return if ($self->{-is_epoch} ||
712 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
713 write_makefile($dst, 1);
714 index_cloned_inbox($self, 1);
717 sub v2_done { # called via OnDestroy
719 return if $self->{dry_run} || !$LIVE;
720 my $dst = $self->{cur_dst} // $self->{dst};
721 require PublicInbox::Lock;
722 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
723 my $lck = $lk->lock_for_scope($$);
724 _write_inbox_config($self);
725 require PublicInbox::MultiGit;
726 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
727 $mg->fill_alternates;
728 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
729 for my $edst (@{delete($self->{-read_only}) // []}) {
730 my @st = stat($edst) or die "stat($edst): $!";
731 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
733 write_makefile($dst, 2);
735 eval { set_description($self) };
737 index_cloned_inbox($self, 2);
740 sub clone_v2_prep ($$;$) {
741 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
742 my $lei = $self->{lei};
743 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
744 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
745 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
746 my $dst = $self->{cur_dst} // $self->{dst};
747 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
748 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
749 delete $task->{todo}; # $self->{todo} still exists
751 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
752 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
753 my ($uri, $key) = @{$v2_epochs->{$nr}};
754 my $src = $uri->as_string;
756 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
757 failed to extract epoch number from $src
759 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
760 $edst .= "/git/$nr.git";
764 die("BUG: `$key' not in manifest.js.gz");
765 if (defined(my $d = $ent->{description})) {
766 $d =~ s/ \[epoch [0-9]+\]\z//s;
770 if (!$want || $want->{$nr}) {
771 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
772 $etask->{-ent} = $ent; # may have {reference}
773 $etask->{cur_src} = $src;
774 $etask->{cur_dst} = $edst;
775 $etask->{-is_epoch} = $fini;
776 my $ref = $ent->{reference} // '';
777 push @{$self->{todo}->{$ref}}, $etask;
778 $self->{any_want}->{$key} = 1;
779 } else { # create a placeholder so users only need to chmod +w
780 init_placeholder($src, $edst, $ent);
781 push @{$task->{-read_only}}, $edst;
785 # filter out the epochs we skipped
786 $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
788 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
790 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
791 _get_txt_start($task, '_/text/config/raw', $fini);
793 defined($desc) ? ($task->{'txt.description'} = $desc) :
794 _get_txt_start($task, 'description', $fini);
797 sub decode_manifest ($$$) {
798 my ($fh, $fn, $uri) = @_;
800 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
801 gunzip(\$gz => \$js, MultiStream => 1) or
802 die "gunzip($uri): $GunzipError\n";
803 my $m = eval { PublicInbox::Config->json->decode($js) };
804 die "$uri: error decoding `$js': $@\n" if $@;
805 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
809 sub load_current_manifest ($) {
811 my $fn = $self->{-manifest} // return;
812 if (open(my $fh, '<', $fn)) {
813 decode_manifest($fh, $fn, $fn);
814 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
815 warn "open($fn): $!\n";
818 die "open($fn): $!\n";
822 sub multi_inbox ($$$) {
823 my ($self, $path, $m) = @_;
824 my $incl = $self->{lei}->{opt}->{include};
825 my $excl = $self->{lei}->{opt}->{exclude};
827 # assuming everything not v2 is v1, for now
828 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
829 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
833 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
834 push @{$v2->{$1}}, $_;
836 my $n = scalar(keys %$v2) + scalar(@v1);
837 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
839 my $re = '(?:'.join('\\z|', map {
840 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
842 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
843 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
844 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
845 @v1 = grep(/$re/, @v1);
848 my $re = '(?:'.join('\\z|', map {
849 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
851 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
852 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
853 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
854 @v1 = grep(!/$re/, @v1);
856 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
857 $ret->{v1} = \@v1 if @v1;
858 $ret->{v2} = $v2 if keys %$v2;
859 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
860 join("\n\t", sort @orig)
861 : "Nothing available to clone\n";
864 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
866 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
867 @v2_epochs) == @v2_epochs) {
868 $$path =~ s!\A(/[^/]+)/!/! or last;
872 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
876 ($path_pfx, $n, $ret);
881 my $todo = delete $self->{todo};
882 my $nodep = delete $todo->{''};
884 # do not download unwanted deps
885 my $any_want = delete $self->{any_want};
886 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
887 my @nodep = delete(@$todo{@unwanted});
888 push(@$nodep, @$_) for @nodep;
890 # handle no-dependency repos, first
893 return if $self->{lei}->{child_error};
895 # resolve references, deepest, first:
896 while (scalar keys %$todo) {
897 for my $x (keys %$todo) {
899 # resolve multi-level references
900 while ($m && defined($nxt = $m->{$x}->{reference})) {
901 exists($todo->{$nxt}) or last;
902 die <<EOM if ++$nr > 1000;
903 E: dependency loop detected (`$x' => `$nxt')
907 my $y = delete $todo->{$x} // next; # already done
910 return if $self->{lei}->{child_error};
912 last; # restart %$todo iteration
915 do_reap($self, 1); # finish all fingerprint checks
916 fgrp_fetch_all($self);
920 sub dump_manifest ($$) {
922 # write the smaller manifest if epochs were skipped so
923 # users won't have to delete manifest if they +w an
924 # epoch they no longer want to skip
925 my $json = PublicInbox::Config->json->encode($m);
926 my $mtime = (stat($ft))[9];
927 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
928 truncate($ft, 0) or die "truncate($ft): $!";
929 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
930 $ft->flush or die "flush($ft): $!";
931 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
934 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
937 my $uri = URI->new($self->{src});
938 my $lei = $self->{lei};
939 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
940 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
941 my $path = $uri->path;
942 chop($path) eq '/' or die "BUG: $uri not canonicalized";
943 $uri->path($path . '/manifest.js.gz');
944 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX',
945 UNLINK => 1, TMPDIR => 1, SUFFIX => '.tmp');
946 my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
947 my %opt = map { $_ => $lei->{$_} } (0..2);
948 my $cerr = run_reap($lei, $cmd, \%opt);
950 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
951 return $lei->child_error($cerr, "@$cmd failed");
953 my $m = eval { decode_manifest($ft, $ft, $uri) };
956 return try_scrape($self);
958 local $self->{-local_manifest} = load_current_manifest($self);
959 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
960 return $lei->child_error(1, $multi) if !ref($multi);
961 my $v2 = delete $multi->{v2};
962 local $self->{todo} = {};
963 local $self->{fgrp_todo} = {}; # { objstore_dir => [fgrp, ...] }
965 for my $name (sort keys %$v2) {
966 my $epochs = delete $v2->{$name};
967 my %v2_epochs = map {
968 $uri->path($n > 1 ? $path_pfx.$path.$_
970 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
971 $e // die "no [0-9]+\.git in `$uri'";
972 $e => [ $uri->clone, $_ ];
974 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
975 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
976 local $self->{cur_src} = $1;
977 local $self->{cur_dst} = $self->{dst};
978 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
979 git/[0-9]+\.git\z!x) {
980 $self->{cur_dst} .= "/$1";
982 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
983 E: `$self->{cur_dst}' must not contain newline
985 clone_v2_prep($self, \%v2_epochs, $m);
986 return if $self->{lei}->{child_error};
989 if (my $v1 = delete $multi->{v1}) {
990 my $p = $path_pfx.$path;
991 chop($p) if substr($p, -1, 1) eq '/';
993 for my $name (@$v1) {
994 my $task = bless { %$self }, __PACKAGE__;
995 $task->{-ent} = $m->{$name} //
996 die("BUG: no `$name' in manifest");
997 $task->{cur_src} = "$uri";
998 $task->{cur_dst} = $task->{dst};
999 $task->{-key} = $name;
1001 $task->{cur_dst} .= $name;
1002 $task->{cur_src} .= $name;
1004 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1005 E: `$task->{cur_dst}' must not contain newline
1007 $task->{cur_src} .= '/';
1008 my $dep = $task->{-ent}->{reference} // '';
1009 push @{$self->{todo}->{$dep}}, $task; # for clone_all
1010 $self->{any_want}->{$name} = 1;
1013 delete local $lei->{opt}->{epoch} if defined($v2);
1014 clone_all($self, $m);
1015 return if $self->{lei}->{child_error} || $self->{dry_run};
1017 # set by clone_v2_prep/-I/--exclude
1018 dump_manifest($m => $ft) if delete $self->{-culled_manifest};
1019 ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
1020 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
1023 sub start_clone_url {
1025 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1026 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1029 sub do_mirror { # via wq_io_do or public-inbox-clone
1031 my $lei = $self->{lei};
1032 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1033 umask($lei->{client_umask}) if defined $lei->{client_umask};
1035 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1036 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1037 --inbox-config must be one of `always', `v2', `v1', or `never'
1039 # we support --objstore= and --manifest= with '' (empty string)
1040 for my $default (qw(objstore manifest.js.gz)) {
1041 my ($k) = (split(/\./, $default))[0];
1042 my $v = $lei->{opt}->{$k} // next;
1043 $v = $default if $v eq '';
1044 $v = "$self->{dst}/$v" if $v !~ m!\A/!;
1045 $self->{"-$k"} = $v;
1048 my $iv = $lei->{opt}->{'inbox-version'} //
1049 return start_clone_url($self);
1050 return clone_v1($self) if $iv == 1;
1051 die "bad --inbox-version=$iv\n" if $iv != 2;
1052 die <<EOM if $self->{src} !~ m!://!;
1053 cloning local v2 inboxes not supported
1055 try_scrape($self, 1);
1057 $lei->fail($@) if $@;
1061 my ($cls, $lei, $src, $dst) = @_;
1062 my $self = bless { src => $src, dst => $dst }, $cls;
1063 $lei->request_umask;
1064 my ($op_c, $ops) = $lei->workers_start($self, 1);
1065 $lei->{wq1} = $self;
1066 $self->wq_io_do('do_mirror', []);
1068 $lei->wait_wq_events($op_c, $ops);
1071 sub ipc_atfork_child {
1073 $self->{lei}->_lei_atfork_child;
1074 $self->SUPER::ipc_atfork_child;
1077 sub write_makefile {
1078 my ($dir, $ibx_ver) = @_;
1079 my $f = "$dir/Makefile";
1080 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1081 print $fh <<EOM or die "print($f) $!";
1082 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1083 # manpage for more information on the format. This Makefile is
1084 # intended as a familiar wrapper for users unfamiliar with
1085 # public-inbox-* commands.
1087 # See the respective manpages for public-inbox-fetch(1),
1088 # public-inbox-index(1), etc for more information on
1089 # some of the commands used by this Makefile.
1091 # This Makefile will not be modified nor read by public-inbox,
1092 # so you may edit it freely with your own convenience targets
1093 # and notes. public-inbox-fetch will recreate it if removed.
1095 print $fh <<'EOM' or die "print($f): $!";
1096 # the default target:
1098 @echo Common targets:
1099 @echo ' make fetch - fetch from remote git repostorie(s)'
1100 @echo ' make update - fetch and update index '
1102 @echo Rarely needed targets:
1103 @echo ' make reindex - may be needed for new features/bugfixes'
1104 @echo ' make compact - rewrite Xapian storage to save space'
1105 @echo ' make index - initial index after clone
1110 @if ! public-inbox-fetch --exit-code; \
1113 test $$c -eq 127 && exit 0; \
1115 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1117 public-inbox-index; \
1119 echo 'public-inbox index not initialized'; \
1120 echo 'see public-inbox-index(1) man page'; \
1125 public-inbox-index --reindex
1127 public-inbox-compact
1129 .PHONY : help fetch update index reindex compact
1131 close $fh or die "close($f): $!";
1133 die "open($f): $!" unless $!{EEXIST};