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