]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Fetch.pm
3b6aa389f383405981a17c047d8a9bcaddddfedf
[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 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
48 # TODO: remove, handle multi-inbox fetch
49 sub deduce_epochs ($$) {
50         my ($m, $path) = @_;
51         my ($v1_ent, @v2_epochs);
52         my $path_pfx = '';
53         $path =~ s!/+\z!!;
54         do {
55                 $v1_ent = $m->{$path};
56                 @v2_epochs = grep(m!\A\Q$path\E/git/[0-9]+\.git\z!, keys %$m);
57         } while (!defined($v1_ent) && !@v2_epochs &&
58                 $path =~ s!\A(/[^/]+)/!/! and $path_pfx .= $1);
59         ($path_pfx, $v1_ent ? $path : undef, @v2_epochs);
60 }
61
62 sub do_manifest ($$$) {
63         my ($lei, $dir, $ibx_uri) = @_;
64         my $muri = URI->new("$ibx_uri/manifest.js.gz");
65         my $ft = File::Temp->new(TEMPLATE => 'm-XXXX',
66                                 UNLINK => 1, DIR => $dir, SUFFIX => '.tmp');
67         my $fn = $ft->filename;
68         my $mf = "$dir/manifest.js.gz";
69         my $m0; # current manifest.js.gz contents
70         if (open my $fh, '<', $mf) {
71                 $m0 = eval {
72                         PublicInbox::LeiMirror::decode_manifest($fh, $mf, $mf)
73                 };
74                 warn($@) if $@;
75         }
76         my ($bn) = ($fn =~ m!/([^/]+)\z!);
77         my $curl_cmd = $lei->{curl}->for_uri($lei, $muri, qw(-R -o), $bn);
78         my $opt = { -C => $dir };
79         $opt->{$_} = $lei->{$_} for (0..2);
80         my $cerr = PublicInbox::LeiMirror::run_reap($lei, $curl_cmd, $opt);
81         if ($cerr) {
82                 return [ 404, $muri ] if ($cerr >> 8) == 22; # 404 Missing
83                 $lei->child_error($cerr, "@$curl_cmd failed");
84                 return;
85         }
86         my $m1 = eval {
87                 PublicInbox::LeiMirror::decode_manifest($ft, $fn, $muri);
88         } or return [ 404, $muri ];
89         my $mdiff = { %$m1 };
90
91         # filter out unchanged entries.  We check modified, too, since
92         # fingerprints are SHA-1, so there's a teeny chance they'll collide
93         while (my ($k, $v0) = each %{$m0 // {}}) {
94                 my $cur = $m1->{$k} // next;
95                 my $f0 = $v0->{fingerprint} // next;
96                 my $f1 = $cur->{fingerprint} // next;
97                 my $t0 = $v0->{modified} // next;
98                 my $t1 = $cur->{modified} // next;
99                 delete($mdiff->{$k}) if $f0 eq $f1 && $t0 == $t1;
100         }
101         unless (keys %$mdiff) {
102                 $lei->child_error(127 << 8) if $lei->{opt}->{'exit-code'};
103                 return;
104         }
105         my (undef, $v1_path, @v2_epochs) =
106                 deduce_epochs($mdiff, $ibx_uri->path);
107         [ 200, $muri, $v1_path, \@v2_epochs, $ft, $mf, $m1 ];
108 }
109
110 sub get_fingerprint2 {
111         my ($git_dir) = @_;
112         require Digest::SHA;
113         my $rd = popen_rd([qw(git show-ref)], undef, { -C => $git_dir });
114         Digest::SHA::sha256(do { local $/; <$rd> });
115 }
116
117 sub writable_dir ($) {
118         my ($dir) = @_;
119         return unless -d $dir && -w _;
120         my @st = stat($dir);
121         $st[2] & 0222; # any writable bits set? (in case of root)
122 }
123
124 sub do_fetch { # main entry point
125         my ($cls, $lei, $cd) = @_;
126         my $ibx_ver;
127         $lei->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
128         my $dir = PublicInbox::Admin::resolve_inboxdir($cd, \$ibx_ver);
129         my ($ibx_uri, @git_dir, @epochs, $mg, @new_epoch, $skip);
130         if ($ibx_ver == 1) {
131                 my $url = remote_url($lei, $dir) //
132                         die "E: $dir missing remote.*.url\n";
133                 $ibx_uri = URI->new($url);
134         } else { # v2:
135                 require PublicInbox::MultiGit;
136                 $mg = PublicInbox::MultiGit->new($dir, 'all.git', 'git');
137                 @epochs = $mg->git_epochs;
138                 my ($git_url, $epoch);
139                 for my $nr (@epochs) { # try newest epoch, first
140                         my $edir = "$dir/git/$nr.git";
141                         if (!writable_dir($edir)) {
142                                 $skip->{$nr} = 1;
143                                 next;
144                         }
145                         next if defined $git_url;
146                         if (defined(my $url = remote_url($lei, $edir))) {
147                                 $git_url = $url;
148                                 $epoch = $nr;
149                         } else {
150                                 warn "W: $edir missing remote.*.url\n";
151                                 my $pid = spawn([qw(git config -l)], undef,
152                                         { 1 => $lei->{2}, 2 => $lei->{2} });
153                                 waitpid($pid, 0);
154                                 $lei->child_error($?) if $?;
155                         }
156                 }
157                 @epochs = grep { !$skip->{$_} } @epochs if $skip;
158                 $skip //= {}; # makes code below easier
159                 $git_url or die "Unable to determine git URL\n";
160                 my $inbox_url = $git_url;
161                 $inbox_url =~ s!/git/$epoch(?:\.git)?/?\z!! or
162                         $inbox_url =~ s!/$epoch(?:\.git)?/?\z!! or die <<EOM;
163 Unable to infer inbox URL from <$git_url>
164 EOM
165                 $ibx_uri = URI->new($inbox_url);
166         }
167         PublicInbox::LeiMirror::write_makefile($dir, $ibx_ver);
168         $lei->qerr("# inbox URL: $ibx_uri/");
169         my $res = do_manifest($lei, $dir, $ibx_uri) or return;
170         my ($code, $muri, $v1_path, $v2_epochs, $ft, $mf, $m1) = @$res;
171         if ($code == 404) {
172                 # any pre-manifest.js.gz instances running? Just fetch all
173                 # existing ones and unconditionally try cloning the next
174                 $v2_epochs = [ map { "$dir/git/$_.git" } @epochs ];
175                 if (@epochs) {
176                         my $n = $epochs[-1] + 1;
177                         push @$v2_epochs, "$dir/git/$n.git" if !$skip->{$n};
178                 }
179         } else {
180                 $code == 200 or die "BUG unexpected code $code\n";
181         }
182         my $mculled;
183         if ($ibx_ver == 2) {
184                 defined($v1_path) and warn <<EOM;
185 E: got v1 `$v1_path' when expecting v2 epoch(s) in <$muri>, WTF?
186 EOM
187                 @git_dir = map { "$dir/git/$_.git" } sort { $a <=> $b } map {
188                                 my ($nr) = (m!/([0-9]+)\.git\z!g);
189                                 $skip->{$nr} ? () : $nr;
190                         } @$v2_epochs;
191                 if ($m1 && scalar keys %$skip) {
192                         my $re = join('|', keys %$skip);
193                         my @del = grep(m!/git/$re\.git\z!, keys %$m1);
194                         delete @$m1{@del};
195                         $mculled = 1;
196                 }
197         } else {
198                 $git_dir[0] = $dir;
199         }
200         # n.b. this expects all epochs are from the same host
201         my $torsocks = $lei->{curl}->torsocks($lei, $muri);
202         my $fp2 = $lei->{opt}->{'exit-code'} ? [] : undef;
203         my $xit = 127;
204         for my $d (@git_dir) {
205                 my $cmd;
206                 my $opt = {}; # for spawn
207                 if (-d $d) {
208                         $fp2->[0] = get_fingerprint2($d) if $fp2;
209                         $cmd = [ @$torsocks, 'git', "--git-dir=$d",
210                                 fetch_args($lei, $opt) ];
211                 } else {
212                         my $e_uri = $ibx_uri->clone;
213                         my ($epath) = ($d =~ m!(/git/[0-9]+\.git)\z!);
214                         defined($epath) or
215                                 die "BUG: $d is not an epoch to clone\n";
216                         $e_uri->path($ibx_uri->path.$epath);
217                         $cmd = [ @$torsocks,
218                                 PublicInbox::LeiMirror::clone_cmd($lei, $opt),
219                                 $$e_uri, $d];
220                         push @new_epoch, substr($epath, 5, -4) + 0;
221                         $xit = 0;
222                 }
223                 my $cerr = PublicInbox::LeiMirror::run_reap($lei, $cmd, $opt);
224                 # do not bail on clone failure if we didn't have a manifest
225                 if ($cerr && ($code == 200 || -d $d)) {
226                         $lei->child_error($cerr, "@$cmd failed");
227                         return;
228                 }
229                 if ($fp2 && $xit) {
230                         $fp2->[1] = get_fingerprint2($d);
231                         $xit = 0 if $fp2->[0] ne $fp2->[1];
232                 }
233         }
234         for my $i (@new_epoch) { $mg->epoch_cfg_set($i) }
235         if ($ft) {
236                 if ($mculled) {
237                         my $json = PublicInbox::Config->json->encode($m1);
238                         my $fn = $ft->filename;
239                         my $mtime = (stat($fn))[9];
240                         gzip(\$json => $fn) or die "gzip: $GzipError";
241                         utime($mtime, $mtime, $fn) or die "utime(..., $fn): $!";
242                 }
243                 PublicInbox::LeiMirror::ft_rename($ft, $mf, 0666);
244         }
245         $lei->child_error($xit << 8) if $fp2 && $xit;
246 }
247
248 1;