]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use PublicInbox::Config;
10 use PublicInbox::AutoReap;
11 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
12 use IO::Compress::Gzip qw(gzip $GzipError);
13 use PublicInbox::Spawn qw(popen_rd spawn);
14 use File::Temp ();
15 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
16 use Carp qw(croak);
17
18 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
19         my ($arg, $pid) = @_;
20         my ($mrr, $lei) = @$arg;
21         my $f = "$mrr->{dst}/mirror.done";
22         if ($?) {
23                 $lei->child_error($?);
24         } elsif (!unlink($f)) {
25                 warn("unlink($f): $!\n") unless $!{ENOENT};
26         } else {
27                 if ($lei->{cmd} ne 'public-inbox-clone') {
28                         $lei->lazy_cb('add-external', '_finish_'
29                                         )->($lei, $mrr->{dst});
30                 }
31                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
32         }
33         $lei->dclose;
34 }
35
36 # for old installations without manifest.js.gz
37 sub try_scrape {
38         my ($self) = @_;
39         my $uri = URI->new($self->{src});
40         my $lei = $self->{lei};
41         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
42         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
43         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
44         my $fh = popen_rd($cmd, undef, $opt);
45         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
46         close($fh) or return $lei->child_error($?, "@$cmd failed");
47
48         # we grep with URL below, we don't want Subject/From headers
49         # making us clone random URLs
50         my @html = split(/<hr>/, $html);
51         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
52         my $url = $uri->as_string;
53         chop($url) eq '/' or die "BUG: $uri not canonicalized";
54
55         # since this is for old instances w/o manifest.js.gz, try v1 first
56         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
57         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
58                 my %v2_epochs = map {
59                         my ($n) = (m!/([0-9]+)\z!);
60                         $n => URI->new($_)
61                 } @v2_urls; # uniq
62                 return clone_v2($self, \%v2_epochs);
63         }
64
65         # filter out common URLs served by WWW (e.g /$MSGID/T/)
66         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
67                         grep(m!\A\Q$url\E/*\z!, @urls)) {
68                 die <<"";
69 E: confused by scraping <$uri>, did you mean <$url>?
70
71         }
72         @urls and die <<"";
73 E: confused by scraping <$uri>, got ambiguous results:
74 @urls
75
76         die "E: scraping <$uri> revealed nothing\n";
77 }
78
79 sub clone_cmd {
80         my ($lei, $opt) = @_;
81         my @cmd = qw(git);
82         $opt->{$_} = $lei->{$_} for (0..2);
83         # we support "-c $key=$val" for arbitrary git config options
84         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
85         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
86         push @cmd, qw(clone --mirror);
87         push @cmd, '-q' if $lei->{opt}->{quiet};
88         push @cmd, '-v' if $lei->{opt}->{verbose};
89         # XXX any other options to support?
90         # --reference is tricky with multiple epochs...
91         @cmd;
92 }
93
94 sub ft_rename ($$$) {
95         my ($ft, $dst, $open_mode) = @_;
96         my $fn = $ft->filename;
97         my @st = stat($dst);
98         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
99         chmod($mode, $ft) or croak "E: chmod $fn: $!";
100         rename($fn, $dst) or croak "E: rename($fn => $ft): $!";
101         $ft->unlink_on_destroy(0);
102 }
103
104 sub _get_txt { # non-fatal
105         my ($self, $endpoint, $file, $mode) = @_;
106         my $uri = URI->new($self->{src});
107         my $lei = $self->{lei};
108         my $path = $uri->path;
109         chop($path) eq '/' or die "BUG: $uri not canonicalized";
110         $uri->path("$path/$endpoint");
111         my $ft = File::Temp->new(TEMPLATE => "$file-XXXX", DIR => $self->{dst});
112         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
113         my $cmd = $self->{curl}->for_uri($lei, $uri,
114                                         qw(--compressed -R -o), $ft->filename);
115         my $cerr = run_reap($lei, $cmd, $opt);
116         return "$uri missing" if ($cerr >> 8) == 22;
117         return "# @$cmd failed (non-fatal)" if $cerr;
118         ft_rename($ft, "$self->{dst}/$file", $mode);
119         undef; # success
120 }
121
122 # tries the relatively new /$INBOX/_/text/config/raw endpoint
123 sub _try_config {
124         my ($self) = @_;
125         my $dst = $self->{dst};
126         if (!-d $dst || !mkdir($dst)) {
127                 require File::Path;
128                 File::Path::mkpath($dst);
129                 -d $dst or die "mkpath($dst): $!\n";
130         }
131         my $err = _get_txt($self,
132                         qw(_/text/config/raw inbox.config.example), 0444);
133         return warn($err, "\n") if $err;
134         my $f = "$self->{dst}/inbox.config.example";
135         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
136         my $ibx = $self->{ibx} = {};
137         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
138                 for (qw(address newsgroup nntpmirror)) {
139                         $ibx->{$_} = $cfg->{"$sec.$_"};
140                 }
141         }
142 }
143
144 sub set_description ($) {
145         my ($self) = @_;
146         my $f = "$self->{dst}/description";
147         open my $fh, '+>>', $f or die "open($f): $!";
148         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
149         chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
150         if ($d eq '($INBOX_DIR/description missing)' ||
151                         $d =~ /^Unnamed repository/ || $d !~ /\S/) {
152                 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
153                 truncate($fh, 0) or die "truncate($f): $!";
154                 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
155                 close $fh or die "close($f): $!";
156         }
157 }
158
159 sub index_cloned_inbox {
160         my ($self, $iv) = @_;
161         my $lei = $self->{lei};
162         my $err = _get_txt($self, qw(description description), 0666);
163         warn($err, "\n") if $err; # non fatal
164         eval { set_description($self) };
165         warn $@ if $@;
166
167         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
168         # lei is useless without Xapian + SQLite
169         if ($lei->{cmd} ne 'public-inbox-clone') {
170                 my $ibx = delete($self->{ibx}) // {
171                         address => [ 'lei@example.com' ],
172                         version => $iv,
173                 };
174                 $ibx->{inboxdir} = $self->{dst};
175                 PublicInbox::Inbox->new($ibx);
176                 PublicInbox::InboxWritable->new($ibx);
177                 my $opt = {};
178                 for my $sw ($lei->index_opt) {
179                         my ($k) = ($sw =~ /\A([\w-]+)/);
180                         $opt->{$k} = $lei->{opt}->{$k};
181                 }
182                 # force synchronous dwaitpid for v2:
183                 local $PublicInbox::DS::in_loop = 0;
184                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
185                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
186                 local %ENV = (%ENV, %$env) if $env;
187                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
188                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
189         }
190         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
191 }
192
193 sub run_reap {
194         my ($lei, $cmd, $opt) = @_;
195         $lei->qerr("# @$cmd");
196         my $ar = PublicInbox::AutoReap->new(spawn($cmd, undef, $opt));
197         $ar->join;
198         my $ret = $?;
199         $? = 0; # don't let it influence normal exit
200         $ret;
201 }
202
203 sub clone_v1 {
204         my ($self) = @_;
205         my $lei = $self->{lei};
206         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
207         my $uri = URI->new($self->{src});
208         defined($lei->{opt}->{epoch}) and
209                 die "$uri is a v1 inbox, --epoch is not supported\n";
210         my $pfx = $curl->torsocks($lei, $uri) or return;
211         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
212                         $uri->as_string, $self->{dst} ];
213         my $cerr = run_reap($lei, $cmd, $opt);
214         return $lei->child_error($cerr, "@$cmd failed") if $cerr;
215         _try_config($self);
216         write_makefile($self->{dst}, 1);
217         index_cloned_inbox($self, 1);
218 }
219
220 sub parse_epochs ($$) {
221         my ($opt_epochs, $v2_epochs) = @_; # $epcohs "LOW..HIGH"
222         $opt_epochs // return; # undef => all epochs
223         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
224         undef($lo) if ($lo // '') eq '';
225         my $re = qr/\A~?[0-9]+\z/;
226         if (@extra || (($lo // '0') !~ $re) ||
227                         (($hi // '0') !~ $re) ||
228                         !(grep(defined, $lo, $hi))) {
229                 die <<EOM;
230 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
231 EOM
232         }
233         my @n = sort { $a <=> $b } keys %$v2_epochs;
234         for (grep(defined, $lo, $hi)) {
235                 if (/\A[0-9]+\z/) {
236                         $_ > $n[-1] and die
237 "`$_' exceeds maximum available epoch ($n[-1])\n";
238                         $_ < $n[0] and die
239 "`$_' is lower than minimum available epoch ($n[0])\n";
240                 } elsif (/\A~([0-9]+)/) {
241                         my $off = -$1 - 1;
242                         $n[$off] // die "`$_' is out of range\n";
243                         $_ = $n[$off];
244                 } else { die "`$_' not understood\n" }
245         }
246         defined($lo) && defined($hi) && $lo > $hi and die
247 "low value (`$lo') exceeds high (`$hi')\n";
248         $lo //= $n[0] if $dotdot;
249         $hi //= $n[-1] if $dotdot;
250         $hi //= $lo;
251         my $want = {};
252         for ($lo..$hi) {
253                 if (defined $v2_epochs->{$_}) {
254                         $want->{$_} = 1;
255                 } else {
256                         warn
257 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
258                 }
259         }
260         $want
261 }
262
263 sub init_placeholder ($$) {
264         my ($src, $edst) = @_;
265         PublicInbox::Import::init_bare($edst);
266         my $f = "$edst/config";
267         open my $fh, '>>', $f or die "open($f): $!";
268         print $fh <<EOM or die "print($f): $!";
269 [remote "origin"]
270         url = $src
271         fetch = +refs/*:refs/*
272         mirror = true
273
274 ; This git epoch was created read-only and "public-inbox-fetch"
275 ; will not fetch updates for it unless write permission is added.
276 EOM
277         close $fh or die "close:($f): $!";
278 }
279
280 sub clone_v2 ($$;$) {
281         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
282         my $lei = $self->{lei};
283         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
284         my $pfx = $curl->torsocks($lei, (values %$v2_epochs)[0]) or return;
285         my $dst = $self->{dst};
286         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
287         my (@src_edst, @read_only, @skip_nr);
288         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
289                 my $uri = $v2_epochs->{$nr};
290                 my $src = $uri->as_string;
291                 my $edst = $dst;
292                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
293 failed to extract epoch number from $src
294
295                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
296                 $edst .= "/git/$nr.git";
297                 if (!$want || $want->{$nr}) {
298                         push @src_edst, $src, $edst;
299                 } else { # create a placeholder so users only need to chmod +w
300                         init_placeholder($src, $edst);
301                         push @read_only, $edst;
302                         push @skip_nr, $nr;
303                 }
304         }
305         if (@skip_nr) { # filter out the epochs we skipped
306                 my $re = join('|', @skip_nr);
307                 my @del = grep(m!/git/$re\.git\z!, keys %$m);
308                 delete @$m{@del};
309                 $self->{-culled_manifest} = 1;
310         }
311         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
312         _try_config($self);
313         my $on_destroy = $lk->lock_for_scope($$);
314         my @cmd = clone_cmd($lei, my $opt = {});
315         while (my ($src, $edst) = splice(@src_edst, 0, 2)) {
316                 my $cmd = [ @$pfx, @cmd, $src, $edst ];
317                 my $cerr = run_reap($lei, $cmd, $opt);
318                 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
319         }
320         require PublicInbox::MultiGit;
321         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
322         $mg->fill_alternates;
323         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
324         for my $edst (@read_only) {
325                 my @st = stat($edst) or die "stat($edst): $!";
326                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
327         }
328         write_makefile($self->{dst}, 2);
329         undef $on_destroy; # unlock
330         index_cloned_inbox($self, 2);
331 }
332
333 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
334 sub deduce_epochs ($$) {
335         my ($m, $path) = @_;
336         my ($v1_ent, @v2_epochs);
337         my $path_pfx = '';
338         $path =~ s!/+\z!!;
339         do {
340                 $v1_ent = $m->{$path};
341                 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
342         } while (!defined($v1_ent) && !@v2_epochs &&
343                 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
344         ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
345 }
346
347 sub decode_manifest ($$$) {
348         my ($fh, $fn, $uri) = @_;
349         my $js;
350         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
351         gunzip(\$gz => \$js, MultiStream => 1) or
352                 die "gunzip($uri): $GunzipError\n";
353         my $m = eval { PublicInbox::Config->json->decode($js) };
354         die "$uri: error decoding `$js': $@\n" if $@;
355         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
356         $m;
357 }
358
359 sub try_manifest {
360         my ($self) = @_;
361         my $uri = URI->new($self->{src});
362         my $lei = $self->{lei};
363         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
364         my $path = $uri->path;
365         chop($path) eq '/' or die "BUG: $uri not canonicalized";
366         $uri->path($path . '/manifest.js.gz');
367         my $pdir = $lei->rel2abs($self->{dst});
368         $pdir =~ s!/[^/]+/?\z!!;
369         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
370                                 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
371         my $fn = $ft->filename;
372         my ($bn) = ($fn =~ m!/([^/]+)\z!);
373         my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
374         my $opt = { -C => $pdir };
375         $opt->{$_} = $lei->{$_} for (0..2);
376         my $cerr = run_reap($lei, $cmd, $opt);
377         if ($cerr) {
378                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
379                 return $lei->child_error($cerr, "@$cmd failed");
380         }
381         my $m = eval { decode_manifest($ft, $fn, $uri) };
382         if ($@) {
383                 warn $@;
384                 return try_scrape($self);
385         }
386         my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
387         if (@v2_epochs) {
388                 # It may be possible to have v1 + v2 in parallel someday:
389                 warn(<<EOM) if defined $v1_path;
390 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
391 # @v2_epochs
392 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
393 EOM
394                 my %v2_epochs = map {
395                         $uri->path($path_pfx.$_);
396                         my ($n) = ("$uri" =~ m!/([0-9]+)\.git\z!);
397                         $n => $uri->clone
398                 } @v2_epochs;
399                 clone_v2($self, \%v2_epochs, $m);
400         } elsif (defined $v1_path) {
401                 clone_v1($self);
402         } else {
403                 die "E: confused by <$uri>, possible matches:\n\t",
404                         join(', ', sort keys %$m), "\n";
405         }
406         if (delete $self->{-culled_manifest}) { # set by clone_v2
407                 # write the smaller manifest if epochs were skipped so
408                 # users won't have to delete manifest if they +w an
409                 # epoch they no longer want to skip
410                 my $json = PublicInbox::Config->json->encode($m);
411                 gzip(\$json => $fn) or die "gzip: $GzipError";
412         }
413         ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
414 }
415
416 sub start_clone_url {
417         my ($self) = @_;
418         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
419         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
420 }
421
422 sub do_mirror { # via wq_io_do
423         my ($self) = @_;
424         my $lei = $self->{lei};
425         umask($lei->{client_umask}) if defined $lei->{client_umask};
426         eval {
427                 my $iv = $lei->{opt}->{'inbox-version'};
428                 if (defined $iv) {
429                         return clone_v1($self) if $iv == 1;
430                         return try_scrape($self) if $iv == 2;
431                         die "bad --inbox-version=$iv\n";
432                 }
433                 return start_clone_url($self) if $self->{src} =~ m!://!;
434                 die "TODO: cloning local directories not supported, yet";
435         };
436         $lei->fail($@) if $@;
437 }
438
439 sub start {
440         my ($cls, $lei, $src, $dst) = @_;
441         my $self = bless { src => $src, dst => $dst }, $cls;
442         if ($src =~ m!https?://!) {
443                 require URI;
444                 require PublicInbox::LeiCurl;
445         }
446         require PublicInbox::Lock;
447         require PublicInbox::Inbox;
448         require PublicInbox::Admin;
449         require PublicInbox::InboxWritable;
450         $lei->request_umask;
451         my ($op_c, $ops) = $lei->workers_start($self, 1);
452         $lei->{wq1} = $self;
453         $self->wq_io_do('do_mirror', []);
454         $self->wq_close;
455         $lei->wait_wq_events($op_c, $ops);
456 }
457
458 sub ipc_atfork_child {
459         my ($self) = @_;
460         $self->{lei}->_lei_atfork_child;
461         $self->SUPER::ipc_atfork_child;
462 }
463
464 sub write_makefile {
465         my ($dir, $ibx_ver) = @_;
466         my $f = "$dir/Makefile";
467         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
468                 print $fh <<EOM or die "print($f) $!";
469 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
470 # manpage for more information on the format.  This Makefile is
471 # intended as a familiar wrapper for users unfamiliar with
472 # public-inbox-* commands.
473 #
474 # See the respective manpages for public-inbox-fetch(1),
475 # public-inbox-index(1), etc for more information on
476 # some of the commands used by this Makefile.
477 #
478 # This Makefile will not be modified nor read by public-inbox,
479 # so you may edit it freely with your own convenience targets
480 # and notes.  public-inbox-fetch will recreate it if removed.
481 EOM
482                 print $fh <<'EOM' or die "print($f): $!";
483 # the default target:
484 help :
485         @echo Common targets:
486         @echo '    make fetch        - fetch from remote git repostorie(s)'
487         @echo '    make update       - fetch and update index '
488         @echo
489         @echo Rarely needed targets:
490         @echo '    make reindex      - may be needed for new features/bugfixes'
491         @echo '    make compact      - rewrite Xapian storage to save space'
492
493 fetch :
494         public-inbox-fetch
495 update :
496         @if ! public-inbox-fetch --exit-code; \
497         then \
498                 c=$$?; \
499                 test $$c -eq 127 && exit 0; \
500                 exit $$c; \
501         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
502         then \
503                 public-inbox-index; \
504         else \
505                 echo 'public-inbox index not initialized'; \
506                 echo 'see public-inbox-index(1) man page'; \
507         fi
508 reindex :
509         public-inbox-index --reindex
510 compact :
511         public-inbox-compact
512
513 .PHONY : help fetch update reindex compact
514 EOM
515                 close $fh or die "close($f): $!";
516         } else {
517                 die "open($f): $!" unless $!{EEXIST};
518         }
519 }
520
521 1;