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