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 defined($lei->{opt}->{epoch}) and
537 die "$uri is a v1 inbox, --epoch is not supported\n";
538 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
539 my $dst = $self->{cur_dst} // $self->{dst};
540 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
541 my $resume = -d $dst;
542 if (my $fgrp = forkgroup_prep($self, $uri)) {
543 $fgrp->{-fini} = $fini;
544 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
545 : fgrp_enqueue($fgrp, $end);
547 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
548 } else { # normal clone
549 my $cmd = [ @{$self->{-torsocks}},
550 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
551 if (defined($self->{-ent})) {
552 if (defined(my $ref = $self->{-ent}->{reference})) {
553 -e "$self->{dst}$ref" and
554 push @$cmd, '--reference',
558 start_cmd($self, $cmd, $opt, $fini);
560 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
561 /\A(?:always|v1)\z/s) {
562 _get_txt_start($self, '_/text/config/raw', $fini);
565 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
566 $self->{'txt.description'} = $d if defined $d;
567 (!defined($d) && !$end) and
568 _get_txt_start($self, 'description', $fini);
570 $end or do_reap($self, 1); # for non-manifest clone
573 sub parse_epochs ($$) {
574 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
575 $opt_epochs // return; # undef => all epochs
576 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
577 undef($lo) if ($lo // '') eq '';
578 my $re = qr/\A~?[0-9]+\z/;
579 if (@extra || (($lo // '0') !~ $re) ||
580 (($hi // '0') !~ $re) ||
581 !(grep(defined, $lo, $hi))) {
583 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
586 my @n = sort { $a <=> $b } keys %$v2_epochs;
587 for (grep(defined, $lo, $hi)) {
590 "`$_' exceeds maximum available epoch ($n[-1])\n";
592 "`$_' is lower than minimum available epoch ($n[0])\n";
593 } elsif (/\A~([0-9]+)/) {
595 $n[$off] // die "`$_' is out of range\n";
597 } else { die "`$_' not understood\n" }
599 defined($lo) && defined($hi) && $lo > $hi and die
600 "low value (`$lo') exceeds high (`$hi')\n";
601 $lo //= $n[0] if $dotdot;
602 $hi //= $n[-1] if $dotdot;
606 if (defined $v2_epochs->{$_}) {
610 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
616 sub init_placeholder ($$$) {
617 my ($src, $edst, $ent) = @_;
618 PublicInbox::Import::init_bare($edst);
619 my $f = "$edst/config";
620 open my $fh, '>>', $f or die "open($f): $!";
621 print $fh <<EOM or die "print($f): $!";
624 fetch = +refs/*:refs/*
627 ; This git epoch was created read-only and "public-inbox-fetch"
628 ; will not fetch updates for it unless write permission is added.
629 ; Hint: chmod +w $edst
631 if (defined($ent->{owner})) {
632 print $fh <<EOM or die "print($f): $!";
634 owner = $ent->{owner}
637 close $fh or die "close($f): $!";
638 my %map = (head => 'HEAD', description => undef);
639 while (my ($key, $fn) = each %map) {
640 my $val = $ent->{$key} // next;
643 open $fh, '>', $fn or die "open($fn): $!";
644 print $fh $val, "\n" or die "print($fn): $!";
645 close $fh or die "close($fn): $!";
649 sub reap_cmd { # async, called via SIGCHLD
650 my ($self, $cmd) = @_;
652 $? = 0; # don't let it influence normal exit
653 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
658 return if !keep_going($self);
659 my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
660 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
661 $self->{-ent} // die 'BUG: no -ent';
662 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
663 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
665 $self->{-ent}->{fingerprint} = $B;
666 push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
669 # modifies the to-be-written manifest entry, and sets values from it, too
672 my $key = $self->{-key} // die 'BUG: no -key';
673 my $new = $self->{-ent}->{fingerprint};
674 my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
675 my $dst = $self->{cur_dst} // $self->{dst};
676 if (defined($new) && $new ne $cur) {
677 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
678 my $opt = { 2 => $self->{lei}->{2} };
679 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
680 $self->{-show_ref_up} = $opt->{1};
681 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
682 start_cmd($self, $cmd, $opt, $done);
685 $new = $self->{-ent}->{head};
686 $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
687 if (defined($new) && $new ne $cur) {
688 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
689 my $cmd = [ 'git', "--git-dir=$dst" ];
690 if ($new =~ s/\Aref: //) {
691 push @$cmd, qw(symbolic-ref HEAD), $new;
692 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
693 push @$cmd, qw(update-ref --no-deref HEAD), $new;
696 warn "W: $key: {head} => `$new' not understood\n";
698 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
700 if (my $symlinks = $self->{-ent}->{symlinks}) {
701 my $top = File::Spec->rel2abs($self->{dst});
702 for my $p (@$symlinks) {
705 my (undef, $dn, $bn) = File::Spec->splitpath($ln);
706 File::Path::mkpath($dn);
707 my $tgt = "$top/$key";
708 $tgt = File::Spec->abs2rel($tgt, $dn);
711 next if readlink($ln) eq $tgt;
712 unlink($ln) or die "unlink($ln): $!";
714 push @{$self->{chg}->{badlink}}, $p;
717 symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
720 $new = $self->{-ent}->{owner} // return;
721 $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
722 return if $cur eq $new;
723 my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
724 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
727 sub v1_done { # called via OnDestroy
729 return if $self->{dry_run} || !keep_going($self);
730 _write_inbox_config($self);
731 my $dst = $self->{cur_dst} // $self->{dst};
732 update_ent($self) if $self->{-ent};
733 my $o = "$dst/objects";
734 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
735 my $base = File::Spec->rel2abs($o);
740 $_ = File::Spec->abs2rel($_, $base);
741 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
745 print $ft @l or die "print($ft): $!";
746 $ft->flush or die "flush($ft): $!";
747 ft_rename($ft, $fn, 0666, $fh);
750 eval { set_description($self) };
752 return if ($self->{-is_epoch} ||
753 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
754 write_makefile($dst, 1);
755 index_cloned_inbox($self, 1);
758 sub v2_done { # called via OnDestroy
760 return if $self->{dry_run} || !keep_going($self);
761 my $dst = $self->{cur_dst} // $self->{dst};
762 require PublicInbox::Lock;
763 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
764 my $lck = $lk->lock_for_scope($$);
765 _write_inbox_config($self);
766 require PublicInbox::MultiGit;
767 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
768 $mg->fill_alternates;
769 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
770 for my $edst (@{delete($self->{-read_only}) // []}) {
771 my @st = stat($edst) or die "stat($edst): $!";
772 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
774 write_makefile($dst, 2);
776 eval { set_description($self) };
778 index_cloned_inbox($self, 2);
781 sub clone_v2_prep ($$;$) {
782 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
783 my $lei = $self->{lei};
784 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
785 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
786 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
787 my $dst = $self->{cur_dst} // $self->{dst};
788 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
789 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
791 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
792 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
793 my ($uri, $key) = @{$v2_epochs->{$nr}};
794 my $src = $uri->as_string;
796 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
797 failed to extract epoch number from $src
799 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
800 $edst .= "/git/$nr.git";
804 die("BUG: `$key' not in manifest.js.gz");
805 if (defined(my $d = $ent->{description})) {
806 $d =~ s/ \[epoch [0-9]+\]\z//s;
810 if (!$want || $want->{$nr}) {
811 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
812 $etask->{-ent} = $ent; # may have {reference}
813 $etask->{cur_src} = $src;
814 $etask->{cur_dst} = $edst;
815 $etask->{-is_epoch} = $fini;
816 my $ref = $ent->{reference} // '';
817 push @{$TODO->{$ref}}, $etask;
818 $self->{any_want}->{$key} = 1;
819 } else { # create a placeholder so users only need to chmod +w
820 init_placeholder($src, $edst, $ent);
821 push @{$task->{-read_only}}, $edst;
825 # filter out the epochs we skipped
826 $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
828 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
830 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
831 _get_txt_start($task, '_/text/config/raw', $fini);
833 defined($desc) ? ($task->{'txt.description'} = $desc) :
834 _get_txt_start($task, 'description', $fini);
837 sub decode_manifest ($$$) {
838 my ($fh, $fn, $uri) = @_;
840 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
841 gunzip(\$gz => \$js, MultiStream => 1) or
842 die "gunzip($uri): $GunzipError\n";
843 my $m = eval { PublicInbox::Config->json->decode($js) };
844 die "$uri: error decoding `$js': $@\n" if $@;
845 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
849 sub load_current_manifest ($) {
851 my $fn = $self->{-manifest} // return;
852 if (open(my $fh, '<', $fn)) {
853 decode_manifest($fh, $fn, $fn);
854 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
855 warn "open($fn): $!\n" if !$self->{-initial_clone};
858 die "open($fn): $!\n";
862 sub multi_inbox ($$$) {
863 my ($self, $path, $m) = @_;
864 my $incl = $self->{lei}->{opt}->{include};
865 my $excl = $self->{lei}->{opt}->{exclude};
867 # assuming everything not v2 is v1, for now
868 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
869 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
873 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
874 push @{$v2->{$1}}, $_;
876 my $n = scalar(keys %$v2) + scalar(@v1);
877 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
879 my $re = '(?:'.join('\\z|', map {
880 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
882 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
883 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
884 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
885 @v1 = grep(/$re/, @v1);
888 my $re = '(?:'.join('\\z|', map {
889 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
891 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
892 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
893 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
894 @v1 = grep(!/$re/, @v1);
896 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
897 $ret->{v1} = \@v1 if @v1;
898 $ret->{v2} = $v2 if keys %$v2;
899 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
900 join("\n\t", sort @orig)
901 : "Nothing available to clone\n";
904 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
906 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
907 @v2_epochs) == @v2_epochs) {
908 $$path =~ s!\A(/[^/]+)/!/! or last;
912 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
916 ($path_pfx, $n, $ret);
922 $TODO = \'BUG on further use';
923 my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
925 my $nodep = delete $todo->{''};
927 # do not download unwanted deps
928 my $any_want = delete $self->{any_want};
929 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
930 my @nodep = delete(@$todo{@unwanted});
931 push(@$nodep, @$_) for @nodep;
933 # handle no-dependency repos, first
936 return if !keep_going($self);
939 # resolve references, deepest, first:
940 while (scalar keys %$todo) {
941 for my $x (keys %$todo) {
943 # resolve multi-level references
944 while ($m && defined($nxt = $m->{$x}->{reference})) {
945 exists($todo->{$nxt}) or last;
946 die <<EOM if ++$nr > 1000;
947 E: dependency loop detected (`$x' => `$nxt')
951 my $y = delete $todo->{$x} // next; # already done
954 return if !keep_going($self);
956 last; # restart %$todo iteration
960 # $end->DESTROY will call fgrp_fetch_all once all references
961 # in $LIVE are gone, and do_reap will eventually drain $LIVE
966 sub dump_manifest ($$) {
968 # write the smaller manifest if epochs were skipped so
969 # users won't have to delete manifest if they +w an
970 # epoch they no longer want to skip
971 my $json = PublicInbox::Config->json->encode($m);
972 my $mtime = (stat($ft))[9];
973 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
974 truncate($ft, 0) or die "truncate($ft): $!";
975 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
976 $ft->flush or die "flush($ft): $!";
977 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
980 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
983 my $uri = URI->new($self->{src});
984 my $lei = $self->{lei};
985 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
986 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
987 my $path = $uri->path;
988 chop($path) eq '/' or die "BUG: $uri not canonicalized";
989 $uri->path($path . '/manifest.js.gz');
990 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
991 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
992 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
993 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
996 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
997 my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
998 push(@$cmd, '-z', $manifest) if -f $manifest;
1000 %opt = map { $_ => $lei->{$_} } (0..2);
1001 my $cerr = run_reap($lei, $cmd, \%opt);
1003 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1004 return $lei->child_error($cerr, "@$cmd failed");
1007 # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1008 return $lei->qerr("# $manifest unchanged") if -f $manifest && !-s $ft;
1010 my $m = eval { decode_manifest($ft, $ft, $uri) };
1013 return try_scrape($self);
1015 local $self->{chg} = {};
1016 local $self->{-local_manifest} = load_current_manifest($self);
1017 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1018 return $lei->child_error(1, $multi) if !ref($multi);
1019 my $v2 = delete $multi->{v2};
1021 for my $name (sort keys %$v2) {
1022 my $epochs = delete $v2->{$name};
1023 my %v2_epochs = map {
1024 $uri->path($n > 1 ? $path_pfx.$path.$_
1026 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1027 $e // die "no [0-9]+\.git in `$uri'";
1028 $e => [ $uri->clone, $_ ];
1030 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1031 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1032 local $self->{cur_src} = $1;
1033 local $self->{cur_dst} = $self->{dst};
1034 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1035 git/[0-9]+\.git\z!x) {
1036 $self->{cur_dst} .= "/$1";
1038 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1039 E: `$self->{cur_dst}' must not contain newline
1041 clone_v2_prep($self, \%v2_epochs, $m);
1042 return if !keep_going($self);
1045 if (my $v1 = delete $multi->{v1}) {
1046 my $p = $path_pfx.$path;
1047 chop($p) if substr($p, -1, 1) eq '/';
1049 for my $name (@$v1) {
1050 my $task = bless { %$self }, __PACKAGE__;
1051 $task->{-ent} = $m->{$name} //
1052 die("BUG: no `$name' in manifest");
1053 $task->{cur_src} = "$uri";
1054 $task->{cur_dst} = $task->{dst};
1055 $task->{-key} = $name;
1057 $task->{cur_dst} .= $name;
1058 $task->{cur_src} .= $name;
1060 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1061 E: `$task->{cur_dst}' must not contain newline
1063 $task->{cur_src} .= '/';
1064 my $dep = $task->{-ent}->{reference} // '';
1065 push @{$TODO->{$dep}}, $task; # for clone_all
1066 $self->{any_want}->{$name} = 1;
1069 delete local $lei->{opt}->{epoch} if defined($v2);
1070 clone_all($self, $m);
1071 return if $self->{dry_run} || !keep_going($self);
1073 # set by clone_v2_prep/-I/--exclude
1074 my $mis = delete $self->{chg}->{fp_mismatch};
1076 my $t = (stat($ft))[9];
1078 $t = POSIX::strftime('%Y-%m-%d %k:%M:%S %z', localtime($t));
1080 W: Fingerprints for the following repositories do not match
1082 W: These repositories may have updated since $t:
1084 warn "\t", $_, "\n" for @$mis;
1085 warn <<EOM if !$self->{lei}->{opt}->{prune};
1086 W: The above fingerprints may never match without --prune
1089 dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1090 my $bad = delete $self->{chg}->{badlink};
1091 warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1092 W: The following exist and have not been converted to symlinks
1094 ft_rename($ft, $manifest, 0666);
1097 sub start_clone_url {
1099 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1100 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1103 sub do_mirror { # via wq_io_do or public-inbox-clone
1105 my $lei = $self->{lei};
1106 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1107 umask($lei->{client_umask}) if defined $lei->{client_umask};
1108 $self->{-initial_clone} = 1 if !-d $self->{dst};
1110 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1111 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1112 --inbox-config must be one of `always', `v2', `v1', or `never'
1114 # we support --objstore= and --manifest= with '' (empty string)
1115 for my $default (qw(objstore manifest.js.gz)) {
1116 my ($k) = (split(/\./, $default))[0];
1117 my $v = $lei->{opt}->{$k} // next;
1118 $v = $default if $v eq '';
1119 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1120 $self->{"-$k"} = $v;
1124 local $FGRP_TODO = {};
1125 my $iv = $lei->{opt}->{'inbox-version'} //
1126 return start_clone_url($self);
1127 return clone_v1($self) if $iv == 1;
1128 die "bad --inbox-version=$iv\n" if $iv != 2;
1129 die <<EOM if $self->{src} !~ m!://!;
1130 cloning local v2 inboxes not supported
1132 try_scrape($self, 1);
1134 $lei->fail($@) if $@;
1138 my ($cls, $lei, $src, $dst) = @_;
1139 my $self = bless { src => $src, dst => $dst }, $cls;
1140 $lei->request_umask;
1141 my ($op_c, $ops) = $lei->workers_start($self, 1);
1142 $lei->{wq1} = $self;
1143 $self->wq_io_do('do_mirror', []);
1145 $lei->wait_wq_events($op_c, $ops);
1148 sub ipc_atfork_child {
1150 $self->{lei}->_lei_atfork_child;
1151 $self->SUPER::ipc_atfork_child;
1154 sub write_makefile {
1155 my ($dir, $ibx_ver) = @_;
1156 my $f = "$dir/Makefile";
1157 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1158 print $fh <<EOM or die "print($f) $!";
1159 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1160 # manpage for more information on the format. This Makefile is
1161 # intended as a familiar wrapper for users unfamiliar with
1162 # public-inbox-* commands.
1164 # See the respective manpages for public-inbox-fetch(1),
1165 # public-inbox-index(1), etc for more information on
1166 # some of the commands used by this Makefile.
1168 # This Makefile will not be modified nor read by public-inbox,
1169 # so you may edit it freely with your own convenience targets
1170 # and notes. public-inbox-fetch will recreate it if removed.
1172 print $fh <<'EOM' or die "print($f): $!";
1173 # the default target:
1175 @echo Common targets:
1176 @echo ' make fetch - fetch from remote git repostorie(s)'
1177 @echo ' make update - fetch and update index '
1179 @echo Rarely needed targets:
1180 @echo ' make reindex - may be needed for new features/bugfixes'
1181 @echo ' make compact - rewrite Xapian storage to save space'
1182 @echo ' make index - initial index after clone
1187 @if ! public-inbox-fetch --exit-code; \
1190 test $$c -eq 127 && exit 0; \
1192 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1194 public-inbox-index; \
1196 echo 'public-inbox index not initialized'; \
1197 echo 'see public-inbox-index(1) man page'; \
1202 public-inbox-index --reindex
1204 public-inbox-compact
1206 .PHONY : help fetch update index reindex compact
1208 close $fh or die "close($f): $!";
1210 die "open($f): $!" unless $!{EEXIST};