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