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