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