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