]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
lei: drop redundant WQ EOF callbacks
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) 2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn run_die);
11 use File::Temp ();
12 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
13
14 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
15         my ($arg, $pid) = @_;
16         my ($mrr, $lei) = @$arg;
17         my $f = "$mrr->{dst}/mirror.done";
18         if ($?) {
19                 $lei->child_error($?);
20         } elsif (!unlink($f)) {
21                 $lei->err("unlink($f): $!") unless $!{ENOENT};
22         } else {
23                 if ($lei->{cmd} ne 'public-inbox-clone') {
24                         $lei->add_external_finish($mrr->{dst});
25                 }
26                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
27         }
28         $lei->dclose;
29 }
30
31 # for old installations without manifest.js.gz
32 sub try_scrape {
33         my ($self) = @_;
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");
42
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";
48
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 ]);
54         }
55
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)) {
59                 die <<"";
60 E: confused by scraping <$uri>, did you mean <$url>?
61
62         }
63         @urls and die <<"";
64 E: confused by scraping <$uri>, got ambiguous results:
65 @urls
66
67         die "E: scraping <$uri> revealed nothing\n";
68 }
69
70 sub clone_cmd {
71         my ($lei, $opt) = @_;
72         my @cmd = qw(git);
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...
82         @cmd;
83 }
84
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);
103         undef; # success
104 }
105
106 # tries the relatively new /$INBOX/_/text/config/raw endpoint
107 sub _try_config {
108         my ($self) = @_;
109         my $dst = $self->{dst};
110         if (!-d $dst || !mkdir($dst)) {
111                 require File::Path;
112                 File::Path::mkpath($dst);
113                 -d $dst or die "mkpath($dst): $!\n";
114         }
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.$_"};
123                 }
124         }
125 }
126
127 sub set_description ($) {
128         my ($self) = @_;
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): $!";
139         }
140 }
141
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) };
148         warn $@ if $@;
149
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' ],
155                         version => $iv,
156                 };
157                 $ibx->{inboxdir} = $self->{dst};
158                 PublicInbox::Inbox->new($ibx);
159                 PublicInbox::InboxWritable->new($ibx);
160                 my $opt = {};
161                 for my $sw ($lei->index_opt) {
162                         my ($k) = ($sw =~ /\A([\w-]+)/);
163                         $opt->{$k} = $lei->{opt}->{$k};
164                 }
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);
172         }
173         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
174 }
175
176 sub run_reap {
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
184         $?
185 }
186
187 sub clone_v1 {
188         my ($self) = @_;
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;
197         _try_config($self);
198         write_makefile($self->{dst}, 1);
199         index_cloned_inbox($self, 1);
200 }
201
202 sub clone_v2 {
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};
208         my @src_edst;
209         for my $uri (@$v2_uris) {
210                 my $src = $uri->as_string;
211                 my $edst = $dst;
212                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
213 failed to extract epoch number from $src
214
215                 my $nr = $1 + 0;
216                 $edst .= "/git/$nr.git";
217                 push @src_edst, $src, $edst;
218         }
219         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
220         _try_config($self);
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;
227         }
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);
235 }
236
237 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
238 sub deduce_epochs ($$) {
239         my ($m, $path) = @_;
240         my ($v1_ent, @v2_epochs);
241         my $path_pfx = '';
242         $path =~ s!/+\z!!;
243         do {
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);
249 }
250
251 sub decode_manifest ($$$) {
252         my ($fh, $fn, $uri) = @_;
253         my $js;
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);
260         $m;
261 }
262
263 sub try_manifest {
264         my ($self) = @_;
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);
281         if ($cerr) {
282                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
283                 return $lei->child_error($cerr, "@$cmd failed");
284         }
285         my $m = decode_manifest($ft, $fn, $uri);
286         my ($path_pfx, $v1_path, @v2_epochs) = deduce_epochs($m, $path);
287         if (@v2_epochs) {
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:
291 # @v2_epochs
292 # ignoring $v1_path (use --inbox-version=1 to force v1 instead)
293 EOM
294                 @v2_epochs = map {
295                         $uri->path($path_pfx.$_);
296                         $uri->clone
297                 } @v2_epochs;
298                 clone_v2($self, \@v2_epochs);
299         } elsif (defined $v1_path) {
300                 clone_v1($self);
301         } else {
302                 die "E: confused by <$uri>, possible matches:\n\t",
303                         join(', ', sort keys %$m), "\n";
304         }
305         my $fin = "$self->{dst}/manifest.js.gz";
306         rename($fn, $fin) or die "E: rename($fn, $fin): $!";
307         $ft->unlink_on_destroy(0);
308 }
309
310 sub start_clone_url {
311         my ($self) = @_;
312         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
313         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
314 }
315
316 sub do_mirror { # via wq_io_do
317         my ($self) = @_;
318         my $lei = $self->{lei};
319         eval {
320                 my $iv = $lei->{opt}->{'inbox-version'};
321                 if (defined $iv) {
322                         return clone_v1($self) if $iv == 1;
323                         return try_scrape($self) if $iv == 2;
324                         die "bad --inbox-version=$iv\n";
325                 }
326                 return start_clone_url($self) if $self->{src} =~ m!://!;
327                 die "TODO: cloning local directories not supported, yet";
328         };
329         $lei->fail($@) if $@;
330 }
331
332 sub start {
333         my ($cls, $lei, $src, $dst) = @_;
334         my $self = bless { src => $src, dst => $dst }, $cls;
335         if ($src =~ m!https?://!) {
336                 require URI;
337                 require PublicInbox::LeiCurl;
338         }
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);
344         $lei->{wq1} = $self;
345         $self->wq_io_do('do_mirror', []);
346         $self->wq_close(1);
347         $lei->wait_wq_events($op_c, $ops);
348 }
349
350 sub ipc_atfork_child {
351         my ($self) = @_;
352         $self->{lei}->_lei_atfork_child;
353         $SIG{TERM} = sub { exit(128 + 15) }; # trigger OnDestroy $reap
354         $self->SUPER::ipc_atfork_child;
355 }
356
357 sub write_makefile {
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.
366 #
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.
370 #
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.
374 EOM
375                 print $fh <<'EOM' or die "print($f): $!";
376 # the default target:
377 help :
378         @echo Common targets:
379         @echo '    make fetch        - fetch from remote git repostorie(s)'
380         @echo '    make update       - fetch and update index '
381         @echo
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'
385
386 fetch :
387         public-inbox-fetch
388 update :
389         @if ! public-inbox-fetch --exit-code; \
390         then \
391                 c=$$?; \
392                 test $$c -eq 127 && exit 0; \
393                 exit $$c; \
394         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
395         then \
396                 public-inbox-index; \
397         else \
398                 echo 'public-inbox index not initialized'; \
399                 echo 'see public-inbox-index(1) man page'; \
400         fi
401 reindex :
402         public-inbox-index --reindex
403 compact :
404         public-inbox-compact
405
406 .PHONY : help fetch update reindex compact
407 EOM
408                 close $fh or die "close($f): $!";
409         } else {
410                 die "open($f): $!" unless $!{EEXIST};
411         }
412 }
413
414 1;