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