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