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 (also "public-inbox-clone");
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 run_die);
12 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
14 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
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 # for old installations without manifest.js.gz
34 my $uri = URI->new($self->{src});
35 my $lei = $self->{lei};
36 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
37 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
38 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
39 my $fh = popen_rd($cmd, undef, $opt);
40 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
41 close($fh) or return $lei->child_error($?, "@$cmd failed");
43 # we grep with URL below, we don't want Subject/From headers
44 # making us clone random URLs
45 my @urls = ($html =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
46 my $url = $uri->as_string;
47 chop($url) eq '/' or die "BUG: $uri not canonicalized";
49 # since this is for old instances w/o manifest.js.gz, try v1 first
50 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
51 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
52 my %v2_uris = map { $_ => URI->new($_) } @v2_urls; # uniq
53 return clone_v2($self, [ values %v2_uris ]);
56 # filter out common URLs served by WWW (e.g /$MSGID/T/)
57 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
58 grep(m!\A\Q$url\E/*\z!, @urls)) {
60 E: confused by scraping <$uri>, did you mean <$url>?
64 E: confused by scraping <$uri>, got ambiguous results:
67 die "E: scraping <$uri> revealed nothing\n";
73 $opt->{$_} = $lei->{$_} for (0..2);
74 # we support "-c $key=$val" for arbitrary git config options
75 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
76 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
77 push @cmd, qw(clone --mirror);
78 push @cmd, '-q' if $lei->{opt}->{quiet};
79 push @cmd, '-v' if $lei->{opt}->{verbose};
80 # XXX any other options to support?
81 # --reference is tricky with multiple epochs...
85 sub _get_txt { # non-fatal
86 my ($self, $endpoint, $file) = @_;
87 my $uri = URI->new($self->{src});
88 my $lei = $self->{lei};
89 my $path = $uri->path;
90 chop($path) eq '/' or die "BUG: $uri not canonicalized";
91 $uri->path("$path/$endpoint");
92 my $cmd = $self->{curl}->for_uri($lei, $uri, '--compressed');
93 my $ce = "$self->{dst}/$file";
94 my $ft = File::Temp->new(TEMPLATE => "$file-XXXX",
95 UNLINK => 1, DIR => $self->{dst});
96 my $opt = { 0 => $lei->{0}, 1 => $ft, 2 => $lei->{2} };
97 my $cerr = run_reap($lei, $cmd, $opt);
98 return "$uri missing" if ($cerr >> 8) == 22;
99 return "# @$cmd failed (non-fatal)" if $cerr;
100 my $f = $ft->filename;
101 rename($f, $ce) or return "rename($f, $ce): $! (non-fatal)";
102 $ft->unlink_on_destroy(0);
106 # tries the relatively new /$INBOX/_/text/config/raw endpoint
109 my $dst = $self->{dst};
110 if (!-d $dst || !mkdir($dst)) {
112 File::Path::mkpath($dst);
113 -d $dst or die "mkpath($dst): $!\n";
115 my $err = _get_txt($self, qw(_/text/config/raw inbox.config.example));
116 return $self->{lei}->err($err) if $err;
117 my $f = "$self->{dst}/inbox.config.example";
118 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
119 my $ibx = $self->{ibx} = {};
120 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
121 for (qw(address newsgroup nntpmirror)) {
122 $ibx->{$_} = $cfg->{"$sec.$_"};
127 sub set_description ($) {
129 my $f = "$self->{dst}/description";
130 open my $fh, '+>>', $f or die "open($f): $!";
131 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
132 chomp(my $d = do { local $/; <$fh> } // die "read($f): $!");
133 if ($d eq '($INBOX_DIR/description missing)' ||
134 $d =~ /^Unnamed repository/ || $d !~ /\S/) {
135 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
136 truncate($fh, 0) or die "truncate($f): $!";
137 print $fh "mirror of $self->{src}\n" or die "print($f): $!";
138 close $fh or die "close($f): $!";
142 sub index_cloned_inbox {
143 my ($self, $iv) = @_;
144 my $lei = $self->{lei};
145 my $err = _get_txt($self, qw(description description));
146 $lei->err($err) if $err; # non fatal
147 eval { set_description($self) };
150 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
151 # lei is useless without Xapian + SQLite
152 if ($lei->{cmd} ne 'public-inbox-clone') {
153 my $ibx = delete($self->{ibx}) // {
154 address => [ 'lei@example.com' ],
157 $ibx->{inboxdir} = $self->{dst};
158 PublicInbox::Inbox->new($ibx);
159 PublicInbox::InboxWritable->new($ibx);
161 for my $sw ($lei->index_opt) {
162 my ($k) = ($sw =~ /\A([\w-]+)/);
163 $opt->{$k} = $lei->{opt}->{$k};
165 # force synchronous dwaitpid for v2:
166 local $PublicInbox::DS::in_loop = 0;
167 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
168 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
169 local %ENV = (%ENV, %$env) if $env;
170 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
171 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
173 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
177 my ($lei, $cmd, $opt) = @_;
178 $lei->qerr("# @$cmd");
179 $opt->{pgid} = 0 if $lei->{sock};
180 my $pid = spawn($cmd, undef, $opt);
181 my $reap = PublicInbox::OnDestroy->new($lei->can('sigint_reap'), $pid);
182 waitpid($pid, 0) == $pid or die "waitpid @$cmd: $!";
183 @$reap = (); # cancel reap
189 my $lei = $self->{lei};
190 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
191 my $uri = URI->new($self->{src});
192 my $pfx = $curl->torsocks($lei, $uri) or return;
193 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}),
194 $uri->as_string, $self->{dst} ];
195 my $cerr = run_reap($lei, $cmd, $opt);
196 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
198 write_makefile($self->{dst}, 1);
199 index_cloned_inbox($self, 1);
203 my ($self, $v2_uris) = @_;
204 my $lei = $self->{lei};
205 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
206 my $pfx //= $curl->torsocks($lei, $v2_uris->[0]) or return;
207 my $dst = $self->{dst};
209 for my $uri (@$v2_uris) {
210 my $src = $uri->as_string;
212 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
213 failed to extract epoch number from $src
216 $edst .= "/git/$nr.git";
217 push @src_edst, $src, $edst;
219 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
221 my $on_destroy = $lk->lock_for_scope($$);
222 my @cmd = clone_cmd($lei, my $opt = {});
223 while (my ($src, $edst) = splice(@src_edst, 0, 2)) {
224 my $cmd = [ @$pfx, @cmd, $src, $edst ];
225 my $cerr = run_reap($lei, $cmd, $opt);
226 return $lei->child_error($cerr, "@$cmd failed") if $cerr;
228 require PublicInbox::MultiGit;
229 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
230 $mg->fill_alternates;
231 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
232 write_makefile($self->{dst}, 2);
233 undef $on_destroy; # unlock
234 index_cloned_inbox($self, 2);
237 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
238 sub deduce_epochs ($$) {
240 my ($v1_ent, @v2_epochs);
244 $v1_ent = $m->{$path};
245 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
246 } while (!defined($v1_ent) && !@v2_epochs &&
247 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
248 ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
251 sub decode_manifest ($$$) {
252 my ($fh, $fn, $uri) = @_;
254 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
255 gunzip(\$gz => \$js, MultiStream => 1) or
256 die "gunzip($uri): $GunzipError\n";
257 my $m = eval { PublicInbox::Config->json->decode($js) };
258 die "$uri: error decoding `$js': $@\n" if $@;
259 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
265 my $uri = URI->new($self->{src});
266 my $lei = $self->{lei};
267 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
268 my $path = $uri->path;
269 chop($path) eq '/' or die "BUG: $uri not canonicalized";
270 $uri->path($path . '/manifest.js.gz');
271 my $pdir = $lei->rel2abs($self->{dst});
272 $pdir =~ s!/[^/]+/?\z!!;
273 my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
274 UNLINK => 1, DIR => $pdir, SUFFIX => '.tmp');
275 my $fn = $ft->filename;
276 my ($bn) = ($fn =~ m!/([^/]+)\z!);
277 my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $bn);
278 my $opt = { -C => $pdir };
279 $opt->{$_} = $lei->{$_} for (0..2);
280 my $cerr = run_reap($lei, $cmd, $opt);
282 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
283 return $lei->child_error($cerr, "@$cmd failed");
285 my $m = decode_manifest($ft, $fn, $uri);
286 my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
288 # It may be possible to have v1 + v2 in parallel someday:
289 $lei->err(<<EOM) if defined $v1_path;
290 # `$v1_path' appears to be a v1 inbox while v2 epochs exist:
292 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
295 $uri->path($path_pfx.$_);
298 clone_v2($self, \@v2_epochs);
299 } elsif (defined $v1_path) {
302 die "E: confused by <$uri>, possible matches:\n\t",
303 join(', ', sort keys %$m), "\n";
305 my $fin = "$self->{dst}/manifest.js.gz";
306 rename($fn, $fin) or die "E: rename($fn, $fin): $!";
307 $ft->unlink_on_destroy(0);
310 sub start_clone_url {
312 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
313 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
316 sub do_mirror { # via wq_io_do
318 my $lei = $self->{lei};
320 my $iv = $lei->{opt}->{'inbox-version'};
322 return clone_v1($self) if $iv == 1;
323 return try_scrape($self) if $iv == 2;
324 die "bad --inbox-version=$iv\n";
326 return start_clone_url($self) if $self->{src} =~ m!://!;
327 die "TODO: cloning local directories not supported, yet";
329 $lei->fail($@) if $@;
333 my ($cls, $lei, $src, $dst) = @_;
334 my $self = bless { src => $src, dst => $dst }, $cls;
335 if ($src =~ m!https?://!) {
337 require PublicInbox::LeiCurl;
339 require PublicInbox::Lock;
340 require PublicInbox::Inbox;
341 require PublicInbox::Admin;
342 require PublicInbox::InboxWritable;
343 my ($op_c, $ops) = $lei->workers_start($self, 1);
345 $self->wq_io_do('do_mirror', []);
347 $lei->wait_wq_events($op_c, $ops);
350 sub ipc_atfork_child {
352 $self->{lei}->_lei_atfork_child;
353 $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
354 $self->SUPER::ipc_atfork_child;
358 my ($dir, $ibx_ver) = @_;
359 my $f = "$dir/Makefile";
360 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
361 print $fh <<EOM or die "print($f) $!";
362 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
363 # manpage for more information on the format. This Makefile is
364 # intended as a familiar wrapper for users unfamiliar with
365 # public-inbox-* commands.
367 # See the respective manpages for public-inbox-fetch(1),
368 # public-inbox-index(1), etc for more information on
369 # some of the commands used by this Makefile.
371 # This Makefile will not be modified nor read by public-inbox,
372 # so you may edit it freely with your own convenience targets
373 # and notes. public-inbox-fetch will recreate it if removed.
375 print $fh <<'EOM' or die "print($f): $!";
376 # the default target:
378 @echo Common targets:
379 @echo ' make fetch - fetch from remote git repostorie(s)'
380 @echo ' make update - fetch and update index '
382 @echo Rarely needed targets:
383 @echo ' make reindex - may be needed for new features/bugfixes'
384 @echo ' make compact - rewrite Xapian storage to save space'
389 @if ! public-inbox-fetch --exit-code; \
392 test $$c -eq 127 && exit 0; \
394 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
396 public-inbox-index; \
398 echo 'public-inbox index not initialized'; \
399 echo 'see public-inbox-index(1) man page'; \
402 public-inbox-index --reindex
406 .PHONY : help fetch update reindex compact
408 close $fh or die "close($f): $!";
410 die "open($f): $!" unless $!{EEXIST};