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);
11 use PublicInbox::PktOp;
13 sub do_finish_mirror { # dwaitpid callback
15 my ($mrr, $lei) = @$arg;
16 if ($? == 0 && unlink("$mrr->{dst}/mirror.done")) {
17 $lei->add_external_finish($mrr->{dst});
22 sub mirror_done { # EOF callback for main daemon
24 my $mrr = delete $lei->{mrr} or return;
25 $mrr->wq_wait_old(\&do_finish_mirror, $lei);
28 # for old installations without manifest.js.gz
31 my $uri = URI->new($self->{src});
32 my $lei = $self->{lei};
33 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
34 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
35 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
36 my $fh = popen_rd($cmd, $lei->{env}, $opt);
37 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
38 close($fh) or return $lei->child_error($?, "@$cmd failed");
40 # we grep with URL below, we don't want Subject/From headers
41 # making us clone random URLs
42 my @urls = ($html =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
43 my $url = $uri->as_string;
44 chop($url) eq '/' or die "BUG: $uri not canonicalized";
46 # since this is for old instances w/o manifest.js.gz, try v1 first
47 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
48 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
49 my %v2_uris = map { $_ => URI->new($_) } @v2_urls; # uniq
50 return clone_v2($self, [ values %v2_uris ]);
53 # filter out common URLs served by WWW (e.g /$MSGID/T/)
54 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
55 grep(m!\A\Q$url\E/*\z!, @urls)) {
57 E: confused by scraping <$uri>, did you mean <$url>?
61 E: confused by scraping <$uri>, got ambiguous results:
64 die "E: scraping <$uri> revealed nothing\n";
70 $opt->{$_} = $lei->{$_} for (0..2);
71 # we support "-c $key=$val" for arbitrary git config options
72 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
73 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
74 push @cmd, qw(clone --mirror);
75 push @cmd, '-q' if $lei->{opt}->{quiet};
76 push @cmd, '-v' if $lei->{opt}->{verbose};
77 # XXX any other options to support?
78 # --reference is tricky with multiple epochs...
82 # tries the relatively new /$INBOX/_/text/config/raw endpoint
85 my $dst = $self->{dst};
86 if (!-d $dst || !mkdir($dst)) {
88 File::Path::mkpath($dst);
89 -d $dst or die "mkpath($dst): $!\n";
91 my $uri = URI->new($self->{src});
92 my $lei = $self->{lei};
93 my $path = $uri->path;
94 chop($path) eq '/' or die "BUG: $uri not canonicalized";
95 $uri->path($path . '/_/text/config/raw');
96 my $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
97 my $ce = "$dst/inbox.config.example";
99 open(my $fh, '+>', $f) or return $lei->err("open $f: $! (non-fatal)");
100 my $opt = { 0 => $lei->{0}, 1 => $fh, 2 => $lei->{2} };
101 my $cerr = run_reap($lei, $cmd, $opt) // return;
102 if (($cerr >> 8) == 22) { # 404 missing
103 unlink($f) if -s $fh == 0;
106 return $lei->err("# @$cmd failed (non-fatal)") if $cerr;
107 rename($f, $ce) or return $lei->err("link($f, $ce): $! (non-fatal)");
108 my $cfg = PublicInbox::Config::git_config_dump($f);
109 my $ibx = $self->{ibx} = {};
110 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
111 for (qw(address newsgroup nntpmirror)) {
112 $ibx->{$_} = $cfg->{"$sec.$_"};
117 sub index_cloned_inbox {
118 my ($self, $iv) = @_;
119 my $ibx = delete($self->{ibx}) // {
120 address => [ 'lei@example.com' ],
123 $ibx->{inboxdir} = $self->{dst};
124 PublicInbox::Inbox->new($ibx);
125 PublicInbox::InboxWritable->new($ibx);
127 my $lei = $self->{lei};
128 for my $sw ($lei->index_opt) {
129 my ($k) = ($sw =~ /\A([\w-]+)/);
130 $opt->{$k} = $lei->{opt}->{$k};
132 # force synchronous dwaitpid for v2:
133 local $PublicInbox::DS::in_loop = 0;
134 my $cfg = PublicInbox::Config->new;
135 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
136 local %ENV = (%ENV, %$env) if $env;
137 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
138 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
139 open my $x, '>', "$self->{dst}/mirror.done"; # for do_finish_mirror
143 my ($lei, $cmd, $opt) = @_;
144 $lei->qerr("# @$cmd");
146 my $pid = spawn($cmd, $lei->{env}, $opt);
147 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
148 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
149 @$reap = (); # cancel reap
150 $err ? $lei->err($err) : $?
155 my $lei = $self->{lei};
156 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
157 my $uri = URI->new($self->{src});
158 my $pfx = $curl->torsocks($lei, $uri) or return;
159 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
160 $uri->as_string, $self->{dst} ];
161 my $cerr = run_reap($lei, $cmd, $opt) // return;
162 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
164 index_cloned_inbox($self, 1);
168 my ($self, $v2_uris) = @_;
169 my $lei = $self->{lei};
170 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
171 my $pfx //= $curl->torsocks($lei, $v2_uris->[0]) or return;
173 my $dst = $self->{dst};
175 for my $uri (@$v2_uris) {
176 my $src = $uri->as_string;
178 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
179 failed to extract epoch number from $src
182 $edst .= "/git/$nr.git";
183 push @src_edst, [ $src, $edst ];
185 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
187 my $on_destroy = $lk->lock_for_scope($$);
188 my @cmd = clone_cmd($lei, my $opt = {});
189 while (my $pair = shift(@src_edst)) {
190 my $cmd = [ @$pfx, @cmd, @$pair ];
191 my $cerr = run_reap($lei, $cmd, $opt) // return;
192 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
194 undef $on_destroy; # unlock
195 index_cloned_inbox($self, 2);
200 my $uri = URI->new($self->{src});
201 my $lei = $self->{lei};
202 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
203 my $path = $uri->path;
204 chop($path) eq '/' or die "BUG: $uri not canonicalized";
205 $uri->path($path . '/manifest.js.gz');
206 my $cmd = $curl->for_uri($lei, $uri);
207 $lei->qerr("# @$cmd");
208 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
209 my ($fh, $pid) = popen_rd($cmd, $lei->{env}, $opt);
210 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
211 my $gz = do { local $/; <$fh> } // die "read(curl $uri): $!";
213 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
215 return $lei->err($err) if $err;
217 return try_scrape($self) if ($? >> 8) == 22; # 404 missing
218 return $lei->child_error($?, "@$cmd failed");
221 gunzip(\$gz => \$js, MultiStream => 1) or
222 die "gunzip($uri): $GunzipError";
223 my $m = eval { PublicInbox::Config->json->decode($js) };
224 die "$uri: error decoding `$js': $@" if $@;
225 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
227 my $v1_bare = $m->{$path};
228 my @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
230 # It may be possible to have v1 + v2 in parallel someday:
231 $lei->err(<<EOM) if defined $v1_bare;
232 # `$v1_bare' appears to be a v1 inbox while v2 epochs exist:
234 # ignoring $v1_bare (use --inbox-version=1 to force v1 instead)
236 @v2_epochs = map { $uri->path($_); $uri->clone } @v2_epochs;
237 clone_v2($self, \@v2_epochs);
240 } elsif (my @maybe = grep(m!\Q$path\E!, keys %$m)) {
241 die "E: confused by <$uri>, possible matches:\n@maybe";
243 die "E: confused by <$uri>";
247 sub start_clone_url {
249 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
250 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
253 sub do_mirror { # via wq_io_do
255 my $lei = $self->{lei};
257 my $iv = $lei->{opt}->{'inbox-version'};
259 return clone_v1($self) if $iv == 1;
260 return try_scrape($self) if $iv == 2;
261 die "bad --inbox-version=$iv\n";
263 return start_clone_url($self) if $self->{src} =~ m!://!;
264 die "TODO: cloning local directories not supported, yet";
266 return $lei->fail($@) if $@;
267 $lei->qerr("# mirrored $self->{src} => $self->{dst}");
271 my ($cls, $lei, $src, $dst) = @_;
272 my $self = bless { lei => $lei, src => $src, dst => $dst }, $cls;
274 if ($src =~ m!https?://!) {
276 require PublicInbox::LeiCurl;
278 require PublicInbox::Lock;
279 require PublicInbox::Inbox;
280 require PublicInbox::Admin;
281 require PublicInbox::InboxWritable;
283 '!' => [ $lei->can('fail_handler'), $lei ],
284 'x_it' => [ $lei->can('x_it'), $lei ],
285 'child_error' => [ $lei->can('child_error'), $lei ],
286 '' => [ \&mirror_done, $lei ],
288 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
289 $self->wq_workers_start('lei_mirror', 1, $lei->oldset, {lei => $lei});
290 my $op = delete $lei->{pkt_op_c};
291 delete $lei->{pkt_op_p};
292 $self->wq_io_do('do_mirror', []);
294 $lei->event_step_init; # wait for shutdowns
295 if ($lei->{oneshot}) {
296 while ($op->{sock}) { $op->event_step }
300 sub ipc_atfork_child {
302 $self->{lei}->lei_atfork_child;
303 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
304 $self->SUPER::ipc_atfork_child;