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