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