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);
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);
97 push @$cmd, '--compressed'; # curl decompresses for us
98 my $ce = "$dst/inbox.config.example";
100 open(my $fh, '+>', $f) or return $lei->err("open $f: $! (non-fatal)");
101 my $opt = { 0 => $lei->{0}, 1 => $fh, 2 => $lei->{2} };
102 my $cerr = run_reap($lei, $cmd, $opt) // return;
103 if (($cerr >> 8) == 22) { # 404 missing
104 unlink($f) if -s $fh == 0;
107 return $lei->err("# @$cmd failed (non-fatal)") if $cerr;
108 rename($f, $ce) or return $lei->err("link($f, $ce): $! (non-fatal)");
109 my $cfg = PublicInbox::Config::git_config_dump($f);
110 my $ibx = $self->{ibx} = {};
111 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
112 for (qw(address newsgroup nntpmirror)) {
113 $ibx->{$_} = $cfg->{"$sec.$_"};
118 sub index_cloned_inbox {
119 my ($self, $iv) = @_;
120 my $ibx = delete($self->{ibx}) // {
121 address => [ 'lei@example.com' ],
124 $ibx->{inboxdir} = $self->{dst};
125 PublicInbox::Inbox->new($ibx);
126 PublicInbox::InboxWritable->new($ibx);
128 my $lei = $self->{lei};
129 for my $sw ($lei->index_opt) {
130 my ($k) = ($sw =~ /\A([\w-]+)/);
131 $opt->{$k} = $lei->{opt}->{$k};
133 # force synchronous dwaitpid for v2:
134 local $PublicInbox::DS::in_loop = 0;
135 my $cfg = PublicInbox::Config->new;
136 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
137 local %ENV = (%ENV, %$env) if $env;
138 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
139 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
140 open my $x, '>', "$self->{dst}/mirror.done"; # for do_finish_mirror
144 my ($lei, $cmd, $opt) = @_;
145 $lei->qerr("# @$cmd");
147 my $pid = spawn($cmd, $lei->{env}, $opt);
148 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
149 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
150 @$reap = (); # cancel reap
151 $err ? $lei->err($err) : $?
156 my $lei = $self->{lei};
157 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
158 my $uri = URI->new($self->{src});
159 my $pfx = $curl->torsocks($lei, $uri) or return;
160 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
161 $uri->as_string, $self->{dst} ];
162 my $cerr = run_reap($lei, $cmd, $opt) // return;
163 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
165 index_cloned_inbox($self, 1);
169 my ($self, $v2_uris) = @_;
170 my $lei = $self->{lei};
171 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
172 my $pfx //= $curl->torsocks($lei, $v2_uris->[0]) or return;
174 my $dst = $self->{dst};
176 for my $uri (@$v2_uris) {
177 my $src = $uri->as_string;
179 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
180 failed to extract epoch number from $src
183 $edst .= "/git/$nr.git";
184 push @src_edst, [ $src, $edst ];
186 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
188 my $on_destroy = $lk->lock_for_scope($$);
189 my @cmd = clone_cmd($lei, my $opt = {});
190 while (my $pair = shift(@src_edst)) {
191 my $cmd = [ @$pfx, @cmd, @$pair ];
192 my $cerr = run_reap($lei, $cmd, $opt) // return;
193 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
195 undef $on_destroy; # unlock
196 index_cloned_inbox($self, 2);
201 my $uri = URI->new($self->{src});
202 my $lei = $self->{lei};
203 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
204 my $path = $uri->path;
205 chop($path) eq '/' or die "BUG: $uri not canonicalized";
206 $uri->path($path . '/manifest.js.gz');
207 my $cmd = $curl->for_uri($lei, $uri);
208 $lei->qerr("# @$cmd");
209 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
210 my ($fh, $pid) = popen_rd($cmd, $lei->{env}, $opt);
211 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
212 my $gz = do { local $/; <$fh> } // die "read(curl $uri): $!";
214 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
216 return $lei->err($err) if $err;
218 return try_scrape($self) if ($? >> 8) == 22; # 404 missing
219 return $lei->child_error($?, "@$cmd failed");
222 gunzip(\$gz => \$js, MultiStream => 1) or
223 die "gunzip($uri): $GunzipError";
224 my $m = eval { PublicInbox::Config->json->decode($js) };
225 die "$uri: error decoding `$js': $@" if $@;
226 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
228 my $v1_bare = $m->{$path};
229 my @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
231 # It may be possible to have v1 + v2 in parallel someday:
232 $lei->err(<<EOM) if defined $v1_bare;
233 # `$v1_bare' appears to be a v1 inbox while v2 epochs exist:
235 # ignoring $v1_bare (use --inbox-version=1 to force v1 instead)
237 @v2_epochs = map { $uri->path($_); $uri->clone } @v2_epochs;
238 clone_v2($self, \@v2_epochs);
241 } elsif (my @maybe = grep(m!\Q$path\E!, keys %$m)) {
242 die "E: confused by <$uri>, possible matches:\n@maybe";
244 die "E: confused by <$uri>";
248 sub start_clone_url {
250 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
251 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
254 sub do_mirror { # via wq_do
256 my $lei = $self->{lei};
258 my $iv = $lei->{opt}->{'inbox-version'};
260 return clone_v1($self) if $iv == 1;
261 return try_scrape($self) if $iv == 2;
262 die "bad --inbox-version=$iv\n";
264 return start_clone_url($self) if $self->{src} =~ m!://!;
265 die "TODO: cloning local directories not supported, yet";
267 return $lei->fail($@) if $@;
268 $lei->qerr("# mirrored $self->{src} => $self->{dst}");
272 my ($cls, $lei, $src, $dst) = @_;
273 my $self = bless { lei => $lei, src => $src, dst => $dst }, $cls;
275 if ($src =~ m!https?://!) {
277 require PublicInbox::LeiCurl;
279 require PublicInbox::Lock;
280 require PublicInbox::Inbox;
281 require PublicInbox::Admin;
282 require PublicInbox::InboxWritable;
284 '!' => [ $lei->can('fail_handler'), $lei ],
285 'x_it' => [ $lei->can('x_it'), $lei ],
286 'child_error' => [ $lei->can('child_error'), $lei ],
287 '' => [ \&mirror_done, $lei ],
289 ($lei->{pkt_op_c}, $lei->{pkt_op_p}) = PublicInbox::PktOp->pair($ops);
290 $self->wq_workers_start('lei_mirror', 1, $lei->oldset, {lei => $lei});
291 my $op = delete $lei->{pkt_op_c};
292 delete $lei->{pkt_op_p};
293 $self->wq_do('do_mirror', []);
295 $lei->event_step_init; # wait for shutdowns
296 if ($lei->{oneshot}) {
297 while ($op->{sock}) { $op->event_step }
301 sub ipc_atfork_child {
303 $self->{lei}->lei_atfork_child;
304 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
305 $self->SUPER::ipc_atfork_child;