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 sub do_finish_mirror { # dwaitpid callback
14 my ($mrr, $lei) = @$arg;
15 my $f = "$mrr->{dst}/mirror.done";
17 $lei->child_error($?);
18 } elsif (!unlink($f)) {
19 $lei->err("unlink($f): $!");
21 $lei->add_external_finish($mrr->{dst});
22 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
27 sub mirror_done { # EOF callback for main daemon
29 my $mrr = delete $lei->{mrr} or return;
30 $mrr->wq_wait_old(\&do_finish_mirror, $lei);
33 # for old installations without manifest.js.gz
36 my $uri = URI->new($self->{src});
37 my $lei = $self->{lei};
38 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
39 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
40 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
41 my $fh = popen_rd($cmd, undef, $opt);
42 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
43 close($fh) or return $lei->child_error($?, "@$cmd failed");
45 # we grep with URL below, we don't want Subject/From headers
46 # making us clone random URLs
47 my @urls = ($html =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
48 my $url = $uri->as_string;
49 chop($url) eq '/' or die "BUG: $uri not canonicalized";
51 # since this is for old instances w/o manifest.js.gz, try v1 first
52 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
53 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
54 my %v2_uris = map { $_ => URI->new($_) } @v2_urls; # uniq
55 return clone_v2($self, [ values %v2_uris ]);
58 # filter out common URLs served by WWW (e.g /$MSGID/T/)
59 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
60 grep(m!\A\Q$url\E/*\z!, @urls)) {
62 E: confused by scraping <$uri>, did you mean <$url>?
66 E: confused by scraping <$uri>, got ambiguous results:
69 die "E: scraping <$uri> revealed nothing\n";
75 $opt->{$_} = $lei->{$_} for (0..2);
76 # we support "-c $key=$val" for arbitrary git config options
77 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
78 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
79 push @cmd, qw(clone --mirror);
80 push @cmd, '-q' if $lei->{opt}->{quiet};
81 push @cmd, '-v' if $lei->{opt}->{verbose};
82 # XXX any other options to support?
83 # --reference is tricky with multiple epochs...
87 # tries the relatively new /$INBOX/_/text/config/raw endpoint
90 my $dst = $self->{dst};
91 if (!-d $dst || !mkdir($dst)) {
93 File::Path::mkpath($dst);
94 -d $dst or die "mkpath($dst): $!\n";
96 my $uri = URI->new($self->{src});
97 my $lei = $self->{lei};
98 my $path = $uri->path;
99 chop($path) eq '/' or die "BUG: $uri not canonicalized";
100 $uri->path($path . '/_/text/config/raw');
101 my $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
102 my $ce = "$dst/inbox.config.example";
103 my $f = "$ce-$$.tmp";
104 open(my $fh, '+>', $f) or return $lei->err("open $f: $! (non-fatal)");
105 my $opt = { 0 => $lei->{0}, 1 => $fh, 2 => $lei->{2} };
106 my $cerr = run_reap($lei, $cmd, $opt) // return;
107 if (($cerr >> 8) == 22) { # 404 missing
108 unlink($f) if -s $fh == 0;
111 return $lei->err("# @$cmd failed (non-fatal)") if $cerr;
112 rename($f, $ce) or return $lei->err("link($f, $ce): $! (non-fatal)");
113 my $cfg = PublicInbox::Config->git_config_dump($f);
114 my $ibx = $self->{ibx} = {};
115 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
116 for (qw(address newsgroup nntpmirror)) {
117 $ibx->{$_} = $cfg->{"$sec.$_"};
122 sub index_cloned_inbox {
123 my ($self, $iv) = @_;
124 my $ibx = delete($self->{ibx}) // {
125 address => [ 'lei@example.com' ],
128 $ibx->{inboxdir} = $self->{dst};
129 PublicInbox::Inbox->new($ibx);
130 PublicInbox::InboxWritable->new($ibx);
132 my $lei = $self->{lei};
133 for my $sw ($lei->index_opt) {
134 my ($k) = ($sw =~ /\A([\w-]+)/);
135 $opt->{$k} = $lei->{opt}->{$k};
137 # force synchronous dwaitpid for v2:
138 local $PublicInbox::DS::in_loop = 0;
139 my $cfg = PublicInbox::Config->new;
140 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
141 local %ENV = (%ENV, %$env) if $env;
142 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
143 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
144 open my $x, '>', "$self->{dst}/mirror.done"; # for do_finish_mirror
148 my ($lei, $cmd, $opt) = @_;
149 $lei->qerr("# @$cmd");
151 my $pid = spawn($cmd, undef, $opt);
152 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
153 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
154 @$reap = (); # cancel reap
155 $err ? $lei->err($err) : $?
160 my $lei = $self->{lei};
161 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
162 my $uri = URI->new($self->{src});
163 my $pfx = $curl->torsocks($lei, $uri) or return;
164 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
165 $uri->as_string, $self->{dst} ];
166 my $cerr = run_reap($lei, $cmd, $opt) // return;
167 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
169 index_cloned_inbox($self, 1);
173 my ($self, $v2_uris) = @_;
174 my $lei = $self->{lei};
175 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
176 my $pfx //= $curl->torsocks($lei, $v2_uris->[0]) or return;
178 my $dst = $self->{dst};
180 for my $uri (@$v2_uris) {
181 my $src = $uri->as_string;
183 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
184 failed to extract epoch number from $src
187 $edst .= "/git/$nr.git";
188 push @src_edst, [ $src, $edst ];
190 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
192 my $on_destroy = $lk->lock_for_scope($$);
193 my @cmd = clone_cmd($lei, my $opt = {});
194 while (my $pair = shift(@src_edst)) {
195 my $cmd = [ @$pfx, @cmd, @$pair ];
196 my $cerr = run_reap($lei, $cmd, $opt) // return;
197 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
199 undef $on_destroy; # unlock
200 index_cloned_inbox($self, 2);
205 my $uri = URI->new($self->{src});
206 my $lei = $self->{lei};
207 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
208 my $path = $uri->path;
209 chop($path) eq '/' or die "BUG: $uri not canonicalized";
210 $uri->path($path . '/manifest.js.gz');
211 my $cmd = $curl->for_uri($lei, $uri);
212 $lei->qerr("# @$cmd");
213 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
214 my ($fh, $pid) = popen_rd($cmd, undef, $opt);
215 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
216 my $gz = do { local $/; <$fh> } // die "read(curl $uri): $!";
218 my $err = waitpid($pid, 0) == $pid ? undef : "waitpid @$cmd: $!";
220 return $lei->err($err) if $err;
222 return try_scrape($self) if ($? >> 8) == 22; # 404 missing
223 return $lei->child_error($?, "@$cmd failed");
226 gunzip(\$gz => \$js, MultiStream => 1) or
227 die "gunzip($uri): $GunzipError";
228 my $m = eval { PublicInbox::Config->json->decode($js) };
229 die "$uri: error decoding `$js': $@" if $@;
230 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
232 my $v1_bare = $m->{$path};
233 my @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
235 # It may be possible to have v1 + v2 in parallel someday:
236 $lei->err(<<EOM) if defined $v1_bare;
237 # `$v1_bare' appears to be a v1 inbox while v2 epochs exist:
239 # ignoring $v1_bare (use --inbox-version=1 to force v1 instead)
241 @v2_epochs = map { $uri->path($_); $uri->clone } @v2_epochs;
242 clone_v2($self, \@v2_epochs);
245 } elsif (my @maybe = grep(m!\Q$path\E!, keys %$m)) {
246 die "E: confused by <$uri>, possible matches:\n@maybe";
248 die "E: confused by <$uri>";
252 sub start_clone_url {
254 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
255 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
258 sub do_mirror { # via wq_io_do
260 my $lei = $self->{lei};
262 my $iv = $lei->{opt}->{'inbox-version'};
264 return clone_v1($self) if $iv == 1;
265 return try_scrape($self) if $iv == 2;
266 die "bad --inbox-version=$iv\n";
268 return start_clone_url($self) if $self->{src} =~ m!://!;
269 die "TODO: cloning local directories not supported, yet";
271 $lei->fail($@) if $@;
275 my ($cls, $lei, $src, $dst) = @_;
276 my $self = bless { src => $src, dst => $dst }, $cls;
277 if ($src =~ m!https?://!) {
279 require PublicInbox::LeiCurl;
281 require PublicInbox::Lock;
282 require PublicInbox::Inbox;
283 require PublicInbox::Admin;
284 require PublicInbox::InboxWritable;
285 my ($op, $ops) = $lei->workers_start($self, 'lei_mirror', 1, {
286 '' => [ \&mirror_done, $lei ]
289 $self->wq_io_do('do_mirror', []);
291 $op->op_wait_event($ops);
294 sub ipc_atfork_child {
296 $self->{lei}->_lei_atfork_child;
297 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
298 $self->SUPER::ipc_atfork_child;