]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Fetch.pm
imap+nntp: share COMPRESS implementation
[public-inbox.git] / lib / PublicInbox / Fetch.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # Wrapper to "git fetch" remote public-inboxes
4 package PublicInbox::Fetch;
5 use strict;
6 use v5.10.1;
7 use parent qw(PublicInbox::IPC);
8 use URI ();
9 use PublicInbox::Spawn qw(popen_rd run_die spawn);
10 use PublicInbox::Admin;
11 use PublicInbox::LEI;
12 use PublicInbox::LeiCurl;
13 use PublicInbox::LeiMirror;
14 use File::Temp ();
15 use PublicInbox::Config;
16 use IO::Compress::Gzip qw(gzip $GzipError);
17
18 sub new { bless {}, __PACKAGE__ }
19
20 sub fetch_args ($$) {
21         my ($lei, $opt) = @_;
22         my @cmd; # (git --git-dir=...) to be added by caller
23         $opt->{$_} = $lei->{$_} for (0..2);
24         # we support "-c $key=$val" for arbitrary git config options
25         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
26         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
27         push @cmd, 'fetch';
28         push @cmd, '-q' if $lei->{opt}->{quiet};
29         push @cmd, '-v' if $lei->{opt}->{verbose};
30         @cmd;
31 }
32
33 sub remote_url ($$) {
34         my ($lei, $dir) = @_;
35         my $rn = $lei->{opt}->{'try-remote'} // [ 'origin', '_grokmirror' ];
36         for my $r (@$rn) {
37                 my $cmd = [ qw(git config), "remote.$r.url" ];
38                 my $fh = popen_rd($cmd, undef, { -C => $dir, 2 => $lei->{2} });
39                 my $url = <$fh>;
40                 close $fh or next;
41                 $url =~ s!/*\n!!s;
42                 return $url;
43         }
44         undef
45 }
46
47 sub do_manifest ($$$) {
48         my ($lei, $dir, $ibx_uri) = @_;
49         my $muri = URI->new("$ibx_uri/manifest.js.gz");
50         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
51                                 UNLINK => 1, DIR => $dir, SUFFIX => '.tmp');
52         my $fn = $ft->filename;
53         my $mf = "$dir/manifest.js.gz";
54         my $m0; # current manifest.js.gz contents
55         if (open my $fh, '<', $mf) {
56                 $m0 = eval {
57                         PublicInbox::LeiMirror::decode_manifest($fh, $mf, $mf)
58                 };
59                 warn($@) if $@;
60         }
61         my ($bn) = ($fn =~ m!/([^/]+)\z!);
62         my $curl_cmd = $lei->{curl}->for_uri($lei, $muri, qw(-R -o), $bn);
63         my $opt = { -C => $dir };
64         $opt->{$_} = $lei->{$_} for (0..2);
65         my $cerr = PublicInbox::LeiMirror::run_reap($lei, $curl_cmd, $opt);
66         if ($cerr) {
67                 return [ 404, $muri ] if ($cerr >> 8) == 22; # 404 Missing
68                 $lei->child_error($cerr, "@$curl_cmd failed");
69                 return;
70         }
71         my $m1 = eval {
72                 PublicInbox::LeiMirror::decode_manifest($ft, $fn, $muri);
73         } or return [ 404, $muri ];
74         my $mdiff = { %$m1 };
75
76         # filter out unchanged entries.  We check modified, too, since
77         # fingerprints are SHA-1, so there's a teeny chance they'll collide
78         while (my ($k, $v0) = each %{$m0 // {}}) {
79                 my $cur = $m1->{$k} // next;
80                 my $f0 = $v0->{fingerprint} // next;
81                 my $f1 = $cur->{fingerprint} // next;
82                 my $t0 = $v0->{modified} // next;
83                 my $t1 = $cur->{modified} // next;
84                 delete($mdiff->{$k}) if $f0 eq $f1 && $t0 == $t1;
85         }
86         unless (keys %$mdiff) {
87                 $lei->child_error(127 << 8) if $lei->{opt}->{'exit-code'};
88                 return;
89         }
90         my (undef, $v1_path, @v2_epochs) =
91                 PublicInbox::LeiMirror::deduce_epochs($mdiff, $ibx_uri->path);
92         [ 200, $muri, $v1_path, \@v2_epochs, $ft, $mf, $m1 ];
93 }
94
95 sub get_fingerprint2 {
96         my ($git_dir) = @_;
97         require Digest::SHA;
98         my $rd = popen_rd([qw(git show-ref)], undef, { -C => $git_dir });
99         Digest::SHA::sha256(do { local $/; <$rd> });
100 }
101
102 sub writable_dir ($) {
103         my ($dir) = @_;
104         return unless -d $dir && -w _;
105         my @st = stat($dir);
106         $st[2] & 0222; # any writable bits set? (in case of root)
107 }
108
109 sub do_fetch { # main entry point
110         my ($cls, $lei, $cd) = @_;
111         my $ibx_ver;
112         $lei->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
113         my $dir = PublicInbox::Admin::resolve_inboxdir($cd, \$ibx_ver);
114         my ($ibx_uri, @git_dir, @epochs, $mg, @new_epoch, $skip);
115         if ($ibx_ver == 1) {
116                 my $url = remote_url($lei, $dir) //
117                         die "E: $dir missing remote.*.url\n";
118                 $ibx_uri = URI->new($url);
119         } else { # v2:
120                 require PublicInbox::MultiGit;
121                 $mg = PublicInbox::MultiGit->new($dir, 'all.git', 'git');
122                 @epochs = $mg->git_epochs;
123                 my ($git_url, $epoch);
124                 for my $nr (@epochs) { # try newest epoch, first
125                         my $edir = "$dir/git/$nr.git";
126                         if (!writable_dir($edir)) {
127                                 $skip->{$nr} = 1;
128                                 next;
129                         }
130                         next if defined $git_url;
131                         if (defined(my $url = remote_url($lei, $edir))) {
132                                 $git_url = $url;
133                                 $epoch = $nr;
134                         } else {
135                                 warn "W: $edir missing remote.*.url\n";
136                                 my $pid = spawn([qw(git config -l)], undef,
137                                         { 1 => $lei->{2}, 2 => $lei->{2} });
138                                 waitpid($pid, 0);
139                                 $lei->child_error($?) if $?;
140                         }
141                 }
142                 @epochs = grep { !$skip->{$_} } @epochs if $skip;
143                 $skip //= {}; # makes code below easier
144                 $git_url or die "Unable to determine git URL\n";
145                 my $inbox_url = $git_url;
146                 $inbox_url =~ s!/git/$epoch(?:\.git)?/?\z!! or
147                         $inbox_url =~ s!/$epoch(?:\.git)?/?\z!! or die <<EOM;
148 Unable to infer inbox URL from <$git_url>
149 EOM
150                 $ibx_uri = URI->new($inbox_url);
151         }
152         PublicInbox::LeiMirror::write_makefile($dir, $ibx_ver);
153         $lei->qerr("# inbox URL: $ibx_uri/");
154         my $res = do_manifest($lei, $dir, $ibx_uri) or return;
155         my ($code, $muri, $v1_path, $v2_epochs, $ft, $mf, $m1) = @$res;
156         if ($code == 404) {
157                 # any pre-manifest.js.gz instances running? Just fetch all
158                 # existing ones and unconditionally try cloning the next
159                 $v2_epochs = [ map { "$dir/git/$_.git" } @epochs ];
160                 if (@epochs) {
161                         my $n = $epochs[-1] + 1;
162                         push @$v2_epochs, "$dir/git/$n.git" if !$skip->{$n};
163                 }
164         } else {
165                 $code == 200 or die "BUG unexpected code $code\n";
166         }
167         my $mculled;
168         if ($ibx_ver == 2) {
169                 defined($v1_path) and warn <<EOM;
170 E: got v1 `$v1_path' when expecting v2 epoch(s) in <$muri>, WTF?
171 EOM
172                 @git_dir = map { "$dir/git/$_.git" } sort { $a <=> $b } map {
173                                 my ($nr) = (m!/([0-9]+)\.git\z!g);
174                                 $skip->{$nr} ? () : $nr;
175                         } @$v2_epochs;
176                 if ($m1 && scalar keys %$skip) {
177                         my $re = join('|', keys %$skip);
178                         my @del = grep(m!/git/$re\.git\z!, keys %$m1);
179                         delete @$m1{@del};
180                         $mculled = 1;
181                 }
182         } else {
183                 $git_dir[0] = $dir;
184         }
185         # n.b. this expects all epochs are from the same host
186         my $torsocks = $lei->{curl}->torsocks($lei, $muri);
187         my $fp2 = $lei->{opt}->{'exit-code'} ? [] : undef;
188         my $xit = 127;
189         for my $d (@git_dir) {
190                 my $cmd;
191                 my $opt = {}; # for spawn
192                 if (-d $d) {
193                         $fp2->[0] = get_fingerprint2($d) if $fp2;
194                         $cmd = [ @$torsocks, 'git', "--git-dir=$d",
195                                 fetch_args($lei, $opt) ];
196                 } else {
197                         my $e_uri = $ibx_uri->clone;
198                         my ($epath) = ($d =~ m!(/git/[0-9]+\.git)\z!);
199                         defined($epath) or
200                                 die "BUG: $d is not an epoch to clone\n";
201                         $e_uri->path($ibx_uri->path.$epath);
202                         $cmd = [ @$torsocks,
203                                 PublicInbox::LeiMirror::clone_cmd($lei, $opt),
204                                 $$e_uri, $d];
205                         push @new_epoch, substr($epath, 5, -4) + 0;
206                         $xit = 0;
207                 }
208                 my $cerr = PublicInbox::LeiMirror::run_reap($lei, $cmd, $opt);
209                 # do not bail on clone failure if we didn't have a manifest
210                 if ($cerr && ($code == 200 || -d $d)) {
211                         $lei->child_error($cerr, "@$cmd failed");
212                         return;
213                 }
214                 if ($fp2 && $xit) {
215                         $fp2->[1] = get_fingerprint2($d);
216                         $xit = 0 if $fp2->[0] ne $fp2->[1];
217                 }
218         }
219         for my $i (@new_epoch) { $mg->epoch_cfg_set($i) }
220         if ($ft) {
221                 if ($mculled) {
222                         my $json = PublicInbox::Config->json->encode($m1);
223                         my $fn = $ft->filename;
224                         gzip(\$json => $fn) or die "gzip: $GzipError";
225                 }
226                 PublicInbox::LeiMirror::ft_rename($ft, $mf, 0666);
227         }
228         $lei->child_error($xit << 8) if $fp2 && $xit;
229 }
230
231 1;