taskd: Guard against cloning projects not for clone or already being cloned
[girocco/mytab.git] / taskd / taskd.pl
blob264ac84d0c919f5a2f333ba603645438cecb14f0
1 #!/usr/bin/perl
3 # taskd - Clone repositories on request
5 # taskd is Girocco mirroring servant; it processes requests for clones
6 # of given URLs received over its socket.
8 # When a request is received, new process is spawned that sets up
9 # the repository and reports further progress
10 # to .clonelog within the repository. In case the clone fails,
11 # .clone_failed is touched and .clone_in_progress is removed.
13 # Protocol:
14 # Alice sets up repository and touches .cloning
15 # Alice opens connection to Bob
16 # Alice sends project name through the connection
17 # Bob opens the repository and sends back 0 if ok, error code otherwise
18 # Bob closes connection
19 # Alice polls .clonelog in case of 0.
20 # If Alice reads "@OVER@" from .clonelog, it stops polling.
22 # Based on perlipc example.
24 use strict;
25 use warnings;
27 use Girocco::Config;
28 use Girocco::Project;
29 use Socket;
31 $| = 1;
33 sub logmsg { print '['.(scalar localtime)."] $0 $$: @_\n" }
35 my $NAME = $Girocco::Config::chroot.'/etc/taskd.socket';
36 my $uaddr = sockaddr_un($NAME);
38 socket(Server, PF_UNIX, SOCK_STREAM, 0) or die "socket: $!";
39 unlink($NAME);
40 bind(Server, $uaddr) or die "bind: $!";
41 listen(Server, SOMAXCONN) or die "listen: $!";
42 chmod 0666, $NAME or die "chmod: $!";
45 use POSIX ":sys_wait_h";
46 sub REAPER {
47 my $child;
48 my $waitedpid;
49 while (($waitedpid = waitpid(-1, WNOHANG)) > 0) {
50 logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
52 $SIG{CHLD} = \&REAPER; # loathe sysV
55 $SIG{CHLD} = \&REAPER; # Apollo 440
57 sub spawn {
58 my $coderef = shift;
60 my $pid = fork;
61 if (not defined $pid) {
62 logmsg "cannot fork: $!";
63 return;
64 } elsif ($pid) {
65 logmsg "begat $pid";
66 return; # I'm the parent
69 open STDIN, "<&Client" or die "can't dup client to stdin";
70 open STDOUT, ">&Client" or die "can't dup client to stdout";
71 exit &$coderef();
74 sub clone {
75 my ($name) = @_;
76 my $proj = Girocco::Project->load($name);
77 $proj or die "failed to load project $name";
78 $proj->{clone_in_progress} or die "project $name is not marked for cloning";
79 $proj->{clone_logged} and die "project $name is already being cloned";
80 print STDERR "cloning $name\n";
81 open STDOUT, ">".$Girocco::Config::reporoot."/".$name.".git/.clonelog" or die "cannot open clonelog: $!";
82 open STDERR, ">&STDOUT";
83 open STDIN, "</dev/null";
84 exec $Girocco::Config::basedir.'/taskd/clone.sh', "$name.git" or die "exec failed: $!";
87 while (1) {
88 unless (accept(Client, Server)) {
89 logmsg "accept failed: $!";
90 next;
92 logmsg "connection on $NAME";
93 spawn sub {
94 my $inp = <>;
95 chomp $inp;
96 my ($cmd, $arg) = $inp =~ /^([a-zA-Z0-9-]+)\s+(.*)$/;
97 if ($cmd eq 'clone') {
98 clone($arg);
99 } else {
100 die "unknown command: $cmd";
103 close Client;
104 sleep 1;