]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Git.pm
git: idle rbuf for async
[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->{$out} = $out_w;
127         $self->{$in} = $in_r;
128 }
129
130 sub my_read ($$$) {
131         my ($fh, $rbuf, $len) = @_;
132         my $left = $len - length($$rbuf);
133         my $r;
134         while ($left > 0) {
135                 $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
136                 if ($r) {
137                         $left -= $r;
138                 } else {
139                         next if (!defined($r) && $! == EINTR);
140                         return $r;
141                 }
142         }
143         \substr($$rbuf, 0, $len, '');
144 }
145
146 sub my_readline ($$) {
147         my ($fh, $rbuf) = @_;
148         while (1) {
149                 if ((my $n = index($$rbuf, "\n")) >= 0) {
150                         return substr($$rbuf, 0, $n + 1, '');
151                 }
152                 my $r = sysread($fh, $$rbuf, $PIPE_BUFSIZ, length($$rbuf));
153                 next if $r || (!defined($r) && $! == EINTR);
154                 return defined($r) ? '' : undef; # EOF or error
155         }
156 }
157
158 sub cat_async_step ($$) {
159         my ($self, $inflight) = @_;
160         die 'BUG: inflight empty or odd' if scalar(@$inflight) < 2;
161         my ($cb, $arg) = splice(@$inflight, 0, 2);
162         my $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
163         my ($bref, $oid, $type, $size);
164         my $head = my_readline($self->{in}, $rbuf);
165         if ($head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/) {
166                 ($oid, $type, $size) = ($1, $2, $3 + 0);
167                 $bref = my_read($self->{in}, $rbuf, $size + 1) or
168                         fail($self, defined($bref) ? 'read EOF' : "read: $!");
169                 chop($$bref) eq "\n" or fail($self, 'LF missing after blob');
170         } elsif ($head !~ / missing$/) {
171                 fail($self, "Unexpected result from async git cat-file: $head");
172         }
173         eval { $cb->($bref, $oid, $type, $size, $arg) };
174         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
175         warn "E: $oid: $@\n" if $@;
176 }
177
178 sub cat_async_wait ($) {
179         my ($self) = @_;
180         my $inflight = delete $self->{inflight} or return;
181         while (scalar(@$inflight)) {
182                 cat_async_step($self, $inflight);
183         }
184 }
185
186 sub batch_prepare ($) {
187         _bidi_pipe($_[0], qw(--batch in out pid));
188 }
189
190 sub cat_file {
191         my ($self, $obj, $sizeref) = @_;
192         my ($retried, $head, $rbuf);
193         cat_async_wait($self);
194 again:
195         batch_prepare($self);
196         $rbuf = delete($self->{cat_rbuf}) // \(my $new = '');
197         print { $self->{out} } $obj, "\n" or fail($self, "write error: $!");
198         $head = my_readline($self->{in}, $rbuf);
199         if ($head =~ / missing$/) {
200                 if (!$retried && alternates_changed($self)) {
201                         $retried = 1;
202                         cleanup($self);
203                         goto again;
204                 }
205                 return;
206         }
207         $head =~ /^[0-9a-f]{40} \S+ ([0-9]+)$/ or
208                 fail($self, "Unexpected result from git cat-file: $head");
209
210         my $size = $1 + 0;
211         $$sizeref = $size if $sizeref;
212         my $ret = my_read($self->{in}, $rbuf, $size + 1);
213         $self->{cat_rbuf} = $rbuf if $$rbuf ne '';
214         fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
215         chop($$ret) eq "\n" or fail($self, 'newline missing after blob');
216         $ret;
217 }
218
219 sub check {
220         my ($self, $obj) = @_;
221         _bidi_pipe($self, qw(--batch-check in_c out_c pid_c err_c));
222         print { $self->{out_c} } $obj, "\n" or fail($self, "write error: $!");
223         my $rbuf = ''; # TODO: async + {chk_rbuf}
224         chomp(my $line = my_readline($self->{in_c}, \$rbuf));
225         my ($hex, $type, $size) = split(' ', $line);
226
227         # Future versions of git.git may show 'ambiguous', but for now,
228         # we must handle 'dangling' below (and maybe some other oddball
229         # stuff):
230         # https://public-inbox.org/git/20190118033845.s2vlrb3wd3m2jfzu@dcvr/T/
231         return if $type eq 'missing' || $type eq 'ambiguous';
232
233         if ($hex eq 'dangling' || $hex eq 'notdir' || $hex eq 'loop') {
234                 my $ret = my_read($self->{in_c}, \$rbuf, $type + 1);
235                 fail($self, defined($ret) ? 'read EOF' : "read: $!") if !$ret;
236                 return;
237         }
238
239         ($hex, $type, $size);
240 }
241
242 sub _destroy {
243         my ($self, $rbuf, $in, $out, $pid, $err) = @_;
244         my $p = delete $self->{$pid} or return;
245         delete @$self{($rbuf, $in, $out)};
246         delete $self->{$err} if $err; # `err_c'
247
248         # PublicInbox::DS may not be loaded
249         eval { PublicInbox::DS::dwaitpid($p, undef, undef) };
250         waitpid($p, 0) if $@; # wait synchronously if not in event loop
251 }
252
253 sub cat_async_abort ($) {
254         my ($self) = @_;
255         my $inflight = delete $self->{inflight} or die 'BUG: not in async';
256         cleanup($self);
257 }
258
259 sub fail {
260         my ($self, $msg) = @_;
261         $self->{inflight} ? cat_async_abort($self) : cleanup($self);
262         die $msg;
263 }
264
265 sub popen {
266         my ($self, @cmd) = @_;
267         @cmd = ('git', "--git-dir=$self->{git_dir}", @cmd);
268         popen_rd(\@cmd);
269 }
270
271 sub qx {
272         my ($self, @cmd) = @_;
273         my $fh = $self->popen(@cmd);
274         local $/ = "\n";
275         return <$fh> if wantarray;
276         local $/;
277         <$fh>
278 }
279
280 # returns true if there are pending "git cat-file" processes
281 sub cleanup {
282         my ($self) = @_;
283         cat_async_wait($self);
284         _destroy($self, qw(cat_rbuf in out pid));
285         _destroy($self, qw(chk_rbuf in_c out_c pid_c err_c));
286         !!($self->{pid} || $self->{pid_c});
287 }
288
289 # assuming a well-maintained repo, this should be a somewhat
290 # accurate estimation of its size
291 # TODO: show this in the WWW UI as a hint to potential cloners
292 sub packed_bytes {
293         my ($self) = @_;
294         my $n = 0;
295         my $pack_dir = git_path($self, 'objects/pack');
296         foreach my $p (bsd_glob("$pack_dir/*.pack", GLOB_NOSORT)) {
297                 $n += -s $p;
298         }
299         $n
300 }
301
302 sub DESTROY { cleanup(@_) }
303
304 sub local_nick ($) {
305         my ($self) = @_;
306         my $ret = '???';
307         # don't show full FS path, basename should be OK:
308         if ($self->{git_dir} =~ m!/([^/]+)(?:/\.git)?\z!) {
309                 $ret = "/path/to/$1";
310         }
311         wantarray ? ($ret) : $ret;
312 }
313
314 sub host_prefix_url ($$) {
315         my ($env, $url) = @_;
316         return $url if index($url, '//') >= 0;
317         my $scheme = $env->{'psgi.url_scheme'};
318         my $host_port = $env->{HTTP_HOST} //
319                 "$env->{SERVER_NAME}:$env->{SERVER_PORT}";
320         "$scheme://$host_port". ($env->{SCRIPT_NAME} || '/') . $url;
321 }
322
323 sub pub_urls {
324         my ($self, $env) = @_;
325         if (my $urls = $self->{cgit_url}) {
326                 return map { host_prefix_url($env, $_) } @$urls;
327         }
328         local_nick($self);
329 }
330
331 sub cat_async_begin {
332         my ($self) = @_;
333         cleanup($self) if alternates_changed($self);
334         batch_prepare($self);
335         die 'BUG: already in async' if $self->{inflight};
336         $self->{inflight} = [];
337 }
338
339 sub cat_async ($$$;$) {
340         my ($self, $oid, $cb, $arg) = @_;
341         my $inflight = $self->{inflight} // cat_async_begin($self);
342         if (scalar(@$inflight) >= MAX_INFLIGHT) {
343                 cat_async_step($self, $inflight);
344         }
345
346         print { $self->{out} } $oid, "\n" or fail($self, "write error: $!");
347         push(@$inflight, $cb, $arg);
348 }
349
350 sub extract_cmt_time {
351         my ($bref, undef, undef, undef, $modified) = @_;
352
353         if ($$bref =~ /^committer .*?> ([0-9]+) [\+\-]?[0-9]+/sm) {
354                 my $cmt_time = $1 + 0;
355                 $$modified = $cmt_time if $cmt_time > $$modified;
356         }
357 }
358
359 # returns the modified time of a git repo, same as the "modified" field
360 # of a grokmirror manifest
361 sub modified ($) {
362         my ($self) = @_;
363         my $modified = 0;
364         my $fh = popen($self, qw(rev-parse --branches));
365         local $/ = "\n";
366         while (my $oid = <$fh>) {
367                 chomp $oid;
368                 cat_async($self, $oid, \&extract_cmt_time, \$modified);
369         }
370         cat_async_wait($self);
371         $modified || time;
372 }
373
374 1;
375 __END__
376 =pod
377
378 =head1 NAME
379
380 PublicInbox::Git - git wrapper
381
382 =head1 VERSION
383
384 version 1.0
385
386 =head1 SYNOPSIS
387
388         use PublicInbox::Git;
389         chomp(my $git_dir = `git rev-parse --git-dir`);
390         $git_dir or die "GIT_DIR= must be specified\n";
391         my $git = PublicInbox::Git->new($git_dir);
392
393 =head1 DESCRIPTION
394
395 Unstable API outside of the L</new> method.
396 It requires L<git(1)> to be installed.
397
398 =head1 METHODS
399
400 =cut
401
402 =head2 new
403
404         my $git = PublicInbox::Git->new($git_dir);
405
406 Initialize a new PublicInbox::Git object for use with L<PublicInbox::Import>
407 This is the only public API method we support.  Everything else
408 in this module is subject to change.
409
410 =head1 SEE ALSO
411
412 L<Git>, L<PublicInbox::Import>
413
414 =head1 CONTACT
415
416 All feedback welcome via plain-text mail to L<mailto:meta@public-inbox.org>
417
418 The mail archives are hosted at L<https://public-inbox.org/meta/>
419
420 =head1 COPYRIGHT
421
422 Copyright (C) 2016 all contributors L<mailto:meta@public-inbox.org>
423
424 License: AGPL-3.0+ L<http://www.gnu.org/licenses/agpl-3.0.txt>
425
426 =cut