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;
34 $lei->child_error($?);
35 } elsif (!$lei->{child_error}) {
36 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
37 require PublicInbox::LeiAddExternal;
38 PublicInbox::LeiAddExternal::_finish_add_external(
41 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
46 # for old installations without manifest.js.gz
48 my ($self, $fallback_manifest) = @_;
49 my $uri = URI->new($self->{src});
50 my $lei = $self->{lei};
51 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
52 my $cmd = $curl->for_uri($lei, $uri, qw(-f --compressed));
53 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
54 my $fh = popen_rd($cmd, undef, $opt);
55 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
56 close($fh) or return $lei->child_error($?, "@$cmd failed");
58 # we grep with URL below, we don't want Subject/From headers
59 # making us clone random URLs. This assumes remote instances
60 # prior to public-inbox 1.7.0
61 # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
62 my @html = split(/<hr>/, $html);
63 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
64 if (!@urls && $fallback_manifest) {
66 W: failed to extract URLs from $uri, trying manifest.js.gz...
68 return start_clone_url($self);
70 my $url = $uri->as_string;
71 chop($url) eq '/' or die "BUG: $uri not canonicalized";
73 # since this is for old instances w/o manifest.js.gz, try v1 first
74 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
75 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
77 my ($n) = (m!/([0-9]+)\z!);
78 $n => [ URI->new($_), '' ]
80 clone_v2_prep($self, \%v2_epochs);
81 delete local $lei->{opt}->{epoch};
86 # filter out common URLs served by WWW (e.g /$MSGID/T/)
87 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
88 grep(m!\A\Q$url\E/*\z!, @urls)) {
90 E: confused by scraping <$uri>, did you mean <$url>?
94 E: confused by scraping <$uri>, got ambiguous results:
97 die "E: scraping <$uri> revealed nothing\n";
101 my ($lei, $opt) = @_;
103 $opt->{$_} = $lei->{$_} for (0..2);
104 # we support "-c $key=$val" for arbitrary git config options
105 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
106 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
107 push @cmd, qw(clone --mirror);
108 push @cmd, '-q' if $lei->{opt}->{quiet} ||
109 ($lei->{opt}->{jobs} // 1) > 1;
110 push @cmd, '-v' if $lei->{opt}->{verbose};
111 # XXX any other options to support?
112 # --reference is tricky with multiple epochs, but handled
113 # automatically if using manifest.js.gz
117 sub ft_rename ($$$;$) {
118 my ($ft, $dst, $open_mode, $fh) = @_;
119 my @st = stat($fh // $dst);
120 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
121 chmod($mode, $ft) or croak "E: chmod($ft): $!";
123 File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
124 $ft->unlink_on_destroy(0);
128 my ($self, $jobs) = @_;
129 $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
130 $jobs = 1 if $jobs < 1;
131 while (keys(%$LIVE) >= $jobs) {
132 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
133 if (my $x = delete $LIVE->{$pid}) {
137 warn "reaped unknown PID=$pid ($?)\n";
142 sub _get_txt_start { # non-fatal
143 my ($self, $endpoint, $fini) = @_;
144 my $uri = URI->new($self->{cur_src} // $self->{src});
145 my $lei = $self->{lei};
146 my $path = $uri->path;
147 chop($path) eq '/' or die "BUG: $uri not canonicalized";
148 $uri->path("$path/$endpoint");
149 my $f = (split(m!/!, $endpoint))[-1];
150 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
151 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
152 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(-f --compressed -R -o),
155 $lei->qerr("# @$cmd");
156 return if $self->{dry_run};
157 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
158 $LIVE->{spawn($cmd, undef, $opt)} =
159 [ \&_get_txt_done, $self, $endpoint, $fini ];
162 sub _get_txt_done { # returns true on error (non-fatal), undef on success
163 my ($self, $endpoint) = @_;
164 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
166 $? = 0; # don't influence normal lei exit
167 return warn("$uri missing\n") if ($cerr >> 8) == 22;
168 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
169 seek($fh, SEEK_SET, 0) or die "seek: $!";
170 $self->{"mtime.$endpoint"} = (stat($fh))[9];
172 $self->{"txt.$endpoint"} = <$fh>;
176 sub _write_inbox_config {
178 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
179 my $dst = $self->{cur_dst} // $self->{dst};
180 my $f = "$dst/inbox.config.example";
181 open my $fh, '>', $f or die "open($f): $!";
182 print $fh $buf or die "print: $!";
183 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
184 my $mtime = delete $self->{'mtime._/text/config/raw'};
185 $fh->flush or die "flush($f): $!";
186 if (defined $mtime) {
187 utime($mtime, $mtime, $fh) or die "utime($f): $!";
189 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
190 my $ibx = $self->{ibx} = {};
191 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
192 for (qw(address newsgroup nntpmirror)) {
193 $ibx->{$_} = $cfg->{"$sec.$_"};
198 sub set_description ($) {
200 my $dst = $self->{cur_dst} // $self->{dst};
201 my $f = "$dst/description";
202 open my $fh, '+>>', $f or die "open($f): $!";
203 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
204 my $d = do { local $/; <$fh> } // die "read($f): $!";
205 chomp(my $orig = $d);
206 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
207 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
208 $d = delete($self->{'txt.description'});
210 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
212 return if $d eq $orig;
213 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
214 truncate($fh, 0) or die "truncate($f): $!";
215 print $fh $d, "\n" or die "print($f): $!";
216 close $fh or die "close($f): $!";
219 sub index_cloned_inbox {
220 my ($self, $iv) = @_;
221 my $lei = $self->{lei};
223 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
224 # lei is useless without Xapian + SQLite
225 if ($lei->{cmd} ne 'public-inbox-clone') {
226 require PublicInbox::InboxWritable;
227 require PublicInbox::Admin;
228 my $ibx = delete($self->{ibx}) // {
229 address => [ 'lei@example.com' ],
232 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
233 PublicInbox::Inbox->new($ibx);
234 PublicInbox::InboxWritable->new($ibx);
236 for my $sw ($lei->index_opt) {
237 my ($k) = ($sw =~ /\A([\w-]+)/);
238 $opt->{$k} = $lei->{opt}->{$k};
240 # force synchronous dwaitpid for v2:
241 local $PublicInbox::DS::in_loop = 0;
242 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
243 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
244 local %ENV = (%ENV, %$env) if $env;
245 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
246 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
248 return if defined $self->{cur_dst}; # one of many repos to clone
252 my ($lei, $cmd, $opt) = @_;
253 $lei->qerr("# @$cmd");
254 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
256 $? = 0; # don't let it influence normal exit
261 my ($self, $cmd, $opt, $fini) = @_;
263 $self->{lei}->qerr("# @$cmd");
264 return if $self->{dry_run};
265 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
268 sub fetch_args ($$) {
269 my ($lei, $opt) = @_;
270 my @cmd; # (git --git-dir=...) to be added by caller
271 $opt->{$_} = $lei->{$_} for (0..2);
272 # we support "-c $key=$val" for arbitrary git config options
273 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
274 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
276 push @cmd, '-q' if $lei->{opt}->{quiet} ||
277 ($lei->{opt}->{jobs} // 1) > 1;
278 push @cmd, '-v' if $lei->{opt}->{verbose};
279 push(@cmd, '-p') if $lei->{opt}->{prune};
283 sub upr { # feed `git update-ref --stdin -z' verbosely
284 my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
285 $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
286 print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
291 return if !keep_going($fgrp);
292 my $srcfh = delete $fgrp->{srcfh} or return;
293 my $dstfh = delete $fgrp->{dstfh} or return;
294 seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
295 seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
296 my %src = map { chomp; split(/\0/) } (<$srcfh>);
298 my %dst = map { chomp; split(/\0/) } (<$dstfh>);
300 pipe(my ($r, $w)) or die "pipe: $!";
301 my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
302 qw(update-ref --stdin -z) ];
303 my $lei = $fgrp->{lei};
304 my $pack = PublicInbox::OnDestroy->new($$, \&pack_dst, $fgrp);
305 start_cmd($fgrp, $cmd, { 0 => $r, 2 => $lei->{2} }, $pack);
306 close $r or die "close(r): $!";
307 return if $fgrp->{dry_run};
308 for my $ref (keys %dst) {
309 my $new = delete $src{$ref};
310 my $old = $dst{$ref};
313 upr($lei, $w, 'update', $ref, $new, $old);
315 upr($lei, $w, 'delete', $ref, $old);
318 while (my ($ref, $oid) = each %src) {
319 upr($lei, $w, 'create', $ref, $oid);
321 close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
324 sub pack_dst { # packs lightweight satellite repos
326 pack_refs($fgrp, $fgrp->{cur_dst});
327 delete($fgrp->{-fini}) // die 'BUG: no {-fini}'; # call v1_done
331 my ($self, $git_dir) = @_;
332 my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
333 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
339 my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
340 return if !keep_going($first);
341 pack_refs($first, $first->{-osdir}); # objstore refs always packed
342 for my $fgrp (@$fgrpv) {
343 my $rn = $fgrp->{-remote};
344 my %opt = ( 2 => $fgrp->{lei}->{2} );
346 my $update_ref = PublicInbox::OnDestroy->new($$,
347 \&fgrp_update, $fgrp);
349 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
350 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
351 "refs/remotes/$rn/" ];
352 open(my $sfh, '+>', undef) or die "open(src): $!";
353 $fgrp->{srcfh} = $sfh;
354 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
355 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
356 '--format=%(refname)%00%(objectname)' ];
357 open(my $dfh, '+>', undef) or die "open(dst): $!";
358 $fgrp->{dstfh} = $dfh;
359 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
365 my $todo = delete $self->{fgrp_todo} or return;
366 keys(%$todo) or return;
368 # Rely on the fgrptmp remote groups in the config file rather
369 # than listing all remotes since the remote name list may exceed
370 # system argv limits:
373 my @git = (@{$self->{-torsocks}}, 'git');
374 my $j = $self->{lei}->{opt}->{jobs};
377 local $self->{lei}->{opt}->{jobs} = 1;
378 (fetch_args($self->{lei}, $opt),
379 qw(--no-tags --multiple));
381 push(@fetch, "-j$j") if $j;
382 while (my ($osdir, $fgrpv) = each %$todo) {
383 my $f = "$osdir/config";
385 # clobber group from previous run atomically
386 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
387 $f, '--unset-all', "remotes.$grp"];
388 $self->{lei}->qerr("# @$cmd");
389 if (!$self->{dry_run}) {
390 my $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
391 waitpid($pid, 0) // die "waitpid: $!";
392 die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
394 # update the config atomically via O_APPEND while
395 # respecting git-config locking
396 sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
397 or die "open($f.lock): $!";
398 open my $fh, '>>', $f or die "open(>>$f): $!";
400 my $buf = join('', "[remotes]\n",
401 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
402 print $fh $buf or die "print($f): $!";
403 close $fh or die "close($f): $!";
404 unlink("$f.lock") or die "unlink($f.lock): $!";
407 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
408 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
409 start_cmd($self, $cmd, $opt, $end);
413 # keep this idempotent for future use by public-inbox-fetch
415 my ($self, $uri) = @_;
416 $self->{-ent} // return;
417 my $os = $self->{-objstore} // return;
418 my $fg = $self->{-ent}->{forkgroup} // return;
419 my $dir = "$os/$fg.git";
420 if (!-d $dir && !$self->{dry_run}) {
421 PublicInbox::Import::init_bare($dir);
422 my @cmd = ('git', "--git-dir=$dir", 'config');
423 my $opt = { 2 => $self->{lei}->{2} };
424 for ('repack.useDeltaIslands=true',
425 'pack.island=refs/remotes/([^/]+)/') {
426 run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
429 my $key = $self->{-key} // die 'BUG: no -key';
430 my $rn = substr(sha256_hex($key), 0, 16);
431 if (!-d $self->{cur_dst} && !$self->{dry_run}) {
432 my $alt = File::Spec->rel2abs("$dir/objects");
433 PublicInbox::Import::init_bare($self->{cur_dst});
434 my $o = "$self->{cur_dst}/objects";
435 my $f = "$o/info/alternates";
436 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
437 open my $fh, '+>>', $f or die "open($f): $!";
438 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
439 chomp(my @cur = <$fh>);
440 if (!grep(/\A\Q$l\E\z/, @cur)) {
441 say $fh $l or die "say($f): $!";
443 close $fh or die "close($f): $!";
444 $f = "$self->{cur_dst}/config";
445 open $fh, '+>>', $f or die "open:($f): $!";
446 print $fh <<EOM or die "print($f): $!";
447 ; rely on the "$rn" remote in the
448 ; $fg fork group for fetches
449 ; only uncomment the following iff you detach from fork groups
452 ; fetch = +refs/*:refs/*
455 close $fh or die "close($f): $!";
458 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
463 my ($self, $cb, @arg) = @_;
464 return if !keep_going($self);
465 my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
466 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
467 $self->{-ent} // die 'BUG: no -ent';
468 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
469 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
470 return $cb->($self, @arg) if $A ne $B;
471 $self->{lei}->qerr("# $self->{-key} up-to-date");
475 my ($self, $cb, @arg) = @_;
476 # $cb is either resume_fetch or fgrp_enqueue
477 $self->{-ent} // return $cb->($self, @arg);
478 my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
479 my $key = $self->{-key} // die 'BUG: no -key';
480 if (my $cur_ent = $self->{-local_manifest}->{$key}) {
481 # runs go_fetch->DESTROY run if eq
482 return if $cur_ent->{fingerprint} eq $new;
484 my $dst = $self->{cur_dst} // $self->{dst};
485 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
486 my $opt = { 2 => $self->{lei}->{2} };
487 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
488 $self->{-show_ref} = $opt->{1};
489 my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $cb, @arg);
490 start_cmd($self, $cmd, $opt, $done);
494 my ($self, $uri, $fini) = @_;
495 return if !keep_going($self);
496 my $dst = $self->{cur_dst} // $self->{dst};
497 my @git = ('git', "--git-dir=$dst");
498 my $opt = { 2 => $self->{lei}->{2} };
499 my $rn = 'origin'; # configurable?
500 for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
501 my @kv = split(/=/, $_, 2);
502 $kv[0] = "remote.$rn.$kv[0]";
503 next if $self->{dry_run};
504 run_die([@git, 'config', @kv], undef, $opt);
506 my $cmd = [ @{$self->{-torsocks}}, @git,
507 fetch_args($self->{lei}, $opt), $rn ];
508 push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
509 start_cmd($self, $cmd, $opt, $fini);
514 return if !keep_going($fgrp);
515 my $opt = { 2 => $fgrp->{lei}->{2} };
516 # --no-tags is required to avoid conflicts
517 my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
518 my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
519 my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
520 for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
521 my @kv = split(/=/, $_, 2);
522 $kv[0] = "remote.$rn.$kv[0]";
523 $fgrp->{dry_run} ? $fgrp->{lei}->qerr("# @cmd @kv") :
524 run_die([@cmd, @kv], undef, $opt);
526 $fgrp->{fgrp_todo} // die 'BUG: no fgrp_todo';
527 push @{$fgrp->{fgrp_todo}->{$fgrp->{-osdir}}}, $fgrp;
531 my ($self, $nohang) = @_;
532 my $lei = $self->{lei};
533 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
534 my $uri = URI->new($self->{cur_src} // $self->{src});
535 defined($lei->{opt}->{epoch}) and
536 die "$uri is a v1 inbox, --epoch is not supported\n";
537 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
538 my $dst = $self->{cur_dst} // $self->{dst};
539 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
540 my $resume = -d $dst;
541 if (my $fgrp = forkgroup_prep($self, $uri)) {
542 $fgrp->{-fini} = $fini;
543 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue) : fgrp_enqueue($fgrp)
545 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
546 } else { # normal clone
547 my $cmd = [ @{$self->{-torsocks}},
548 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
549 if (defined($self->{-ent})) {
550 if (defined(my $ref = $self->{-ent}->{reference})) {
551 -e "$self->{dst}$ref" and
552 push @$cmd, '--reference',
556 start_cmd($self, $cmd, $opt, $fini);
558 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
559 /\A(?:always|v1)\z/s) {
560 _get_txt_start($self, '_/text/config/raw', $fini);
563 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
564 $self->{'txt.description'} = $d if defined $d;
565 (!defined($d) && !$nohang) and
566 _get_txt_start($self, 'description', $fini);
568 $nohang or do_reap($self, 1); # for non-manifest clone
571 sub parse_epochs ($$) {
572 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
573 $opt_epochs // return; # undef => all epochs
574 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
575 undef($lo) if ($lo // '') eq '';
576 my $re = qr/\A~?[0-9]+\z/;
577 if (@extra || (($lo // '0') !~ $re) ||
578 (($hi // '0') !~ $re) ||
579 !(grep(defined, $lo, $hi))) {
581 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
584 my @n = sort { $a <=> $b } keys %$v2_epochs;
585 for (grep(defined, $lo, $hi)) {
588 "`$_' exceeds maximum available epoch ($n[-1])\n";
590 "`$_' is lower than minimum available epoch ($n[0])\n";
591 } elsif (/\A~([0-9]+)/) {
593 $n[$off] // die "`$_' is out of range\n";
595 } else { die "`$_' not understood\n" }
597 defined($lo) && defined($hi) && $lo > $hi and die
598 "low value (`$lo') exceeds high (`$hi')\n";
599 $lo //= $n[0] if $dotdot;
600 $hi //= $n[-1] if $dotdot;
604 if (defined $v2_epochs->{$_}) {
608 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
614 sub init_placeholder ($$$) {
615 my ($src, $edst, $ent) = @_;
616 PublicInbox::Import::init_bare($edst);
617 my $f = "$edst/config";
618 open my $fh, '>>', $f or die "open($f): $!";
619 print $fh <<EOM or die "print($f): $!";
622 fetch = +refs/*:refs/*
625 ; This git epoch was created read-only and "public-inbox-fetch"
626 ; will not fetch updates for it unless write permission is added.
627 ; Hint: chmod +w $edst
629 if (defined($ent->{owner})) {
630 print $fh <<EOM or die "print($f): $!";
632 owner = $ent->{owner}
635 close $fh or die "close($f): $!";
636 my %map = (head => 'HEAD', description => undef);
637 while (my ($key, $fn) = each %map) {
638 my $val = $ent->{$key} // next;
641 open $fh, '>', $fn or die "open($fn): $!";
642 print $fh $val, "\n" or die "print($fn): $!";
643 close $fh or die "close($fn): $!";
647 sub reap_cmd { # async, called via SIGCHLD
648 my ($self, $cmd) = @_;
650 $? = 0; # don't let it influence normal exit
651 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
656 return if !keep_going($self);
657 my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
658 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
659 $self->{-ent} // die 'BUG: no -ent';
660 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
661 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
663 $self->{-ent}->{fingerprint} = $B;
664 push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
669 my $key = $self->{-key} // die 'BUG: no -key';
670 my $new = $self->{-ent}->{fingerprint};
671 my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
672 my $dst = $self->{cur_dst} // $self->{dst};
673 if (defined($new) && $new ne $cur) {
674 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
675 my $opt = { 2 => $self->{lei}->{2} };
676 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
677 $self->{-show_ref_up} = $opt->{1};
678 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
679 start_cmd($self, $cmd, $opt, $done);
681 $new = $self->{-ent}->{owner} // return;
682 $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
683 return if $cur eq $new;
684 my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
685 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
688 sub v1_done { # called via OnDestroy
690 return if $self->{dry_run} || !keep_going($self);
691 _write_inbox_config($self);
692 my $dst = $self->{cur_dst} // $self->{dst};
693 update_ent($self) if $self->{-ent};
694 my $o = "$dst/objects";
695 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
696 my $base = File::Spec->rel2abs($o);
701 $_ = File::Spec->abs2rel($_, $base);
702 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
706 print $ft @l or die "print($ft): $!";
707 $ft->flush or die "flush($ft): $!";
708 ft_rename($ft, $fn, 0666, $fh);
711 eval { set_description($self) };
713 return if ($self->{-is_epoch} ||
714 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
715 write_makefile($dst, 1);
716 index_cloned_inbox($self, 1);
719 sub v2_done { # called via OnDestroy
721 return if $self->{dry_run} || !keep_going($self);
722 my $dst = $self->{cur_dst} // $self->{dst};
723 require PublicInbox::Lock;
724 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
725 my $lck = $lk->lock_for_scope($$);
726 _write_inbox_config($self);
727 require PublicInbox::MultiGit;
728 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
729 $mg->fill_alternates;
730 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
731 for my $edst (@{delete($self->{-read_only}) // []}) {
732 my @st = stat($edst) or die "stat($edst): $!";
733 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
735 write_makefile($dst, 2);
737 eval { set_description($self) };
739 index_cloned_inbox($self, 2);
742 sub clone_v2_prep ($$;$) {
743 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
744 my $lei = $self->{lei};
745 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
746 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
747 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
748 my $dst = $self->{cur_dst} // $self->{dst};
749 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
750 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
751 delete $task->{todo}; # $self->{todo} still exists
753 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
754 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
755 my ($uri, $key) = @{$v2_epochs->{$nr}};
756 my $src = $uri->as_string;
758 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
759 failed to extract epoch number from $src
761 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
762 $edst .= "/git/$nr.git";
766 die("BUG: `$key' not in manifest.js.gz");
767 if (defined(my $d = $ent->{description})) {
768 $d =~ s/ \[epoch [0-9]+\]\z//s;
772 if (!$want || $want->{$nr}) {
773 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
774 $etask->{-ent} = $ent; # may have {reference}
775 $etask->{cur_src} = $src;
776 $etask->{cur_dst} = $edst;
777 $etask->{-is_epoch} = $fini;
778 my $ref = $ent->{reference} // '';
779 push @{$self->{todo}->{$ref}}, $etask;
780 $self->{any_want}->{$key} = 1;
781 } else { # create a placeholder so users only need to chmod +w
782 init_placeholder($src, $edst, $ent);
783 push @{$task->{-read_only}}, $edst;
787 # filter out the epochs we skipped
788 $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
790 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
792 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
793 _get_txt_start($task, '_/text/config/raw', $fini);
795 defined($desc) ? ($task->{'txt.description'} = $desc) :
796 _get_txt_start($task, 'description', $fini);
799 sub decode_manifest ($$$) {
800 my ($fh, $fn, $uri) = @_;
802 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
803 gunzip(\$gz => \$js, MultiStream => 1) or
804 die "gunzip($uri): $GunzipError\n";
805 my $m = eval { PublicInbox::Config->json->decode($js) };
806 die "$uri: error decoding `$js': $@\n" if $@;
807 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
811 sub load_current_manifest ($) {
813 my $fn = $self->{-manifest} // return;
814 if (open(my $fh, '<', $fn)) {
815 decode_manifest($fh, $fn, $fn);
816 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
817 warn "open($fn): $!\n" if !$self->{-initial_clone};
820 die "open($fn): $!\n";
824 sub multi_inbox ($$$) {
825 my ($self, $path, $m) = @_;
826 my $incl = $self->{lei}->{opt}->{include};
827 my $excl = $self->{lei}->{opt}->{exclude};
829 # assuming everything not v2 is v1, for now
830 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
831 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
835 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
836 push @{$v2->{$1}}, $_;
838 my $n = scalar(keys %$v2) + scalar(@v1);
839 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
841 my $re = '(?:'.join('\\z|', map {
842 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
844 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
845 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
846 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
847 @v1 = grep(/$re/, @v1);
850 my $re = '(?:'.join('\\z|', map {
851 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
853 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
854 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
855 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
856 @v1 = grep(!/$re/, @v1);
858 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
859 $ret->{v1} = \@v1 if @v1;
860 $ret->{v2} = $v2 if keys %$v2;
861 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
862 join("\n\t", sort @orig)
863 : "Nothing available to clone\n";
866 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
868 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
869 @v2_epochs) == @v2_epochs) {
870 $$path =~ s!\A(/[^/]+)/!/! or last;
874 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
878 ($path_pfx, $n, $ret);
883 my $todo = delete $self->{todo};
884 my $nodep = delete $todo->{''};
886 # do not download unwanted deps
887 my $any_want = delete $self->{any_want};
888 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
889 my @nodep = delete(@$todo{@unwanted});
890 push(@$nodep, @$_) for @nodep;
892 # handle no-dependency repos, first
895 return if !keep_going($self);
897 # resolve references, deepest, first:
898 while (scalar keys %$todo) {
899 for my $x (keys %$todo) {
901 # resolve multi-level references
902 while ($m && defined($nxt = $m->{$x}->{reference})) {
903 exists($todo->{$nxt}) or last;
904 die <<EOM if ++$nr > 1000;
905 E: dependency loop detected (`$x' => `$nxt')
909 my $y = delete $todo->{$x} // next; # already done
912 return if !keep_going($self);
914 last; # restart %$todo iteration
917 do_reap($self, 1); # finish all fingerprint checks
918 fgrp_fetch_all($self);
922 sub dump_manifest ($$) {
924 # write the smaller manifest if epochs were skipped so
925 # users won't have to delete manifest if they +w an
926 # epoch they no longer want to skip
927 my $json = PublicInbox::Config->json->encode($m);
928 my $mtime = (stat($ft))[9];
929 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
930 truncate($ft, 0) or die "truncate($ft): $!";
931 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
932 $ft->flush or die "flush($ft): $!";
933 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
936 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
939 my $uri = URI->new($self->{src});
940 my $lei = $self->{lei};
941 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
942 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
943 my $path = $uri->path;
944 chop($path) eq '/' or die "BUG: $uri not canonicalized";
945 $uri->path($path . '/manifest.js.gz');
946 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
947 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
948 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
949 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
952 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
953 my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
955 %opt = map { $_ => $lei->{$_} } (0..2);
956 my $cerr = run_reap($lei, $cmd, \%opt);
958 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
959 return $lei->child_error($cerr, "@$cmd failed");
961 my $m = eval { decode_manifest($ft, $ft, $uri) };
964 return try_scrape($self);
966 local $self->{chg} = {};
967 local $self->{-local_manifest} = load_current_manifest($self);
968 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
969 return $lei->child_error(1, $multi) if !ref($multi);
970 my $v2 = delete $multi->{v2};
971 local $self->{todo} = {};
972 local $self->{fgrp_todo} = {}; # { objstore_dir => [fgrp, ...] }
974 for my $name (sort keys %$v2) {
975 my $epochs = delete $v2->{$name};
976 my %v2_epochs = map {
977 $uri->path($n > 1 ? $path_pfx.$path.$_
979 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
980 $e // die "no [0-9]+\.git in `$uri'";
981 $e => [ $uri->clone, $_ ];
983 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
984 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
985 local $self->{cur_src} = $1;
986 local $self->{cur_dst} = $self->{dst};
987 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
988 git/[0-9]+\.git\z!x) {
989 $self->{cur_dst} .= "/$1";
991 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
992 E: `$self->{cur_dst}' must not contain newline
994 clone_v2_prep($self, \%v2_epochs, $m);
995 return if !keep_going($self);
998 if (my $v1 = delete $multi->{v1}) {
999 my $p = $path_pfx.$path;
1000 chop($p) if substr($p, -1, 1) eq '/';
1002 for my $name (@$v1) {
1003 my $task = bless { %$self }, __PACKAGE__;
1004 $task->{-ent} = $m->{$name} //
1005 die("BUG: no `$name' in manifest");
1006 $task->{cur_src} = "$uri";
1007 $task->{cur_dst} = $task->{dst};
1008 $task->{-key} = $name;
1010 $task->{cur_dst} .= $name;
1011 $task->{cur_src} .= $name;
1013 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1014 E: `$task->{cur_dst}' must not contain newline
1016 $task->{cur_src} .= '/';
1017 my $dep = $task->{-ent}->{reference} // '';
1018 push @{$self->{todo}->{$dep}}, $task; # for clone_all
1019 $self->{any_want}->{$name} = 1;
1022 delete local $lei->{opt}->{epoch} if defined($v2);
1023 clone_all($self, $m);
1024 return if $self->{dry_run} || !keep_going($self);
1026 # set by clone_v2_prep/-I/--exclude
1027 my $mis = delete $self->{chg}->{fp_mismatch};
1029 my $t = (stat($ft))[9];
1031 $t = POSIX::strftime('%Y-%m-%d %k:%M:%S %z', localtime($t));
1033 W: Fingerprints for the following repositories do not match
1035 W: These repositories may have updated since $t:
1037 warn "\t", $_, "\n" for @$mis;
1038 warn <<EOM if !$self->{lei}->{opt}->{prune};
1039 W: The above fingerprints may never match without --prune
1042 dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1043 ft_rename($ft, $manifest, 0666);
1046 sub start_clone_url {
1048 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1049 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1052 sub do_mirror { # via wq_io_do or public-inbox-clone
1054 my $lei = $self->{lei};
1055 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1056 umask($lei->{client_umask}) if defined $lei->{client_umask};
1057 $self->{-initial_clone} = 1 if !-d $self->{dst};
1059 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1060 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1061 --inbox-config must be one of `always', `v2', `v1', or `never'
1063 # we support --objstore= and --manifest= with '' (empty string)
1064 for my $default (qw(objstore manifest.js.gz)) {
1065 my ($k) = (split(/\./, $default))[0];
1066 my $v = $lei->{opt}->{$k} // next;
1067 $v = $default if $v eq '';
1068 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1069 $self->{"-$k"} = $v;
1072 my $iv = $lei->{opt}->{'inbox-version'} //
1073 return start_clone_url($self);
1074 return clone_v1($self) if $iv == 1;
1075 die "bad --inbox-version=$iv\n" if $iv != 2;
1076 die <<EOM if $self->{src} !~ m!://!;
1077 cloning local v2 inboxes not supported
1079 try_scrape($self, 1);
1081 $lei->fail($@) if $@;
1085 my ($cls, $lei, $src, $dst) = @_;
1086 my $self = bless { src => $src, dst => $dst }, $cls;
1087 $lei->request_umask;
1088 my ($op_c, $ops) = $lei->workers_start($self, 1);
1089 $lei->{wq1} = $self;
1090 $self->wq_io_do('do_mirror', []);
1092 $lei->wait_wq_events($op_c, $ops);
1095 sub ipc_atfork_child {
1097 $self->{lei}->_lei_atfork_child;
1098 $self->SUPER::ipc_atfork_child;
1101 sub write_makefile {
1102 my ($dir, $ibx_ver) = @_;
1103 my $f = "$dir/Makefile";
1104 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1105 print $fh <<EOM or die "print($f) $!";
1106 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1107 # manpage for more information on the format. This Makefile is
1108 # intended as a familiar wrapper for users unfamiliar with
1109 # public-inbox-* commands.
1111 # See the respective manpages for public-inbox-fetch(1),
1112 # public-inbox-index(1), etc for more information on
1113 # some of the commands used by this Makefile.
1115 # This Makefile will not be modified nor read by public-inbox,
1116 # so you may edit it freely with your own convenience targets
1117 # and notes. public-inbox-fetch will recreate it if removed.
1119 print $fh <<'EOM' or die "print($f): $!";
1120 # the default target:
1122 @echo Common targets:
1123 @echo ' make fetch - fetch from remote git repostorie(s)'
1124 @echo ' make update - fetch and update index '
1126 @echo Rarely needed targets:
1127 @echo ' make reindex - may be needed for new features/bugfixes'
1128 @echo ' make compact - rewrite Xapian storage to save space'
1129 @echo ' make index - initial index after clone
1134 @if ! public-inbox-fetch --exit-code; \
1137 test $$c -eq 127 && exit 0; \
1139 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1141 public-inbox-index; \
1143 echo 'public-inbox index not initialized'; \
1144 echo 'see public-inbox-index(1) man page'; \
1149 public-inbox-index --reindex
1151 public-inbox-compact
1153 .PHONY : help fetch update index reindex compact
1155 close $fh or die "close($f): $!";
1157 die "open($f): $!" unless $!{EEXIST};