]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
bc2e749c064a22261f86c64e65d7e2ddb81a9fd2
[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
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 PublicInbox::Spawn qw(popen_rd spawn);
11 use File::Temp ();
12 use Fcntl qw(SEEK_SET);
13
14 sub do_finish_mirror { # dwaitpid callback
15         my ($arg, $pid) = @_;
16         my ($mrr, $lei) = @$arg;
17         my $f = "$mrr->{dst}/mirror.done";
18         if ($?) {
19                 $lei->child_error($?);
20         } elsif (!unlink($f)) {
21                 $lei->err("unlink($f): $!") unless $!{ENOENT};
22         } else {
23                 if ($lei->{cmd} ne 'public-inbox-clone') {
24                         $lei->add_external_finish($mrr->{dst});
25                 }
26                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
27         }
28         $lei->dclose;
29 }
30
31 sub _lei_wq_eof { # EOF callback for main daemon
32         my ($lei) = @_;
33         my $mrr = delete $lei->{wq1} or return $lei->fail;
34         $mrr->wq_wait_old(\&do_finish_mirror, $lei);
35 }
36
37 # for old installations without manifest.js.gz
38 sub try_scrape {
39         my ($self) = @_;
40         my $uri = URI->new($self->{src});
41         my $lei = $self->{lei};
42         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
43         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
44         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
45         my $fh = popen_rd($cmd, undef, $opt);
46         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
47         close($fh) or return $lei->child_error($?, "@$cmd failed");
48
49         # we grep with URL below, we don't want Subject/From headers
50         # making us clone random URLs
51         my @urls = ($html =~ 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_uris = map { $_ => URI->new($_) } @v2_urls; # uniq
59                 return clone_v2($self, [ values %v2_uris ]);
60         }
61
62         # filter out common URLs served by WWW (e.g /$MSGID/T/)
63         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
64                         grep(m!\A\Q$url\E/*\z!, @urls)) {
65                 die <<"";
66 E: confused by scraping <$uri>, did you mean <$url>?
67
68         }
69         @urls and die <<"";
70 E: confused by scraping <$uri>, got ambiguous results:
71 @urls
72
73         die "E: scraping <$uri> revealed nothing\n";
74 }
75
76 sub clone_cmd {
77         my ($lei, $opt) = @_;
78         my @cmd = qw(git);
79         $opt->{$_} = $lei->{$_} for (0..2);
80         # we support "-c $key=$val" for arbitrary git config options
81         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
82         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
83         push @cmd, qw(clone --mirror);
84         push @cmd, '-q' if $lei->{opt}->{quiet};
85         push @cmd, '-v' if $lei->{opt}->{verbose};
86         # XXX any other options to support?
87         # --reference is tricky with multiple epochs...
88         @cmd;
89 }
90
91 sub _get_txt { # non-fatal
92         my ($self, $endpoint, $file) = @_;
93         my $uri = URI->new($self->{src});
94         my $lei = $self->{lei};
95         my $path = $uri->path;
96         chop($path) eq '/' or die "BUG: $uri not canonicalized";
97         $uri->path("$path/$endpoint");
98         my $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
99         my $ce = "$self->{dst}/$file";
100         my $ft = File::Temp->new(TEMPLATE => "$file-XXXX",
101                                 UNLINK => 1, DIR => $self->{dst});
102         my $opt = { 0 => $lei->{0}, 1 => $ft, 2 => $lei->{2} };
103         my $cerr = run_reap($lei, $cmd, $opt);
104         return "$uri missing" if ($cerr >> 8) == 22;
105         return "# @$cmd failed (non-fatal)" if $cerr;
106         my $f = $ft->filename;
107         rename($f, $ce) or return "rename($f, $ce): $! (non-fatal)";
108         $ft->unlink_on_destroy(0);
109         undef; # success
110 }
111
112 # tries the relatively new /$INBOX/_/text/config/raw endpoint
113 sub _try_config {
114         my ($self) = @_;
115         my $dst = $self->{dst};
116         if (!-d $dst || !mkdir($dst)) {
117                 require File::Path;
118                 File::Path::mkpath($dst);
119                 -d $dst or die "mkpath($dst): $!\n";
120         }
121         my $err = _get_txt($self, qw(_/text/config/raw inbox.config.example));
122         return $self->{lei}->err($err) if $err;
123         my $f = "$self->{dst}/inbox.config.example";
124         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
125         my $ibx = $self->{ibx} = {};
126         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
127                 for (qw(address newsgroup nntpmirror)) {
128                         $ibx->{$_} = $cfg->{"$sec.$_"};
129                 }
130         }
131 }
132
133 sub set_description ($) {
134         my ($self) = @_;
135         my $f = "$self->{dst}/description";
136         open my $fh, '+>>', $f or die "open($f): $!";
137         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
138         chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
139         if ($d eq '($INBOX_DIR/description missing)' ||
140                         $d =~ /^Unnamed repository/ || $d !~ /\S/) {
141                 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
142                 truncate($fh, 0) or die "truncate($f): $!";
143                 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
144                 close $fh or die "close($f): $!";
145         }
146 }
147
148 sub index_cloned_inbox {
149         my ($self, $iv) = @_;
150         my $lei = $self->{lei};
151         my $err = _get_txt($self, qw(description description));
152         $lei->err($err) if $err; # non fatal
153         eval { set_description($self) };
154         warn $@ if $@;
155
156         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
157         # lei is useless without Xapian + SQLite
158         if ($lei->{cmd} ne 'public-inbox-clone') {
159                 my $ibx = delete($self->{ibx}) // {
160                         address => [ 'lei@example.com' ],
161                         version => $iv,
162                 };
163                 $ibx->{inboxdir} = $self->{dst};
164                 PublicInbox::Inbox->new($ibx);
165                 PublicInbox::InboxWritable->new($ibx);
166                 my $opt = {};
167                 for my $sw ($lei->index_opt) {
168                         my ($k) = ($sw =~ /\A([\w-]+)/);
169                         $opt->{$k} = $lei->{opt}->{$k};
170                 }
171                 # force synchronous dwaitpid for v2:
172                 local $PublicInbox::DS::in_loop = 0;
173                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
174                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
175                 local %ENV = (%ENV, %$env) if $env;
176                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
177                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
178         }
179         open my $x, '>', "$self->{dst}/mirror.done"; # for do_finish_mirror
180 }
181
182 sub run_reap {
183         my ($lei, $cmd, $opt) = @_;
184         $lei->qerr("# @$cmd" . ($opt->{-C} ? " (in $opt->{-C})" : ''));
185         $opt->{pgid} = 0 if $lei->{sock};
186         my $pid = spawn($cmd, undef, $opt);
187         my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
188         waitpid($pid, 0) == $pid or die "waitpid @$cmd: $!";
189         @$reap = (); # cancel reap
190         $?
191 }
192
193 sub clone_v1 {
194         my ($self) = @_;
195         my $lei = $self->{lei};
196         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
197         my $uri = URI->new($self->{src});
198         my $pfx = $curl->torsocks($lei, $uri) or return;
199         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
200                         $uri->as_string, $self->{dst} ];
201         my $cerr = run_reap($lei, $cmd, $opt);
202         return $lei->child_error($cerr, "@$cmd failed") if $cerr;
203         _try_config($self);
204         index_cloned_inbox($self, 1);
205 }
206
207 sub clone_v2 {
208         my ($self, $v2_uris) = @_;
209         my $lei = $self->{lei};
210         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
211         my $pfx //= $curl->torsocks($lei, $v2_uris->[0]) or return;
212         my @epochs;
213         my $dst = $self->{dst};
214         my @src_edst;
215         for my $uri (@$v2_uris) {
216                 my $src = $uri->as_string;
217                 my $edst = $dst;
218                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
219 failed to extract epoch number from $src
220
221                 my $nr = $1 + 0;
222                 $edst .= "/git/$nr.git";
223                 push @src_edst, [ $src, $edst ];
224         }
225         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
226         _try_config($self);
227         my $on_destroy = $lk->lock_for_scope($$);
228         my @cmd = clone_cmd($lei, my $opt = {});
229         while (my $pair = shift(@src_edst)) {
230                 my $cmd = [ @$pfx, @cmd, @$pair ];
231                 my $cerr = run_reap($lei, $cmd, $opt);
232                 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
233         }
234         undef $on_destroy; # unlock
235         index_cloned_inbox($self, 2);
236 }
237
238 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
239 sub deduce_epochs ($$) {
240         my ($m, $path) = @_;
241         my ($v1_ent, @v2_epochs);
242         my $path_pfx = '';
243         $path =~ s!/+\z!!;
244         do {
245                 $v1_ent = $m->{$path};
246                 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
247         } while (!defined($v1_ent) && !@v2_epochs &&
248                 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
249         ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
250 }
251
252 sub decode_manifest ($$$) {
253         my ($fh, $fn, $uri) = @_;
254         my $js;
255         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
256         gunzip(\$gz => \$js, MultiStream => 1) or
257                 die "gunzip($uri): $GunzipError\n";
258         my $m = eval { PublicInbox::Config->json->decode($js) };
259         die "$uri: error decoding `$js': $@\n" if $@;
260         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
261         $m;
262 }
263
264 sub try_manifest {
265         my ($self) = @_;
266         my $uri = URI->new($self->{src});
267         my $lei = $self->{lei};
268         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
269         my $path = $uri->path;
270         chop($path) eq '/' or die "BUG: $uri not canonicalized";
271         $uri->path($path . '/manifest.js.gz');
272         my $pdir = $lei->rel2abs($self->{dst});
273         $pdir =~ s!/[^/]+/?\z!!;
274         my $ft = File::Temp->new(TEMPLATE => 'manifest-XXXX',
275                                 UNLINK => 1, DIR => $pdir);
276         my $fn = $ft->filename;
277         my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $fn);
278         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
279         my $cerr = run_reap($lei, $cmd, $opt);
280         if ($cerr) {
281                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
282                 return $lei->child_error($cerr, "@$cmd failed");
283         }
284         my $m = decode_manifest($ft, $fn, $uri);
285         my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
286         if (@v2_epochs) {
287                 # It may be possible to have v1 + v2 in parallel someday:
288                 $lei->err(<<EOM) if defined $v1_path;
289 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
290 # @v2_epochs
291 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
292 EOM
293                 @v2_epochs = map {
294                         $uri->path($path_pfx.$_);
295                         $uri->clone
296                 } @v2_epochs;
297                 clone_v2($self, \@v2_epochs);
298         } elsif (defined $v1_path) {
299                 clone_v1($self);
300         } else {
301                 die "E: confused by <$uri>, possible matches:\n\t",
302                         join(', ', sort keys %$m), "\n";
303         }
304         my $fin = "$self->{dst}/manifest.js.gz";
305         rename($fn, $fin) or die "E: rename($fn, $fin): $!";
306         $ft->unlink_on_destroy(0);
307 }
308
309 sub start_clone_url {
310         my ($self) = @_;
311         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
312         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
313 }
314
315 sub do_mirror { # via wq_io_do
316         my ($self) = @_;
317         my $lei = $self->{lei};
318         eval {
319                 my $iv = $lei->{opt}->{'inbox-version'};
320                 if (defined $iv) {
321                         return clone_v1($self) if $iv == 1;
322                         return try_scrape($self) if $iv == 2;
323                         die "bad --inbox-version=$iv\n";
324                 }
325                 return start_clone_url($self) if $self->{src} =~ m!://!;
326                 die "TODO: cloning local directories not supported, yet";
327         };
328         $lei->fail($@) if $@;
329 }
330
331 sub start {
332         my ($cls, $lei, $src, $dst) = @_;
333         my $self = bless { src => $src, dst => $dst }, $cls;
334         if ($src =~ m!https?://!) {
335                 require URI;
336                 require PublicInbox::LeiCurl;
337         }
338         require PublicInbox::Lock;
339         require PublicInbox::Inbox;
340         require PublicInbox::Admin;
341         require PublicInbox::InboxWritable;
342         my ($op_c, $ops) = $lei->workers_start($self, 1);
343         $lei->{wq1} = $self;
344         $self->wq_io_do('do_mirror', []);
345         $self->wq_close(1);
346         $lei->wait_wq_events($op_c, $ops);
347 }
348
349 sub ipc_atfork_child {
350         my ($self) = @_;
351         $self->{lei}->_lei_atfork_child;
352         $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
353         $self->SUPER::ipc_atfork_child;
354 }
355
356 1;