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