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
26 $LIVE && (!$_[0]->{lei}->{child_error} ||
27 $_[0]->{lei}->{opt}->{'keep-going'});
30 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
32 my ($mrr, $lei) = @$arg;
33 my $f = "$mrr->{dst}/mirror.done";
35 $lei->child_error($?);
36 } elsif (!$mrr->{dry_run} && !unlink($f)) {
37 warn("unlink($f): $!\n") unless $!{ENOENT};
39 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
40 require PublicInbox::LeiAddExternal;
41 PublicInbox::LeiAddExternal::_finish_add_external(
44 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
49 # for old installations without manifest.js.gz
51 my ($self, $fallback_manifest) = @_;
52 my $uri = URI->new($self->{src});
53 my $lei = $self->{lei};
54 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
55 my $cmd = $curl->for_uri($lei, $uri, qw(-f --compressed));
56 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
57 my $fh = popen_rd($cmd, undef, $opt);
58 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
59 close($fh) or return $lei->child_error($?, "@$cmd failed");
61 # we grep with URL below, we don't want Subject/From headers
62 # making us clone random URLs. This assumes remote instances
63 # prior to public-inbox 1.7.0
64 # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
65 my @html = split(/<hr>/, $html);
66 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
67 if (!@urls && $fallback_manifest) {
69 W: failed to extract URLs from $uri, trying manifest.js.gz...
71 return start_clone_url($self);
73 my $url = $uri->as_string;
74 chop($url) eq '/' or die "BUG: $uri not canonicalized";
76 # since this is for old instances w/o manifest.js.gz, try v1 first
77 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
78 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
80 my ($n) = (m!/([0-9]+)\z!);
81 $n => [ URI->new($_), '' ]
83 clone_v2_prep($self, \%v2_epochs);
84 delete local $lei->{opt}->{epoch};
89 # filter out common URLs served by WWW (e.g /$MSGID/T/)
90 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
91 grep(m!\A\Q$url\E/*\z!, @urls)) {
93 E: confused by scraping <$uri>, did you mean <$url>?
97 E: confused by scraping <$uri>, got ambiguous results:
100 die "E: scraping <$uri> revealed nothing\n";
104 my ($lei, $opt) = @_;
106 $opt->{$_} = $lei->{$_} for (0..2);
107 # we support "-c $key=$val" for arbitrary git config options
108 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
109 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
110 push @cmd, qw(clone --mirror);
111 push @cmd, '-q' if $lei->{opt}->{quiet} ||
112 ($lei->{opt}->{jobs} // 1) > 1;
113 push @cmd, '-v' if $lei->{opt}->{verbose};
114 # XXX any other options to support?
115 # --reference is tricky with multiple epochs, but handled
116 # automatically if using manifest.js.gz
120 sub ft_rename ($$$;$) {
121 my ($ft, $dst, $open_mode, $fh) = @_;
122 my @st = stat($fh // $dst);
123 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
124 chmod($mode, $ft) or croak "E: chmod($ft): $!";
126 File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
127 $ft->unlink_on_destroy(0);
131 my ($self, $jobs) = @_;
132 $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
133 $jobs = 1 if $jobs < 1;
134 while (keys(%$LIVE) >= $jobs) {
135 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
136 if (my $x = delete $LIVE->{$pid}) {
140 warn "reaped unknown PID=$pid ($?)\n";
145 sub _get_txt_start { # non-fatal
146 my ($self, $endpoint, $fini) = @_;
147 my $uri = URI->new($self->{cur_src} // $self->{src});
148 my $lei = $self->{lei};
149 my $path = $uri->path;
150 chop($path) eq '/' or die "BUG: $uri not canonicalized";
151 $uri->path("$path/$endpoint");
152 my $f = (split(m!/!, $endpoint))[-1];
153 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
154 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
155 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(-f --compressed -R -o),
158 $lei->qerr("# @$cmd");
159 return if $self->{dry_run};
160 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
161 $LIVE->{spawn($cmd, undef, $opt)} =
162 [ \&_get_txt_done, $self, $endpoint, $fini ];
165 sub _get_txt_done { # returns true on error (non-fatal), undef on success
166 my ($self, $endpoint) = @_;
167 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
169 $? = 0; # don't influence normal lei exit
170 return warn("$uri missing\n") if ($cerr >> 8) == 22;
171 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
172 seek($fh, SEEK_SET, 0) or die "seek: $!";
173 $self->{"mtime.$endpoint"} = (stat($fh))[9];
175 $self->{"txt.$endpoint"} = <$fh>;
179 sub _write_inbox_config {
181 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
182 my $dst = $self->{cur_dst} // $self->{dst};
183 my $f = "$dst/inbox.config.example";
184 open my $fh, '>', $f or die "open($f): $!";
185 print $fh $buf or die "print: $!";
186 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
187 my $mtime = delete $self->{'mtime._/text/config/raw'};
188 $fh->flush or die "flush($f): $!";
189 if (defined $mtime) {
190 utime($mtime, $mtime, $fh) or die "utime($f): $!";
192 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
193 my $ibx = $self->{ibx} = {};
194 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
195 for (qw(address newsgroup nntpmirror)) {
196 $ibx->{$_} = $cfg->{"$sec.$_"};
201 sub set_description ($) {
203 my $dst = $self->{cur_dst} // $self->{dst};
204 my $f = "$dst/description";
205 open my $fh, '+>>', $f or die "open($f): $!";
206 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
207 my $d = do { local $/; <$fh> } // die "read($f): $!";
208 chomp(my $orig = $d);
209 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
210 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
211 $d = delete($self->{'txt.description'});
213 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
215 return if $d eq $orig;
216 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
217 truncate($fh, 0) or die "truncate($f): $!";
218 print $fh $d, "\n" or die "print($f): $!";
219 close $fh or die "close($f): $!";
222 sub index_cloned_inbox {
223 my ($self, $iv) = @_;
224 my $lei = $self->{lei};
226 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
227 # lei is useless without Xapian + SQLite
228 if ($lei->{cmd} ne 'public-inbox-clone') {
229 require PublicInbox::InboxWritable;
230 require PublicInbox::Admin;
231 my $ibx = delete($self->{ibx}) // {
232 address => [ 'lei@example.com' ],
235 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
236 PublicInbox::Inbox->new($ibx);
237 PublicInbox::InboxWritable->new($ibx);
239 for my $sw ($lei->index_opt) {
240 my ($k) = ($sw =~ /\A([\w-]+)/);
241 $opt->{$k} = $lei->{opt}->{$k};
243 # force synchronous dwaitpid for v2:
244 local $PublicInbox::DS::in_loop = 0;
245 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
246 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
247 local %ENV = (%ENV, %$env) if $env;
248 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
249 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
251 return if defined $self->{cur_dst}; # one of many repos to clone
252 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
256 my ($lei, $cmd, $opt) = @_;
257 $lei->qerr("# @$cmd");
258 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
260 $? = 0; # don't let it influence normal exit
265 my ($self, $cmd, $opt, $fini) = @_;
267 $self->{lei}->qerr("# @$cmd");
268 return if $self->{dry_run};
269 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
272 sub fetch_args ($$) {
273 my ($lei, $opt) = @_;
274 my @cmd; # (git --git-dir=...) to be added by caller
275 $opt->{$_} = $lei->{$_} for (0..2);
276 # we support "-c $key=$val" for arbitrary git config options
277 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
278 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
280 push @cmd, '-q' if $lei->{opt}->{quiet} ||
281 ($lei->{opt}->{jobs} // 1) > 1;
282 push @cmd, '-v' if $lei->{opt}->{verbose};
283 push(@cmd, '-p') if $lei->{opt}->{prune};
287 sub upr { # feed `git update-ref --stdin -z' verbosely
288 my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
289 $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
290 print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
295 return if !keep_going($fgrp);
296 my $srcfh = delete $fgrp->{srcfh} or return;
297 my $dstfh = delete $fgrp->{dstfh} or return;
298 seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
299 seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
300 my %src = map { chomp; split(/\0/) } (<$srcfh>);
302 my %dst = map { chomp; split(/\0/) } (<$dstfh>);
304 pipe(my ($r, $w)) or die "pipe: $!";
305 my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
306 qw(update-ref --stdin -z) ];
307 my $lei = $fgrp->{lei};
308 $lei->qerr("# @$cmd");
309 my $opt = { 0 => $r, 2 => $lei->{2} };
310 my $pid = spawn($cmd, undef, $opt);
311 close $r or die "close(r): $!";
312 for my $ref (keys %dst) {
313 my $new = delete $src{$ref};
314 my $old = $dst{$ref};
317 upr($lei, $w, 'update', $ref, $new, $old);
319 upr($lei, $w, 'delete', $ref, $old);
322 while (my ($ref, $oid) = each %src) {
323 upr($lei, $w, 'create', $ref, $oid);
325 close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
326 my $pack = PublicInbox::OnDestroy->new($$, \&pack_dst, $fgrp);
327 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd, $pack ];
330 sub pack_dst { # packs lightweight satellite repos
332 pack_refs($fgrp, $fgrp->{cur_dst});
336 my ($self, $git_dir) = @_;
338 return if !keep_going($self);
339 my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
340 $self->{lei}->qerr("# @$cmd");
341 return if $self->{dry_run};
342 my $opt = { 2 => $self->{lei}->{2} };
343 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd ];
350 my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
351 return if !keep_going($first);
352 pack_refs($first, $first->{-osdir}); # objstore refs always packed
353 for my $fgrp (@$fgrpv) {
354 my $rn = $fgrp->{-remote};
355 my %opt = ( 2 => $fgrp->{lei}->{2} );
357 my $update_ref = $fgrp->{dry_run} ? undef :
358 PublicInbox::OnDestroy->new($$, \&fgrp_update, $fgrp);
360 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
361 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
362 "refs/remotes/$rn/" ];
364 $fgrp->{lei}->qerr("# @$src >SRC");
366 open(my $fh, '+>', undef) or die "open(src): $!";
367 $pid = spawn($src, undef, { %opt, 1 => $fh });
368 $fgrp->{srcfh} = $fh;
369 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $src, $update_ref ]
371 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
372 '--format=%(refname)%00%(objectname)' ];
374 $fgrp->{lei}->qerr("# @$dst >DST");
376 open(my $fh, '+>', undef) or die "open(dst): $!";
377 $pid = spawn($dst, undef, { %opt, 1 => $fh });
378 $fgrp->{dstfh} = $fh;
379 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $dst, $update_ref ]
386 my $todo = delete $self->{fgrp_todo} or return;
387 keys(%$todo) or return;
389 # Rely on the fgrptmp remote groups in the config file rather
390 # than listing all remotes since the remote name list may exceed
391 # system argv limits:
394 my @git = (@{$self->{-torsocks}}, 'git');
395 my $j = $self->{lei}->{opt}->{jobs};
398 local $self->{lei}->{opt}->{jobs} = 1;
399 (fetch_args($self->{lei}, $opt),
400 qw(--no-tags --multiple));
402 push(@fetch, "-j$j") if $j;
404 while (my ($osdir, $fgrpv) = each %$todo) {
405 my $f = "$osdir/config";
407 # clobber group from previous run atomically
408 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
409 $f, '--unset-all', "remotes.$grp"];
410 $self->{lei}->qerr("# @$cmd");
411 if (!$self->{dry_run}) {
412 $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
413 waitpid($pid, 0) // die "waitpid: $!";
414 die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
416 # update the config atomically via O_APPEND while
417 # respecting git-config locking
418 sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
419 or die "open($f.lock): $!";
420 open my $fh, '>>', $f or die "open(>>$f): $!";
422 my $buf = join('', "[remotes]\n",
423 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
424 print $fh $buf or die "print($f): $!";
425 close $fh or die "close($f): $!";
426 unlink("$f.lock") or die "unlink($f.lock): $!";
429 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
431 $self->{lei}->qerr("# @$cmd");
432 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
433 return if $self->{dry_run};
434 $pid = spawn($cmd, undef, $opt);
435 $LIVE->{$pid} = [ \&reap_cmd, $self, $cmd, $end ];
439 # keep this idempotent for future use by public-inbox-fetch
441 my ($self, $uri) = @_;
442 $self->{-ent} // return;
443 my $os = $self->{-objstore} // return;
444 my $fg = $self->{-ent}->{forkgroup} // return;
445 my $dir = "$os/$fg.git";
446 if (!-d $dir && !$self->{dry_run}) {
447 PublicInbox::Import::init_bare($dir);
448 my @cmd = ('git', "--git-dir=$dir", 'config');
449 my $opt = { 2 => $self->{lei}->{2} };
450 for ('repack.useDeltaIslands=true',
451 'pack.island=refs/remotes/([^/]+)/') {
452 run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
455 my $key = $self->{-key} // die 'BUG: no -key';
456 my $rn = substr(sha256_hex($key), 0, 16);
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): $!";
484 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
489 my ($self, $go_fetch) = @_;
490 return if !keep_going($self);
491 my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
492 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
493 $self->{-ent} // die 'BUG: no -ent';
494 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
495 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
496 return if $A ne $B; # $go_fetch->DESTROY fires
498 $self->{lei}->qerr("# $self->{-key} up-to-date");
502 my ($self, $go_fetch) = @_;
503 # $go_fetch is either resume_fetch or fgrp_enqueue
504 my $new = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
505 my $key = $self->{-key} // die 'BUG: no -key';
506 if (my $cur_ent = $self->{-local_manifest}->{$key}) {
507 # runs go_fetch->DESTROY run if eq
508 return $go_fetch->cancel if $cur_ent->{fingerprint} eq $new;
510 my $dst = $self->{cur_dst} // $self->{dst};
511 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
512 my $opt = { 2 => $self->{lei}->{2} };
513 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
514 $self->{-show_ref} = $opt->{1};
515 my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $go_fetch);
516 start_cmd($self, $cmd, $opt, $done);
519 sub resume_fetch_maybe {
520 my ($self, $uri, $fini) = @_;
521 my $go_fetch = PublicInbox::OnDestroy->new($$, \&resume_fetch, @_);
522 cmp_fp_fetch($self, $go_fetch) if $self->{-ent} &&
523 defined($self->{-ent}->{fingerprint});
527 my ($self, $uri, $fini) = @_;
528 return if !keep_going($self);
529 my $dst = $self->{cur_dst} // $self->{dst};
530 my @git = ('git', "--git-dir=$dst");
531 my $opt = { 2 => $self->{lei}->{2} };
532 my $rn = 'origin'; # configurable?
533 for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
534 my @kv = split(/=/, $_, 2);
535 $kv[0] = "remote.$rn.$kv[0]";
536 next if $self->{dry_run};
537 run_die([@git, 'config', @kv], undef, $opt);
539 my $cmd = [ @{$self->{-torsocks}}, @git,
540 fetch_args($self->{lei}, $opt), $rn ];
541 push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
542 start_cmd($self, $cmd, $opt, $fini);
545 sub fgrp_enqueue_maybe {
546 my ($self, $fgrp) = @_;
547 my $enq = PublicInbox::OnDestroy->new($$, \&fgrp_enqueue, $self, $fgrp);
548 cmp_fp_fetch($self, $enq) if $self->{-ent} &&
549 defined($self->{-ent}->{fingerprint});
550 # $enq->DESTROY calls fgrp_enqueue otherwise
554 my ($self, $fgrp) = @_;
555 return if !keep_going($self);
556 my $opt = { 2 => $self->{lei}->{2} };
557 # --no-tags is required to avoid conflicts
558 my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
559 my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
560 my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
561 for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
562 my @kv = split(/=/, $_, 2);
563 $kv[0] = "remote.$rn.$kv[0]";
564 $self->{dry_run} ? $self->{lei}->qerr("# @cmd @kv") :
565 run_die([@cmd, @kv], undef, $opt);
567 push @{$self->{fgrp_todo}->{$fgrp->{-osdir}}}, $fgrp;
571 my ($self, $nohang) = @_;
572 my $lei = $self->{lei};
573 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
574 my $uri = URI->new($self->{cur_src} // $self->{src});
575 defined($lei->{opt}->{epoch}) and
576 die "$uri is a v1 inbox, --epoch is not supported\n";
577 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
578 my $dst = $self->{cur_dst} // $self->{dst};
579 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
580 my $resume = -d $dst;
581 if (my $fgrp = forkgroup_prep($self, $uri)) {
582 $fgrp->{-fini} = $fini;
583 $resume ? fgrp_enqueue_maybe($self, $fgrp) :
584 fgrp_enqueue($self, $fgrp);
586 resume_fetch_maybe($self, $uri, $fini);
587 } else { # normal clone
588 my $cmd = [ @{$self->{-torsocks}},
589 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
590 if (defined($self->{-ent})) {
591 if (defined(my $ref = $self->{-ent}->{reference})) {
592 -e "$self->{dst}$ref" and
593 push @$cmd, '--reference',
597 start_cmd($self, $cmd, $opt, $fini);
599 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
600 /\A(?:always|v1)\z/s) {
601 _get_txt_start($self, '_/text/config/raw', $fini);
604 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
605 $self->{'txt.description'} = $d if defined $d;
606 (!defined($d) && !$nohang) and
607 _get_txt_start($self, 'description', $fini);
609 $nohang or do_reap($self, 1); # for non-manifest clone
612 sub parse_epochs ($$) {
613 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
614 $opt_epochs // return; # undef => all epochs
615 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
616 undef($lo) if ($lo // '') eq '';
617 my $re = qr/\A~?[0-9]+\z/;
618 if (@extra || (($lo // '0') !~ $re) ||
619 (($hi // '0') !~ $re) ||
620 !(grep(defined, $lo, $hi))) {
622 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
625 my @n = sort { $a <=> $b } keys %$v2_epochs;
626 for (grep(defined, $lo, $hi)) {
629 "`$_' exceeds maximum available epoch ($n[-1])\n";
631 "`$_' is lower than minimum available epoch ($n[0])\n";
632 } elsif (/\A~([0-9]+)/) {
634 $n[$off] // die "`$_' is out of range\n";
636 } else { die "`$_' not understood\n" }
638 defined($lo) && defined($hi) && $lo > $hi and die
639 "low value (`$lo') exceeds high (`$hi')\n";
640 $lo //= $n[0] if $dotdot;
641 $hi //= $n[-1] if $dotdot;
645 if (defined $v2_epochs->{$_}) {
649 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
655 sub init_placeholder ($$$) {
656 my ($src, $edst, $ent) = @_;
657 PublicInbox::Import::init_bare($edst);
658 my $f = "$edst/config";
659 open my $fh, '>>', $f or die "open($f): $!";
660 print $fh <<EOM or die "print($f): $!";
663 fetch = +refs/*:refs/*
666 ; This git epoch was created read-only and "public-inbox-fetch"
667 ; will not fetch updates for it unless write permission is added.
668 ; Hint: chmod +w $edst
670 if (defined($ent->{owner})) {
671 print $fh <<EOM or die "print($f): $!";
673 owner = $ent->{owner}
676 close $fh or die "close($f): $!";
677 my %map = (head => 'HEAD', description => undef);
678 while (my ($key, $fn) = each %map) {
679 my $val = $ent->{$key} // next;
682 open $fh, '>', $fn or die "open($fn): $!";
683 print $fh $val, "\n" or die "print($fn): $!";
684 close $fh or die "close($fn): $!";
688 sub reap_cmd { # async, called via SIGCHLD
689 my ($self, $cmd) = @_;
691 $? = 0; # don't let it influence normal exit
692 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
697 return if !keep_going($self);
698 my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
699 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
700 $self->{-ent} // die 'BUG: no -ent';
701 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
702 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
704 $self->{-ent}->{fingerprint} = $B;
705 push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
710 my $key = $self->{-key} // die 'BUG: no -key';
711 my $new = $self->{-ent}->{fingerprint};
712 my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
713 my $dst = $self->{cur_dst} // $self->{dst};
714 if (defined($new) && $new ne $cur) {
715 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
716 my $opt = { 2 => $self->{lei}->{2} };
717 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
718 $self->{-show_ref_up} = $opt->{1};
719 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
720 start_cmd($self, $cmd, $opt, $done);
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;
792 delete $task->{todo}; # $self->{todo} still exists
794 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
795 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
796 my ($uri, $key) = @{$v2_epochs->{$nr}};
797 my $src = $uri->as_string;
799 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
800 failed to extract epoch number from $src
802 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
803 $edst .= "/git/$nr.git";
807 die("BUG: `$key' not in manifest.js.gz");
808 if (defined(my $d = $ent->{description})) {
809 $d =~ s/ \[epoch [0-9]+\]\z//s;
813 if (!$want || $want->{$nr}) {
814 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
815 $etask->{-ent} = $ent; # may have {reference}
816 $etask->{cur_src} = $src;
817 $etask->{cur_dst} = $edst;
818 $etask->{-is_epoch} = $fini;
819 my $ref = $ent->{reference} // '';
820 push @{$self->{todo}->{$ref}}, $etask;
821 $self->{any_want}->{$key} = 1;
822 } else { # create a placeholder so users only need to chmod +w
823 init_placeholder($src, $edst, $ent);
824 push @{$task->{-read_only}}, $edst;
828 # filter out the epochs we skipped
829 $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
831 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
833 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
834 _get_txt_start($task, '_/text/config/raw', $fini);
836 defined($desc) ? ($task->{'txt.description'} = $desc) :
837 _get_txt_start($task, 'description', $fini);
840 sub decode_manifest ($$$) {
841 my ($fh, $fn, $uri) = @_;
843 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
844 gunzip(\$gz => \$js, MultiStream => 1) or
845 die "gunzip($uri): $GunzipError\n";
846 my $m = eval { PublicInbox::Config->json->decode($js) };
847 die "$uri: error decoding `$js': $@\n" if $@;
848 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
852 sub load_current_manifest ($) {
854 my $fn = $self->{-manifest} // return;
855 if (open(my $fh, '<', $fn)) {
856 decode_manifest($fh, $fn, $fn);
857 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
858 warn "open($fn): $!\n" if !$self->{-initial_clone};
861 die "open($fn): $!\n";
865 sub multi_inbox ($$$) {
866 my ($self, $path, $m) = @_;
867 my $incl = $self->{lei}->{opt}->{include};
868 my $excl = $self->{lei}->{opt}->{exclude};
870 # assuming everything not v2 is v1, for now
871 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
872 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
876 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
877 push @{$v2->{$1}}, $_;
879 my $n = scalar(keys %$v2) + scalar(@v1);
880 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
882 my $re = '(?:'.join('\\z|', map {
883 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
885 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
886 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
887 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
888 @v1 = grep(/$re/, @v1);
891 my $re = '(?:'.join('\\z|', map {
892 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
894 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
895 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
896 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
897 @v1 = grep(!/$re/, @v1);
899 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
900 $ret->{v1} = \@v1 if @v1;
901 $ret->{v2} = $v2 if keys %$v2;
902 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
903 join("\n\t", sort @orig)
904 : "Nothing available to clone\n";
907 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
909 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
910 @v2_epochs) == @v2_epochs) {
911 $$path =~ s!\A(/[^/]+)/!/! or last;
915 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
919 ($path_pfx, $n, $ret);
924 my $todo = delete $self->{todo};
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);
938 # resolve references, deepest, first:
939 while (scalar keys %$todo) {
940 for my $x (keys %$todo) {
942 # resolve multi-level references
943 while ($m && defined($nxt = $m->{$x}->{reference})) {
944 exists($todo->{$nxt}) or last;
945 die <<EOM if ++$nr > 1000;
946 E: dependency loop detected (`$x' => `$nxt')
950 my $y = delete $todo->{$x} // next; # already done
953 return if !keep_going($self);
955 last; # restart %$todo iteration
958 do_reap($self, 1); # finish all fingerprint checks
959 fgrp_fetch_all($self);
963 sub dump_manifest ($$) {
965 # write the smaller manifest if epochs were skipped so
966 # users won't have to delete manifest if they +w an
967 # epoch they no longer want to skip
968 my $json = PublicInbox::Config->json->encode($m);
969 my $mtime = (stat($ft))[9];
970 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
971 truncate($ft, 0) or die "truncate($ft): $!";
972 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
973 $ft->flush or die "flush($ft): $!";
974 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
977 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
980 my $uri = URI->new($self->{src});
981 my $lei = $self->{lei};
982 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
983 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
984 my $path = $uri->path;
985 chop($path) eq '/' or die "BUG: $uri not canonicalized";
986 $uri->path($path . '/manifest.js.gz');
987 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
988 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
989 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
990 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
993 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
994 my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
996 %opt = map { $_ => $lei->{$_} } (0..2);
997 my $cerr = run_reap($lei, $cmd, \%opt);
999 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1000 return $lei->child_error($cerr, "@$cmd failed");
1002 my $m = eval { decode_manifest($ft, $ft, $uri) };
1005 return try_scrape($self);
1007 local $self->{chg} = {};
1008 local $self->{-local_manifest} = load_current_manifest($self);
1009 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1010 return $lei->child_error(1, $multi) if !ref($multi);
1011 my $v2 = delete $multi->{v2};
1012 local $self->{todo} = {};
1013 local $self->{fgrp_todo} = {}; # { objstore_dir => [fgrp, ...] }
1015 for my $name (sort keys %$v2) {
1016 my $epochs = delete $v2->{$name};
1017 my %v2_epochs = map {
1018 $uri->path($n > 1 ? $path_pfx.$path.$_
1020 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1021 $e // die "no [0-9]+\.git in `$uri'";
1022 $e => [ $uri->clone, $_ ];
1024 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1025 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1026 local $self->{cur_src} = $1;
1027 local $self->{cur_dst} = $self->{dst};
1028 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1029 git/[0-9]+\.git\z!x) {
1030 $self->{cur_dst} .= "/$1";
1032 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1033 E: `$self->{cur_dst}' must not contain newline
1035 clone_v2_prep($self, \%v2_epochs, $m);
1036 return if !keep_going($self);
1039 if (my $v1 = delete $multi->{v1}) {
1040 my $p = $path_pfx.$path;
1041 chop($p) if substr($p, -1, 1) eq '/';
1043 for my $name (@$v1) {
1044 my $task = bless { %$self }, __PACKAGE__;
1045 $task->{-ent} = $m->{$name} //
1046 die("BUG: no `$name' in manifest");
1047 $task->{cur_src} = "$uri";
1048 $task->{cur_dst} = $task->{dst};
1049 $task->{-key} = $name;
1051 $task->{cur_dst} .= $name;
1052 $task->{cur_src} .= $name;
1054 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1055 E: `$task->{cur_dst}' must not contain newline
1057 $task->{cur_src} .= '/';
1058 my $dep = $task->{-ent}->{reference} // '';
1059 push @{$self->{todo}->{$dep}}, $task; # for clone_all
1060 $self->{any_want}->{$name} = 1;
1063 delete local $lei->{opt}->{epoch} if defined($v2);
1064 clone_all($self, $m);
1065 return if $self->{dry_run} || !keep_going($self);
1067 # set by clone_v2_prep/-I/--exclude
1068 my $mis = delete $self->{chg}->{fp_mismatch};
1070 my $t = (stat($ft))[9];
1072 $t = POSIX::strftime('%Y-%m-%d %k:%M:%S %z', localtime($t));
1074 W: Fingerprints for the following repositories do not match
1076 W: These repositories may have updated since $t:
1078 warn "\t", $_, "\n" for @$mis;
1079 warn <<EOM if !$self->{lei}->{opt}->{prune};
1080 W: The above fingerprints may never match without --prune
1083 dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1084 ft_rename($ft, $manifest, 0666);
1085 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
1088 sub start_clone_url {
1090 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1091 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1094 sub do_mirror { # via wq_io_do or public-inbox-clone
1096 my $lei = $self->{lei};
1097 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1098 umask($lei->{client_umask}) if defined $lei->{client_umask};
1099 $self->{-initial_clone} = 1 if !-d $self->{dst};
1101 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1102 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1103 --inbox-config must be one of `always', `v2', `v1', or `never'
1105 # we support --objstore= and --manifest= with '' (empty string)
1106 for my $default (qw(objstore manifest.js.gz)) {
1107 my ($k) = (split(/\./, $default))[0];
1108 my $v = $lei->{opt}->{$k} // next;
1109 $v = $default if $v eq '';
1110 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1111 $self->{"-$k"} = $v;
1114 my $iv = $lei->{opt}->{'inbox-version'} //
1115 return start_clone_url($self);
1116 return clone_v1($self) if $iv == 1;
1117 die "bad --inbox-version=$iv\n" if $iv != 2;
1118 die <<EOM if $self->{src} !~ m!://!;
1119 cloning local v2 inboxes not supported
1121 try_scrape($self, 1);
1123 $lei->fail($@) if $@;
1127 my ($cls, $lei, $src, $dst) = @_;
1128 my $self = bless { src => $src, dst => $dst }, $cls;
1129 $lei->request_umask;
1130 my ($op_c, $ops) = $lei->workers_start($self, 1);
1131 $lei->{wq1} = $self;
1132 $self->wq_io_do('do_mirror', []);
1134 $lei->wait_wq_events($op_c, $ops);
1137 sub ipc_atfork_child {
1139 $self->{lei}->_lei_atfork_child;
1140 $self->SUPER::ipc_atfork_child;
1143 sub write_makefile {
1144 my ($dir, $ibx_ver) = @_;
1145 my $f = "$dir/Makefile";
1146 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1147 print $fh <<EOM or die "print($f) $!";
1148 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1149 # manpage for more information on the format. This Makefile is
1150 # intended as a familiar wrapper for users unfamiliar with
1151 # public-inbox-* commands.
1153 # See the respective manpages for public-inbox-fetch(1),
1154 # public-inbox-index(1), etc for more information on
1155 # some of the commands used by this Makefile.
1157 # This Makefile will not be modified nor read by public-inbox,
1158 # so you may edit it freely with your own convenience targets
1159 # and notes. public-inbox-fetch will recreate it if removed.
1161 print $fh <<'EOM' or die "print($f): $!";
1162 # the default target:
1164 @echo Common targets:
1165 @echo ' make fetch - fetch from remote git repostorie(s)'
1166 @echo ' make update - fetch and update index '
1168 @echo Rarely needed targets:
1169 @echo ' make reindex - may be needed for new features/bugfixes'
1170 @echo ' make compact - rewrite Xapian storage to save space'
1171 @echo ' make index - initial index after clone
1176 @if ! public-inbox-fetch --exit-code; \
1179 test $$c -eq 127 && exit 0; \
1181 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1183 public-inbox-index; \
1185 echo 'public-inbox index not initialized'; \
1186 echo 'see public-inbox-index(1) man page'; \
1191 public-inbox-index --reindex
1193 public-inbox-compact
1195 .PHONY : help fetch update index reindex compact
1197 close $fh or die "close($f): $!";
1199 die "open($f): $!" unless $!{EEXIST};