]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
git: reduce stat buffer storage overhead
[public-inbox.git] / lib / PublicInbox / Git.pm
1 # Copyright (C) 2014-2020 all contributors <meta@public-inbox.org>
2 # License: GPLv2 or later <https://www.gnu.org/licenses/gpl-2.0.txt>
3 #
4 # Used to read files from a git repository without excessive forking.
5 # Used in our web interfaces as well as our -nntpd server.
6 # This is based on code in Git.pm which is GPLv2+, but modified to avoid
7 # dependence on environment variables for compatibility with mod_perl.
8 # There are also API changes to simplify our usage and data set.
9 package PublicInbox::Git;
10 use strict;
11 use warnings;
12 use POSIX ();
13 use IO::Handle; # ->autoflush
14 use File::Glob qw(bsd_glob GLOB_NOSORT);
15 use PublicInbox::Spawn qw(popen_rd);
16 use PublicInbox::Tmpfile;
17 use base qw(Exporter);
18 our @EXPORT_OK = qw(git_unquote git_quote);
19
20 use constant MAX_INFLIGHT =>
21         ($^O eq 'linux' ? 4096 : POSIX::_POSIX_PIPE_BUF())
22         /
23         65; # SHA-256 hex size + "\n" in preparation for git using non-SHA1
24
25 my %GIT_ESC = (
26         a => "\a",
27         b => "\b",
28         f => "\f",
29         n => "\n",
30         r => "\r",
31         t => "\t",
32         v => "\013",
33         '"' => '"',
34         '\\' => '\\',
35 );
36 my %ESC_GIT = map { $GIT_ESC{$_} => $_ } keys %GIT_ESC;
37
38
39 # unquote pathnames used by git, see quote.c::unquote_c_style.c in git.git
40 sub git_unquote ($) {
41         return $_[0] unless ($_[0] =~ /\A"(.*)"\z/);
42         $_[0] = $1;
43         $_[0] =~ s/\\([\\"abfnrtv])/$GIT_ESC{$1}/g;
44         $_[0] =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
45         $_[0];
46 }
47
48 sub git_quote ($) {
49         if ($_[0] =~ s/([\\"\a\b\f\n\r\t\013]|[^[:print:]])/
50                       '\\'.($ESC_GIT{$1}||sprintf("%0o",ord($1)))/egs) {
51                 return qq{"$_[0]"};
52         }
53         $_[0];
54 }
55
56 sub new {
57         my ($class, $git_dir) = @_;
58         # may contain {-tmp} field for File::Temp::Dir
59         bless { git_dir => $git_dir, alt_st => '', -git_path => {} }, $class
60 }
61
62 sub git_path ($$) {
63         my ($self, $path) = @_;
64         $self->{-git_path}->{$path} ||= do {
65                 local $/ = "\n";
66                 chomp(my $str = $self->qx(qw(rev-parse --git-path), $path));
67
68                 # git prior to 2.5.0 did not understand --git-path
69                 if ($str eq "--git-path\n$path") {
70                         $str = "$self->{git_dir}/$path";
71                 }
72                 $str;
73         };
74 }
75
76 sub alternates_changed {
77         my ($self) = @_;
78         my $alt = git_path($self, 'objects/info/alternates');
79         my @st = stat($alt) or return 0;
80
81         # can't rely on 'q' on some 32-bit builds, but `d' works
82         my $st = pack('dd', $st[10], $st[7]); # 10: ctime, 7: size
83         return 0 if $self->{alt_st} eq $st;
84         $self->{alt_st} = $st; # always a true value
85 }
86
87 sub last_check_err {
88         my ($self) = @_;
89         my $fh = $self->{err_c} or return;
90         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
91         defined(sysread($fh, my $buf, -s $fh)) or
92                         fail($self, "sysread failed: $!");
93         $buf;
94 }
95
96 sub _bidi_pipe {
97         my ($self, $batch, $in, $out, $pid, $err) = @_;
98         if ($self->{$pid}) {
99                 if (defined $err) { # "err_c"
100                         my $fh = $self->{$err};
101                         sysseek($fh, 0, 0) or fail($self, "sysseek failed: $!");
102                         truncate($fh, 0) or fail($self, "truncate failed: $!");
103                 }
104                 return;
105         }
106         my ($out_r, $out_w);
107         pipe($out_r, $out_w) or fail($self, "pipe failed: $!");
108         my @cmd = (qw(git), "--git-dir=$self->{git_dir}",
109                         qw(-c core.abbrev=40 cat-file), $batch);
110         my $redir = { 0 => $out_r };
111         if ($err) {
112                 my $id = "git.$self->{git_dir}$batch.err";
113                 my $fh = tmpfile($id) or fail($self, "tmpfile($id): $!");
114                 $self->{$err} = $fh;
115                 $redir->{2} = $fh;
116         }
117         my ($in_r, $p) = popen_rd(\@cmd, undef, $redir);
118         $self->{$pid} = $p;
119         $out_w->autoflush(1);
120         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ
121                 fcntl($out_w, 1031, 4096);
122                 fcntl($in_r, 1031, 4096) if $batch eq '--batch-check';
123         }
124         $self->{$out} = $out_w;
125         $self->{$in} = $in_r;
126 }
127
128 sub read_cat_in_full ($$$) {
129         my ($self, $in, $left) = @_;
130         my $offset = 0;
131         my $buf = '';
132         while ($left > 0) {
133                 my $r = read($in, $buf, $left, $offset);
134                 defined($r) or fail($self, "read failed: $!");
135                 $r == 0 and fail($self, 'exited unexpectedly');
136                 $left -= $r;
137                 $offset += $r;
138         }
139         my $r = read($in, my $lf, 1);
140         defined($r) or fail($self, "read failed: $!");
141         fail($self, 'newline missing after blob') if ($r != 1 || $lf ne "\n");
142         \$buf;
143 }
144
145 sub _cat_async_step ($$$) {
146         my ($self, $inflight, $in) = @_;
147         my $pair = shift @$inflight or die 'BUG: inflight empty';
148         my ($cb, $arg) = @$pair;
149         local $/ = "\n";
150         my $head = $in->getline;
151         $head =~ / missing$/ and return
152                 eval { $cb->(undef, undef, undef, undef, $arg) };
153
154         $head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/ or
155                 fail($self, "Unexpected result from async git cat-file: $head");
156         my ($oid_hex, $type, $size) = ($1, $2, $3 + 0);
157         my $bref = read_cat_in_full($self, $in, $size);
158         eval { $cb->($bref, $oid_hex, $type, $size, $arg) };
159 }
160
161 sub cat_async_wait ($) {
162         my ($self) = @_;
163         my $inflight = delete $self->{inflight} or return;
164         my $in = $self->{in};
165         while (scalar(@$inflight)) {
166                 _cat_async_step($self, $inflight, $in);
167         }
168 }
169
170 sub cat_file {
171         my ($self, $obj, $ref) = @_;
172         my ($retried, $in, $head);
173         cat_async_wait($self);
174 again:
175         batch_prepare($self);
176         $self->{out}->print($obj, "\n") or fail($self, "write error: $!");
177
178         $in = $self->{in};
179         local $/ = "\n";
180         $head = $in->getline;
181         if ($head =~ / missing$/) {
182                 if (!$retried && alternates_changed($self)) {
183                         $retried = 1;
184                         cleanup($self);
185                         goto again;
186                 }
187                 return;
188         }
189         $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
190                 fail($self, "Unexpected result from git cat-file: $head");
191
192         my $size = $1;
193         $$ref = $size if $ref;
194         read_cat_in_full($self, $in, $size);
195 }
196
197 sub batch_prepare ($) { _bidi_pipe($_[0], qw(--batch in out pid)) }
198
199 sub check {
200         my ($self, $obj) = @_;
201         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
202         $self->{out_c}->print($obj, "\n") or fail($self, "write error: $!");
203         local $/ = "\n";
204         chomp(my $line = $self->{in_c}->getline);
205         my ($hex, $type, $size) = split(' ', $line);
206
207         # Future versions of git.git may show 'ambiguous', but for now,
208         # we must handle 'dangling' below (and maybe some other oddball
209         # stuff):
210         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
211         return if $type eq 'missing' || $type eq 'ambiguous';
212
213         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
214                 $size = $type + length("\n");
215                 my $r = read($self->{in_c}, my $buf, $size);
216                 defined($r) or fail($self, "read failed: $!");
217                 return;
218         }
219
220         ($hex, $type, $size);
221 }
222
223 sub _destroy {
224         my ($self, $in, $out, $pid, $err) = @_;
225         my $p = delete $self->{$pid} or return;
226         delete @$self{($in, $out)};
227         delete $self->{$err} if $err; # `err_c'
228
229         # PublicInbox::DS may not be loaded
230         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
231         waitpid($p, 0) if $@; # wait synchronously if not in event loop
232 }
233
234 sub cat_async_abort ($) {
235         my ($self) = @_;
236         my $inflight = delete $self->{inflight} or die 'BUG: not in async';
237         cleanup($self);
238 }
239
240 sub fail {
241         my ($self, $msg) = @_;
242         $self->{inflight} ? cat_async_abort($self) : cleanup($self);
243         die $msg;
244 }
245
246 sub popen {
247         my ($self, @cmd) = @_;
248         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
249         popen_rd(\@cmd);
250 }
251
252 sub qx {
253         my ($self, @cmd) = @_;
254         my $fh = $self->popen(@cmd);
255         local $/ = "\n";
256         return <$fh> if wantarray;
257         local $/;
258         <$fh>
259 }
260
261 # returns true if there are pending "git cat-file" processes
262 sub cleanup {
263         my ($self) = @_;
264         _destroy($self, qw(in out pid));
265         _destroy($self, qw(in_c out_c pid_c err_c));
266         !!($self->{pid} || $self->{pid_c});
267 }
268
269 # assuming a well-maintained repo, this should be a somewhat
270 # accurate estimation of its size
271 # TODO: show this in the WWW UI as a hint to potential cloners
272 sub packed_bytes {
273         my ($self) = @_;
274         my $n = 0;
275         my $pack_dir = git_path($self, 'objects/pack');
276         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
277                 $n += -s $p;
278         }
279         $n
280 }
281
282 sub DESTROY { cleanup(@_) }
283
284 sub local_nick ($) {
285         my ($self) = @_;
286         my $ret = '???';
287         # don't show full FS path, basename should be OK:
288         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
289                 $ret = "/path/to/$1";
290         }
291         wantarray ? ($ret) : $ret;
292 }
293
294 sub host_prefix_url ($$) {
295         my ($env, $url) = @_;
296         return $url if index($url, '//') >= 0;
297         my $scheme = $env->{'psgi.url_scheme'};
298         my $host_port = $env->{HTTP_HOST} //
299                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
300         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
301 }
302
303 sub pub_urls {
304         my ($self, $env) = @_;
305         if (my $urls = $self->{cgit_url}) {
306                 return map { host_prefix_url($env, $_) } @$urls;
307         }
308         local_nick($self);
309 }
310
311 sub cat_async_begin {
312         my ($self) = @_;
313         cleanup($self) if alternates_changed($self);
314         batch_prepare($self);
315         die 'BUG: already in async' if $self->{inflight};
316         $self->{inflight} = [];
317 }
318
319 sub cat_async ($$$;$) {
320         my ($self, $oid, $cb, $arg) = @_;
321         my $inflight = $self->{inflight} or die 'BUG: not in async';
322         if (scalar(@$inflight) >= MAX_INFLIGHT) {
323                 _cat_async_step($self, $inflight, $self->{in});
324         }
325
326         $self->{out}->print($oid, "\n") or fail($self, "write error: $!");
327         push(@$inflight, [ $cb, $arg ]);
328 }
329
330 sub extract_cmt_time {
331         my ($bref, undef, undef, undef, $modified) = @_;
332
333         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
334                 my $cmt_time = $1 + 0;
335                 $$modified = $cmt_time if $cmt_time > $$modified;
336         }
337 }
338
339 # returns the modified time of a git repo, same as the "modified" field
340 # of a grokmirror manifest
341 sub modified ($) {
342         my ($self) = @_;
343         my $modified = 0;
344         my $fh = popen($self, qw(rev-parse --branches));
345         cat_async_begin($self);
346         local $/ = "\n";
347         while (my $oid = <$fh>) {
348                 chomp $oid;
349                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
350         }
351         cat_async_wait($self);
352         $modified || time;
353 }
354
355 1;
356 __END__
357 =pod
358
359 =head1 NAME
360
361 PublicInbox::Git - git wrapper
362
363 =head1 VERSION
364
365 version 1.0
366
367 =head1 SYNOPSIS
368
369         use PublicInbox::Git;
370         chomp(my $git_dir = `git rev-parse --git-dir`);
371         $git_dir or die "GIT_DIR= must be specified\n";
372         my $git = PublicInbox::Git->new($git_dir);
373
374 =head1 DESCRIPTION
375
376 Unstable API outside of the L</new> method.
377 It requires L<git(1)> to be installed.
378
379 =head1 METHODS
380
381 =cut
382
383 =head2 new
384
385         my $git = PublicInbox::Git->new($git_dir);
386
387 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
388 This is the only public API method we support.  Everything else
389 in this module is subject to change.
390
391 =head1 SEE ALSO
392
393 L<Git>, L<PublicInbox::Import>
394
395 =head1 CONTACT
396
397 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
398
399 The mail archives are hosted at L<https://public-inbox.org/meta/>
400
401 =head1 COPYRIGHT
402
403 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
404
405 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
406
407 =cut