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