1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # "lei add-external --mirror" support
5 package PublicInbox::LeiMirror;
8 use parent qw(PublicInbox::IPC);
9 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn);
12 use Fcntl qw(SEEK_SET);
14 sub do_finish_mirror { # dwaitpid callback
16 my ($mrr, $lei) = @$arg;
17 my $f = "$mrr->{dst}/mirror.done";
19 $lei->child_error($?);
20 } elsif (!unlink($f)) {
21 $lei->err("unlink($f): $!") unless $!{ENOENT};
23 if ($lei->{cmd} ne 'public-inbox-clone') {
24 $lei->add_external_finish($mrr->{dst});
26 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
31 sub _lei_wq_eof { # EOF callback for main daemon
33 my $mrr = delete $lei->{wq1} or return $lei->fail;
34 $mrr->wq_wait_old(\&do_finish_mirror, $lei);
37 # for old installations without manifest.js.gz
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");
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";
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 ]);
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)) {
66 E: confused by scraping <$uri>, did you mean <$url>?
70 E: confused by scraping <$uri>, got ambiguous results:
73 die "E: scraping <$uri> revealed nothing\n";
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...
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);
112 # tries the relatively new /$INBOX/_/text/config/raw endpoint
115 my $dst = $self->{dst};
116 if (!-d $dst || !mkdir($dst)) {
118 File::Path::mkpath($dst);
119 -d $dst or die "mkpath($dst): $!\n";
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.$_"};
133 sub set_description ($) {
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): $!";
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) };
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' ],
163 $ibx->{inboxdir} = $self->{dst};
164 PublicInbox::Inbox->new($ibx);
165 PublicInbox::InboxWritable->new($ibx);
167 for my $sw ($lei->index_opt) {
168 my ($k) = ($sw =~ /\A([\w-]+)/);
169 $opt->{$k} = $lei->{opt}->{$k};
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);
179 open my $x, '>', "$self->{dst}/mirror.done"; # for do_finish_mirror
183 my ($lei, $cmd, $opt) = @_;
184 $lei->qerr("# @$cmd");
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
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;
204 index_cloned_inbox($self, 1);
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;
213 my $dst = $self->{dst};
215 for my $uri (@$v2_uris) {
216 my $src = $uri->as_string;
218 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
219 failed to extract epoch number from $src
222 $edst .= "/git/$nr.git";
223 push @src_edst, [ $src, $edst ];
225 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
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;
234 undef $on_destroy; # unlock
235 index_cloned_inbox($self, 2);
238 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
239 sub deduce_epochs ($$) {
241 my ($v1_bare, @v2_epochs);
245 $v1_bare = $m->{$path};
246 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
247 } while (!defined($v1_bare) && !@v2_epochs &&
248 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
249 ($path_pfx, $v1_bare, @v2_epochs);
252 sub decode_manifest ($$$) {
253 my ($fh, $fn, $uri) = @_;
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);
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);
281 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
282 return $lei->child_error($cerr, "@$cmd failed");
284 my $m = decode_manifest($ft, $fn, $uri);
285 my ($path_pfx, $v1_bare, @v2_epochs) = deduce_epochs($m, $path);
287 # It may be possible to have v1 + v2 in parallel someday:
288 $lei->err(<<EOM) if defined $v1_bare;
289 # `$v1_bare' appears to be a v1 inbox while v2 epochs exist:
291 # ignoring $v1_bare (use --inbox-version=1 to force v1 instead)
294 $uri->path($path_pfx.$_);
297 clone_v2($self, \@v2_epochs);
298 my $fin = "$self->{dst}/manifest.js.gz";
299 rename($fn, $fin) or die "E: rename($fn, $fin): $!";
300 $ft->unlink_on_destroy(0);
301 } elsif (defined $v1_bare) {
304 die "E: confused by <$uri>, possible matches:\n\t",
305 join(', ', sort keys %$m), "\n";
309 sub start_clone_url {
311 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
312 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
315 sub do_mirror { # via wq_io_do
317 my $lei = $self->{lei};
319 my $iv = $lei->{opt}->{'inbox-version'};
321 return clone_v1($self) if $iv == 1;
322 return try_scrape($self) if $iv == 2;
323 die "bad --inbox-version=$iv\n";
325 return start_clone_url($self) if $self->{src} =~ m!://!;
326 die "TODO: cloning local directories not supported, yet";
328 $lei->fail($@) if $@;
332 my ($cls, $lei, $src, $dst) = @_;
333 my $self = bless { src => $src, dst => $dst }, $cls;
334 if ($src =~ m!https?://!) {
336 require PublicInbox::LeiCurl;
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);
344 $self->wq_io_do('do_mirror', []);
346 $lei->wait_wq_events($op_c, $ops);
349 sub ipc_atfork_child {
351 $self->{lei}->_lei_atfork_child;
352 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
353 $self->SUPER::ipc_atfork_child;