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;
695 sub v1_done { # called via OnDestroy
697 return if $self->{dry_run} || !keep_going($self);
698 _write_inbox_config($self);
699 my $dst = $self->{cur_dst} // $self->{dst};
700 if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
701 my $key = $self->{-key} // die 'BUG: no -key';
702 my $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
703 $cur eq $o or run_die([qw(git config -f),
704 "$dst/config", 'gitweb.owner', $o]);
706 my $o = "$dst/objects";
707 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
708 my $base = File::Spec->rel2abs($o);
713 $_ = File::Spec->abs2rel($_, $base);
714 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
718 print $ft @l or die "print($ft): $!";
719 $ft->flush or die "flush($ft): $!";
720 ft_rename($ft, $fn, 0666, $fh);
723 eval { set_description($self) };
725 return if ($self->{-is_epoch} ||
726 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
727 write_makefile($dst, 1);
728 index_cloned_inbox($self, 1);
731 sub v2_done { # called via OnDestroy
733 return if $self->{dry_run} || !keep_going($self);
734 my $dst = $self->{cur_dst} // $self->{dst};
735 require PublicInbox::Lock;
736 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
737 my $lck = $lk->lock_for_scope($$);
738 _write_inbox_config($self);
739 require PublicInbox::MultiGit;
740 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
741 $mg->fill_alternates;
742 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
743 for my $edst (@{delete($self->{-read_only}) // []}) {
744 my @st = stat($edst) or die "stat($edst): $!";
745 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
747 write_makefile($dst, 2);
749 eval { set_description($self) };
751 index_cloned_inbox($self, 2);
754 sub clone_v2_prep ($$;$) {
755 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
756 my $lei = $self->{lei};
757 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
758 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
759 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
760 my $dst = $self->{cur_dst} // $self->{dst};
761 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
762 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
763 delete $task->{todo}; # $self->{todo} still exists
765 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
766 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
767 my ($uri, $key) = @{$v2_epochs->{$nr}};
768 my $src = $uri->as_string;
770 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
771 failed to extract epoch number from $src
773 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
774 $edst .= "/git/$nr.git";
778 die("BUG: `$key' not in manifest.js.gz");
779 if (defined(my $d = $ent->{description})) {
780 $d =~ s/ \[epoch [0-9]+\]\z//s;
784 if (!$want || $want->{$nr}) {
785 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
786 $etask->{-ent} = $ent; # may have {reference}
787 $etask->{cur_src} = $src;
788 $etask->{cur_dst} = $edst;
789 $etask->{-is_epoch} = $fini;
790 my $ref = $ent->{reference} // '';
791 push @{$self->{todo}->{$ref}}, $etask;
792 $self->{any_want}->{$key} = 1;
793 } else { # create a placeholder so users only need to chmod +w
794 init_placeholder($src, $edst, $ent);
795 push @{$task->{-read_only}}, $edst;
799 # filter out the epochs we skipped
800 $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
802 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
804 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
805 _get_txt_start($task, '_/text/config/raw', $fini);
807 defined($desc) ? ($task->{'txt.description'} = $desc) :
808 _get_txt_start($task, 'description', $fini);
811 sub decode_manifest ($$$) {
812 my ($fh, $fn, $uri) = @_;
814 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
815 gunzip(\$gz => \$js, MultiStream => 1) or
816 die "gunzip($uri): $GunzipError\n";
817 my $m = eval { PublicInbox::Config->json->decode($js) };
818 die "$uri: error decoding `$js': $@\n" if $@;
819 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
823 sub load_current_manifest ($) {
825 my $fn = $self->{-manifest} // return;
826 if (open(my $fh, '<', $fn)) {
827 decode_manifest($fh, $fn, $fn);
828 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
829 warn "open($fn): $!\n" if !$self->{-initial_clone};
832 die "open($fn): $!\n";
836 sub multi_inbox ($$$) {
837 my ($self, $path, $m) = @_;
838 my $incl = $self->{lei}->{opt}->{include};
839 my $excl = $self->{lei}->{opt}->{exclude};
841 # assuming everything not v2 is v1, for now
842 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
843 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
847 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
848 push @{$v2->{$1}}, $_;
850 my $n = scalar(keys %$v2) + scalar(@v1);
851 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
853 my $re = '(?:'.join('\\z|', map {
854 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
856 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
857 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
858 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
859 @v1 = grep(/$re/, @v1);
862 my $re = '(?:'.join('\\z|', map {
863 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
865 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
866 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
867 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
868 @v1 = grep(!/$re/, @v1);
870 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
871 $ret->{v1} = \@v1 if @v1;
872 $ret->{v2} = $v2 if keys %$v2;
873 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
874 join("\n\t", sort @orig)
875 : "Nothing available to clone\n";
878 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
880 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
881 @v2_epochs) == @v2_epochs) {
882 $$path =~ s!\A(/[^/]+)/!/! or last;
886 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
890 ($path_pfx, $n, $ret);
895 my $todo = delete $self->{todo};
896 my $nodep = delete $todo->{''};
898 # do not download unwanted deps
899 my $any_want = delete $self->{any_want};
900 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
901 my @nodep = delete(@$todo{@unwanted});
902 push(@$nodep, @$_) for @nodep;
904 # handle no-dependency repos, first
907 return if !keep_going($self);
909 # resolve references, deepest, first:
910 while (scalar keys %$todo) {
911 for my $x (keys %$todo) {
913 # resolve multi-level references
914 while ($m && defined($nxt = $m->{$x}->{reference})) {
915 exists($todo->{$nxt}) or last;
916 die <<EOM if ++$nr > 1000;
917 E: dependency loop detected (`$x' => `$nxt')
921 my $y = delete $todo->{$x} // next; # already done
924 return if !keep_going($self);
926 last; # restart %$todo iteration
929 do_reap($self, 1); # finish all fingerprint checks
930 fgrp_fetch_all($self);
934 sub dump_manifest ($$) {
936 # write the smaller manifest if epochs were skipped so
937 # users won't have to delete manifest if they +w an
938 # epoch they no longer want to skip
939 my $json = PublicInbox::Config->json->encode($m);
940 my $mtime = (stat($ft))[9];
941 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
942 truncate($ft, 0) or die "truncate($ft): $!";
943 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
944 $ft->flush or die "flush($ft): $!";
945 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
948 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
951 my $uri = URI->new($self->{src});
952 my $lei = $self->{lei};
953 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
954 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
955 my $path = $uri->path;
956 chop($path) eq '/' or die "BUG: $uri not canonicalized";
957 $uri->path($path . '/manifest.js.gz');
958 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
959 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
960 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
961 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
964 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
965 my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
966 %opt = map { $_ => $lei->{$_} } (0..2);
967 my $cerr = run_reap($lei, $cmd, \%opt);
969 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
970 return $lei->child_error($cerr, "@$cmd failed");
972 my $m = eval { decode_manifest($ft, $ft, $uri) };
975 return try_scrape($self);
977 local $self->{-local_manifest} = load_current_manifest($self);
978 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
979 return $lei->child_error(1, $multi) if !ref($multi);
980 my $v2 = delete $multi->{v2};
981 local $self->{todo} = {};
982 local $self->{fgrp_todo} = {}; # { objstore_dir => [fgrp, ...] }
984 for my $name (sort keys %$v2) {
985 my $epochs = delete $v2->{$name};
986 my %v2_epochs = map {
987 $uri->path($n > 1 ? $path_pfx.$path.$_
989 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
990 $e // die "no [0-9]+\.git in `$uri'";
991 $e => [ $uri->clone, $_ ];
993 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
994 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
995 local $self->{cur_src} = $1;
996 local $self->{cur_dst} = $self->{dst};
997 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
998 git/[0-9]+\.git\z!x) {
999 $self->{cur_dst} .= "/$1";
1001 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1002 E: `$self->{cur_dst}' must not contain newline
1004 clone_v2_prep($self, \%v2_epochs, $m);
1005 return if !keep_going($self);
1008 if (my $v1 = delete $multi->{v1}) {
1009 my $p = $path_pfx.$path;
1010 chop($p) if substr($p, -1, 1) eq '/';
1012 for my $name (@$v1) {
1013 my $task = bless { %$self }, __PACKAGE__;
1014 $task->{-ent} = $m->{$name} //
1015 die("BUG: no `$name' in manifest");
1016 $task->{cur_src} = "$uri";
1017 $task->{cur_dst} = $task->{dst};
1018 $task->{-key} = $name;
1020 $task->{cur_dst} .= $name;
1021 $task->{cur_src} .= $name;
1023 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1024 E: `$task->{cur_dst}' must not contain newline
1026 $task->{cur_src} .= '/';
1027 my $dep = $task->{-ent}->{reference} // '';
1028 push @{$self->{todo}->{$dep}}, $task; # for clone_all
1029 $self->{any_want}->{$name} = 1;
1032 delete local $lei->{opt}->{epoch} if defined($v2);
1033 clone_all($self, $m);
1034 return if $self->{dry_run} || !keep_going($self);
1036 # set by clone_v2_prep/-I/--exclude
1037 dump_manifest($m => $ft) if delete $self->{-culled_manifest};
1038 ft_rename($ft, $manifest, 0666);
1039 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
1042 sub start_clone_url {
1044 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1045 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1048 sub do_mirror { # via wq_io_do or public-inbox-clone
1050 my $lei = $self->{lei};
1051 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1052 umask($lei->{client_umask}) if defined $lei->{client_umask};
1053 $self->{-initial_clone} = 1 if !-d $self->{dst};
1055 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1056 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1057 --inbox-config must be one of `always', `v2', `v1', or `never'
1059 # we support --objstore= and --manifest= with '' (empty string)
1060 for my $default (qw(objstore manifest.js.gz)) {
1061 my ($k) = (split(/\./, $default))[0];
1062 my $v = $lei->{opt}->{$k} // next;
1063 $v = $default if $v eq '';
1064 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1065 $self->{"-$k"} = $v;
1068 my $iv = $lei->{opt}->{'inbox-version'} //
1069 return start_clone_url($self);
1070 return clone_v1($self) if $iv == 1;
1071 die "bad --inbox-version=$iv\n" if $iv != 2;
1072 die <<EOM if $self->{src} !~ m!://!;
1073 cloning local v2 inboxes not supported
1075 try_scrape($self, 1);
1077 $lei->fail($@) if $@;
1081 my ($cls, $lei, $src, $dst) = @_;
1082 my $self = bless { src => $src, dst => $dst }, $cls;
1083 $lei->request_umask;
1084 my ($op_c, $ops) = $lei->workers_start($self, 1);
1085 $lei->{wq1} = $self;
1086 $self->wq_io_do('do_mirror', []);
1088 $lei->wait_wq_events($op_c, $ops);
1091 sub ipc_atfork_child {
1093 $self->{lei}->_lei_atfork_child;
1094 $self->SUPER::ipc_atfork_child;
1097 sub write_makefile {
1098 my ($dir, $ibx_ver) = @_;
1099 my $f = "$dir/Makefile";
1100 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1101 print $fh <<EOM or die "print($f) $!";
1102 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1103 # manpage for more information on the format. This Makefile is
1104 # intended as a familiar wrapper for users unfamiliar with
1105 # public-inbox-* commands.
1107 # See the respective manpages for public-inbox-fetch(1),
1108 # public-inbox-index(1), etc for more information on
1109 # some of the commands used by this Makefile.
1111 # This Makefile will not be modified nor read by public-inbox,
1112 # so you may edit it freely with your own convenience targets
1113 # and notes. public-inbox-fetch will recreate it if removed.
1115 print $fh <<'EOM' or die "print($f): $!";
1116 # the default target:
1118 @echo Common targets:
1119 @echo ' make fetch - fetch from remote git repostorie(s)'
1120 @echo ' make update - fetch and update index '
1122 @echo Rarely needed targets:
1123 @echo ' make reindex - may be needed for new features/bugfixes'
1124 @echo ' make compact - rewrite Xapian storage to save space'
1125 @echo ' make index - initial index after clone
1130 @if ! public-inbox-fetch --exit-code; \
1133 test $$c -eq 127 && exit 0; \
1135 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1137 public-inbox-index; \
1139 echo 'public-inbox index not initialized'; \
1140 echo 'see public-inbox-index(1) man page'; \
1145 public-inbox-index --reindex
1147 public-inbox-compact
1149 .PHONY : help fetch update index reindex compact
1151 close $fh or die "close($f): $!";
1153 die "open($f): $!" unless $!{EEXIST};