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