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