chiark / gitweb /
git-cache-proxy: more wip, restructure done, before add housekeeping
[chiark-utils.git] / scripts / git-cache-proxy
1 #!/usr/bin/perl -w
2 #
3 # git caching proxy
4
5 # usage: run it on some port, and then clone or fetch
6 #  "git://<realhost>:<realport>/<real-git-url>[ <options>]"
7 # where <real-git-url> is http://<host>/... or git://<host>/...
8 # and <options> is zero or more (whitespace-separated) of
9 #    [<some-option>]      will be ignored if not recognised
10 #    {<some-option>}      error if not recognised
11 # options currently known:
12 #    fetch=must           fail if the fetch/clone from upstream fails
13 #    fetch=no             just use what is in the cache
14 #    fetch=try            use what is in the cache if the fetch/clone fails
15 #    timeout=<seconds>    length of time to allow for fetch/clone
16
17 # git-cache-proxy is free software; you can redistribute it and/or
18 # modify them under the terms of the GNU General Public License as
19 # published by the Free Software Foundation; either version 3, or (at
20 # your option) any later version.
21
22 # git-cache-proxy is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25 # General Public License for more details.
26
27 # You should have received a copy of the GNU General Public License along
28 # with this program; if not, consult the Free Software Foundation's
29 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
30
31 # (Some code taken from userv-utils's git-daemon.in and git-service.in
32 # which were written by Tony Finch <dot@dotat.at> and subsequently
33 # heavily modified by Ian Jackson <ijackson@chiark.greenend.org.uk>
34 # and were released under CC0 1.0.  The whole program is now GPLv3+.)
35
36 use strict;
37 use warnings;
38
39 use POSIX;
40 use Socket;
41 use Sys::Syslog;
42 use Fcntl qw(:flock SEEK_SET);
43
44 our $us = 'git-cache-proxy';
45
46 #---------- error handling and logging ----------
47
48 # This is a bit fiddly, because we want to catch errors sent to stderr
49 # and dump them to syslog if we can, but only if we are running as an
50 # inetd service.
51
52 our $log; # filehandle (ref), or "1" meaning syslog
53
54 sub ntoa {
55     my $sockaddr = shift;
56     return ('(local)') unless defined $sockaddr;
57     my ($port,$addr) = sockaddr_in $sockaddr;
58     $addr = inet_ntoa $addr;
59     return ("[$addr]:$port",$addr,$port);
60 }
61
62 our ($client) = ntoa getpeername STDIN;
63 our ($server) = ntoa getsockname STDIN;
64
65 sub ensurelog () {
66     return if $log;
67     openlog $us, qw(pid), 'daemon';
68     $log = 1;
69 }
70
71 sub logm ($$) {
72     my ($pri, $msg) = @_;
73     if ($client eq '(local)') {
74         print STDERR "$us: $pri: $msg\n" or die $!;
75         exit 1;
76     }
77     ensurelog();
78     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
79     if (ref $log) {
80         my $wholemsg = sprintf("%s [%d] %s: %s\n",
81                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
82                                $$,
83                                $pri,
84                                $mainmsg);
85         print $log $wholemsg;
86     } else {
87         syslog $pri, $mainmsg;
88     }
89 }
90
91 if ($client ne '(local)') {
92     open STDERR, ">/dev/null" or exit 255;
93     open TEMPERR, "+>", undef or exit 255;
94     open STDERR, ">&TEMPERR" or exit 255;
95 }
96
97 END {
98     if ($client ne '(local)') {
99         if ($?) { logm 'crit', "crashing ($?)"; }
100         seek TEMPERR, 0, SEEK_SET;
101         while (<TEMPERR>) {
102             chomp;
103             logm 'crit', $_;
104         }
105     }
106     exit $?;
107 }
108
109 sub fail ($) {
110     my ($msg) = @_;
111     logm 'err', $msg;
112     exit 0;
113 }
114
115 sub gitfail ($) {
116     my ($msg) = @_;
117     close LOCK;
118     alarm 60;
119     logm 'notice', $msg;
120     my $gitmsg = "ERR $us: $msg";
121     $gitmsg = substr($gitmsg,0,65535); # just in case
122     printf "%04x%s", length($gitmsg)+4, $gitmsg;
123     flush STDOUT;
124     exit 0;
125 }
126
127 #---------- argument parsing ----------
128
129 our $fetchtimeout = 1800;
130 our $maxfetchtimeout = 3600;
131 our $cachedir = '/var/cache/git-cache-proxy';
132
133 for (;;) {
134     last unless @ARGV;
135     last unless $ARGV[0] =~ m/^-/;
136     $_ = shift @ARGV;
137     for (;;) {
138         last unless m/^-./;
139         if (s/^-L(.*)$//) {
140             my $logfile = $_;
141             open STDERR, ">>", $logfile or fail "open $logfile: $!";
142             $log = \*STDERR;
143         } elsif (s/^-d(.*)$//) {
144             $cachedir = $1;
145         } elsif (s/^--(maxfetchtimeout|fetchtimeout)=(\d+)$//) {
146             ${ $::{$1} } = $2;
147         } else {
148             fail "bad usage: unknown option `$_'";
149         }
150     }
151 }
152
153 !@ARGV or fail "bad usage: no non-option arguments permitted";
154
155 #---------- main program ----------
156
157 chdir $cachedir or fail "chdir $cachedir: $!";
158
159 our ($service,$specpath,$spechost,$subdir);
160 our ($tmpd,$gitd,$lock);
161 our ($fetch,$url);
162
163 sub xread {
164     my $length = shift;
165     my $buffer = "";
166     while ($length > length $buffer) {
167         my $ret = sysread STDIN, $buffer, $length, length $buffer;
168         fail "expected $length bytes, got ".length $buffer
169                             if defined $ret and $ret == 0;
170         fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
171     }
172     return $buffer;
173 }
174
175 sub readcommand () {
176     $SIG{ALRM} = sub { fail "timeout" };
177     alarm 30;
178
179     my $hex_len = xread 4;
180     fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
181     my $line = xread -4 + hex $hex_len;
182     unless (($service,$specpath,$spechost) = $line =~
183             m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
184         $line =~ s|[^ -~]+| |g;
185         gitfail "unknown/unsupported instruction `$line'"
186     }
187
188     alarm 0;
189
190     $service eq 'git-upload-pack'
191         or gitfail "unknown/unsupported service `$service'";
192
193     $fetch = 2; # 0:don't; 1:try; 2:force
194     $url = $specpath;
195
196     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
197            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
198         $_ = $2;
199         my $must = $1 eq '{';
200         if (m/^fetch=try$/) {
201             $fetch = 1;
202         } elsif (m/^fetch=no$/) {
203             $fetch = 0;
204         } elsif (m/^fetch=must$/) {
205             $fetch = 2; # the default
206         } elsif (m/^timeout=(\d+)$/) {
207             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
208         } elsif ($must) {
209             gitfail "unknown/unsupported option `$_'";
210         }
211     }
212
213     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
214         or gitfail "unknown/unsupported url scheme or format `$url'";
215
216     $subdir = $url;
217     $subdir =~ s|\\|\\\\|g;
218     $subdir =~ s|,|\\,|g;
219     $subdir =~ s|/|,|g;
220
221     logm 'info', "$specpath locking";
222     
223     $tmpd= "$subdir\\.tmp";
224     $gitd= "$subdir\\.git";
225     $lock = "$subdir\\.lock";
226 }
227
228 sub clonefetch () {
229     open LOCK, "+>", $lock or fail "open/create $lock: $!";
230     flock LOCK, LOCK_EX or fail "lock exclusive $lock: $!";
231
232     my $exists = stat $gitd;
233     $exists or $!==ENOENT or fail "stat $gitd: $!";
234
235     our $fetchfail = '';
236
237     if ($fetch) {
238
239         our @cmd;
240
241         if (!$exists) {
242             system qw(rm -rf --), $tmpd;
243             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
244             logm 'info', "$specpath cloning @cmd";
245         } else {
246             @cmd = (qw(git remote update --prune));
247             logm 'info', "$specpath fetching @cmd";
248         }
249         my $cmd = "@cmd[0..1]";
250
251         my $child = open FETCHERR, "-|";
252         defined $child or fail "fork: $!";
253         if (!$child) {
254             if ($exists) {
255                 chdir $gitd or fail "chdir $gitd: $!";
256             }
257             setpgrp or fail "setpgrp: $!";
258             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
259             exec @cmd or fail "exec $cmd[0]: $!";
260         }
261
262         my $fetcherr = '';
263         my $timedout = 0;
264         {
265             local $SIG{ALRM} = sub {
266                 logm 'info', "$specpath fetch/clone timeout";
267                 $timedout=1; kill 9, -$child;
268             };
269 logm 'info', "timeout=$fetchtimeout";
270             alarm($fetchtimeout);
271             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
272             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
273             alarm(10);
274         }
275
276         kill -9, $child or fail "kill fetch/clone: $!";
277         $!=0; $?=0; if (!close FETCHERR) {
278             fail "reap fetch/clone: $!" if $!;
279             my $fetchfail =
280                 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
281                 $? != 9 ? "$cmd died due to fatal signa, status $?" :
282                 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
283                 "$cmd died due to unexpected SIGKILL";
284             if (length $fetcherr) {
285                 $fetchfail .= "\n$fetcherr";
286                 $fetchfail =~ s/\n$//;
287                 $fetchfail =~ s{\n}{ // }g;
288             }
289             if ($fetch >= 2) {
290                 gitfail $fetchfail;
291             } else {
292                 logm 'info', "$specpath fetch/clone failed: $fetchfail";
293             }
294         }
295
296         if (!$exists) {
297             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
298             $exists = 1;
299         }
300     } else {
301         $fetchfail = 'not attempted';
302     }
303
304     if (!$exists) {
305         gitfail "no cached data, and not cloned: $fetchfail";
306     }
307
308     logm 'info', "$specpath sharing";
309     flock LOCK, LOCK_UN or fail "unlock $lock: $!";
310     flock LOCK, LOCK_SH or fail "lock shared $lock: $!";
311     # actually, just relocking as shared would have the same semantics
312     # but it's best to be explicit
313
314     if (chdir $gitd) {
315         return 1;
316     }
317     $!==ENOENT or fail "chdir $gitd: $!";
318
319     # Well, err, someone must have taken the lock in between
320     # and garbage collected it.  How annoying.
321     return 0;
322 }
323
324 sub runcommand () {
325     logm 'info', "$specpath servicing";
326     exec qw(git-upload-pack --strict --timeout=1000 .)
327         or fail "exec git-upload-pack: $!";
328 }
329
330 sub daemonservice () {
331     readcommand();
332     while (!clonefetch()) { }
333     runcommand();
334 }
335
336 daemonservice();