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