]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
dd6356bbc340d8fc754d781148351c5ce7a32c14
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use v5.12;
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);
11 use File::Path ();
12 use File::Temp ();
13 use File::Spec ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15 use Carp qw(croak);
16 use URI;
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::Git;
20 use PublicInbox::LeiCurl;
21 use PublicInbox::OnDestroy;
22 use PublicInbox::SHA qw(sha256_hex sha1_hex);
23 use POSIX qw(strftime);
24
25 our $LIVE; # pid => callback
26 our $FGRP_TODO; # objstore -> [ fgrp mirror objects ]
27 our $TODO; # reference => [ non-fgrp mirror objects ]
28 our @PUH; # post-update hooks
29
30 sub keep_going ($) {
31         $LIVE && (!$_[0]->{lei}->{child_error} ||
32                 $_[0]->{lei}->{opt}->{'keep-going'});
33 }
34
35 sub _wq_done_wait { # awaitpid cb (via wq_eof)
36         my ($pid, $mrr, $lei) = @_;
37         if ($?) {
38                 $lei->child_error($?);
39         } elsif (!$lei->{child_error}) {
40                 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
41                         require PublicInbox::LeiAddExternal;
42                         PublicInbox::LeiAddExternal::_finish_add_external(
43                                                         $lei, $mrr->{dst});
44                 }
45                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
46         }
47         $lei->dclose;
48 }
49
50 # for old installations without manifest.js.gz
51 sub try_scrape {
52         my ($self, $fallback_manifest) = @_;
53         my $uri = URI->new($self->{src});
54         my $lei = $self->{lei};
55         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
56         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
57         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
58         my $fh = popen_rd($cmd, undef, $opt);
59         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
60         close($fh) or return $lei->child_error($?, "@$cmd failed");
61
62         # we grep with URL below, we don't want Subject/From headers
63         # making us clone random URLs.  This assumes remote instances
64         # prior to public-inbox 1.7.0
65         # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
66         my @html = split(/<hr>/, $html);
67         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
68         if (!@urls && $fallback_manifest) {
69                 warn <<EOM;
70 W: failed to extract URLs from $uri, trying manifest.js.gz...
71 EOM
72                 return start_clone_url($self);
73         }
74         my $url = $uri->as_string;
75         chop($url) eq '/' or die "BUG: $uri not canonicalized";
76
77         # since this is for old instances w/o manifest.js.gz, try v1 first
78         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
79         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
80                 my %v2_epochs = map {
81                         my ($n) = (m!/([0-9]+)\z!);
82                         $n => [ URI->new($_), '' ]
83                 } @v2_urls; # uniq
84                 clone_v2_prep($self, \%v2_epochs);
85                 delete local $lei->{opt}->{epoch};
86                 clone_all($self);
87                 return;
88         }
89
90         # filter out common URLs served by WWW (e.g /$MSGID/T/)
91         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
92                         grep(m!\A\Q$url\E/*\z!, @urls)) {
93                 die <<"";
94 E: confused by scraping <$uri>, did you mean <$url>?
95
96         }
97         @urls and die <<"";
98 E: confused by scraping <$uri>, got ambiguous results:
99 @urls
100
101         die "E: scraping <$uri> revealed nothing\n";
102 }
103
104 sub clone_cmd {
105         my ($lei, $opt) = @_;
106         my @cmd = qw(git);
107         $opt->{$_} = $lei->{$_} for (0..2);
108         # we support "-c $key=$val" for arbitrary git config options
109         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
110         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
111         push @cmd, qw(clone --mirror);
112         push @cmd, '-q' if $lei->{opt}->{quiet} ||
113                         ($lei->{opt}->{jobs} // 1) > 1;
114         push @cmd, '-v' if $lei->{opt}->{verbose};
115         # XXX any other options to support?
116         # --reference is tricky with multiple epochs, but handled
117         # automatically if using manifest.js.gz
118         @cmd;
119 }
120
121 sub ft_rename ($$$;$) {
122         my ($ft, $dst, $open_mode, $fh) = @_;
123         my @st = stat($fh // $dst);
124         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
125         chmod($mode, $ft) or croak "E: chmod($ft): $!";
126         require File::Copy;
127         File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
128         $ft->unlink_on_destroy(0);
129 }
130
131 sub do_reap ($;$) {
132         my ($self, $jobs) = @_;
133         $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
134         $jobs = 1 if $jobs < 1;
135         while (keys(%$LIVE) >= $jobs) {
136                 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
137                 if (my $x = delete $LIVE->{$pid}) {
138                         my $cb = shift @$x;
139                         $cb->(@$x) if $cb;
140                 } else {
141                         warn "reaped unknown PID=$pid ($?)\n";
142                 }
143         }
144 }
145
146 sub _get_txt_start { # non-fatal
147         my ($self, $endpoint, $fini) = @_;
148         my $uri = URI->new($self->{cur_src} // $self->{src});
149         my $lei = $self->{lei};
150         my $path = $uri->path;
151         chop($path) eq '/' or die "BUG: $uri not canonicalized";
152         $uri->path("$path/$endpoint");
153         my $f = (split(m!/!, $endpoint))[-1];
154         my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
155         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
156         my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
157                                         $ft->filename);
158         do_reap($self);
159         $lei->qerr("# @$cmd");
160         return if $self->{dry_run};
161         $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
162         $LIVE->{spawn($cmd, undef, $opt)} =
163                         [ \&_get_txt_done, $self, $endpoint, $fini ];
164 }
165
166 sub _get_txt_done { # returns true on error (non-fatal), undef on success
167         my ($self, $endpoint) = @_;
168         my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
169         my $cerr = $?;
170         $? = 0; # don't influence normal lei exit
171         return warn("$uri missing\n") if ($cerr >> 8) == 22;
172         return warn("# @$cmd failed (non-fatal)\n") if $cerr;
173         seek($fh, SEEK_SET, 0) or die "seek: $!";
174         $self->{"mtime.$endpoint"} = (stat($fh))[9];
175         local $/;
176         $self->{"txt.$endpoint"} = <$fh>;
177         undef; # success
178 }
179
180 sub _write_inbox_config {
181         my ($self) = @_;
182         my $buf = delete($self->{'txt._/text/config/raw'}) // return;
183         my $dst = $self->{cur_dst} // $self->{dst};
184         my $f = "$dst/inbox.config.example";
185         my $mtime = delete $self->{'mtime._/text/config/raw'};
186         if (sysopen(my $fh, $f, O_CREAT|O_EXCL|O_WRONLY)) {
187                 print $fh $buf or die "print: $!";
188                 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
189                 $fh->flush or die "flush($f): $!";
190                 if (defined $mtime) {
191                         utime($mtime, $mtime, $fh) or die "utime($f): $!";
192                 }
193         } elsif (!$!{EEXIST}) {
194                 die "open($f): $!";
195         }
196         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
197         my $ibx = $self->{ibx} = {};
198         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
199                 for (qw(address newsgroup nntpmirror)) {
200                         $ibx->{$_} = $cfg->{"$sec.$_"};
201                 }
202         }
203 }
204
205 sub set_description ($) {
206         my ($self) = @_;
207         my $dst = $self->{cur_dst} // $self->{dst};
208         chomp(my $orig = PublicInbox::Git::try_cat("$dst/description"));
209         my $d = $orig;
210         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
211                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
212                 $d = delete($self->{'txt.description'});
213         }
214         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
215         atomic_write($dst, 'description', $d."\n") if $d ne $orig;
216 }
217
218 sub index_cloned_inbox {
219         my ($self, $iv) = @_;
220         my $lei = $self->{lei};
221
222         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
223         # lei is useless without Xapian + SQLite
224         if ($lei->{cmd} ne 'public-inbox-clone') {
225                 require PublicInbox::InboxWritable;
226                 require PublicInbox::Admin;
227                 my $ibx = delete($self->{ibx}) // {
228                         address => [ 'lei@example.com' ],
229                         version => $iv,
230                 };
231                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
232                 PublicInbox::Inbox->new($ibx);
233                 PublicInbox::InboxWritable->new($ibx);
234                 my $opt = {};
235                 for my $sw ($lei->index_opt) {
236                         my ($k) = ($sw =~ /\A([\w-]+)/);
237                         $opt->{$k} = $lei->{opt}->{$k};
238                 }
239                 # force synchronous awaitpid for v2:
240                 local $PublicInbox::DS::in_loop = 0;
241                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
242                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
243                 local %ENV = (%ENV, %$env) if $env;
244                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
245                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
246         }
247         return if defined $self->{cur_dst}; # one of many repos to clone
248 }
249
250 sub run_reap {
251         my ($lei, $cmd, $opt) = @_;
252         $lei->qerr("# @$cmd");
253         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
254         my $ret = $?;
255         $? = 0; # don't let it influence normal exit
256         $ret;
257 }
258
259 sub start_cmd {
260         my ($self, $cmd, $opt, $fini) = @_;
261         do_reap($self);
262         utf8::decode(my $msg = "# @$cmd");
263         $self->{lei}->qerr($msg);
264         return if $self->{dry_run};
265         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
266 }
267
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} // []};
275         push @cmd, 'fetch';
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};
280         PublicInbox::Git::version() >= ((2 << 24) | (29 << 16)) and
281                 push(@cmd, '--no-write-fetch-head');
282         @cmd;
283 }
284
285 sub upr { # feed `git update-ref --stdin -z' verbosely
286         my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
287         $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
288         print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
289 }
290
291 sub start_update_ref {
292         my ($fgrp) = @_;
293         pipe(my ($r, $w)) or die "pipe: $!";
294         my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
295                 qw(update-ref --stdin -z) ];
296         my $pack = PublicInbox::OnDestroy->new($$, \&satellite_done, $fgrp);
297         start_cmd($fgrp, $cmd, { 0 => $r, 2 => $fgrp->{lei}->{2} }, $pack);
298         close $r or die "close(r): $!";
299         $fgrp->{dry_run} ? undef : $w;
300 }
301
302 sub upref_warn { warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n" }
303
304 sub fgrp_update {
305         my ($fgrp) = @_;
306         return if !keep_going($fgrp);
307         my $srcfh = delete $fgrp->{srcfh} or return;
308         my $dstfh = delete $fgrp->{dstfh} or return;
309         seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
310         seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
311         my %src = map { chomp; split(/\0/) } (<$srcfh>);
312         close $srcfh;
313         my %dst = map { chomp; split(/\0/) } (<$dstfh>);
314         close $dstfh;
315         my $w = start_update_ref($fgrp) or return;
316         my $lei = $fgrp->{lei};
317         my $ndel;
318         for my $ref (keys %dst) {
319                 my $new = delete $src{$ref};
320                 my $old = $dst{$ref};
321                 if (defined $new) {
322                         $new eq $old or
323                                 upr($lei, $w, 'update', $ref, $new, $old);
324                 } else {
325                         upr($lei, $w, 'delete', $ref, $old);
326                         ++$ndel;
327                 }
328         }
329         # git's ref files backend doesn't allow directory/file conflicts
330         # between `delete' and `create' ops:
331         if ($ndel && scalar(keys %src)) {
332                 $fgrp->{-create_refs} = \%src;
333         } else {
334                 while (my ($ref, $oid) = each %src) {
335                         upr($lei, $w, 'create', $ref, $oid);
336                 }
337         }
338         close($w) or upref_warn();
339 }
340
341 sub satellite_done {
342         my ($fgrp) = @_;
343         if (my $create = delete $fgrp->{-create_refs}) {
344                 my $w = start_update_ref($fgrp) or return;
345                 while (my ($ref, $oid) = each %$create) {
346                         upr($fgrp->{lei}, $w, 'create', $ref, $oid);
347                 }
348                 close($w) or upref_warn();
349         } else {
350                 pack_refs($fgrp, $fgrp->{cur_dst});
351                 run_puh($fgrp);
352         }
353 }
354
355 sub pack_refs {
356         my ($self, $git_dir) = @_;
357         my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
358         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
359 }
360
361 sub fgrpv_done {
362         my ($fgrpv) = @_;
363         return if !$LIVE;
364         my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
365         return if !keep_going($first);
366         pack_refs($first, $first->{-osdir}); # objstore refs always packed
367         for my $fgrp (@$fgrpv) {
368                 my $rn = $fgrp->{-remote};
369                 my %opt = ( 2 => $fgrp->{lei}->{2} );
370
371                 my $update_ref = PublicInbox::OnDestroy->new($$,
372                                                         \&fgrp_update, $fgrp);
373
374                 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
375                         "--format=refs/%(refname:lstrip=3)%00%(objectname)",
376                         "refs/remotes/$rn/" ];
377                 open(my $sfh, '+>', undef) or die "open(src): $!";
378                 $fgrp->{srcfh} = $sfh;
379                 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
380                 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
381                         '--format=%(refname)%00%(objectname)' ];
382                 open(my $dfh, '+>', undef) or die "open(dst): $!";
383                 $fgrp->{dstfh} = $dfh;
384                 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
385         }
386 }
387
388 sub fgrp_fetch_all {
389         my ($self) = @_;
390         my $todo = $FGRP_TODO;
391         $FGRP_TODO = \'BUG on further use';
392         keys(%$todo) or return;
393
394         # Rely on the fgrptmp remote groups in the config file rather
395         # than listing all remotes since the remote name list may exceed
396         # system argv limits:
397         my $grp = 'fgrptmp';
398
399         my @git = (@{$self->{-torsocks}}, 'git');
400         my $j = $self->{lei}->{opt}->{jobs};
401         my $opt = {};
402         my @fetch = do {
403                 local $self->{lei}->{opt}->{jobs} = 1;
404                 (fetch_args($self->{lei}, $opt), qw(--no-tags --multiple));
405         };
406         push(@fetch, "-j$j") if $j;
407         while (my ($osdir, $fgrpv) = each %$todo) {
408                 my $f = "$osdir/config";
409                 return if !keep_going($self);
410
411                 my $cmd = ['git', "--git-dir=$osdir", qw(config -f), $f ];
412                 # clobber group from previous run atomically
413                 for ("remotes.$grp") { # TODO: hideRefs
414                         my $c = [ @$cmd, '--unset-all', $_ ];
415                         $self->{lei}->qerr("# @$c");
416                         next if $self->{dry_run};
417                         my $pid = spawn($c, undef, $opt);
418                         waitpid($pid, 0) // die "waitpid: $!";
419                         die "E: @$c \$?=$?" if ($? && ($? >> 8) != 5);
420                 }
421
422                 # permanent configs:
423                 my $cfg = PublicInbox::Config->git_config_dump($f);
424                 for my $fgrp (@$fgrpv) {
425                         my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
426                         my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
427                         for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*",
428                                         'tagopt=--no-tags') {
429                                 my ($k, $v) = split(/=/, $_, 2);
430                                 $k = "remote.$rn.$k";
431                                 next if ($cfg->{$k} // '') eq $v;
432                                 my $c = [@$cmd, $k, $v];
433                                 $fgrp->{lei}->qerr("# @$c");
434                                 next if $fgrp->{dry_run};
435                                 run_die($c, undef, $opt);
436                         }
437                 }
438
439                 if (!$self->{dry_run}) {
440                         # update the config atomically via O_APPEND while
441                         # respecting git-config locking
442                         sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
443                                 or die "open($f.lock): $!";
444                         open my $fh, '>>', $f or die "open(>>$f): $!";
445                         $fh->autoflush(1);
446                         my $buf = join('', "[remotes]\n",
447                                 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
448                         print $fh $buf or die "print($f): $!";
449                         close $fh or die "close($f): $!";
450                         unlink("$f.lock") or die "unlink($f.lock): $!";
451                 }
452                 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
453                 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
454                 start_cmd($self, $cmd, $opt, $end);
455         }
456 }
457
458 # keep this idempotent for future use by public-inbox-fetch
459 sub forkgroup_prep {
460         my ($self, $uri) = @_;
461         $self->{-ent} // return;
462         my $os = $self->{-objstore} // return;
463         my $fg = $self->{-ent}->{forkgroup} // return;
464         my $dir = "$os/$fg.git";
465         if (!-d $dir && !$self->{dry_run}) {
466                 PublicInbox::Import::init_bare($dir);
467                 my $f = "$dir/config";
468                 open my $fh, '+>>', $f or die "open:($f): $!";
469                 print $fh <<EOM or die "print($f): $!";
470 [repack]
471         useDeltaIslands = true
472 [pack]
473         island = refs/remotes/([^/]+)/
474 EOM
475                 close $fh or die "close($f): $!";
476         }
477         my $key = $self->{-key} // die 'BUG: no -key';
478         my $rn = substr(sha256_hex($key), 0, 16);
479         if (!-d $self->{cur_dst} && !$self->{dry_run}) {
480                 PublicInbox::Import::init_bare($self->{cur_dst});
481                 my $f = "$self->{cur_dst}/config";
482                 open my $fh, '+>>', $f or die "open:($f): $!";
483                 print $fh <<EOM or die "print($f): $!";
484 ; rely on the "$rn" remote in the
485 ; $fg fork group for fetches
486 ; only uncomment the following iff you detach from fork groups
487 ; [remote "origin"]
488 ;       url = $uri
489 ;       fetch = +refs/*:refs/*
490 ;       mirror = true
491 EOM
492                 close $fh or die "close($f): $!";
493         }
494         if (!$self->{dry_run}) {
495                 my $alt = File::Spec->rel2abs("$dir/objects");
496                 my $o = "$self->{cur_dst}/objects";
497                 my $f = "$o/info/alternates";
498                 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
499                 open my $fh, '+>>', $f or die "open($f): $!";
500                 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
501                 chomp(my @cur = <$fh>);
502                 if (!grep(/\A\Q$l\E\z/, @cur)) {
503                         say $fh $l or die "say($f): $!";
504                 }
505                 close $fh or die "close($f): $!";
506         }
507         bless {
508                 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
509         }, __PACKAGE__;
510 }
511
512 sub fp_done {
513         my ($self, $cmd, $cb, @arg) = @_;
514         if ($?) {
515                 $self->{lei}->err("@$cmd failed (\$?=$?) (non-fatal)");
516                 $? = 0; # don't let it influence normal exit
517         }
518         return if !keep_going($self);
519         my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
520         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
521         $self->{-ent} // die 'BUG: no -ent';
522         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
523         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
524         return $cb->($self, @arg) if $A ne $B;
525         $self->{lei}->qerr("# $self->{-key} up-to-date");
526 }
527
528 sub cmp_fp_do {
529         my ($self, $cb, @arg) = @_;
530         # $cb is either resume_fetch or fgrp_enqueue
531         $self->{-ent} // return $cb->($self, @arg);
532         my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
533         my $key = $self->{-key} // die 'BUG: no -key';
534         if (my $cur_ent = $self->{-local_manifest}->{$key}) {
535                 # runs go_fetch->DESTROY run if eq
536                 return if $cur_ent->{fingerprint} eq $new;
537         }
538         my $dst = $self->{cur_dst} // $self->{dst};
539         my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
540         my $opt = { 2 => $self->{lei}->{2} };
541         open($opt->{1}, '+>', undef) or die "open(tmp): $!";
542         $self->{-show_ref} = $opt->{1};
543         do_reap($self);
544         $self->{lei}->qerr("# @$cmd");
545         $LIVE->{spawn($cmd, undef, $opt)} = [ \&fp_done, $self, $cmd,
546                                                 $cb, @arg ];
547 }
548
549 sub resume_fetch {
550         my ($self, $uri, $fini) = @_;
551         return if !keep_going($self);
552         my $dst = $self->{cur_dst} // $self->{dst};
553         my @git = ('git', "--git-dir=$dst");
554         my $opt = { 2 => $self->{lei}->{2} };
555         my $rn = 'random'.int(rand(1 << 30));
556         for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
557                 push @git, '-c', "remote.$rn.$_";
558         }
559         my $cmd = [ @{$self->{-torsocks}}, @git,
560                         fetch_args($self->{lei}, $opt), $rn ];
561         push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
562         my $run_puh = PublicInbox::OnDestroy->new($$, \&run_puh, $self, $fini);
563         ++$self->{chg}->{nr_chg};
564         start_cmd($self, $cmd, $opt, $run_puh);
565 }
566
567 sub fgrp_enqueue {
568         my ($fgrp, $end) = @_; # $end calls fgrp_fetch_all
569         return if !keep_going($fgrp);
570         ++$fgrp->{chg}->{nr_chg};
571         push @{$FGRP_TODO->{$fgrp->{-osdir}}}, $fgrp;
572 }
573
574 sub clone_v1 {
575         my ($self, $end) = @_;
576         my $lei = $self->{lei};
577         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
578         my $uri = URI->new($self->{cur_src} // $self->{src});
579         my $path = $uri->path;
580         $path =~ s!/*\z!! and $uri->path($path);
581         defined($lei->{opt}->{epoch}) and
582                 die "$uri is a v1 inbox, --epoch is not supported\n";
583         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
584         my $dst = $self->{cur_dst} // $self->{dst};
585         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
586         my $resume = -d $dst;
587         if (my $fgrp = forkgroup_prep($self, $uri)) {
588                 $fgrp->{-fini} = $fini;
589                 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
590                         : fgrp_enqueue($fgrp, $end);
591         } elsif ($resume) {
592                 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
593         } else { # normal clone
594                 my $cmd = [ @{$self->{-torsocks}},
595                                 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
596                 if (defined($self->{-ent})) {
597                         if (defined(my $ref = $self->{-ent}->{reference})) {
598                                 -e "$self->{dst}$ref" and
599                                         push @$cmd, '--reference',
600                                                 "$self->{dst}$ref";
601                         }
602                 }
603                 ++$self->{chg}->{nr_chg};
604                 start_cmd($self, $cmd, $opt, PublicInbox::OnDestroy->new($$,
605                                                 \&run_puh, $self, $fini));
606         }
607         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
608                                 /\A(?:always|v1)\z/s) {
609                 _get_txt_start($self, '_/text/config/raw', $fini);
610         }
611
612         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
613         $self->{'txt.description'} = $d if defined $d;
614         (!defined($d) && !$end) and
615                 _get_txt_start($self, 'description', $fini);
616
617         $end or do_reap($self, 1); # for non-manifest clone
618 }
619
620 sub parse_epochs ($$) {
621         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
622         $opt_epochs // return; # undef => all epochs
623         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
624         undef($lo) if ($lo // '') eq '';
625         my $re = qr/\A~?[0-9]+\z/;
626         if (@extra || (($lo // '0') !~ $re) ||
627                         (($hi // '0') !~ $re) ||
628                         !(grep(defined, $lo, $hi))) {
629                 die <<EOM;
630 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
631 EOM
632         }
633         my @n = sort { $a <=> $b } keys %$v2_epochs;
634         for (grep(defined, $lo, $hi)) {
635                 if (/\A[0-9]+\z/) {
636                         $_ > $n[-1] and die
637 "`$_' exceeds maximum available epoch ($n[-1])\n";
638                         $_ < $n[0] and die
639 "`$_' is lower than minimum available epoch ($n[0])\n";
640                 } elsif (/\A~([0-9]+)/) {
641                         my $off = -$1 - 1;
642                         $n[$off] // die "`$_' is out of range\n";
643                         $_ = $n[$off];
644                 } else { die "`$_' not understood\n" }
645         }
646         defined($lo) && defined($hi) && $lo > $hi and die
647 "low value (`$lo') exceeds high (`$hi')\n";
648         $lo //= $n[0] if $dotdot;
649         $hi //= $n[-1] if $dotdot;
650         $hi //= $lo;
651         my $want = {};
652         for ($lo..$hi) {
653                 if (defined $v2_epochs->{$_}) {
654                         $want->{$_} = 1;
655                 } else {
656                         warn
657 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
658                 }
659         }
660         $want
661 }
662
663 sub init_placeholder ($$$) {
664         my ($src, $edst, $ent) = @_;
665         PublicInbox::Import::init_bare($edst);
666         my $f = "$edst/config";
667         open my $fh, '>>', $f or die "open($f): $!";
668         print $fh <<EOM or die "print($f): $!";
669 [remote "origin"]
670         url = $src
671         fetch = +refs/*:refs/*
672         mirror = true
673
674 ; This git epoch was created read-only and "public-inbox-fetch"
675 ; will not fetch updates for it unless write permission is added.
676 ; Hint: chmod +w $edst
677 EOM
678         if (defined($ent->{owner})) {
679                 print $fh <<EOM or die "print($f): $!";
680 [gitweb]
681         owner = $ent->{owner}
682 EOM
683         }
684         close $fh or die "close($f): $!";
685         my %map = (head => 'HEAD', description => undef);
686         while (my ($key, $fn) = each %map) {
687                 my $val = $ent->{$key} // next;
688                 $fn //= $key;
689                 $fn = "$edst/$fn";
690                 open $fh, '>', $fn or die "open($fn): $!";
691                 print $fh $val, "\n" or die "print($fn): $!";
692                 close $fh or die "close($fn): $!";
693         }
694 }
695
696 sub reap_cmd { # async, called via SIGCHLD
697         my ($self, $cmd) = @_;
698         my $cerr = $?;
699         $? = 0; # don't let it influence normal exit
700         $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
701 }
702
703 sub up_fp_done {
704         my ($self) = @_;
705         return if !keep_going($self);
706         my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
707         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
708         $self->{-ent} // die 'BUG: no -ent';
709         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
710         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
711         return if $A eq $B;
712         $self->{-ent}->{fingerprint} = $B;
713         push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
714 }
715
716 sub atomic_write ($$$) {
717         my ($dn, $bn, $raw) = @_;
718         my $ft = File::Temp->new(DIR => $dn, TEMPLATE => "$bn-XXXX");
719         print $ft $raw or die "print($ft): $!";
720         $ft->flush or die "flush($ft): $!";
721         ft_rename($ft, "$dn/$bn", 0666);
722 }
723
724 sub run_next_puh {
725         my ($self) = @_;
726         my $puh = shift @{$self->{-puh_todo}} // return delete($self->{-fini});
727         my $fini = PublicInbox::OnDestroy->new($$, \&run_next_puh, $self);
728         my $cmd = [ @$puh, ($self->{cur_dst} // $self->{dst}) ];
729         my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
730         start_cmd($self, $cmd, undef, $opt, $fini);
731 }
732
733 sub run_puh {
734         my ($self, $fini) = @_;
735         $self->{-fini} = $fini;
736         @{$self->{-puh_todo}} = @PUH;
737         run_next_puh($self);
738 }
739
740 # modifies the to-be-written manifest entry, and sets values from it, too
741 sub update_ent {
742         my ($self) = @_;
743         my $key = $self->{-key} // die 'BUG: no -key';
744         my $new = $self->{-ent}->{fingerprint};
745         my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
746         my $dst = $self->{cur_dst} // $self->{dst};
747         if (defined($new) && $new ne $cur) {
748                 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
749                 my $opt = { 2 => $self->{lei}->{2} };
750                 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
751                 $self->{-show_ref_up} = $opt->{1};
752                 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
753                 start_cmd($self, $cmd, $opt, $done);
754         }
755         $new = $self->{-ent}->{head};
756         $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
757         if (defined($new) && $new ne $cur) {
758                 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
759                 my $cmd = [ 'git', "--git-dir=$dst" ];
760                 if ($new =~ s/\Aref: //) {
761                         push @$cmd, qw(symbolic-ref HEAD), $new;
762                 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
763                         push @$cmd, qw(update-ref --no-deref HEAD), $new;
764                 } else {
765                         undef $cmd;
766                         warn "W: $key: {head} => `$new' not understood\n";
767                 }
768                 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
769         }
770         if (my $symlinks = $self->{-ent}->{symlinks}) {
771                 my $top = File::Spec->rel2abs($self->{dst});
772                 push @{$self->{-new_symlinks}}, @$symlinks;
773                 for my $p (@$symlinks) {
774                         my $ln = "$top/$p";
775                         $ln =~ tr!/!/!s;
776                         my (undef, $dn, $bn) = File::Spec->splitpath($ln);
777                         File::Path::mkpath($dn);
778                         my $tgt = "$top/$key";
779                         $tgt = File::Spec->abs2rel($tgt, $dn);
780                         if (lstat($ln)) {
781                                 if (-l _) {
782                                         next if readlink($ln) eq $tgt;
783                                         unlink($ln) or die "unlink($ln): $!";
784                                 } else {
785                                         push @{$self->{chg}->{badlink}}, $p;
786                                 }
787                         }
788                         symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
789                         ++$self->{chg}->{nr_chg};
790                 }
791         }
792         if (defined(my $t = $self->{-ent}->{modified})) {
793                 my ($dn, $bn) = ("$dst/info/web", 'last-modified');
794                 my $orig = PublicInbox::Git::try_cat("$dn/$bn");
795                 $t = strftime('%F %T', gmtime($t))." +0000\n";
796                 File::Path::mkpath($dn);
797                 atomic_write($dn, $bn, $t) if $orig ne $t;
798         }
799
800         $new = $self->{-ent}->{owner} // return;
801         $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
802         return if $cur eq $new;
803         my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
804         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
805 }
806
807 sub v1_done { # called via OnDestroy
808         my ($self) = @_;
809         return if $self->{dry_run} || !keep_going($self);
810         _write_inbox_config($self);
811         my $dst = $self->{cur_dst} // $self->{dst};
812         update_ent($self) if $self->{-ent};
813         my $o = "$dst/objects";
814         if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
815                 my $base = File::Spec->rel2abs($o);
816                 my @l = <$fh>;
817                 my $ft;
818                 for (@l) {
819                         next unless m!\A/!;
820                         $_ = File::Spec->abs2rel($_, $base);
821                         $ft //= File::Temp->new(TEMPLATE => '.XXXX',
822                                                 DIR => "$o/info");
823                 }
824                 if ($ft) {
825                         print $ft @l or die "print($ft): $!";
826                         $ft->flush or die "flush($ft): $!";
827                         ft_rename($ft, $fn, 0666, $fh);
828                 }
829         }
830         eval { set_description($self) };
831         warn $@ if $@;
832         return if ($self->{-is_epoch} ||
833                 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
834         write_makefile($dst, 1);
835         index_cloned_inbox($self, 1);
836 }
837
838 sub v2_done { # called via OnDestroy
839         my ($self) = @_;
840         return if $self->{dry_run} || !keep_going($self);
841         my $dst = $self->{cur_dst} // $self->{dst};
842         require PublicInbox::Lock;
843         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
844         my $lck = $lk->lock_for_scope($$);
845         _write_inbox_config($self);
846         require PublicInbox::MultiGit;
847         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
848         $mg->fill_alternates;
849         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
850         for my $edst (@{delete($self->{-read_only}) // []}) {
851                 my @st = stat($edst) or die "stat($edst): $!";
852                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
853         }
854         write_makefile($dst, 2);
855         undef $lck; # unlock
856         eval { set_description($self) };
857         warn $@ if $@;
858         index_cloned_inbox($self, 2);
859 }
860
861 sub clone_v2_prep ($$;$) {
862         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
863         my $lei = $self->{lei};
864         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
865         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
866         $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
867         my $dst = $self->{cur_dst} // $self->{dst};
868         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
869         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
870         my (@skip, $desc);
871         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
872         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
873                 my ($uri, $key) = @{$v2_epochs->{$nr}};
874                 my $src = $uri->as_string;
875                 my $edst = $dst;
876                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
877 failed to extract epoch number from $src
878
879                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
880                 $edst .= "/git/$nr.git";
881                 my $ent;
882                 if ($m) {
883                         $ent = $m->{$key} //
884                                 die("BUG: `$key' not in manifest.js.gz");
885                         if (defined(my $d = $ent->{description})) {
886                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
887                                 $desc = $d;
888                         }
889                 }
890                 if (!$want || $want->{$nr}) {
891                         my $etask = bless { %$task, -key => $key }, __PACKAGE__;
892                         $etask->{-ent} = $ent; # may have {reference}
893                         $etask->{cur_src} = $src;
894                         $etask->{cur_dst} = $edst;
895                         $etask->{-is_epoch} = $fini;
896                         my $ref = $ent->{reference} // '';
897                         push @{$TODO->{$ref}}, $etask;
898                         $self->{any_want}->{$key} = 1;
899                 } else { # create a placeholder so users only need to chmod +w
900                         init_placeholder($src, $edst, $ent);
901                         push @{$task->{-read_only}}, $edst;
902                         push @skip, $key;
903                 }
904         }
905         # filter out the epochs we skipped
906         $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
907
908         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
909
910         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
911                 _get_txt_start($task, '_/text/config/raw', $fini);
912
913         defined($desc) ? ($task->{'txt.description'} = $desc) :
914                 _get_txt_start($task, 'description', $fini);
915 }
916
917 sub decode_manifest ($$$) {
918         my ($fh, $fn, $uri) = @_;
919         my $js;
920         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
921         gunzip(\$gz => \$js, MultiStream => 1) or
922                 die "gunzip($uri): $GunzipError\n";
923         my $m = eval { PublicInbox::Config->json->decode($js) };
924         die "$uri: error decoding `$js': $@\n" if $@;
925         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
926         $m;
927 }
928
929 sub load_current_manifest ($) {
930         my ($self) = @_;
931         my $fn = $self->{-manifest} // return;
932         if (open(my $fh, '<', $fn)) {
933                 decode_manifest($fh, $fn, $fn);
934         } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
935                 warn "open($fn): $!\n" if !$self->{-initial_clone};
936                 undef;
937         } else {
938                 die "open($fn): $!\n";
939         }
940 }
941
942 sub multi_inbox ($$$) {
943         my ($self, $path, $m) = @_;
944         my $incl = $self->{lei}->{opt}->{include};
945         my $excl = $self->{lei}->{opt}->{exclude};
946
947         # assuming everything not v2 is v1, for now
948         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
949         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
950         my $v2 = {};
951
952         for (@v2_epochs) {
953                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
954                 push @{$v2->{$1}}, $_;
955         }
956         my $n = scalar(keys %$v2) + scalar(@v1);
957         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
958         if (defined $incl) {
959                 my $re = '(?:'.join('\\z|', map {
960                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
961                         } @$incl).'\\z)';
962                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
963                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
964                 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
965                 @v1 = grep(/$re/, @v1);
966         }
967         if (defined $excl) {
968                 my $re = '(?:'.join('\\z|', map {
969                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
970                         } @$excl).'\\z)';
971                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
972                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
973                 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
974                 @v1 = grep(!/$re/, @v1);
975         }
976         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
977         $ret->{v1} = \@v1 if @v1;
978         $ret->{v2} = $v2 if keys %$v2;
979         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
980                                 join("\n\t", sort @orig)
981                         : "Nothing available to clone\n";
982         my $path_pfx = '';
983
984         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
985         if (@v2_epochs) {
986                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
987                                 @v2_epochs) == @v2_epochs) {
988                         $$path =~ s!\A(/[^/]+)/!/! or last;
989                         $path_pfx .= $1;
990                 }
991         } elsif (@v1) {
992                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
993                         $path_pfx .= $1;
994                 }
995         }
996         ($path_pfx, $n, $ret);
997 }
998
999 sub clone_all {
1000         my ($self, $m) = @_;
1001         my $todo = $TODO;
1002         $TODO = \'BUG on further use';
1003         my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
1004         {
1005                 my $nodep = delete $todo->{''};
1006
1007                 # do not download unwanted deps
1008                 my $any_want = delete $self->{any_want};
1009                 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
1010                 my @nodep = delete(@$todo{@unwanted});
1011                 push(@$nodep, @$_) for @nodep;
1012
1013                 # handle no-dependency repos, first
1014                 for (@$nodep) {
1015                         clone_v1($_, $end);
1016                         return if !keep_going($self);
1017                 }
1018         }
1019         # resolve references, deepest, first:
1020         while (scalar keys %$todo) {
1021                 for my $x (keys %$todo) {
1022                         my ($nr, $nxt);
1023                         # resolve multi-level references
1024                         while ($m && defined($nxt = $m->{$x}->{reference})) {
1025                                 exists($todo->{$nxt}) or last;
1026                                 if (++$nr > 1000) {
1027                                         $m->{$x}->{reference} = undef;
1028                                         $m->{$nxt}->{reference} = undef;
1029                                         warn <<EOM
1030 E: dependency loop detected (`$x' => `$nxt'), breaking
1031 EOM
1032                                 }
1033                                 $x = $nxt;
1034                         }
1035                         my $y = delete $todo->{$x} // next; # already done
1036                         for (@$y) {
1037                                 clone_v1($_, $end);
1038                                 return if !keep_going($self);
1039                         }
1040                         last; # restart %$todo iteration
1041                 }
1042         }
1043
1044         # $end->DESTROY will call fgrp_fetch_all once all references
1045         # in $LIVE are gone, and do_reap will eventually drain $LIVE
1046         $end = undef;
1047         do_reap($self, 1);
1048 }
1049
1050 sub dump_manifest ($$) {
1051         my ($m, $ft) = @_;
1052         # write the smaller manifest if epochs were skipped so
1053         # users won't have to delete manifest if they +w an
1054         # epoch they no longer want to skip
1055         my $json = PublicInbox::Config->json->encode($m);
1056         my $mtime = (stat($ft))[9];
1057         seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
1058         truncate($ft, 0) or die "truncate($ft): $!";
1059         gzip(\$json => $ft) or die "gzip($ft): $GzipError";
1060         $ft->flush or die "flush($ft): $!";
1061         utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
1062 }
1063
1064 sub dump_project_list ($$) {
1065         my ($self, $m) = @_;
1066         my $f = $self->{'-project-list'} // return;
1067         my $old = PublicInbox::Git::try_cat($f);
1068         my %new;
1069
1070         open my $dh, '<', '.' or die "open(.): $!";
1071         chdir($self->{dst}) or die "chdir($self->{dst}): $!";
1072         my @local = grep { -e $_ ? ($new{$_} = undef) : 1 } split(/\n/s, $old);
1073         chdir($dh) or die "chdir(restore): $!";
1074
1075         $new{substr($_, 1)} = 1 for keys %$m; # drop leading '/'
1076         my @list = sort keys %new;
1077         my @remote = grep { !defined($new{$_}) } @list;
1078         my %lnk = map { substr($_, 1) => undef } @{$self->{-new_symlinks}};
1079         @remote = grep { !exists($lnk{$_}) } @remote;
1080
1081         warn <<EOM if @remote;
1082 The following local repositories are ignored/gone from $self->{src}:
1083 EOM
1084         warn "\t", $_, "\n" for @remote;
1085         warn <<EOM if @local;
1086 The following repos in $f no longer exist on the filesystem:
1087 EOM
1088         warn "\t", $_, "\n" for @local;
1089
1090         my (undef, $dn, $bn) = File::Spec->splitpath($f);
1091         $self->{chg}->{nr_chg} += scalar(@remote) + scalar(@local);
1092         my $new = join("\n", @list, '');
1093         atomic_write($dn, $bn, $new) if $new ne $old;
1094 }
1095
1096 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
1097 sub try_manifest {
1098         my ($self) = @_;
1099         my $uri = URI->new($self->{src});
1100         my $lei = $self->{lei};
1101         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
1102         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
1103         my $path = $uri->path;
1104         chop($path) eq '/' or die "BUG: $uri not canonicalized";
1105         $uri->path($path . '/manifest.js.gz');
1106         my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
1107         my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
1108         if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
1109                 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
1110                 delete $opt{TMPDIR};
1111         }
1112         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
1113         my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
1114         push(@$cmd, '-z', $manifest) if -f $manifest;
1115         my $mf_url = "$uri";
1116         %opt = map { $_ => $lei->{$_} } (0..2);
1117         my $cerr = run_reap($lei, $cmd, \%opt);
1118         if ($cerr) {
1119                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1120                 return $lei->child_error($cerr, "@$cmd failed");
1121         }
1122
1123         # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1124         if (-f $manifest && !-s $ft) {
1125                 $lei->child_error(127 << 8) if $lei->{opt}->{'exit-code'};
1126                 return $lei->qerr("# $manifest unchanged");
1127         }
1128
1129         my $m = eval { decode_manifest($ft, $ft, $uri) };
1130         if ($@) {
1131                 warn $@;
1132                 return try_scrape($self);
1133         }
1134         local $self->{chg} = {};
1135         local $self->{-local_manifest} = load_current_manifest($self);
1136         local $self->{-new_symlinks} = [];
1137         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1138         return $lei->child_error(1, $multi) if !ref($multi);
1139         my $v2 = delete $multi->{v2};
1140         if ($v2) {
1141                 for my $name (sort keys %$v2) {
1142                         my $epochs = delete $v2->{$name};
1143                         my %v2_epochs = map {
1144                                 $uri->path($n > 1 ? $path_pfx.$path.$_
1145                                                 : $path_pfx.$_);
1146                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1147                                 $e // die "no [0-9]+\.git in `$uri'";
1148                                 $e => [ $uri->clone, $_ ];
1149                         } @$epochs;
1150                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1151                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1152                         local $self->{cur_src} = $1;
1153                         local $self->{cur_dst} = $self->{dst};
1154                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1155                                                         git/[0-9]+\.git\z!x) {
1156                                 $self->{cur_dst} .= "/$1";
1157                         }
1158                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1159 E: `$self->{cur_dst}' must not contain newline
1160 EOM
1161                         clone_v2_prep($self, \%v2_epochs, $m);
1162                         return if !keep_going($self);
1163                 }
1164         }
1165         if (my $v1 = delete $multi->{v1}) {
1166                 my $p = $path_pfx.$path;
1167                 chop($p) if substr($p, -1, 1) eq '/';
1168                 $uri->path($p);
1169                 for my $name (@$v1) {
1170                         my $task = bless { %$self }, __PACKAGE__;
1171                         $task->{-ent} = $m->{$name} //
1172                                         die("BUG: no `$name' in manifest");
1173                         $task->{cur_src} = "$uri";
1174                         $task->{cur_dst} = $task->{dst};
1175                         $task->{-key} = $name;
1176                         if ($n > 1) {
1177                                 $task->{cur_dst} .= $name;
1178                                 $task->{cur_src} .= $name;
1179                         }
1180                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1181 E: `$task->{cur_dst}' must not contain newline
1182 EOM
1183                         $task->{cur_src} .= '/';
1184                         my $dep = $task->{-ent}->{reference} // '';
1185                         push @{$TODO->{$dep}}, $task; # for clone_all
1186                         $self->{any_want}->{$name} = 1;
1187                 }
1188         }
1189         delete local $lei->{opt}->{epoch} if defined($v2);
1190         clone_all($self, $m);
1191         return if $self->{dry_run} || !keep_going($self);
1192
1193         # set by clone_v2_prep/-I/--exclude
1194         my $mis = delete $self->{chg}->{fp_mismatch};
1195         if ($mis) {
1196                 my $t = (stat($ft))[9];
1197                 $t = strftime('%F %k:%M:%S %z', localtime($t));
1198                 warn <<EOM;
1199 W: Fingerprints for the following repositories do not match
1200 W: $mf_url @ $t:
1201 W: These repositories may have updated since $t:
1202 EOM
1203                 warn "\t", $_, "\n" for @$mis;
1204                 warn <<EOM if !$self->{lei}->{opt}->{prune};
1205 W: The above fingerprints may never match without --prune
1206 EOM
1207         }
1208         dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1209         my $bad = delete $self->{chg}->{badlink};
1210         warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1211 W: The following exist and have not been converted to symlinks
1212 EOM
1213         dump_project_list($self, $m);
1214         ft_rename($ft, $manifest, 0666);
1215         !$self->{chg}->{nr_chg} && $lei->{opt}->{'exit-code'} and
1216                 $lei->child_error(127 << 8);
1217 }
1218
1219 sub start_clone_url {
1220         my ($self) = @_;
1221         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1222         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1223 }
1224
1225 sub do_mirror { # via wq_io_do or public-inbox-clone
1226         my ($self) = @_;
1227         my $lei = $self->{lei};
1228         $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1229         umask($lei->{client_umask}) if defined $lei->{client_umask};
1230         $self->{-initial_clone} = 1 if !-d $self->{dst};
1231         local @PUH;
1232         if (defined(my $puh = $lei->{opt}->{'post-update-hook'})) {
1233                 require Text::ParseWords;
1234                 @PUH = map { [ Text::ParseWords::shellwords($_) ] } @$puh;
1235         }
1236         eval {
1237                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1238                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1239 --inbox-config must be one of `always', `v2', `v1', or `never'
1240
1241                 # we support these switches with '' (empty string).
1242                 # defaults match example conf distributed with grokmirror
1243                 my @pairs = qw(objstore objstore manifest manifest.js.gz
1244                                 project-list projects.list);
1245                 while (@pairs) {
1246                         my ($k, $default) = splice(@pairs, 0, 2);
1247                         my $v = $lei->{opt}->{$k} // next;
1248                         $v = $default if $v eq '';
1249                         $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1250                         $self->{"-$k"} = $v;
1251                 }
1252
1253                 local $LIVE = {};
1254                 local $TODO = {};
1255                 local $FGRP_TODO = {};
1256                 my $iv = $lei->{opt}->{'inbox-version'} //
1257                         return start_clone_url($self);
1258                 return clone_v1($self) if $iv == 1;
1259                 die "bad --inbox-version=$iv\n" if $iv != 2;
1260                 die <<EOM if $self->{src} !~ m!://!;
1261 cloning local v2 inboxes not supported
1262 EOM
1263                 try_scrape($self, 1);
1264         };
1265         $lei->fail($@) if $@;
1266 }
1267
1268 sub start {
1269         my ($cls, $lei, $src, $dst) = @_;
1270         my $self = bless { src => $src, dst => $dst }, $cls;
1271         $lei->request_umask;
1272         my ($op_c, $ops) = $lei->workers_start($self, 1);
1273         $lei->{wq1} = $self;
1274         $self->wq_io_do('do_mirror', []);
1275         $self->wq_close;
1276         $lei->wait_wq_events($op_c, $ops);
1277 }
1278
1279 sub ipc_atfork_child {
1280         my ($self) = @_;
1281         $self->{lei}->_lei_atfork_child;
1282         $self->SUPER::ipc_atfork_child;
1283 }
1284
1285 sub write_makefile {
1286         my ($dir, $ibx_ver) = @_;
1287         my $f = "$dir/Makefile";
1288         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1289                 print $fh <<EOM or die "print($f) $!";
1290 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1291 # manpage for more information on the format.  This Makefile is
1292 # intended as a familiar wrapper for users unfamiliar with
1293 # public-inbox-* commands.
1294 #
1295 # See the respective manpages for public-inbox-fetch(1),
1296 # public-inbox-index(1), etc for more information on
1297 # some of the commands used by this Makefile.
1298 #
1299 # This Makefile will not be modified nor read by public-inbox,
1300 # so you may edit it freely with your own convenience targets
1301 # and notes.  public-inbox-fetch will recreate it if removed.
1302 EOM
1303                 print $fh <<'EOM' or die "print($f): $!";
1304 # the default target:
1305 help :
1306         @echo Common targets:
1307         @echo '    make fetch        - fetch from remote git repostorie(s)'
1308         @echo '    make update       - fetch and update index '
1309         @echo
1310         @echo Rarely needed targets:
1311         @echo '    make reindex      - may be needed for new features/bugfixes'
1312         @echo '    make compact      - rewrite Xapian storage to save space'
1313         @echo '    make index        - initial index after clone
1314
1315 fetch :
1316         public-inbox-fetch
1317 update :
1318         @if ! public-inbox-fetch --exit-code; \
1319         then \
1320                 c=$$?; \
1321                 test $$c -eq 127 && exit 0; \
1322                 exit $$c; \
1323         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1324         then \
1325                 public-inbox-index; \
1326         else \
1327                 echo 'public-inbox index not initialized'; \
1328                 echo 'see public-inbox-index(1) man page'; \
1329         fi
1330 index :
1331         public-inbox-index
1332 reindex :
1333         public-inbox-index --reindex
1334 compact :
1335         public-inbox-compact
1336
1337 .PHONY : help fetch update index reindex compact
1338 EOM
1339                 close $fh or die "close($f): $!";
1340         } else {
1341                 die "open($f): $!" unless $!{EEXIST};
1342         }
1343 }
1344
1345 1;