chiark / gitweb /
git-cache-proxy: introduce lockfile
[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 use File::Path qw(remove_tree);
44
45 our $us = 'git-cache-proxy';
46
47 #---------- error handling and logging ----------
48
49 # This is a bit fiddly, because we want to catch errors sent to stderr
50 # and dump them to syslog if we can, but only if we are running as an
51 # inetd service.
52
53 our $log; # filehandle (ref), or "1" meaning syslog
54
55 sub ntoa {
56     my $sockaddr = shift;
57     return ('(local)') unless defined $sockaddr;
58     my ($port,$addr) = sockaddr_in $sockaddr;
59     $addr = inet_ntoa $addr;
60     return ("[$addr]:$port",$addr,$port);
61 }
62
63 our ($client) = ntoa getpeername STDIN;
64 our ($server) = ntoa getsockname STDIN;
65
66 sub ensurelog () {
67     return if $log;
68     openlog $us, qw(pid), 'daemon';
69     $log = 1;
70 }
71
72 sub logm ($$) {
73     my ($pri, $msg) = @_;
74     if ($client eq '(local)') {
75         print STDERR "$us: $pri: $msg\n" or die $!;
76         exit 1;
77     }
78     ensurelog();
79     my $mainmsg = sprintf "%s-%s: %s", $server, $client, $msg;
80     if (ref $log) {
81         my $wholemsg = sprintf("%s [%d] %s: %s\n",
82                                strftime("%Y-%m-%d %H:%M:%S Z", gmtime),
83                                $$,
84                                $pri,
85                                $mainmsg);
86         print $log $wholemsg;
87     } else {
88         syslog $pri, $mainmsg;
89     }
90 }
91
92 if ($client ne '(local)') {
93     open STDERR, ">/dev/null" or exit 255;
94     open TEMPERR, "+>", undef or exit 255;
95     open STDERR, ">&TEMPERR" or exit 255;
96 }
97
98 END {
99     if ($client ne '(local)') {
100         if ($?) { logm 'crit', "crashing ($?)"; }
101         seek TEMPERR, 0, SEEK_SET;
102         while (<TEMPERR>) {
103             chomp;
104             logm 'crit', $_;
105         }
106     }
107     exit $?;
108 }
109
110 sub fail ($) {
111     my ($msg) = @_;
112     logm 'err', $msg;
113     exit 0;
114 }
115
116 sub gitfail ($) {
117     my ($msg) = @_;
118     close LOCK;
119     alarm 60;
120     logm 'notice', $msg;
121     my $gitmsg = "ERR $us: $msg";
122     $gitmsg = substr($gitmsg,0,65535); # just in case
123     printf "%04x%s", length($gitmsg)+4, $gitmsg;
124     flush STDOUT;
125     exit 0;
126 }
127
128 #---------- argument parsing ----------
129
130 our $housekeepingthreshdays = 1;
131 our $treeexpiredays = 21;
132 our $fetchtimeout = 1800;
133 our $maxfetchtimeout = 3600;
134 our $cachedir = '/var/cache/git-cache-proxy';
135
136 for (;;) {
137     last unless @ARGV;
138     last unless $ARGV[0] =~ m/^-/;
139     $_ = shift @ARGV;
140     for (;;) {
141         last unless m/^-./;
142         if (s/^-L(.*)$//) {
143             my $logfile = $_;
144             open STDERR, ">>", $logfile or fail "open $logfile: $!";
145             $log = \*STDERR;
146         } elsif (s/^-d(.*)$//) {
147             $cachedir = $1;
148         } elsif (s/^--(maxfetchtimeout|fetchtimeout)=(\d+)$//) {
149             ${ $::{$1} } = $2;
150         } else {
151             fail "bad usage: unknown option `$_'";
152         }
153     }
154 }
155
156 !@ARGV or fail "bad usage: no non-option arguments permitted";
157
158 #---------- utility functions ----------
159
160 sub lockfile ($$) {
161     my ($fh, $fn, $flockmode) = @_;
162     for (;;) {
163         close $fh;
164         open $fh, '+>', $fn or fail "open/create $fn for lock: $!";
165         if (!flock $fh, $lockmode) {
166             if ($lockmode & LOCK_NB and $! == EWOULDBLOCK) {
167                 return 0; # ok then
168             }
169             fail "lock $fn".
170                 (($flockmode & ~LOCK_NB) == LOCK_SH ? " (shared)" : "").
171                 ": $!";
172         }
173         stat $fh or fail "stat opened $fn: $!";
174         my $fh_ino = ((stat _)[1]);
175         if (!stat $fn) {
176             $! == ENOENT or fail "stat $fn: $!";
177             next;
178         }
179         my $fn_ino = ((stat _)[1]);
180         return 1 if $fn_ino == $fh_ino;
181         # oh dear
182     }
183 }
184
185 sub xread {
186     my $length = shift;
187     my $buffer = "";
188     while ($length > length $buffer) {
189         my $ret = sysread STDIN, $buffer, $length, length $buffer;
190         fail "expected $length bytes, got ".length $buffer
191                             if defined $ret and $ret == 0;
192         fail "read: $!" if not defined $ret and $! != EINTR and $! != EAGAIN;
193     }
194     return $buffer;
195 }
196
197 #---------- main program ----------
198
199 chdir $cachedir or fail "chdir $cachedir: $!";
200
201 our ($service,$specpath,$spechost,$subdir);
202 our ($tmpd,$gitd,$lock);
203 our ($fetch,$url);
204
205 sub servinfo ($) {
206     my ($msg) = @_;
207     logm 'info', "service `$specpath': $msg";
208 }
209
210 sub readcommand () {
211     $SIG{ALRM} = sub { fail "timeout" };
212     alarm 30;
213
214     my $hex_len = xread 4;
215     fail "Bad hex in packet length" unless $hex_len =~ m|^[0-9a-fA-F]{4}$|;
216     my $line = xread -4 + hex $hex_len;
217     unless (($service,$specpath,$spechost) = $line =~
218             m|^(git-[a-z-]+) /*([!-~ ]+)\0host=([!-~]+)\0$|) {
219         $line =~ s|[^ -~]+| |g;
220         gitfail "unknown/unsupported instruction `$line'"
221     }
222
223     alarm 0;
224
225     $service eq 'git-upload-pack'
226         or gitfail "unknown/unsupported service `$service'";
227
228     $fetch = 2; # 0:don't; 1:try; 2:force
229     $url = $specpath;
230
231     while ($url =~ s#\s+(\[)([^][{}]+)\]$## ||
232            $url =~ s#\s+(\{)([^][{}]+)\}$##) {
233         $_ = $2;
234         my $must = $1 eq '{';
235         if (m/^fetch=try$/) {
236             $fetch = 1;
237         } elsif (m/^fetch=no$/) {
238             $fetch = 0;
239         } elsif (m/^fetch=must$/) {
240             $fetch = 2; # the default
241         } elsif (m/^timeout=(\d+)$/) {
242             $fetchtimeout = $1 <= $maxfetchtimeout ? $1 : $maxfetchtimeout;
243         } elsif ($must) {
244             gitfail "unknown/unsupported option `$_'";
245         }
246     }
247
248     $url =~ m{^(?:https?|git)://[-.0-9a-z]+/}
249         or gitfail "unknown/unsupported url scheme or format `$url'";
250
251     $subdir = $url;
252     $subdir =~ s|\\|\\\\|g;
253     $subdir =~ s|,|\\,|g;
254     $subdir =~ s|/|,|g;
255
256     $tmpd= "$subdir\\.tmp";
257     $gitd= "$subdir\\.git";
258     $lock = "$subdir\\.lock";
259
260     servinfo "locking";
261 }
262
263 sub clonefetch () {
264     lockfile \*LOCK, $lock, LOCK_EX;
265
266     my $exists = lstat $gitd;
267     $exists or $!==ENOENT or fail "lstat $gitd: $!";
268
269     our $fetchfail = '';
270
271     if ($fetch) {
272
273         our @cmd;
274
275         if (!$exists) {
276             system qw(rm -rf --), $tmpd;
277             @cmd = (qw(git clone -q --mirror), $url, $tmpd);
278             servinfo "cloning";
279         } else {
280             @cmd = (qw(git remote update --prune));
281             servinfo "fetching";
282         }
283         my $cmd = "@cmd[0..1]";
284
285         my $child = open FETCHERR, "-|";
286         defined $child or fail "fork: $!";
287         if (!$child) {
288             if ($exists) {
289                 chdir $gitd or fail "chdir $gitd: $!";
290             }
291             setpgrp or fail "setpgrp: $!";
292             open STDERR, ">&STDOUT" or fail "redirect stderr: $!";
293             exec @cmd or fail "exec $cmd[0]: $!";
294         }
295
296         my $fetcherr = '';
297         my $timedout = 0;
298         {
299             local $SIG{ALRM} = sub {
300                 servinfo "fetch/clone timeout";
301                 $timedout=1; kill 9, -$child;
302             };
303             alarm($fetchtimeout);
304             $!=0; { local $/=undef; $fetcherr = <FETCHERR>; }
305             !FETCHERR->error or fail "read pipe from fetch/clone: $!";
306             alarm(10);
307         }
308
309         kill -9, $child or fail "kill fetch/clone: $!";
310         $!=0; $?=0; if (!close FETCHERR) {
311             fail "reap fetch/clone: $!" if $!;
312             my $fetchfail =
313                 !($? & 255) ? "$cmd died with error exit code ".($? >> 8) :
314                 $? != 9 ? "$cmd died due to fatal signa, status $?" :
315                 $timedout ? "$cmd timed out (${fetchtimeout}s)" :
316                 "$cmd died due to unexpected SIGKILL";
317             if (length $fetcherr) {
318                 $fetchfail .= "\n$fetcherr";
319                 $fetchfail =~ s/\n$//;
320                 $fetchfail =~ s{\n}{ // }g;
321             }
322             if ($fetch >= 2) {
323                 gitfail $fetchfail;
324             } else {
325                 servinfo "fetch/clone failed: $fetchfail";
326             }
327         }
328
329         if (!$exists) {
330             rename $tmpd, $gitd or fail "rename fresh $tmpd to $gitd: $!";
331             $exists = 1;
332         }
333     } else {
334         $fetchfail = 'not attempted';
335     }
336
337     if (!$exists) {
338         gitfail "no cached data, and not cloned: $fetchfail";
339     }
340
341     servinfo "sharing";
342     lockfile \*LOCK, $lock, LOCK_SH; # NB releases and relocks
343
344     if (chdir $gitd) {
345         return 1;
346     }
347     $!==ENOENT or fail "chdir $gitd: $!";
348
349     # Well, err, someone must have taken the lock in between
350     # and garbage collected it.  How annoying.
351     return 0;
352 }
353
354 sub housekeeping () {
355     foreach $lock (<[a-z]*\\.lock>) {
356         if (!lstat $lock) {
357             $! == ENOENT or fail "housekeeping: $lock: lstat: $!";
358             next;
359         }
360         if (-M _ <= $treeexpiredays) {
361             logm 'debug', "housekeeping: $lock: not too old";
362             next;
363         }
364         my $subdir = $lock;  $subdir =~ s/\\.lock$//;
365         my $ok = 1;
366         foreach my $suffix (qw(tmp git)) {
367             my $dir = "${subdir}\\.$suffix";
368             my $errs;
369             remove_tree($dir, { safe=>1, error=>\$errs });
370             $ok = 0 if @$errs;
371             foreach my $err (@$errs) {
372                 logm 'warning', "problem deleting: $err[0]: $err[1]";
373             }
374         }
375         if ($ok) {
376             
377
378 sub housekeepingcheck ($$) {
379     my ($dofork, $force) = @_;
380         or fail "open/create Housekeeping.lock: $!";
381     if (!$force) {
382         if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
383             logm 'debug', "housekeeping lock taken, not running";
384             close HLOCK;
385             return 0;
386         }
387     }
388     if ($force) {
389         logm 'info', "housekeeping forced";
390     } elsif (!lstat "Housekeeping.stamp") {
391         $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
392         logm 'info', "housekeeping stamp missing, will run";
393     } elsif (-M _ <= $housekeepingthreshdays) {
394         logm 'debug', "housekeeping done recently";
395         close HLOCK;
396         return 0;
397     }
398     if ($dofork) {
399         my $child = fork;
400         defined $child or fail "fork for housekeeping: $!";
401         if (!$child) {
402             housekeeping();
403             exit 0;
404         }
405         return 1;
406     } else {
407         housekeeping();
408         return 1;
409     }
410 }
411
412 sub runcommand () {
413     servinfo "servicing";
414     exec qw(git-upload-pack --strict --timeout=1000 .)
415         or fail "exec git-upload-pack: $!";
416 }
417
418 sub daemonservice () {
419     readcommand();
420     while (!clonefetch()) { }
421     runcommand();
422 }
423
424 daemonservice();