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