]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
lei_mirror: support --objstore and forkgroups
[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::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use Digest::SHA qw(sha256_hex);
22
23 our $LIVE; # pid => callback
24 my $update_ref_stdin = $ENV{GIT_CAN_UPDATE_REF_STDIN} // 1;
25
26 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
27         my ($arg, $pid) = @_;
28         my ($mrr, $lei) = @$arg;
29         my $f = "$mrr->{dst}/mirror.done";
30         if ($?) {
31                 $lei->child_error($?);
32         } elsif (!$mrr->{dry_run} && !unlink($f)) {
33                 warn("unlink($f): $!\n") unless $!{ENOENT};
34         } else {
35                 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
36                         require PublicInbox::LeiAddExternal;
37                         PublicInbox::LeiAddExternal::_finish_add_external(
38                                                         $lei, $mrr->{dst});
39                 }
40                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
41         }
42         $lei->dclose;
43 }
44
45 # for old installations without manifest.js.gz
46 sub try_scrape {
47         my ($self, $fallback_manifest) = @_;
48         my $uri = URI->new($self->{src});
49         my $lei = $self->{lei};
50         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
51         my $cmd = $curl->for_uri($lei, $uri, qw(-f --compressed));
52         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
53         my $fh = popen_rd($cmd, undef, $opt);
54         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
55         close($fh) or return $lei->child_error($?, "@$cmd failed");
56
57         # we grep with URL below, we don't want Subject/From headers
58         # making us clone random URLs.  This assumes remote instances
59         # prior to public-inbox 1.7.0
60         # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
61         my @html = split(/<hr>/, $html);
62         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
63         if (!@urls && $fallback_manifest) {
64                 warn <<EOM;
65 W: failed to extract URLs from $uri, trying manifest.js.gz...
66 EOM
67                 return start_clone_url($self);
68         }
69         my $url = $uri->as_string;
70         chop($url) eq '/' or die "BUG: $uri not canonicalized";
71
72         # since this is for old instances w/o manifest.js.gz, try v1 first
73         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
74         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
75                 my %v2_epochs = map {
76                         my ($n) = (m!/([0-9]+)\z!);
77                         $n => [ URI->new($_), '' ]
78                 } @v2_urls; # uniq
79                 clone_v2_prep($self, \%v2_epochs);
80                 delete local $lei->{opt}->{epoch};
81                 clone_all($self);
82                 return;
83         }
84
85         # filter out common URLs served by WWW (e.g /$MSGID/T/)
86         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
87                         grep(m!\A\Q$url\E/*\z!, @urls)) {
88                 die <<"";
89 E: confused by scraping <$uri>, did you mean <$url>?
90
91         }
92         @urls and die <<"";
93 E: confused by scraping <$uri>, got ambiguous results:
94 @urls
95
96         die "E: scraping <$uri> revealed nothing\n";
97 }
98
99 sub clone_cmd {
100         my ($lei, $opt) = @_;
101         my @cmd = qw(git);
102         $opt->{$_} = $lei->{$_} for (0..2);
103         # we support "-c $key=$val" for arbitrary git config options
104         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
105         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
106         push @cmd, qw(clone --mirror);
107         push @cmd, '-q' if $lei->{opt}->{quiet} ||
108                         ($lei->{opt}->{jobs} // 1) > 1;
109         push @cmd, '-v' if $lei->{opt}->{verbose};
110         # XXX any other options to support?
111         # --reference is tricky with multiple epochs, but handled
112         # automatically if using manifest.js.gz
113         @cmd;
114 }
115
116 sub ft_rename ($$$) {
117         my ($ft, $dst, $open_mode) = @_;
118         my @st = stat($dst);
119         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
120         chmod($mode, $ft) or croak "E: chmod($ft): $!";
121         require File::Copy;
122         File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
123         $ft->unlink_on_destroy(0);
124 }
125
126 sub _get_txt_start { # non-fatal
127         my ($self, $endpoint, $fini) = @_;
128         my $uri = URI->new($self->{cur_src} // $self->{src});
129         my $lei = $self->{lei};
130         my $path = $uri->path;
131         chop($path) eq '/' or die "BUG: $uri not canonicalized";
132         $uri->path("$path/$endpoint");
133         my $f = (split(m!/!, $endpoint))[-1];
134         my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
135         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
136         my $cmd = $self->{curl}->for_uri($lei, $uri, qw(-f --compressed -R -o),
137                                         $ft->filename);
138         my $jobs = $lei->{opt}->{jobs} // 1;
139         reap_live() while keys(%$LIVE) >= $jobs;
140         $lei->qerr("# @$cmd");
141         return if $self->{dry_run};
142         $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
143         $LIVE->{spawn($cmd, undef, $opt)} =
144                         [ \&_get_txt_done, $self, $endpoint, $fini ];
145 }
146
147 sub _get_txt_done { # returns true on error (non-fatal), undef on success
148         my ($self, $endpoint) = @_;
149         my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
150         my $cerr = $?;
151         $? = 0; # don't influence normal lei exit
152         return warn("$uri missing\n") if ($cerr >> 8) == 22;
153         return warn("# @$cmd failed (non-fatal)\n") if $cerr;
154         seek($fh, SEEK_SET, 0) or die "seek: $!";
155         $self->{"mtime.$endpoint"} = (stat($fh))[9];
156         local $/;
157         $self->{"txt.$endpoint"} = <$fh>;
158         undef; # success
159 }
160
161 sub _write_inbox_config {
162         my ($self) = @_;
163         my $buf = delete($self->{'txt._/text/config/raw'}) // return;
164         my $dst = $self->{cur_dst} // $self->{dst};
165         my $f = "$dst/inbox.config.example";
166         open my $fh, '>', $f or die "open($f): $!";
167         print $fh $buf or die "print: $!";
168         chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
169         my $mtime = delete $self->{'mtime._/text/config/raw'};
170         $fh->flush or die "flush($f): $!";
171         if (defined $mtime) {
172                 utime($mtime, $mtime, $fh) or die "utime($f): $!";
173         }
174         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
175         my $ibx = $self->{ibx} = {};
176         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
177                 for (qw(address newsgroup nntpmirror)) {
178                         $ibx->{$_} = $cfg->{"$sec.$_"};
179                 }
180         }
181 }
182
183 sub set_description ($) {
184         my ($self) = @_;
185         my $dst = $self->{cur_dst} // $self->{dst};
186         my $f = "$dst/description";
187         open my $fh, '+>>', $f or die "open($f): $!";
188         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
189         my $d = do { local $/; <$fh> } // die "read($f): $!";
190         chomp(my $orig = $d);
191         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
192                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
193                 $d = delete($self->{'txt.description'});
194         }
195         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
196         chomp $d;
197         return if $d eq $orig;
198         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
199         truncate($fh, 0) or die "truncate($f): $!";
200         print $fh $d, "\n" or die "print($f): $!";
201         close $fh or die "close($f): $!";
202 }
203
204 sub index_cloned_inbox {
205         my ($self, $iv) = @_;
206         my $lei = $self->{lei};
207         eval { set_description($self) };
208         warn $@ if $@;
209
210         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
211         # lei is useless without Xapian + SQLite
212         if ($lei->{cmd} ne 'public-inbox-clone') {
213                 require PublicInbox::InboxWritable;
214                 require PublicInbox::Admin;
215                 my $ibx = delete($self->{ibx}) // {
216                         address => [ 'lei@example.com' ],
217                         version => $iv,
218                 };
219                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
220                 PublicInbox::Inbox->new($ibx);
221                 PublicInbox::InboxWritable->new($ibx);
222                 my $opt = {};
223                 for my $sw ($lei->index_opt) {
224                         my ($k) = ($sw =~ /\A([\w-]+)/);
225                         $opt->{$k} = $lei->{opt}->{$k};
226                 }
227                 # force synchronous dwaitpid for v2:
228                 local $PublicInbox::DS::in_loop = 0;
229                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
230                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
231                 local %ENV = (%ENV, %$env) if $env;
232                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
233                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
234         }
235         return if defined $self->{cur_dst}; # one of many repos to clone
236         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
237 }
238
239 sub run_reap {
240         my ($lei, $cmd, $opt) = @_;
241         $lei->qerr("# @$cmd");
242         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
243         my $ret = $?;
244         $? = 0; # don't let it influence normal exit
245         $ret;
246 }
247
248 sub start_clone {
249         my ($self, $cmd, $opt, $fini) = @_;
250         my $jobs = $self->{lei}->{opt}->{jobs} // 1;
251         reap_live() while keys(%$LIVE) >= $jobs;
252         $self->{lei}->qerr("# @$cmd");
253         return if $self->{dry_run};
254         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
255 }
256
257 sub fetch_args ($$) {
258         my ($lei, $opt) = @_;
259         my @cmd; # (git --git-dir=...) to be added by caller
260         $opt->{$_} = $lei->{$_} for (0..2);
261         # we support "-c $key=$val" for arbitrary git config options
262         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
263         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
264         push @cmd, 'fetch';
265         push @cmd, '-q' if $lei->{opt}->{quiet} ||
266                         ($lei->{opt}->{jobs} // 1) > 1;
267         push @cmd, '-v' if $lei->{opt}->{verbose};
268         @cmd;
269 }
270
271 sub fgrp_update_old ($) { # for git <1.8.5
272         my ($fgrp) = @_;
273         my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
274                 fetch_args($fgrp->{lei}, my $opt = {}) ];
275         $fgrp->{lei}->qerr("# @$cmd");
276         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $fgrp, $cmd ];
277         my $jobs = $fgrp->{lei}->{opt}->{jobs} // 1;
278         reap_live() while keys(%$LIVE) >= $jobs;
279 }
280
281 sub upr { # feed `git update-ref --stdin -z' verbosely
282         my ($fgrp, $w, $op, $ref, $oid) = @_;
283         $fgrp->{lei}->qerr("# $op $ref $oid");
284         print $w "$op $ref\0$oid\0" or die "print(w): $!";
285 }
286
287 sub fgrp_update {
288         my ($fgrp) = @_;
289         my $srcfh = delete $fgrp->{srcfh} or return;
290         my $dstfh = delete $fgrp->{dstfh} or return;
291         seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
292         seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
293         my %src = map { chomp; split(/\0/) } (<$srcfh>);
294         close $srcfh;
295         my %dst = map { chomp; split(/\0/) } (<$dstfh>);
296         close $dstfh;
297         pipe(my ($r, $w)) or die "pipe: $!";
298         my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
299                 qw(update-ref --stdin -z) ];
300         $fgrp->{lei}->qerr("# @$cmd");
301         my $opt = { 0 => $r, 1 => $fgrp->{lei}->{1}, 2 => $fgrp->{lei}->{2} };
302         my $pid = spawn($cmd, undef, $opt);
303         close $r or die "close(r): $!";
304         for my $ref (keys %dst) {
305                 my $new = delete $src{$ref};
306                 my $old = $dst{$ref};
307                 if (defined $new) {
308                         upr($fgrp, $w, 'update', $ref, $new) if $new ne $old;
309                 } else {
310                         upr($fgrp, $w, 'delete', $ref, $old);
311                 }
312         }
313         while (my ($ref, $oid) = each %src) {
314                 upr($fgrp, $w, 'create', $ref, $oid);
315         }
316         if (close($w)) { # git >= 1.8.5
317                 $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd ];
318                 my $jobs = $fgrp->{lei}->{opt}->{jobs} // 1;
319                 reap_live() while keys(%$LIVE) >= $jobs;
320         } else { # git <1.8.5 w/o update-ref --stdin
321                 warn "E: close(update-ref --stdin): $!\n";
322                 $update_ref_stdin = 0;
323                 waitpid($pid, 0) // die "waitpid(update-ref --stdin): $!";
324                 fgrp_update_old($fgrp);
325         }
326 }
327
328 sub fgrp_fetched {
329         my ($fgrp) = @_;
330         return if $fgrp->{dry_run} || !$LIVE;
331         my $rn = $fgrp->{-remote};
332         my %opt = map { $_ => $fgrp->{lei}->{$_} } (0..2);
333         my $cmd = [ 'git', "--git-dir=$fgrp->{-osdir}",
334                         qw(pack-refs --all --prune) ];
335         $fgrp->{lei}->qerr("# @$cmd");
336         $LIVE->{spawn($cmd, undef, \%opt)} = [ \&reap_cmd, $fgrp, $cmd ];
337         my $jobs = $fgrp->{lei}->{opt}->{jobs} // 1;
338         reap_live() while keys(%$LIVE) >= $jobs;
339
340         $update_ref_stdin or return fgrp_update_old($fgrp);
341
342         my $update_ref = PublicInbox::OnDestroy->new($$, \&fgrp_update, $fgrp);
343
344         my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
345                 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
346                 "refs/remotes/$rn/" ];
347         open($fgrp->{srcfh}, '+>', undef) or die "open(src): $!";
348         $fgrp->{lei}->qerr("# @$src >SRC");
349         my $pid = spawn($src, undef, { %opt, 1 => $fgrp->{srcfh} });
350         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $src, $update_ref ];
351         reap_live() while keys(%$LIVE) >= $jobs;
352
353         my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
354                 '--format=%(refname)%00%(objectname)' ];
355         open($fgrp->{dstfh}, '+>', undef) or die "open(dst): $!";
356         $fgrp->{lei}->qerr("# @$dst >DST");
357         $pid = spawn($dst, undef, { %opt, 1 => $fgrp->{dstfh} });
358         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $dst, $update_ref ];
359         reap_live() while keys(%$LIVE) >= $jobs;
360 }
361
362 sub fgrp_fetch {
363         my ($fgrp, $pfx, $fini) = @_;
364         my $cmd = [ @$pfx, 'git', "--git-dir=$fgrp->{-osdir}",
365                         fetch_args($fgrp->{lei}, my $opt = {}),
366                         $fgrp->{-remote} ];
367         $fgrp->{-fini} = $fini;
368         my $jobs = $fgrp->{lei}->{opt}->{jobs} // 1;
369         reap_live() while keys(%$LIVE) >= $jobs;
370         $fgrp->{lei}->qerr("# @$cmd");
371         return if $fgrp->{dry_run};
372         my $fgrp_fini = PublicInbox::OnDestroy->new($$, \&fgrp_fetched, $fgrp);
373         my $pid = spawn($cmd, undef, $opt);
374         $LIVE->{$pid} = [ \&reap_cmd, $fgrp, $cmd, $fgrp_fini ];
375 }
376
377 # keep this idempotent for future use by public-inbox-fetch
378 sub forkgroup_prep {
379         my ($self, $uri) = @_;
380         $self->{-ent} // return;
381         my $os = $self->{-objstore} // return;
382         my $fg = $self->{-ent}->{forkgroup} // return;
383         my $dir = "$os/$fg.git";
384         my @cmd = ('git', "--git-dir=$dir", 'config');
385         my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
386         if (!-d $dir) {
387                 PublicInbox::Import::init_bare($dir);
388                 for ('repack.useDeltaIslands=true',
389                                 'pack.island=refs/remotes/([^/]+)/') {
390                         run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
391                 }
392         }
393         my $key = $self->{-key} // die 'BUG: no -key';
394         my ($bn) = ($key =~ m{/([a-z0-9_,;=!\+\{\}\|][^/]*)(?:\.git)?\z}i);
395         my $rn = "$bn-".substr(sha256_hex($key), 0, 16);
396         for ("url=$uri", "fetch=+refs/*:refs/remotes/$rn/*") {
397                 my @kv = split(/=/, $_, 2);
398                 $kv[0] = "remote.$rn.$kv[0]";
399                 run_die([@cmd, @kv], undef, $opt);
400         }
401         if (!-d $self->{cur_dst}) {
402                 my $alt = File::Spec->rel2abs("$dir/objects");
403                 PublicInbox::Import::init_bare($self->{cur_dst});
404                 my $o = "$self->{cur_dst}/objects";
405                 my $f = "$o/info/alternates";
406                 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
407                 open my $fh, '+>>', $f or die "open($f): $!";
408                 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
409                 chomp(my @cur = <$fh>);
410                 if (!grep(/\A\Q$l\E\z/, @cur)) {
411                         say $fh $l or die "say($f): $!";
412                 }
413                 close $fh or die "close($f): $!";
414                 @cmd = ('git', "--git-dir=$self->{cur_dst}",
415                         qw(remote add --mirror=fetch origin), "$uri");
416                 my $pid = spawn(\@cmd, undef, $opt);
417                 waitpid($pid, 0) // die "waitpid(@cmd): $!";
418                 die "E: @cmd: \$?=$?" if ($? && ($? >> 8) != 3);
419         }
420         bless { %$self, -osdir => $dir, -remote => $rn }, __PACKAGE__;
421 }
422
423 sub clone_v1 {
424         my ($self, $nohang) = @_;
425         my $lei = $self->{lei};
426         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
427         my $uri = URI->new($self->{cur_src} // $self->{src});
428         defined($lei->{opt}->{epoch}) and
429                 die "$uri is a v1 inbox, --epoch is not supported\n";
430         my $pfx = $curl->torsocks($lei, $uri) or return;
431         my $dst = $self->{cur_dst} // $self->{dst};
432         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
433         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}), "$uri", $dst ];
434         my $fgrp = forkgroup_prep($self, $uri);
435         if (!defined($fgrp) && defined($self->{-ent})) {
436                 if (defined(my $ref = $self->{-ent}->{reference})) {
437                         -e "$self->{dst}$ref" and
438                                 push @$cmd, '--reference', "$self->{dst}$ref";
439                 }
440         }
441         $fgrp ? fgrp_fetch($fgrp, $pfx, $fini) :
442                 start_clone($self, $cmd, $opt, $fini);
443
444         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
445                                 /\A(?:always|v1)\z/s) {
446                 _get_txt_start($self, '_/text/config/raw', $fini);
447         }
448
449         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
450         $self->{'txt.description'} = $d if defined $d;
451         (!defined($d) && !$nohang) and
452                 _get_txt_start($self, 'description', $fini);
453
454         reap_live() until ($nohang || !keys(%$LIVE)); # for non-manifest clone
455 }
456
457 sub parse_epochs ($$) {
458         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
459         $opt_epochs // return; # undef => all epochs
460         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
461         undef($lo) if ($lo // '') eq '';
462         my $re = qr/\A~?[0-9]+\z/;
463         if (@extra || (($lo // '0') !~ $re) ||
464                         (($hi // '0') !~ $re) ||
465                         !(grep(defined, $lo, $hi))) {
466                 die <<EOM;
467 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
468 EOM
469         }
470         my @n = sort { $a <=> $b } keys %$v2_epochs;
471         for (grep(defined, $lo, $hi)) {
472                 if (/\A[0-9]+\z/) {
473                         $_ > $n[-1] and die
474 "`$_' exceeds maximum available epoch ($n[-1])\n";
475                         $_ < $n[0] and die
476 "`$_' is lower than minimum available epoch ($n[0])\n";
477                 } elsif (/\A~([0-9]+)/) {
478                         my $off = -$1 - 1;
479                         $n[$off] // die "`$_' is out of range\n";
480                         $_ = $n[$off];
481                 } else { die "`$_' not understood\n" }
482         }
483         defined($lo) && defined($hi) && $lo > $hi and die
484 "low value (`$lo') exceeds high (`$hi')\n";
485         $lo //= $n[0] if $dotdot;
486         $hi //= $n[-1] if $dotdot;
487         $hi //= $lo;
488         my $want = {};
489         for ($lo..$hi) {
490                 if (defined $v2_epochs->{$_}) {
491                         $want->{$_} = 1;
492                 } else {
493                         warn
494 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
495                 }
496         }
497         $want
498 }
499
500 sub init_placeholder ($$$) {
501         my ($src, $edst, $ent) = @_;
502         PublicInbox::Import::init_bare($edst);
503         my $f = "$edst/config";
504         open my $fh, '>>', $f or die "open($f): $!";
505         print $fh <<EOM or die "print($f): $!";
506 [remote "origin"]
507         url = $src
508         fetch = +refs/*:refs/*
509         mirror = true
510
511 ; This git epoch was created read-only and "public-inbox-fetch"
512 ; will not fetch updates for it unless write permission is added.
513 ; Hint: chmod +w $edst
514 EOM
515         if (defined($ent->{owner})) {
516                 print $fh <<EOM or die "print($f): $!";
517 [gitweb]
518         owner = $ent->{owner}
519 EOM
520         }
521         close $fh or die "close($f): $!";
522         my %map = (head => 'HEAD', description => undef);
523         while (my ($key, $fn) = each %map) {
524                 my $val = $ent->{$key} // next;
525                 $fn //= $key;
526                 $fn = "$edst/$fn";
527                 open $fh, '>', $fn or die "open($fn): $!";
528                 print $fh $val, "\n" or die "print($fn): $!";
529                 close $fh or die "close($fn): $!";
530         }
531 }
532
533 sub reap_cmd { # async, called via SIGCHLD
534         my ($self, $cmd) = @_;
535         my $cerr = $?;
536         $? = 0; # don't let it influence normal exit
537         if ($cerr) {
538                 kill('TERM', keys %$LIVE);
539                 $self->{lei}->child_error($cerr, "@$cmd failed");
540         }
541 }
542
543 sub v1_done { # called via OnDestroy
544         my ($self) = @_;
545         return if $self->{dry_run} || !$LIVE;
546         _write_inbox_config($self);
547         my $dst = $self->{cur_dst} // $self->{dst};
548         if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
549                 run_die([qw(git config -f), "$dst/config", 'gitweb.owner', $o]);
550         }
551         my $o = "$dst/objects";
552         if (open(my $fh, '<', "$o/info/alternates")) {
553                 my $base = File::Spec->rel2abs($o);
554                 chomp(my @l = <$fh>);
555                 for (@l) {
556                         $_ = File::Spec->abs2rel($_, $base) if m!\A/!;
557                         $_ .= "\n";
558                 }
559                 my $f = File::Temp->new(TEMPLATE => '.XXXX', DIR => "$o/info");
560                 print $f @l;
561                 $f->flush or die "flush($f): $!";
562                 rename($f->filename, "$o/info/alternates") or
563                         die "rename($f, $o/info/alternates): $!";
564                 $f->unlink_on_destroy(0);
565         }
566         return if ($self->{-is_epoch} ||
567                 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
568         write_makefile($dst, 1);
569         index_cloned_inbox($self, 1);
570 }
571
572 sub v2_done { # called via OnDestroy
573         my ($self) = @_;
574         return if $self->{dry_run} || !$LIVE;
575         my $dst = $self->{cur_dst} // $self->{dst};
576         require PublicInbox::Lock;
577         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
578         my $lck = $lk->lock_for_scope($$);
579         _write_inbox_config($self);
580         require PublicInbox::MultiGit;
581         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
582         $mg->fill_alternates;
583         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
584         for my $edst (@{delete($self->{-read_only}) // []}) {
585                 my @st = stat($edst) or die "stat($edst): $!";
586                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
587         }
588         write_makefile($dst, 2);
589         undef $lck; # unlock
590         index_cloned_inbox($self, 2);
591 }
592
593 sub reap_live {
594         my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
595         if (my $x = delete $LIVE->{$pid}) {
596                 my $cb = shift @$x;
597                 $cb->(@$x) if $cb;
598         } else {
599                 warn "reaped unknown PID=$pid ($?)\n";
600         }
601 }
602
603 sub clone_v2_prep ($$;$) {
604         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
605         my $lei = $self->{lei};
606         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
607         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
608         my $pfx = $curl->torsocks($lei, $first_uri) or return;
609         my $dst = $self->{cur_dst} // $self->{dst};
610         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
611         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
612         delete $task->{todo}; # $self->{todo} still exists
613         my (@skip, $desc);
614         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
615         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
616                 my ($uri, $key) = @{$v2_epochs->{$nr}};
617                 my $src = $uri->as_string;
618                 my $edst = $dst;
619                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
620 failed to extract epoch number from $src
621
622                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
623                 $edst .= "/git/$nr.git";
624                 my $ent;
625                 if ($m) {
626                         $ent = $m->{$key} //
627                                 die("BUG: `$key' not in manifest.js.gz");
628                         if (defined(my $d = $ent->{description})) {
629                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
630                                 $desc = $d;
631                         }
632                 }
633                 if (!$want || $want->{$nr}) {
634                         my $etask = bless { %$task, -key => $key }, __PACKAGE__;
635                         $etask->{-ent} = $ent; # may have {reference}
636                         $etask->{cur_src} = $src;
637                         $etask->{cur_dst} = $edst;
638                         $etask->{-is_epoch} = $fini;
639                         my $ref = $ent->{reference} // '';
640                         push @{$self->{todo}->{$ref}}, $etask;
641                         $self->{any_want}->{$key} = 1;
642                 } else { # create a placeholder so users only need to chmod +w
643                         init_placeholder($src, $edst, $ent);
644                         push @{$task->{-read_only}}, $edst;
645                         push @skip, $key;
646                 }
647         }
648         # filter out the epochs we skipped
649         $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
650
651         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
652
653         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
654                 _get_txt_start($task, '_/text/config/raw', $fini);
655
656         defined($desc) ? ($task->{'txt.description'} = $desc) :
657                 _get_txt_start($task, 'description', $fini);
658 }
659
660 sub decode_manifest ($$$) {
661         my ($fh, $fn, $uri) = @_;
662         my $js;
663         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
664         gunzip(\$gz => \$js, MultiStream => 1) or
665                 die "gunzip($uri): $GunzipError\n";
666         my $m = eval { PublicInbox::Config->json->decode($js) };
667         die "$uri: error decoding `$js': $@\n" if $@;
668         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
669         $m;
670 }
671
672 sub multi_inbox ($$$) {
673         my ($self, $path, $m) = @_;
674         my $incl = $self->{lei}->{opt}->{include};
675         my $excl = $self->{lei}->{opt}->{exclude};
676
677         # assuming everything not v2 is v1, for now
678         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
679         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
680         my $v2 = {};
681
682         for (@v2_epochs) {
683                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
684                 push @{$v2->{$1}}, $_;
685         }
686         my $n = scalar(keys %$v2) + scalar(@v1);
687         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
688         if (defined $incl) {
689                 my $re = '(?:'.join('\\z|', map {
690                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
691                         } @$incl).'\\z)';
692                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
693                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
694                 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
695                 @v1 = grep(/$re/, @v1);
696         }
697         if (defined $excl) {
698                 my $re = '(?:'.join('\\z|', map {
699                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
700                         } @$excl).'\\z)';
701                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
702                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
703                 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
704                 @v1 = grep(!/$re/, @v1);
705         }
706         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
707         $ret->{v1} = \@v1 if @v1;
708         $ret->{v2} = $v2 if keys %$v2;
709         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
710                                 join("\n\t", sort @orig)
711                         : "Nothing available to clone\n";
712         my $path_pfx = '';
713
714         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
715         if (@v2_epochs) {
716                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
717                                 @v2_epochs) == @v2_epochs) {
718                         $$path =~ s!\A(/[^/]+)/!/! or last;
719                         $path_pfx .= $1;
720                 }
721         } elsif (@v1) {
722                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
723                         $path_pfx .= $1;
724                 }
725         }
726         ($path_pfx, $n, $ret);
727 }
728
729 sub clone_all {
730         my ($self, $m) = @_;
731         my $todo = delete $self->{todo};
732         my $nodep = delete $todo->{''};
733
734         # do not download unwanted deps
735         my $any_want = delete $self->{any_want};
736         my @unwanted = grep { !$any_want->{$_} } keys %$todo;
737         my @nodep = delete(@$todo{@unwanted});
738         push(@$nodep, @$_) for @nodep;
739
740         # handle no-dependency repos, first
741         for (@$nodep) {
742                 clone_v1($_, 1);
743                 return if $self->{lei}->{child_error};
744         }
745         # resolve references, deepest, first:
746         while (scalar keys %$todo) {
747                 for my $x (keys %$todo) {
748                         my ($nr, $nxt);
749                         # resolve multi-level references
750                         while ($m && defined($nxt = $m->{$x}->{reference})) {
751                                 exists($todo->{$nxt}) or last;
752                                 die <<EOM if ++$nr > 1000;
753 E: dependency loop detected (`$x' => `$nxt')
754 EOM
755                                 $x = $nxt;
756                         }
757                         my $y = delete $todo->{$x} // next; # already done
758                         for (@$y) {
759                                 clone_v1($_, 1);
760                                 return if $self->{lei}->{child_error};
761                         }
762                         last; # restart %$todo iteration
763                 }
764         }
765         reap_live() while keys(%$LIVE);
766 }
767
768 sub dump_manifest ($$) {
769         my ($m, $ft) = @_;
770         # write the smaller manifest if epochs were skipped so
771         # users won't have to delete manifest if they +w an
772         # epoch they no longer want to skip
773         my $json = PublicInbox::Config->json->encode($m);
774         my $mtime = (stat($ft))[9];
775         seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
776         truncate($ft, 0) or die "truncate($ft): $!";
777         gzip(\$json => $ft) or die "gzip($ft): $GzipError";
778         $ft->flush or die "flush($ft): $!";
779         utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
780 }
781
782 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
783 sub try_manifest {
784         my ($self) = @_;
785         my $uri = URI->new($self->{src});
786         my $lei = $self->{lei};
787         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
788         my $path = $uri->path;
789         chop($path) eq '/' or die "BUG: $uri not canonicalized";
790         $uri->path($path . '/manifest.js.gz');
791         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX',
792                                 UNLINK => 1, TMPDIR => 1, SUFFIX => '.tmp');
793         my $cmd = $curl->for_uri($lei, $uri, qw(-f -R -o), $ft->filename);
794         my %opt = map { $_ => $lei->{$_} } (0..2);
795         my $cerr = run_reap($lei, $cmd, \%opt);
796         if ($cerr) {
797                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
798                 return $lei->child_error($cerr, "@$cmd failed");
799         }
800         my $m = eval { decode_manifest($ft, $ft, $uri) };
801         if ($@) {
802                 warn $@;
803                 return try_scrape($self);
804         }
805         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
806         return $lei->child_error(1, $multi) if !ref($multi);
807         my $v2 = delete $multi->{v2};
808         local $self->{todo} = {};
809         if ($v2) {
810                 for my $name (sort keys %$v2) {
811                         my $epochs = delete $v2->{$name};
812                         my %v2_epochs = map {
813                                 $uri->path($n > 1 ? $path_pfx.$path.$_
814                                                 : $path_pfx.$_);
815                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
816                                 $e // die "no [0-9]+\.git in `$uri'";
817                                 $e => [ $uri->clone, $_ ];
818                         } @$epochs;
819                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
820                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
821                         local $self->{cur_src} = $1;
822                         local $self->{cur_dst} = $self->{dst};
823                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
824                                                         git/[0-9]+\.git\z!x) {
825                                 $self->{cur_dst} .= "/$1";
826                         }
827                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
828 E: `$self->{cur_dst}' must not contain newline
829 EOM
830                         clone_v2_prep($self, \%v2_epochs, $m);
831                         return if $self->{lei}->{child_error};
832                 }
833         }
834         if (my $v1 = delete $multi->{v1}) {
835                 my $p = $path_pfx.$path;
836                 chop($p) if substr($p, -1, 1) eq '/';
837                 $uri->path($p);
838                 for my $name (@$v1) {
839                         my $task = bless { %$self }, __PACKAGE__;
840                         $task->{-ent} = $m->{$name} //
841                                         die("BUG: no `$name' in manifest");
842                         $task->{cur_src} = "$uri";
843                         $task->{cur_dst} = $task->{dst};
844                         $task->{-key} = $name;
845                         if ($n > 1) {
846                                 $task->{cur_dst} .= $name;
847                                 $task->{cur_src} .= $name;
848                         }
849                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
850 E: `$task->{cur_dst}' must not contain newline
851 EOM
852                         $task->{cur_src} .= '/';
853                         my $dep = $task->{-ent}->{reference} // '';
854                         push @{$self->{todo}->{$dep}}, $task; # for clone_all
855                         $self->{any_want}->{$name} = 1;
856                 }
857         }
858         delete local $lei->{opt}->{epoch} if defined($v2);
859         clone_all($self, $m);
860         return if $self->{lei}->{child_error} || $self->{dry_run};
861
862         # set by clone_v2_prep/-I/--exclude
863         dump_manifest($m => $ft) if delete $self->{-culled_manifest};
864         ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
865         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
866 }
867
868 sub start_clone_url {
869         my ($self) = @_;
870         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
871         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
872 }
873
874 sub do_mirror { # via wq_io_do or public-inbox-clone
875         my ($self) = @_;
876         my $lei = $self->{lei};
877         umask($lei->{client_umask}) if defined $lei->{client_umask};
878         eval {
879                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
880                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
881 --inbox-config must be one of `always', `v2', `v1', or `never'
882
883                 if (defined(my $os = $lei->{opt}->{objstore})) {
884                         $os = 'objstore' if $os eq ''; # --objstore w/o args
885                         $self->{-objstore} = "$self->{dst}/$os";
886                 }
887                 local $LIVE;
888                 my $iv = $lei->{opt}->{'inbox-version'} //
889                         return start_clone_url($self);
890                 return clone_v1($self) if $iv == 1;
891                 die "bad --inbox-version=$iv\n" if $iv != 2;
892                 die <<EOM if $self->{src} !~ m!://!;
893 cloning local v2 inboxes not supported
894 EOM
895                 try_scrape($self, 1);
896         };
897         $lei->fail($@) if $@;
898 }
899
900 sub start {
901         my ($cls, $lei, $src, $dst) = @_;
902         my $self = bless { src => $src, dst => $dst }, $cls;
903         $lei->request_umask;
904         my ($op_c, $ops) = $lei->workers_start($self, 1);
905         $lei->{wq1} = $self;
906         $self->wq_io_do('do_mirror', []);
907         $self->wq_close;
908         $lei->wait_wq_events($op_c, $ops);
909 }
910
911 sub ipc_atfork_child {
912         my ($self) = @_;
913         $self->{lei}->_lei_atfork_child;
914         $self->SUPER::ipc_atfork_child;
915 }
916
917 sub write_makefile {
918         my ($dir, $ibx_ver) = @_;
919         my $f = "$dir/Makefile";
920         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
921                 print $fh <<EOM or die "print($f) $!";
922 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
923 # manpage for more information on the format.  This Makefile is
924 # intended as a familiar wrapper for users unfamiliar with
925 # public-inbox-* commands.
926 #
927 # See the respective manpages for public-inbox-fetch(1),
928 # public-inbox-index(1), etc for more information on
929 # some of the commands used by this Makefile.
930 #
931 # This Makefile will not be modified nor read by public-inbox,
932 # so you may edit it freely with your own convenience targets
933 # and notes.  public-inbox-fetch will recreate it if removed.
934 EOM
935                 print $fh <<'EOM' or die "print($f): $!";
936 # the default target:
937 help :
938         @echo Common targets:
939         @echo '    make fetch        - fetch from remote git repostorie(s)'
940         @echo '    make update       - fetch and update index '
941         @echo
942         @echo Rarely needed targets:
943         @echo '    make reindex      - may be needed for new features/bugfixes'
944         @echo '    make compact      - rewrite Xapian storage to save space'
945         @echo '    make index        - initial index after clone
946
947 fetch :
948         public-inbox-fetch
949 update :
950         @if ! public-inbox-fetch --exit-code; \
951         then \
952                 c=$$?; \
953                 test $$c -eq 127 && exit 0; \
954                 exit $$c; \
955         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
956         then \
957                 public-inbox-index; \
958         else \
959                 echo 'public-inbox index not initialized'; \
960                 echo 'see public-inbox-index(1) man page'; \
961         fi
962 index :
963         public-inbox-index
964 reindex :
965         public-inbox-index --reindex
966 compact :
967         public-inbox-compact
968
969 .PHONY : help fetch update index reindex compact
970 EOM
971                 close $fh or die "close($f): $!";
972         } else {
973                 die "open($f): $!" unless $!{EEXIST};
974         }
975 }
976
977 1;