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