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