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