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
24 our $FGRP_TODO; # objstore -> [ fgrp mirror objects ]
25 our $TODO; # reference => [ non-fgrp mirror objects ]
28 $LIVE && (!$_[0]->{lei}->{child_error} ||
29 $_[0]->{lei}->{opt}->{'keep-going'});
32 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
34 my ($mrr, $lei) = @$arg;
36 $lei->child_error($?);
37 } elsif (!$lei->{child_error}) {
38 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
39 require PublicInbox::LeiAddExternal;
40 PublicInbox::LeiAddExternal::_finish_add_external(
43 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
48 # for old installations without manifest.js.gz
50 my ($self, $fallback_manifest) = @_;
51 my $uri = URI->new($self->{src});
52 my $lei = $self->{lei};
53 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
54 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
55 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
56 my $fh = popen_rd($cmd, undef, $opt);
57 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
58 close($fh) or return $lei->child_error($?, "@$cmd failed");
60 # we grep with URL below, we don't want Subject/From headers
61 # making us clone random URLs. This assumes remote instances
62 # prior to public-inbox 1.7.0
63 # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
64 my @html = split(/<hr>/, $html);
65 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
66 if (!@urls && $fallback_manifest) {
68 W: failed to extract URLs from $uri, trying manifest.js.gz...
70 return start_clone_url($self);
72 my $url = $uri->as_string;
73 chop($url) eq '/' or die "BUG: $uri not canonicalized";
75 # since this is for old instances w/o manifest.js.gz, try v1 first
76 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
77 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
79 my ($n) = (m!/([0-9]+)\z!);
80 $n => [ URI->new($_), '' ]
82 clone_v2_prep($self, \%v2_epochs);
83 delete local $lei->{opt}->{epoch};
88 # filter out common URLs served by WWW (e.g /$MSGID/T/)
89 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
90 grep(m!\A\Q$url\E/*\z!, @urls)) {
92 E: confused by scraping <$uri>, did you mean <$url>?
96 E: confused by scraping <$uri>, got ambiguous results:
99 die "E: scraping <$uri> revealed nothing\n";
103 my ($lei, $opt) = @_;
105 $opt->{$_} = $lei->{$_} for (0..2);
106 # we support "-c $key=$val" for arbitrary git config options
107 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
108 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
109 push @cmd, qw(clone --mirror);
110 push @cmd, '-q' if $lei->{opt}->{quiet} ||
111 ($lei->{opt}->{jobs} // 1) > 1;
112 push @cmd, '-v' if $lei->{opt}->{verbose};
113 # XXX any other options to support?
114 # --reference is tricky with multiple epochs, but handled
115 # automatically if using manifest.js.gz
119 sub ft_rename ($$$;$) {
120 my ($ft, $dst, $open_mode, $fh) = @_;
121 my @st = stat($fh // $dst);
122 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
123 chmod($mode, $ft) or croak "E: chmod($ft): $!";
125 File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
126 $ft->unlink_on_destroy(0);
130 my ($self, $jobs) = @_;
131 $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
132 $jobs = 1 if $jobs < 1;
133 while (keys(%$LIVE) >= $jobs) {
134 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
135 if (my $x = delete $LIVE->{$pid}) {
139 warn "reaped unknown PID=$pid ($?)\n";
144 sub _get_txt_start { # non-fatal
145 my ($self, $endpoint, $fini) = @_;
146 my $uri = URI->new($self->{cur_src} // $self->{src});
147 my $lei = $self->{lei};
148 my $path = $uri->path;
149 chop($path) eq '/' or die "BUG: $uri not canonicalized";
150 $uri->path("$path/$endpoint");
151 my $f = (split(m!/!, $endpoint))[-1];
152 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
153 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
154 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
157 $lei->qerr("# @$cmd");
158 return if $self->{dry_run};
159 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
160 $LIVE->{spawn($cmd, undef, $opt)} =
161 [ \&_get_txt_done, $self, $endpoint, $fini ];
164 sub _get_txt_done { # returns true on error (non-fatal), undef on success
165 my ($self, $endpoint) = @_;
166 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
168 $? = 0; # don't influence normal lei exit
169 return warn("$uri missing\n") if ($cerr >> 8) == 22;
170 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
171 seek($fh, SEEK_SET, 0) or die "seek: $!";
172 $self->{"mtime.$endpoint"} = (stat($fh))[9];
174 $self->{"txt.$endpoint"} = <$fh>;
178 sub _write_inbox_config {
180 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
181 my $dst = $self->{cur_dst} // $self->{dst};
182 my $f = "$dst/inbox.config.example";
183 open my $fh, '>', $f or die "open($f): $!";
184 print $fh $buf or die "print: $!";
185 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
186 my $mtime = delete $self->{'mtime._/text/config/raw'};
187 $fh->flush or die "flush($f): $!";
188 if (defined $mtime) {
189 utime($mtime, $mtime, $fh) or die "utime($f): $!";
191 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
192 my $ibx = $self->{ibx} = {};
193 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
194 for (qw(address newsgroup nntpmirror)) {
195 $ibx->{$_} = $cfg->{"$sec.$_"};
200 sub set_description ($) {
202 my $dst = $self->{cur_dst} // $self->{dst};
203 my $f = "$dst/description";
204 open my $fh, '+>>', $f or die "open($f): $!";
205 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
206 my $d = do { local $/; <$fh> } // die "read($f): $!";
207 chomp(my $orig = $d);
208 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
209 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
210 $d = delete($self->{'txt.description'});
212 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
214 return if $d eq $orig;
215 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
216 truncate($fh, 0) or die "truncate($f): $!";
217 print $fh $d, "\n" or die "print($f): $!";
218 close $fh or die "close($f): $!";
221 sub index_cloned_inbox {
222 my ($self, $iv) = @_;
223 my $lei = $self->{lei};
225 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
226 # lei is useless without Xapian + SQLite
227 if ($lei->{cmd} ne 'public-inbox-clone') {
228 require PublicInbox::InboxWritable;
229 require PublicInbox::Admin;
230 my $ibx = delete($self->{ibx}) // {
231 address => [ 'lei@example.com' ],
234 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
235 PublicInbox::Inbox->new($ibx);
236 PublicInbox::InboxWritable->new($ibx);
238 for my $sw ($lei->index_opt) {
239 my ($k) = ($sw =~ /\A([\w-]+)/);
240 $opt->{$k} = $lei->{opt}->{$k};
242 # force synchronous dwaitpid for v2:
243 local $PublicInbox::DS::in_loop = 0;
244 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
245 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
246 local %ENV = (%ENV, %$env) if $env;
247 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
248 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
250 return if defined $self->{cur_dst}; # one of many repos to clone
254 my ($lei, $cmd, $opt) = @_;
255 $lei->qerr("# @$cmd");
256 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
258 $? = 0; # don't let it influence normal exit
263 my ($self, $cmd, $opt, $fini) = @_;
265 $self->{lei}->qerr("# @$cmd");
266 return if $self->{dry_run};
267 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
270 sub fetch_args ($$) {
271 my ($lei, $opt) = @_;
272 my @cmd; # (git --git-dir=...) to be added by caller
273 $opt->{$_} = $lei->{$_} for (0..2);
274 # we support "-c $key=$val" for arbitrary git config options
275 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
276 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
278 push @cmd, '-q' if $lei->{opt}->{quiet} ||
279 ($lei->{opt}->{jobs} // 1) > 1;
280 push @cmd, '-v' if $lei->{opt}->{verbose};
281 push(@cmd, '-p') if $lei->{opt}->{prune};
285 sub upr { # feed `git update-ref --stdin -z' verbosely
286 my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
287 $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
288 print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
293 return if !keep_going($fgrp);
294 my $srcfh = delete $fgrp->{srcfh} or return;
295 my $dstfh = delete $fgrp->{dstfh} or return;
296 seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
297 seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
298 my %src = map { chomp; split(/\0/) } (<$srcfh>);
300 my %dst = map { chomp; split(/\0/) } (<$dstfh>);
302 pipe(my ($r, $w)) or die "pipe: $!";
303 my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
304 qw(update-ref --stdin -z) ];
305 my $lei = $fgrp->{lei};
306 my $pack = PublicInbox::OnDestroy->new($$, \&pack_dst, $fgrp);
307 start_cmd($fgrp, $cmd, { 0 => $r, 2 => $lei->{2} }, $pack);
308 close $r or die "close(r): $!";
309 return if $fgrp->{dry_run};
310 for my $ref (keys %dst) {
311 my $new = delete $src{$ref};
312 my $old = $dst{$ref};
315 upr($lei, $w, 'update', $ref, $new, $old);
317 upr($lei, $w, 'delete', $ref, $old);
320 while (my ($ref, $oid) = each %src) {
321 upr($lei, $w, 'create', $ref, $oid);
323 close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
326 sub pack_dst { # packs lightweight satellite repos
328 pack_refs($fgrp, $fgrp->{cur_dst});
332 my ($self, $git_dir) = @_;
333 my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
334 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
340 my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
341 return if !keep_going($first);
342 pack_refs($first, $first->{-osdir}); # objstore refs always packed
343 for my $fgrp (@$fgrpv) {
344 my $rn = $fgrp->{-remote};
345 my %opt = ( 2 => $fgrp->{lei}->{2} );
347 my $update_ref = PublicInbox::OnDestroy->new($$,
348 \&fgrp_update, $fgrp);
350 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
351 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
352 "refs/remotes/$rn/" ];
353 open(my $sfh, '+>', undef) or die "open(src): $!";
354 $fgrp->{srcfh} = $sfh;
355 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
356 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
357 '--format=%(refname)%00%(objectname)' ];
358 open(my $dfh, '+>', undef) or die "open(dst): $!";
359 $fgrp->{dstfh} = $dfh;
360 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
366 my $todo = $FGRP_TODO;
367 $FGRP_TODO = \'BUG on further use';
368 keys(%$todo) or return;
370 # Rely on the fgrptmp remote groups in the config file rather
371 # than listing all remotes since the remote name list may exceed
372 # system argv limits:
375 my @git = (@{$self->{-torsocks}}, 'git');
376 my $j = $self->{lei}->{opt}->{jobs};
379 local $self->{lei}->{opt}->{jobs} = 1;
380 (fetch_args($self->{lei}, $opt),
381 qw(--no-tags --multiple));
383 push(@fetch, "-j$j") if $j;
384 while (my ($osdir, $fgrpv) = each %$todo) {
385 my $f = "$osdir/config";
387 # clobber group from previous run atomically
388 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
389 $f, '--unset-all', "remotes.$grp"];
390 $self->{lei}->qerr("# @$cmd");
391 if (!$self->{dry_run}) {
392 my $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
393 waitpid($pid, 0) // die "waitpid: $!";
394 die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
396 # update the config atomically via O_APPEND while
397 # respecting git-config locking
398 sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
399 or die "open($f.lock): $!";
400 open my $fh, '>>', $f or die "open(>>$f): $!";
402 my $buf = join('', "[remotes]\n",
403 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
404 print $fh $buf or die "print($f): $!";
405 close $fh or die "close($f): $!";
406 unlink("$f.lock") or die "unlink($f.lock): $!";
409 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
410 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
411 start_cmd($self, $cmd, $opt, $end);
415 # keep this idempotent for future use by public-inbox-fetch
417 my ($self, $uri) = @_;
418 $self->{-ent} // return;
419 my $os = $self->{-objstore} // return;
420 my $fg = $self->{-ent}->{forkgroup} // return;
421 my $dir = "$os/$fg.git";
422 if (!-d $dir && !$self->{dry_run}) {
423 PublicInbox::Import::init_bare($dir);
424 my @cmd = ('git', "--git-dir=$dir", 'config');
425 my $opt = { 2 => $self->{lei}->{2} };
426 for ('repack.useDeltaIslands=true',
427 'pack.island=refs/remotes/([^/]+)/') {
428 run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
431 my $key = $self->{-key} // die 'BUG: no -key';
432 my $rn = substr(sha256_hex($key), 0, 16);
433 if (!-d $self->{cur_dst} && !$self->{dry_run}) {
434 my $alt = File::Spec->rel2abs("$dir/objects");
435 PublicInbox::Import::init_bare($self->{cur_dst});
436 my $o = "$self->{cur_dst}/objects";
437 my $f = "$o/info/alternates";
438 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
439 open my $fh, '+>>', $f or die "open($f): $!";
440 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
441 chomp(my @cur = <$fh>);
442 if (!grep(/\A\Q$l\E\z/, @cur)) {
443 say $fh $l or die "say($f): $!";
445 close $fh or die "close($f): $!";
446 $f = "$self->{cur_dst}/config";
447 open $fh, '+>>', $f or die "open:($f): $!";
448 print $fh <<EOM or die "print($f): $!";
449 ; rely on the "$rn" remote in the
450 ; $fg fork group for fetches
451 ; only uncomment the following iff you detach from fork groups
454 ; fetch = +refs/*:refs/*
457 close $fh or die "close($f): $!";
460 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
465 my ($self, $cb, @arg) = @_;
466 return if !keep_going($self);
467 my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
468 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
469 $self->{-ent} // die 'BUG: no -ent';
470 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
471 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
472 return $cb->($self, @arg) if $A ne $B;
473 $self->{lei}->qerr("# $self->{-key} up-to-date");
477 my ($self, $cb, @arg) = @_;
478 # $cb is either resume_fetch or fgrp_enqueue
479 $self->{-ent} // return $cb->($self, @arg);
480 my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
481 my $key = $self->{-key} // die 'BUG: no -key';
482 if (my $cur_ent = $self->{-local_manifest}->{$key}) {
483 # runs go_fetch->DESTROY run if eq
484 return if $cur_ent->{fingerprint} eq $new;
486 my $dst = $self->{cur_dst} // $self->{dst};
487 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
488 my $opt = { 2 => $self->{lei}->{2} };
489 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
490 $self->{-show_ref} = $opt->{1};
491 my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $cb, @arg);
492 start_cmd($self, $cmd, $opt, $done);
496 my ($self, $uri, $fini) = @_;
497 return if !keep_going($self);
498 my $dst = $self->{cur_dst} // $self->{dst};
499 my @git = ('git', "--git-dir=$dst");
500 my $opt = { 2 => $self->{lei}->{2} };
501 my $rn = 'origin'; # configurable?
502 for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
503 my @kv = split(/=/, $_, 2);
504 $kv[0] = "remote.$rn.$kv[0]";
505 next if $self->{dry_run};
506 run_die([@git, 'config', @kv], undef, $opt);
508 my $cmd = [ @{$self->{-torsocks}}, @git,
509 fetch_args($self->{lei}, $opt), $rn ];
510 push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
511 start_cmd($self, $cmd, $opt, $fini);
515 my ($fgrp, $end) = @_; # $end calls fgrp_fetch_all
516 return if !keep_going($fgrp);
517 my $opt = { 2 => $fgrp->{lei}->{2} };
518 # --no-tags is required to avoid conflicts
519 my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
520 my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
521 my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
522 for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
523 my @kv = split(/=/, $_, 2);
524 $kv[0] = "remote.$rn.$kv[0]";
525 $fgrp->{dry_run} ? $fgrp->{lei}->qerr("# @cmd @kv") :
526 run_die([@cmd, @kv], undef, $opt);
528 push @{$FGRP_TODO->{$fgrp->{-osdir}}}, $fgrp;
532 my ($self, $end) = @_;
533 my $lei = $self->{lei};
534 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
535 my $uri = URI->new($self->{cur_src} // $self->{src});
536 my $path = $uri->path;
537 $path =~ s!/*\z!! and $uri->path($path);
538 defined($lei->{opt}->{epoch}) and
539 die "$uri is a v1 inbox, --epoch is not supported\n";
540 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
541 my $dst = $self->{cur_dst} // $self->{dst};
542 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
543 my $resume = -d $dst;
544 if (my $fgrp = forkgroup_prep($self, $uri)) {
545 $fgrp->{-fini} = $fini;
546 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
547 : fgrp_enqueue($fgrp, $end);
549 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
550 } else { # normal clone
551 my $cmd = [ @{$self->{-torsocks}},
552 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
553 if (defined($self->{-ent})) {
554 if (defined(my $ref = $self->{-ent}->{reference})) {
555 -e "$self->{dst}$ref" and
556 push @$cmd, '--reference',
560 start_cmd($self, $cmd, $opt, $fini);
562 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
563 /\A(?:always|v1)\z/s) {
564 _get_txt_start($self, '_/text/config/raw', $fini);
567 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
568 $self->{'txt.description'} = $d if defined $d;
569 (!defined($d) && !$end) and
570 _get_txt_start($self, 'description', $fini);
572 $end or do_reap($self, 1); # for non-manifest clone
575 sub parse_epochs ($$) {
576 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
577 $opt_epochs // return; # undef => all epochs
578 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
579 undef($lo) if ($lo // '') eq '';
580 my $re = qr/\A~?[0-9]+\z/;
581 if (@extra || (($lo // '0') !~ $re) ||
582 (($hi // '0') !~ $re) ||
583 !(grep(defined, $lo, $hi))) {
585 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
588 my @n = sort { $a <=> $b } keys %$v2_epochs;
589 for (grep(defined, $lo, $hi)) {
592 "`$_' exceeds maximum available epoch ($n[-1])\n";
594 "`$_' is lower than minimum available epoch ($n[0])\n";
595 } elsif (/\A~([0-9]+)/) {
597 $n[$off] // die "`$_' is out of range\n";
599 } else { die "`$_' not understood\n" }
601 defined($lo) && defined($hi) && $lo > $hi and die
602 "low value (`$lo') exceeds high (`$hi')\n";
603 $lo //= $n[0] if $dotdot;
604 $hi //= $n[-1] if $dotdot;
608 if (defined $v2_epochs->{$_}) {
612 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
618 sub init_placeholder ($$$) {
619 my ($src, $edst, $ent) = @_;
620 PublicInbox::Import::init_bare($edst);
621 my $f = "$edst/config";
622 open my $fh, '>>', $f or die "open($f): $!";
623 print $fh <<EOM or die "print($f): $!";
626 fetch = +refs/*:refs/*
629 ; This git epoch was created read-only and "public-inbox-fetch"
630 ; will not fetch updates for it unless write permission is added.
631 ; Hint: chmod +w $edst
633 if (defined($ent->{owner})) {
634 print $fh <<EOM or die "print($f): $!";
636 owner = $ent->{owner}
639 close $fh or die "close($f): $!";
640 my %map = (head => 'HEAD', description => undef);
641 while (my ($key, $fn) = each %map) {
642 my $val = $ent->{$key} // next;
645 open $fh, '>', $fn or die "open($fn): $!";
646 print $fh $val, "\n" or die "print($fn): $!";
647 close $fh or die "close($fn): $!";
651 sub reap_cmd { # async, called via SIGCHLD
652 my ($self, $cmd) = @_;
654 $? = 0; # don't let it influence normal exit
655 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
660 return if !keep_going($self);
661 my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
662 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
663 $self->{-ent} // die 'BUG: no -ent';
664 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
665 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
667 $self->{-ent}->{fingerprint} = $B;
668 push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
671 # modifies the to-be-written manifest entry, and sets values from it, too
674 my $key = $self->{-key} // die 'BUG: no -key';
675 my $new = $self->{-ent}->{fingerprint};
676 my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
677 my $dst = $self->{cur_dst} // $self->{dst};
678 if (defined($new) && $new ne $cur) {
679 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
680 my $opt = { 2 => $self->{lei}->{2} };
681 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
682 $self->{-show_ref_up} = $opt->{1};
683 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
684 start_cmd($self, $cmd, $opt, $done);
687 $new = $self->{-ent}->{head};
688 $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
689 if (defined($new) && $new ne $cur) {
690 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
691 my $cmd = [ 'git', "--git-dir=$dst" ];
692 if ($new =~ s/\Aref: //) {
693 push @$cmd, qw(symbolic-ref HEAD), $new;
694 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
695 push @$cmd, qw(update-ref --no-deref HEAD), $new;
698 warn "W: $key: {head} => `$new' not understood\n";
700 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
702 if (my $symlinks = $self->{-ent}->{symlinks}) {
703 my $top = File::Spec->rel2abs($self->{dst});
704 for my $p (@$symlinks) {
707 my (undef, $dn, $bn) = File::Spec->splitpath($ln);
708 File::Path::mkpath($dn);
709 my $tgt = "$top/$key";
710 $tgt = File::Spec->abs2rel($tgt, $dn);
713 next if readlink($ln) eq $tgt;
714 unlink($ln) or die "unlink($ln): $!";
716 push @{$self->{chg}->{badlink}}, $p;
719 symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
722 $new = $self->{-ent}->{owner} // return;
723 $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
724 return if $cur eq $new;
725 my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
726 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
729 sub v1_done { # called via OnDestroy
731 return if $self->{dry_run} || !keep_going($self);
732 _write_inbox_config($self);
733 my $dst = $self->{cur_dst} // $self->{dst};
734 update_ent($self) if $self->{-ent};
735 my $o = "$dst/objects";
736 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
737 my $base = File::Spec->rel2abs($o);
742 $_ = File::Spec->abs2rel($_, $base);
743 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
747 print $ft @l or die "print($ft): $!";
748 $ft->flush or die "flush($ft): $!";
749 ft_rename($ft, $fn, 0666, $fh);
752 eval { set_description($self) };
754 return if ($self->{-is_epoch} ||
755 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
756 write_makefile($dst, 1);
757 index_cloned_inbox($self, 1);
760 sub v2_done { # called via OnDestroy
762 return if $self->{dry_run} || !keep_going($self);
763 my $dst = $self->{cur_dst} // $self->{dst};
764 require PublicInbox::Lock;
765 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
766 my $lck = $lk->lock_for_scope($$);
767 _write_inbox_config($self);
768 require PublicInbox::MultiGit;
769 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
770 $mg->fill_alternates;
771 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
772 for my $edst (@{delete($self->{-read_only}) // []}) {
773 my @st = stat($edst) or die "stat($edst): $!";
774 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
776 write_makefile($dst, 2);
778 eval { set_description($self) };
780 index_cloned_inbox($self, 2);
783 sub clone_v2_prep ($$;$) {
784 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
785 my $lei = $self->{lei};
786 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
787 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
788 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
789 my $dst = $self->{cur_dst} // $self->{dst};
790 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
791 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
793 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
794 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
795 my ($uri, $key) = @{$v2_epochs->{$nr}};
796 my $src = $uri->as_string;
798 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
799 failed to extract epoch number from $src
801 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
802 $edst .= "/git/$nr.git";
806 die("BUG: `$key' not in manifest.js.gz");
807 if (defined(my $d = $ent->{description})) {
808 $d =~ s/ \[epoch [0-9]+\]\z//s;
812 if (!$want || $want->{$nr}) {
813 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
814 $etask->{-ent} = $ent; # may have {reference}
815 $etask->{cur_src} = $src;
816 $etask->{cur_dst} = $edst;
817 $etask->{-is_epoch} = $fini;
818 my $ref = $ent->{reference} // '';
819 push @{$TODO->{$ref}}, $etask;
820 $self->{any_want}->{$key} = 1;
821 } else { # create a placeholder so users only need to chmod +w
822 init_placeholder($src, $edst, $ent);
823 push @{$task->{-read_only}}, $edst;
827 # filter out the epochs we skipped
828 $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
830 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
832 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
833 _get_txt_start($task, '_/text/config/raw', $fini);
835 defined($desc) ? ($task->{'txt.description'} = $desc) :
836 _get_txt_start($task, 'description', $fini);
839 sub decode_manifest ($$$) {
840 my ($fh, $fn, $uri) = @_;
842 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
843 gunzip(\$gz => \$js, MultiStream => 1) or
844 die "gunzip($uri): $GunzipError\n";
845 my $m = eval { PublicInbox::Config->json->decode($js) };
846 die "$uri: error decoding `$js': $@\n" if $@;
847 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
851 sub load_current_manifest ($) {
853 my $fn = $self->{-manifest} // return;
854 if (open(my $fh, '<', $fn)) {
855 decode_manifest($fh, $fn, $fn);
856 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
857 warn "open($fn): $!\n" if !$self->{-initial_clone};
860 die "open($fn): $!\n";
864 sub multi_inbox ($$$) {
865 my ($self, $path, $m) = @_;
866 my $incl = $self->{lei}->{opt}->{include};
867 my $excl = $self->{lei}->{opt}->{exclude};
869 # assuming everything not v2 is v1, for now
870 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
871 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
875 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
876 push @{$v2->{$1}}, $_;
878 my $n = scalar(keys %$v2) + scalar(@v1);
879 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
881 my $re = '(?:'.join('\\z|', map {
882 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
884 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
885 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
886 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
887 @v1 = grep(/$re/, @v1);
890 my $re = '(?:'.join('\\z|', map {
891 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
893 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
894 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
895 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
896 @v1 = grep(!/$re/, @v1);
898 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
899 $ret->{v1} = \@v1 if @v1;
900 $ret->{v2} = $v2 if keys %$v2;
901 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
902 join("\n\t", sort @orig)
903 : "Nothing available to clone\n";
906 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
908 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
909 @v2_epochs) == @v2_epochs) {
910 $$path =~ s!\A(/[^/]+)/!/! or last;
914 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
918 ($path_pfx, $n, $ret);
924 $TODO = \'BUG on further use';
925 my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
927 my $nodep = delete $todo->{''};
929 # do not download unwanted deps
930 my $any_want = delete $self->{any_want};
931 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
932 my @nodep = delete(@$todo{@unwanted});
933 push(@$nodep, @$_) for @nodep;
935 # handle no-dependency repos, first
938 return if !keep_going($self);
941 # resolve references, deepest, first:
942 while (scalar keys %$todo) {
943 for my $x (keys %$todo) {
945 # resolve multi-level references
946 while ($m && defined($nxt = $m->{$x}->{reference})) {
947 exists($todo->{$nxt}) or last;
948 die <<EOM if ++$nr > 1000;
949 E: dependency loop detected (`$x' => `$nxt')
953 my $y = delete $todo->{$x} // next; # already done
956 return if !keep_going($self);
958 last; # restart %$todo iteration
962 # $end->DESTROY will call fgrp_fetch_all once all references
963 # in $LIVE are gone, and do_reap will eventually drain $LIVE
968 sub dump_manifest ($$) {
970 # write the smaller manifest if epochs were skipped so
971 # users won't have to delete manifest if they +w an
972 # epoch they no longer want to skip
973 my $json = PublicInbox::Config->json->encode($m);
974 my $mtime = (stat($ft))[9];
975 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
976 truncate($ft, 0) or die "truncate($ft): $!";
977 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
978 $ft->flush or die "flush($ft): $!";
979 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
982 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
985 my $uri = URI->new($self->{src});
986 my $lei = $self->{lei};
987 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
988 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
989 my $path = $uri->path;
990 chop($path) eq '/' or die "BUG: $uri not canonicalized";
991 $uri->path($path . '/manifest.js.gz');
992 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
993 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
994 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
995 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
998 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
999 my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
1000 push(@$cmd, '-z', $manifest) if -f $manifest;
1001 my $mf_url = "$uri";
1002 %opt = map { $_ => $lei->{$_} } (0..2);
1003 my $cerr = run_reap($lei, $cmd, \%opt);
1005 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1006 return $lei->child_error($cerr, "@$cmd failed");
1009 # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1010 return $lei->qerr("# $manifest unchanged") if -f $manifest && !-s $ft;
1012 my $m = eval { decode_manifest($ft, $ft, $uri) };
1015 return try_scrape($self);
1017 local $self->{chg} = {};
1018 local $self->{-local_manifest} = load_current_manifest($self);
1019 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1020 return $lei->child_error(1, $multi) if !ref($multi);
1021 my $v2 = delete $multi->{v2};
1023 for my $name (sort keys %$v2) {
1024 my $epochs = delete $v2->{$name};
1025 my %v2_epochs = map {
1026 $uri->path($n > 1 ? $path_pfx.$path.$_
1028 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1029 $e // die "no [0-9]+\.git in `$uri'";
1030 $e => [ $uri->clone, $_ ];
1032 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1033 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1034 local $self->{cur_src} = $1;
1035 local $self->{cur_dst} = $self->{dst};
1036 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1037 git/[0-9]+\.git\z!x) {
1038 $self->{cur_dst} .= "/$1";
1040 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1041 E: `$self->{cur_dst}' must not contain newline
1043 clone_v2_prep($self, \%v2_epochs, $m);
1044 return if !keep_going($self);
1047 if (my $v1 = delete $multi->{v1}) {
1048 my $p = $path_pfx.$path;
1049 chop($p) if substr($p, -1, 1) eq '/';
1051 for my $name (@$v1) {
1052 my $task = bless { %$self }, __PACKAGE__;
1053 $task->{-ent} = $m->{$name} //
1054 die("BUG: no `$name' in manifest");
1055 $task->{cur_src} = "$uri";
1056 $task->{cur_dst} = $task->{dst};
1057 $task->{-key} = $name;
1059 $task->{cur_dst} .= $name;
1060 $task->{cur_src} .= $name;
1062 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1063 E: `$task->{cur_dst}' must not contain newline
1065 $task->{cur_src} .= '/';
1066 my $dep = $task->{-ent}->{reference} // '';
1067 push @{$TODO->{$dep}}, $task; # for clone_all
1068 $self->{any_want}->{$name} = 1;
1071 delete local $lei->{opt}->{epoch} if defined($v2);
1072 clone_all($self, $m);
1073 return if $self->{dry_run} || !keep_going($self);
1075 # set by clone_v2_prep/-I/--exclude
1076 my $mis = delete $self->{chg}->{fp_mismatch};
1078 my $t = (stat($ft))[9];
1080 $t = POSIX::strftime('%Y-%m-%d %k:%M:%S %z', localtime($t));
1082 W: Fingerprints for the following repositories do not match
1084 W: These repositories may have updated since $t:
1086 warn "\t", $_, "\n" for @$mis;
1087 warn <<EOM if !$self->{lei}->{opt}->{prune};
1088 W: The above fingerprints may never match without --prune
1091 dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1092 my $bad = delete $self->{chg}->{badlink};
1093 warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1094 W: The following exist and have not been converted to symlinks
1096 ft_rename($ft, $manifest, 0666);
1099 sub start_clone_url {
1101 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1102 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1105 sub do_mirror { # via wq_io_do or public-inbox-clone
1107 my $lei = $self->{lei};
1108 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1109 umask($lei->{client_umask}) if defined $lei->{client_umask};
1110 $self->{-initial_clone} = 1 if !-d $self->{dst};
1112 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1113 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1114 --inbox-config must be one of `always', `v2', `v1', or `never'
1116 # we support --objstore= and --manifest= with '' (empty string)
1117 for my $default (qw(objstore manifest.js.gz)) {
1118 my ($k) = (split(/\./, $default))[0];
1119 my $v = $lei->{opt}->{$k} // next;
1120 $v = $default if $v eq '';
1121 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1122 $self->{"-$k"} = $v;
1126 local $FGRP_TODO = {};
1127 my $iv = $lei->{opt}->{'inbox-version'} //
1128 return start_clone_url($self);
1129 return clone_v1($self) if $iv == 1;
1130 die "bad --inbox-version=$iv\n" if $iv != 2;
1131 die <<EOM if $self->{src} !~ m!://!;
1132 cloning local v2 inboxes not supported
1134 try_scrape($self, 1);
1136 $lei->fail($@) if $@;
1140 my ($cls, $lei, $src, $dst) = @_;
1141 my $self = bless { src => $src, dst => $dst }, $cls;
1142 $lei->request_umask;
1143 my ($op_c, $ops) = $lei->workers_start($self, 1);
1144 $lei->{wq1} = $self;
1145 $self->wq_io_do('do_mirror', []);
1147 $lei->wait_wq_events($op_c, $ops);
1150 sub ipc_atfork_child {
1152 $self->{lei}->_lei_atfork_child;
1153 $self->SUPER::ipc_atfork_child;
1156 sub write_makefile {
1157 my ($dir, $ibx_ver) = @_;
1158 my $f = "$dir/Makefile";
1159 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1160 print $fh <<EOM or die "print($f) $!";
1161 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1162 # manpage for more information on the format. This Makefile is
1163 # intended as a familiar wrapper for users unfamiliar with
1164 # public-inbox-* commands.
1166 # See the respective manpages for public-inbox-fetch(1),
1167 # public-inbox-index(1), etc for more information on
1168 # some of the commands used by this Makefile.
1170 # This Makefile will not be modified nor read by public-inbox,
1171 # so you may edit it freely with your own convenience targets
1172 # and notes. public-inbox-fetch will recreate it if removed.
1174 print $fh <<'EOM' or die "print($f): $!";
1175 # the default target:
1177 @echo Common targets:
1178 @echo ' make fetch - fetch from remote git repostorie(s)'
1179 @echo ' make update - fetch and update index '
1181 @echo Rarely needed targets:
1182 @echo ' make reindex - may be needed for new features/bugfixes'
1183 @echo ' make compact - rewrite Xapian storage to save space'
1184 @echo ' make index - initial index after clone
1189 @if ! public-inbox-fetch --exit-code; \
1192 test $$c -eq 127 && exit 0; \
1194 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1196 public-inbox-index; \
1198 echo 'public-inbox index not initialized'; \
1199 echo 'see public-inbox-index(1) man page'; \
1204 public-inbox-index --reindex
1206 public-inbox-compact
1208 .PHONY : help fetch update index reindex compact
1210 close $fh or die "close($f): $!";
1212 die "open($f): $!" unless $!{EEXIST};