gc.sh: joyfully fix furtive typos
[girocco/readme.git] / taskd / taskd.pl
blob1d11b965d8484cadc82d3ccfd92bce81a4597d63
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 # Clone 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 error code if there is a problem
18 # Bob closes connection
19 # Alice polls .clonelog in case of success.
20 # If Alice reads "@OVER@" from .clonelog, it stops polling.
22 # Ref-change protocol:
23 # Alice opens connection to Bob
24 # Alice sends ref-change command for each changed ref
25 # Alice closes connection
26 # Bob sends out notifications
28 # Initially based on perlipc example.
30 use 5.008; # we need safe signals
31 use strict;
32 use warnings;
34 use Getopt::Long;
35 use Pod::Usage;
36 use Socket;
37 use Errno;
38 use Fcntl;
39 use POSIX qw(:sys_wait_h :fcntl_h);
40 use File::Basename;
41 use File::Spec ();
42 use Cwd qw(realpath);
44 use lib "__BASEDIR__";
45 use Girocco::Config;
46 use Girocco::Notify;
47 use Girocco::Project;
48 use Girocco::User;
49 use Girocco::Util qw(noFatalsToBrowser get_git);
50 BEGIN {noFatalsToBrowser}
51 use Girocco::ExecUtil;
53 use constant SOCKFDENV => "GIROCCO_TASKD_SOCKET_FD";
55 # Throttle Classes Defaults
56 # Note that any same-named classes in @Girocco::Config::throttle_classes
57 # will override (completely replacing the entire hash) these ones.
58 my @throttle_defaults = (
60 name => "ref-change",
61 maxproc => 0,
62 maxjobs => 1,
63 interval => 2
66 name => "clone",
67 maxproc => 0,
68 maxjobs => 2,
69 interval => 5
72 name => "snapshot",
73 #maxproc => max(5, cpucount + maxjobs), # this is the default
74 #maxjobs => max(1, int(cpucount / 4)) , # this is the default
75 interval => 5
79 # Options
80 my $quiet;
81 my $progress;
82 my $syslog;
83 my $stderr;
84 my $inetd;
85 my $idle_timeout;
86 my $daemon;
87 my $max_lifetime;
88 my $abbrev = 8;
89 my $showff = 1;
90 my $same_pid;
91 my $statusintv = 60;
92 my $idleintv = 3600;
93 my $maxspawn = 8;
95 $| = 1;
97 my $progname = basename($0);
98 my $children = 0;
99 my $idlestart = time;
100 my $idlestatus = 0;
102 sub cpucount {
103 use Girocco::Util "online_cpus";
104 our $online_cpus_result;
105 $online_cpus_result = online_cpus unless $online_cpus_result;
106 return $online_cpus_result;
109 sub logmsg {
110 my $hdr = "[@{[scalar localtime]}] $progname $$: ";
111 if (tied *STDOUT) {
112 $OStream::only = 2; # STDERR only
113 print "$hdr@_\n";
114 $OStream::only = 1; # syslog only
115 print "@_\n";
116 $OStream::only = 0; # back to default
117 } else {
118 print "$hdr@_\n";
122 sub statmsg {
123 return unless $progress;
124 my $hdr = "[@{[scalar localtime]}] $progname $$: ";
125 if (tied *STDERR) {
126 $OStream::only = 2; # STDERR only
127 print STDERR "$hdr@_\n";
128 $OStream::only = 1; # syslog only
129 print STDERR "@_\n";
130 $OStream::only = 0; # back to default
131 } else {
132 print STDERR "$hdr@_\n";
136 sub duration {
137 my $secs = shift;
138 return $secs unless defined($secs) && $secs >= 0;
139 $secs = int($secs);
140 my $ans = ($secs % 60) . 's';
141 return $ans if $secs < 60;
142 $secs = int($secs / 60);
143 $ans = ($secs % 60) . 'm' . $ans;
144 return $ans if $secs < 60;
145 $secs = int($secs / 60);
146 $ans = ($secs % 24) . 'h' . $ans;
147 return $ans if $secs < 24;
148 $secs = int($secs / 24);
149 return $secs . 'd' . $ans;
152 sub isfdopen {
153 my $fd = shift;
154 return undef unless defined($fd) && $fd >= 0;
155 my $result = POSIX::dup($fd);
156 POSIX::close($result) if defined($result);
157 defined($result);
160 sub setnoncloexec {
161 my $fd = shift;
162 fcntl($fd, F_SETFD, 0) or die "fcntl failed: $!";
165 sub setcloexec {
166 my $fd = shift;
167 fcntl($fd, F_SETFD, FD_CLOEXEC) or die "fcntl failed: $!";
170 sub setnonblock {
171 my $fd = shift;
172 my $flags = fcntl($fd, F_GETFL, 0);
173 defined($flags) or die "fcntl failed: $!";
174 fcntl($fd, F_SETFL, $flags | O_NONBLOCK) or die "fcntl failed: $!";
177 sub setblock {
178 my $fd = shift;
179 my $flags = fcntl($fd, F_GETFL, 0);
180 defined($flags) or die "fcntl failed: $!";
181 fcntl($fd, F_SETFL, $flags & ~O_NONBLOCK) or die "fcntl failed: $!";
184 package Throttle;
187 ## Throttle protocol
189 ## 1) Process needing throttle services acquire a control file descriptor
190 ## a) Either as a result of a fork + exec (the write end of a pipe)
191 ## b) Or by connecting to the taskd socket (not yet implemented)
193 ## 2) The process requesting throttle services will be referred to
194 ## as the supplicant or just "supp" for short.
196 ## 3) The supp first completes any needed setup which may include
197 ## gathering data it needs to perform the action -- if that fails
198 ## then there's no need for any throttling.
200 ## 4) The supp writes a throttle request to the control descriptor in
201 ## this format:
202 ## throttle <pid> <class>\n
203 ## for example if the supp's pid was 1234 and it was requesting throttle
204 ## control as a member of the mail class it would write this message:
205 ## throttle 1234 mail\n
206 ## Note that if the control descriptor happens to be a pipe rather than a
207 ## socket, the message should be preceded by another "\n" just be be safe.
208 ## If the control descriptor is a socket, not a pipe, the message may be
209 ## preceded by a "\n" but that's not recommended.
211 ## 5) For supplicants with a control descriptor that is a pipe
212 ## (getsockopt(SO_TYPE) returns ENOTSOCK) the (5a) protocol should be used.
213 ## If the control descriptor is a socket (getsockname succeeds) then
214 ## protocol (5b) should be used.
216 ## 5a) The supp now enters a "pause" loop awaiting either a SIGUSR1, SIGUSR2 or
217 ## SIGTERM. It should wake up periodically (SIGALRM works well) and attempt
218 ## to write a "keepalive\n" message to the control descriptor. If that
219 ## fails, the controller has gone away and it may make its own decision
220 ## whether or not to proceed at that point. If, on the other hand, it
221 ## receives a SIGTERM, the process limit for its class has been reached
222 ## and it should abort without performing its action. If it receives
223 ## SIGUSR1, it may proceed without writing anything more to the control
224 ## descriptor, any MAY even close the control descriptor. Finally, a
225 ## SIGUSR2 indicates rejection of the throttle request for some other reason
226 ## such as unrecognized class name or invalid pid in which case the supp may
227 ## make its own decision how to proceed.
229 ## 5b) The supp now enters a read wait on the socket -- it need accomodate no
230 ## more than 512 bytes and if a '\n' does not appear within that number of
231 ## bytes the read should be considered failed. Otherwise the read should
232 ## be retried until either a full line has been read or the socket is
233 ## closed from the other end. If the lone read is "proceed\n" then it may
234 ## proceed without reading or writing anything more to the control
235 ## descriptor, but MUST keep the control descriptor open and not call
236 ## shutdown on it either. Any other result (except EINTR or EAGAIN which
237 ## should be retried) constitutes failure. If a full line starting with at
238 ## least one alpha character was read but it was not "proceed" then it
239 ## should abort without performing its action. For any other failure it
240 ## may make its own decision whether or not to proceed as the controller has
241 ## gone away.
243 ## 6) The supp now performs its throttled action.
245 ## 7) The supp now closes its control descriptor (if it hasn't already in the
246 ## case of (5a)) and exits -- in the case of a socket, the other end receives
247 ## notification that the socket has been closed (read EOF). In the case of
248 ## a pipe the other end receives a SIGCHLD (multiple processes have a hold
249 ## of the other end of the pipe, so it will not reaach EOF by the supp's
250 ## exit in that case).
253 # keys are class names, values are hash refs with these fields:
254 # 'maxproc' => integer; maximum number of allowed supplicants (the sum of how
255 # many may be queued waiting plus how many may be
256 # concurrently active) with 0 meaning no limit.
257 # 'maxjobs' => integer; how many supplicants may proceed simultaneously a value
258 # of 0 is unlimited but the number of concurrent
259 # supplicants will always be limited to no more than
260 # the 'maxproc' value (if > 0) no matter what the
261 # 'maxjobs' value is.
262 # 'total' -> integer; the total number of pids belonging to this class that
263 # can currently be found in %pid.
264 # 'active' -> integer; the number of currently active supplicants which should
265 # be the same as (the number of elements of %pid with a
266 # matching class name) - (number of my class in @queue).
267 # 'interval' -> integer; minimum number of seconds between 'proceed' responses
268 # or SIGUSR1 signals to members of this class.
269 # 'lastqueue' -> time; last time a supplicant was successfully queued.
270 # 'lastproceed' => time; last time a supplicant was allowed to proceed.
271 # 'lastthrottle' => time; last time a supplicant was throttled
272 # 'lastdied' => time; last time a supplicant in this class died/exited/etc.
273 my %classes = ();
275 # keys are pid numbers, values are array refs with these elements:
276 # [0] => name of class (key to classes hash)
277 # [1] => supplicant state (0 => queued, non-zero => time it started running)
278 # [2] => descriptive text (e.g. project name)
279 my %pid = ();
281 # minimum number of seconds between any two proceed responses no matter what
282 # class. this takes priority in that it can effectively increase the
283 # class's 'interval' value by delaying proceed notifications if the minimum
284 # interval has not yet elapsed.
285 my $interval = 1;
287 # fifo of pids awaiting notification as soon as the next $interval elapses
288 # provided interval and maxjobs requirements are satisfied
289 # for the class of the pid that will next be triggered.
290 my @queue = ();
292 # time of most recent successful call to AddSupplicant
293 my $lastqueue = 0;
295 # time of most recent proceed notification
296 my $lastproceed = 0;
298 # time of most recent throttle
299 my $lastthrottle = 0;
301 # time of most recent removal
302 my $lastdied = 0;
304 # lifetime count of how many have been queued
305 my $totalqueue = 0;
307 # lifetime count of how many have been allowed to proceed
308 my $totalproceed = 0;
310 # lifetime count of how many have been throttled
311 my $totalthrottle = 0;
313 # lifetime count of how many have died
314 # It should always be true that $totalqueued - $totaldied == $curentlyactive
315 my $totaldied = 0;
317 # Returns an unordered list of currently registered class names
318 sub GetClassList {
319 return keys(%classes);
322 sub _max {
323 return $_[0] if $_[0] >= $_[1];
324 return $_[1];
327 sub _getnum {
328 my ($min, $val, $default) = @_;
329 my $ans;
330 if (defined($val) && $val =~ /^[+-]?\d+$/) {
331 $ans = 0 + $val;
332 } else {
333 $ans = &$default;
335 return _max($min, $ans);
338 # [0] => name of class to find
339 # [1] => if true, create class if it doesn't exist, if a hashref then
340 # it contains initial values for maxproc, maxjobs and interval.
341 # Otherwise maxjobs defaults to max(cpu cores/4, 1), maxprocs
342 # defaults to the max(5, number of cpu cores + maxjobs) and interval
343 # defaults to 1.
344 # Returns a hash ref with info about the class on success
345 sub GetClassInfo {
346 my ($classname, $init) = @_;
347 defined($classname) && $classname =~ /^[a-zA-Z][a-zA-Z0-9._+-]*$/
348 or return;
349 $classname = lc($classname);
350 my %info;
351 if ($classes{$classname}) {
352 %info = %{$classes{$classname}};
353 return \%info;
355 return unless $init;
356 my %newclass = ();
357 ref($init) eq 'HASH' or $init = {};
358 $newclass{'maxjobs'} = _getnum(0, $init->{'maxjobs'}, sub{_max(1, int(::cpucount() / 4))});
359 $newclass{'maxproc'} = _getnum(0, $init->{'maxproc'}, sub{_max(5, ::cpucount() + $newclass{'maxjobs'})});
360 $newclass{'interval'} = _getnum(0, $init->{'interval'}, sub{1});
361 $newclass{'total'} = 0;
362 $newclass{'active'} = 0;
363 $newclass{'lastqueue'} = 0;
364 $newclass{'lastproceed'} = 0;
365 $newclass{'lastthrottle'} = 0;
366 $newclass{'lastdied'} = 0;
367 $classes{$classname} = \%newclass;
368 %info = %newclass;
369 return \%info;
372 # [0] => pid to look up
373 # Returns () if not found otherwise ($classname, $timestarted, $description)
374 # Where $timestarted will be 0 if it's still queued otherwise a time() value
375 sub GetPidInfo {
376 my $pid = shift;
377 return () unless exists $pid{$pid};
378 return @{$pid{$pid}};
381 # Returns array of pid numbers that are currently running sorted
382 # by time started (oldest to newest). Can return an empty array.
383 sub GetRunningPids {
384 return sort({ ${$pid{$a}}[1] <=> ${$pid{$b}}[1] }
385 grep({ ${$pid{$_}}[1] } keys(%pid)));
388 # Returns a hash with various about the current state
389 # 'interval' => global minimum interval between proceeds
390 # 'active' => how many pids are currently queued + how many are running
391 # 'queue' => how many pids are currently queued
392 # 'lastqueue' => time (epoch seconds) of last queue
393 # 'lastproceed' => time (epoch seconds) of last proceed
394 # 'lastthrottle' => time (epoch seconds) of last throttle
395 # 'lastdied' => time (epoch seconds) of last removal
396 # 'totalqueue' => lifetime total number of processes queued
397 # 'totalproceed' => lifetime total number of processes proceeded
398 # 'totalthrottle' => lifetime total number of processes throttled
399 # 'totaldied' => lifetime total number of removed processes
400 sub GetInfo {
401 return {
402 interval => $interval,
403 active => scalar(keys(%pid)) - scalar(@queue),
404 queue => scalar(@queue),
405 lastqueue => $lastqueue,
406 lastproceed => $lastproceed,
407 lastthrottle => $lastthrottle,
408 lastdied => $lastdied,
409 totalqueue => $totalqueue,
410 totalproceed => $totalproceed,
411 totalthrottle => $totalthrottle,
412 totaldied => $totaldied
416 # with no args get the global interval
417 # with one arg set it, returns previous value if set
418 sub Interval {
419 my $ans = $interval;
420 $interval = 0 + $_[0] if defined($_[0]) && $_[0] =~ /^\d+$/;
421 return $ans;
424 sub RemoveSupplicant;
426 # Perform queue service (i.e. send SIGUSR1 to any eligible queued process)
427 # Returns minimum interval until next proceed is possible
428 # Returns undef if there's nothing waiting to proceed or
429 # the 'maxjobs' limits have been reached for all queued items (in which
430 # case it won't be possible to proceed until one of them exits, hence undef)
431 # This is called automatially by AddSupplicant and RemoveSupplicant
432 sub ServiceQueue {
433 RETRY:
434 return undef unless @queue; # if there's nothing queued, nothing to do
435 my $now = time;
436 my $min = _max(0, $interval - ($now - $lastproceed));
437 my $classmin = undef;
438 my $classchecked = 0;
439 my %seenclass = ();
440 my $classcount = scalar(keys(%classes));
441 for (my $i=0; $i <= $#queue && $classchecked < $classcount; ++$i) {
442 my $pid = $queue[$i];
443 my $procinfo = $pid{$pid};
444 if (!$procinfo) {
445 RemoveSupplicant($pid, 1);
446 goto RETRY;
448 my $classinfo = $classes{$$procinfo[0]};
449 if (!$classinfo) {
450 RemoveSupplicant($pid, 1);
451 goto RETRY;
453 if (!$seenclass{$$procinfo[0]}) {
454 $seenclass{$$procinfo[0]} = 1;
455 ++$classchecked;
456 if (!$classinfo->{'maxjobs'} || $classinfo->{'active'} < $classinfo->{'maxjobs'}) {
457 my $cmin = _max(0, $classinfo->{'interval'} - ($now - $classinfo->{'lastproceed'}));
458 if (!$cmin && !$min) {
459 $now = time;
460 $$procinfo[1] = $now;
461 splice(@queue, $i, 1);
462 ++$totalproceed;
463 $lastproceed = $now;
464 $classinfo->{'lastproceed'} = $now;
465 ++$classinfo->{'active'};
466 kill("USR1", $pid) or RemoveSupplicant($pid, 1);
467 goto RETRY;
469 $classmin = $cmin unless defined($classmin) && $classmin < $cmin;
473 return defined($classmin) ? _max($min, $classmin) : undef;
476 # $1 => pid to add (must not already be in %pids)
477 # $2 => class name (must exist)
478 # Returns -1 if no such class or pid already present or invalid
479 # Returns 0 if added successfully (and possibly already SIGUSR1'd)
480 # Return 1 if throttled and cannot be added
481 sub AddSupplicant {
482 my ($pid, $classname, $text, $noservice) = @_;
483 return -1 unless $pid && $pid =~ /^[1-9][0-9]*$/;
484 $pid += 0;
485 kill(0, $pid) or return -1;
486 my $classinfo = $classes{$classname};
487 return -1 unless $classinfo;
488 return -1 if $pid{$pid};
489 $text = '' unless defined($text);
490 my $now = time;
491 if ($classinfo->{'maxproc'} && $classinfo->{'total'} >= $classinfo->{'maxproc'}) {
492 ++$totalthrottle;
493 $lastthrottle = $now;
494 $classinfo->{'lastthrottle'} = $now;
495 return 1;
497 ++$totalqueue;
498 $lastqueue = $now;
499 $pid{$pid} = [$classname, 0, $text];
500 ++$classinfo->{'total'};
501 $classinfo->{'lastqueue'} = $now;
502 push(@queue, $pid);
503 ServiceQueue unless $noservice;
504 return 0;
507 # $1 => pid to remove (died, killed, exited normally, doesn't matter)
508 # Returns 0 if removed
509 # Returns -1 if unknown pid or other error during removal
510 sub RemoveSupplicant {
511 my ($pid, $noservice) = @_;
512 return -1 unless defined($pid) && $pid =~ /^\d+$/;
513 $pid += 0;
514 my $pidinfo = $pid{$pid};
515 $pidinfo or return -1;
516 my $now = time;
517 $lastdied = $now;
518 ++$totaldied;
519 delete $pid{$pid};
520 if (!$$pidinfo[1]) {
521 for (my $i=0; $i<=$#queue; ++$i) {
522 if ($queue[$i] == $pid) {
523 splice(@queue, $i, 1);
524 --$i;
528 my $classinfo = $classes{$$pidinfo[0]};
529 ServiceQueue, return -1 unless $classinfo;
530 --$classinfo->{'active'} if $$pidinfo[1];
531 --$classinfo->{'total'};
532 $classinfo->{'lastdied'} = $now;
533 ServiceQueue unless $noservice;
534 return 0;
537 # Instance Methods
539 package main;
542 ## ---------
543 ## Functions
544 ## ---------
547 my @reapedpids = ();
548 my %signame = (
549 # http://pubs.opengroup.org/onlinepubs/000095399/utilities/trap.html
550 1 => 'SIGHUP',
551 2 => 'SIGINT',
552 3 => 'SIGQUIT',
553 6 => 'SIGABRT',
554 9 => 'SIGKILL',
555 14 => 'SIGALRM',
556 15 => 'SIGTERM',
558 sub REAPER {
559 local $!;
560 my $child;
561 my $waitedpid;
562 while (($waitedpid = waitpid(-1, WNOHANG)) > 0) {
563 my $code = $? & 0xffff;
564 $idlestart = time if !--$children;
565 my $codemsg = '';
566 if (!($code & 0xff)) {
567 $codemsg = " with exit code ".($code >> 8) if $code;
568 } elsif ($code & 0x7f) {
569 my $signum = ($code & 0x7f);
570 $codemsg = " with signal ".
571 ($signame{$signum}?$signame{$signum}:$signum);
573 logmsg "reaped $waitedpid$codemsg";
574 push(@reapedpids, $waitedpid);
576 $SIG{CHLD} = \&REAPER; # loathe sysV
579 $SIG{CHLD} = \&REAPER; # Apollo 440
581 my ($piperead, $pipewrite);
582 sub spawn {
583 my $coderef = shift;
585 my $pid = fork;
586 if (not defined $pid) {
587 logmsg "cannot fork: $!";
588 return;
589 } elsif ($pid) {
590 $idlestart = time if !++$children;
591 $idlestatus = 0;
592 logmsg "begat $pid";
593 return; # I'm the parent
596 close(Server) unless fileno(Server) == 0;
597 close($piperead);
598 $SIG{'CHLD'} = sub {};
600 open STDIN, "+<&Client" or die "can't dup client to stdin";
601 close(Client);
602 exit &$coderef();
605 # returns:
606 # < 0: error
607 # = 0: proceed
608 # > 0: throttled
609 sub request_throttle {
610 use POSIX qw(sigprocmask sigsuspend SIG_SETMASK);
611 my $classname = shift;
612 my $text = shift;
614 Throttle::GetClassInfo($classname)
615 or return -1; # no such throttle class
617 my $throttled = 0;
618 my $proceed = 0;
619 my $error = 0;
620 my $controldead = 0;
621 my $setempty = POSIX::SigSet->new;
622 my $setfull = POSIX::SigSet->new;
623 $setempty->emptyset();
624 $setfull->fillset();
625 $SIG{'TERM'} = sub {$throttled = 1};
626 $SIG{'USR1'} = sub {$proceed = 1};
627 $SIG{'USR2'} = sub {$error = 1};
628 $SIG{'PIPE'} = sub {$controldead = 1};
629 $SIG{'ALRM'} = sub {};
631 # After writing we can expect a SIGTERM, SIGUSR1 or SIGUSR2
632 print $pipewrite "\nthrottle $$ $classname $text\n";
633 my $old = POSIX::SigSet->new;
634 sigprocmask(SIG_SETMASK, $setfull, $old);
635 until ($controldead || $throttled || $proceed || $error) {
636 alarm(30);
637 sigsuspend($setempty);
638 alarm(0);
639 sigprocmask(SIG_SETMASK, $setempty, $old);
640 print $pipewrite "\nkeepalive $$\n";
641 sigprocmask(SIG_SETMASK, $setfull, $old);
643 sigprocmask(SIG_SETMASK, $setempty, $old);
644 $SIG{'TERM'} = "DEFAULT";
645 $SIG{'USR1'} = "DEFAULT";
646 $SIG{'USR2'} = "DEFAULT";
647 $SIG{'ALRM'} = "DEFAULT";
648 $SIG{'PIPE'} = "DEFAULT";
650 my $result = -1;
651 if ($throttled) {
652 $result = 1;
653 } elsif ($proceed) {
654 $result = 0;
656 return $result;
659 sub clone {
660 my ($name) = @_;
661 Girocco::Project::does_exist($name, 1) or die "no such project: $name";
662 my $proj;
663 eval {$proj = Girocco::Project->load($name)};
664 if (!$proj && Girocco::Project::does_exist($name, 1)) {
665 # If the .clone_in_progress file exists, but the .clonelog does not
666 # and neither does the .clone_failed, be helpful and touch the
667 # .clone_failed file so that the mirror can be restarted
668 my $projdir = $Girocco::Config::reporoot."/$name.git";
669 if (-d "$projdir" && -f "$projdir/.clone_in_progress" && ! -f "$projdir/.clonelog" && ! -f "$projdir/.clone_failed") {
670 open X, '>', "$projdir/.clone_failed" and close(X);
673 $proj or die "failed to load project $name";
674 $proj->{clone_in_progress} or die "project $name is not marked for cloning";
675 $proj->{clone_logged} and die "project $name is already being cloned";
676 request_throttle("clone", $name) <= 0 or die "cloning $name aborted (throttled)";
677 statmsg "cloning $name";
678 my $devnullfd = POSIX::open(File::Spec->devnull, O_RDWR);
679 defined($devnullfd) && $devnullfd >= 0 or die "cannot open /dev/null: $!";
680 POSIX::dup2($devnullfd, 0) or
681 die "cannot dup2 STDIN_FILENO: $!";
682 POSIX::close($devnullfd);
683 my $duperr;
684 open $duperr, '>&2' or
685 die "cannot dup STDERR_FILENO: $!";
686 my $clonelogfd = POSIX::open("$Girocco::Config::reporoot/$name.git/.clonelog", O_WRONLY|O_TRUNC|O_CREAT, 0664);
687 defined($clonelogfd) && $clonelogfd >= 0 or die "cannot open clonelog for writing: $!";
688 POSIX::dup2($clonelogfd, 1) or
689 die "cannot dup2 STDOUT_FILENO: $!";
690 POSIX::dup2($clonelogfd, 2) or
691 POSIX::dup2(fileno($duperr), 2), die "cannot dup2 STDERR_FILENO: $!";
692 POSIX::close($clonelogfd);
693 exec "$Girocco::Config::basedir/taskd/clone.sh", "$name.git" or
694 POSIX::dup2(fileno($duperr), 2), die "exec failed: $!";
697 sub ref_indicator {
698 return ' -> ' unless $showff && defined($_[0]);
699 my ($git_dir, $old, $new) = @_;
700 return '..' unless defined($old) && defined($new) && $old !~ /^0+$/ && $new !~ /^0+$/ && $old ne $new;
701 # In many cases `git merge-base` is slower than this even if using the
702 # `--is-ancestor` option available since Git 1.8.0, but it's never faster
703 my $ans = get_git("--git-dir=$git_dir", "rev-list", "-n", "1", "^$new^0", "$old^0", "--") ? '...' : '..';
704 return wantarray ? ($ans, 1) : $ans;
707 sub ref_change {
708 my ($arg) = @_;
709 my ($username, $name, $oldrev, $newrev, $ref) = split(/\s+/, $arg);
710 $username && $name && $oldrev && $newrev && $ref or return 0;
711 $oldrev =~ /^[0-9a-f]{40}$/ && $newrev =~ /^[0-9a-f]{40}$/ && $ref =~ m{^refs/} or return 0;
712 $newrev ne $oldrev or return 0;
713 $Girocco::Config::notify_single_level || $ref =~ m(^refs/[^/]+/[^/]) or return 0;
715 Girocco::Project::does_exist($name, 1) or die "no such project: $name";
716 my $proj = Girocco::Project->load($name);
717 $proj or die "failed to load project $name";
718 my $has_notify = $proj->has_notify;
719 my $type = $has_notify ? "notify" : "change";
721 my $user;
722 if ($username && $username !~ /^%.*%$/) {
723 Girocco::User::does_exist($username, 1) or die "no such user: $username";
724 $user = Girocco::User->load($username);
725 $user or die "failed to load user $username";
726 } elsif ($username eq "%$name%") {
727 $username = "-";
730 request_throttle("ref-change", $name) <= 0 or die "ref-change $name aborted (throttled)";
731 my $ind = ref_indicator($proj->{path}, $oldrev, $newrev);
732 statmsg "ref-$type $username $name ($ref: @{[substr($oldrev,0,$abbrev)]}$ind@{[substr($newrev,0,$abbrev)]})";
733 open STDIN, '<', File::Spec->devnull;
734 Girocco::Notify::ref_changes($proj, $user, [$oldrev, $newrev, $ref]) if $has_notify;
735 return 0;
738 sub ref_changes {
739 my ($arg) = @_;
740 my ($username, $name) = split(/\s+/, $arg);
741 $username && $name or return 0;
743 Girocco::Project::does_exist($name, 1) or die "no such project: $name";
744 my $proj = Girocco::Project->load($name);
745 $proj or die "failed to load project $name";
746 my $has_notify = $proj->has_notify;
747 my $type = $has_notify ? "notify" : "change";
749 my $user;
750 if ($username && $username !~ /^%.*%$/) {
751 Girocco::User::does_exist($username, 1) or die "no such user: $username";
752 $user = Girocco::User->load($username);
753 $user or die "failed to load user $username";
754 } elsif ($username eq "%$name%") {
755 $username = "-";
758 my @changes = ();
759 my %oldheads = ();
760 my %deletedheads = ();
761 while (my $change = <STDIN>) {
762 my ($oldrev, $newrev, $ref) = split(/\s+/, $change);
763 $oldrev ne "done" or last;
764 $oldrev =~ /^[0-9a-f]{40}$/ && $newrev =~ /^[0-9a-f]{40}$/ && $ref =~ m{^refs/} or next;
765 $Girocco::Config::notify_single_level || $ref =~ m(^refs/[^/]+/[^/]) or next;
766 if ($ref =~ m{^refs/heads/.}) {
767 if ($oldrev =~ /^0{40}$/) {
768 delete $oldheads{$ref};
769 $deletedheads{$ref} = 1;
770 } elsif ($newrev ne $oldrev || (!exists($oldheads{$ref}) && !$deletedheads{$ref})) {
771 $oldheads{$ref} = $oldrev;
774 $newrev ne $oldrev or next;
775 push(@changes, [$oldrev, $newrev, $ref]);
777 return 0 unless @changes;
778 open STDIN, '<', File::Spec->devnull;
779 request_throttle("ref-change", $name) <= 0 or die "ref-changes $name aborted (throttled)";
780 my $statproc = sub {
781 my ($old, $new, $ref, $ran_mail_sh) = @_;
782 my ($ind, $ran_git) = ref_indicator($proj->{path}, $old, $new);
783 statmsg "ref-$type $username $name ($ref: @{[substr($old,0,$abbrev)]}$ind@{[substr($new,0,$abbrev)]})";
784 if ($ran_mail_sh) {
785 sleep 2;
786 } elsif ($ran_git) {
787 sleep 1;
790 if ($has_notify) {
791 Girocco::Notify::ref_changes($proj, $user, $statproc, \%oldheads, @changes);
792 } else {
793 &$statproc(@$_) foreach @changes;
795 return 0;
798 sub throttle {
799 my ($arg) = @_;
800 my ($pid, $classname, $text) = split(/\s+/, $arg);
801 $pid =~ /^\d+/ or return 0; # invalid pid
802 $pid += 0;
803 $pid > 0 or return 0; # invalid pid
804 kill(0, $pid) || $!{EPERM} or return 0; # no such process
805 Throttle::GetClassInfo($classname) or return 0; # no such throttle class
806 defined($text) && $text ne '' or return 0; # no text no service
808 my $throttled = 0;
809 my $proceed = 0;
810 my $error = 0;
811 my $controldead = 0;
812 my $suppdead = 0;
813 my ($waker, $wakew);
814 pipe($waker, $wakew) or die "pipe failed: $!";
815 select((select($wakew),$|=1)[0]);
816 setnonblock($wakew);
817 $SIG{'TERM'} = sub {$throttled = 1; syswrite($wakew, '!')};
818 $SIG{'USR1'} = sub {$proceed = 1; syswrite($wakew, '!')};
819 $SIG{'USR2'} = sub {$error = 1; syswrite($wakew, '!')};
820 $SIG{'PIPE'} = sub {$controldead = 1; syswrite($wakew, '!')};
821 select((select(STDIN),$|=1)[0]);
823 logmsg "throttle $pid $classname $text request";
824 # After writing we can expect a SIGTERM or SIGUSR1
825 print $pipewrite "\nthrottle $$ $classname $text\n";
827 # NOTE: the only way to detect the socket close is to read all the
828 # data until EOF is reached -- recv can be used to peek.
829 my $v = '';
830 vec($v, fileno(STDIN), 1) = 1;
831 vec($v, fileno($waker), 1) = 1;
832 setnonblock(\*STDIN);
833 setnonblock($waker);
834 until ($controldead || $throttled || $proceed || $error || $suppdead) {
835 my ($r, $e);
836 select($r=$v, undef, $e=$v, 30);
837 my ($bytes, $discard);
838 do {$bytes = sysread($waker, $discard, 512)} while (defined($bytes) && $bytes > 0);
839 do {$bytes = sysread(STDIN, $discard, 4096)} while (defined($bytes) && $bytes > 0);
840 $suppdead = 1 unless !defined($bytes) && $!{EAGAIN};
841 print $pipewrite "\nkeepalive $$\n";
843 setblock(\*STDIN);
845 if ($throttled && !$suppdead) {
846 print STDIN "throttled\n";
847 logmsg "throttle $pid $classname $text throttled";
848 } elsif ($proceed && !$suppdead) {
849 print STDIN "proceed\n";
850 logmsg "throttle $pid $classname $text proceed";
851 $SIG{'TERM'} = 'DEFAULT';
852 # Stay alive until the child dies which we detect by EOF on STDIN
853 setnonblock(\*STDIN);
854 until ($controldead || $suppdead) {
855 my ($r, $e);
856 select($r=$v, undef, $e=$v, 30);
857 my ($bytes, $discard);
858 do {$bytes = sysread($waker, $discard, 512)} while (defined($bytes) && $bytes > 0);
859 do {$bytes = sysread(STDIN, $discard, 512)} while (defined($bytes) && $bytes > 0);
860 $suppdead = 1 unless !defined($bytes) && $!{EAGAIN};
861 print $pipewrite "\nkeepalive $$\n";
863 setblock(\*STDIN);
864 } else {
865 my $prefix = '';
866 $prefix = "control" if $controldead && !$suppdead;
867 logmsg "throttle $pid $classname $text ${prefix}died";
869 exit 0;
872 sub process_pipe_msg {
873 my ($act, $pid, $cls, $text) = split(/\s+/, $_[0]);
874 if ($act eq "throttle") {
875 $pid =~ /^\d+$/ or return 0;
876 $pid += 0;
877 $pid > 0 or return 0; # invalid pid
878 kill(0, $pid) or return 0; # invalid pid
879 defined($cls) && $cls ne "" or kill('USR2', $pid), return 0;
880 defined($text) && $text ne "" or kill('USR2', $pid), return 0;
881 Throttle::GetClassInfo($cls) or kill('USR2', $pid), return 0;
882 # the AddSupplicant call could send SIGUSR1 before it returns
883 my $result = Throttle::AddSupplicant($pid, $cls, $text);
884 kill('USR2', $pid), return 0 if $result < 0;
885 kill('TERM', $pid), return 0 if $result > 0;
886 # $pid was added to class $cls and will receive SIGUSR1 when
887 # it's time for it to proceed
888 return 0;
889 } elsif ($act eq "keepalive") {
890 # nothing to do although we could verify pid is valid and
891 # still in %Throttle::pids and send a SIGUSR2 if not, but
892 # really keepalive should just be ignored.
893 return 0;
895 print STDERR "discarding unknown pipe message \"$_[0]\"\n";
896 return 0;
900 ## -------
901 ## OStream
902 ## -------
905 package OStream;
907 # Set to 1 for only syslog output (if enabled by mode)
908 # Set to 2 for only stderr output (if enabled by mode)
909 our $only = 0; # This is a hack
911 use Carp 'croak';
912 use Sys::Syslog qw(:DEFAULT :macros);
914 sub writeall {
915 my ($fd, $data) = @_;
916 my $offset = 0;
917 my $remaining = length($data);
918 while ($remaining) {
919 my $bytes = POSIX::write(
920 $fd,
921 substr($data, $offset, $remaining),
922 $remaining);
923 next if !defined($bytes) && $!{EINTR};
924 croak "POSIX::write failed: $!" unless defined $bytes;
925 croak "POSIX::write wrote 0 bytes" unless $bytes;
926 $remaining -= $bytes;
927 $offset += $bytes;
931 sub dumpline {
932 use POSIX qw(STDERR_FILENO);
933 my ($self, $line) = @_;
934 $only = 0 unless defined($only);
935 writeall(STDERR_FILENO, $line) if $self->{'stderr'} && $only != 1;
936 substr($line, -1, 1) = '' if substr($line, -1, 1) eq "\n";
937 return unless length($line);
938 syslog(LOG_NOTICE, "%s", $line) if $self->{'syslog'} && $only != 2;
941 sub TIEHANDLE {
942 my $class = shift || 'OStream';
943 my $mode = shift;
944 my $syslogname = shift;
945 my $syslogfacility = shift;
946 defined($syslogfacility) or $syslogfacility = LOG_USER;
947 my $self = {};
948 $self->{'syslog'} = $mode > 0;
949 $self->{'stderr'} = $mode <= 0 || $mode > 1;
950 $self->{'lastline'} = '';
951 if ($self->{'syslog'}) {
952 # Some Sys::Syslog have a stupid default setlogsock order
953 eval {Sys::Syslog::setlogsock("native"); 1;} or
954 eval {Sys::Syslog::setlogsock("unix");};
955 openlog($syslogname, "ndelay,pid", $syslogfacility)
956 or croak "Sys::Syslog::openlog failed: $!";
958 return bless $self, $class;
961 sub BINMODE {return 1}
962 sub FILENO {return undef}
963 sub EOF {return 0}
964 sub CLOSE {return 1}
966 sub PRINTF {
967 my $self = shift;
968 my $template = shift;
969 return $self->PRINT(sprintf $template, @_);
972 sub PRINT {
973 my $self = shift;
974 my $data = join('', $self->{'lastline'}, @_);
975 my $pos = 0;
976 while ((my $idx = index($data, "\n", $pos)) >= 0) {
977 ++$idx;
978 my $line = substr($data, $pos, $idx - $pos);
979 substr($data, $pos, $idx - $pos) = '';
980 $pos = $idx;
981 $self->dumpline($line);
983 $self->{'lastline'} = $data;
984 return 1;
987 sub DESTROY {
988 my $self = shift;
989 $self->dumpline($self->{'lastline'})
990 if length($self->{'lastline'});
991 closelog;
994 sub WRITE {
995 my $self = shift;
996 my ($scalar, $length, $offset) = @_;
997 $scalar = '' if !defined($scalar);
998 $length = length($scalar) if !defined($length);
999 croak "OStream::WRITE invalid length $length"
1000 if $length < 0;
1001 $offset = 0 if !defined($offset);
1002 $offset += length($scalar) if $offset < 0;
1003 croak "OStream::WRITE invalid write offset"
1004 if $offset < 0 || $offset > $length;
1005 my $max = length($scalar) - $offset;
1006 $length = $max if $length > $max;
1007 $self->PRINT(substr($scalar, $offset, $length));
1008 return $length;
1012 ## ----
1013 ## main
1014 ## ----
1017 package main;
1019 # returns pid of process that will schedule jobd.pl restart on success
1020 # returns 0 if fork or other system call failed with error in $!
1021 # returns undef if jobd.pl does not currently appear to be running (no lockfile)
1022 sub schedule_jobd_restart {
1023 use POSIX qw(_exit setpgid dup2 :fcntl_h);
1024 my $devnull = File::Spec->devnull;
1025 my $newpg = shift;
1026 my $jdlf = "/tmp/jobd-$Girocco::Config::tmpsuffix.lock";
1027 return undef unless -f $jdlf;
1028 my $oldsigchld = $SIG{'CHLD'};
1029 defined($oldsigchld) or $oldsigchld = sub {};
1030 my ($read, $write, $read2, $write2);
1031 pipe($read, $write) or return 0;
1032 select((select($write),$|=1)[0]);
1033 if (!pipe($read2, $write2)) {
1034 local $!;
1035 close $write;
1036 close $read;
1037 return 0;
1039 select((select($write2),$|=1)[0]);
1040 $SIG{'CHLD'} = sub {};
1041 my $retries = 3;
1042 my $child;
1043 while (!defined($child) && $retries--) {
1044 $child = fork;
1045 sleep 1 unless defined($child) || !$retries;
1047 if (!defined($child)) {
1048 local $!;
1049 close $write2;
1050 close $read2;
1051 close $write;
1052 close $read;
1053 $SIG{'CHLD'} = $oldsigchld;
1054 return 0;
1056 # double fork the child
1057 if (!$child) {
1058 close $read2;
1059 my $retries2 = 3;
1060 my $child2;
1061 while (!defined($child2) && $retries2--) {
1062 $child2 = fork;
1063 sleep 1 unless defined($child2) || !$retries2;
1065 if (!defined($child2)) {
1066 my $ec = 0 + $!;
1067 $ec = 255 unless $ec;
1068 print $write2 ":$ec";
1069 close $write2;
1070 _exit 127;
1072 if ($child2) {
1073 # pass new child pid up to parent and exit
1074 print $write2 $child2;
1075 close $write2;
1076 _exit 0;
1077 } else {
1078 # this is the grandchild
1079 close $write2;
1081 } else {
1082 close $write2;
1083 my $result = <$read2>;
1084 close $read2;
1085 chomp $result if defined($result);
1086 if (!defined($result) || $result !~ /^:?\d+$/) {
1087 # something's wrong with the child -- kill it
1088 kill(9, $child) && waitpid($child, 0);
1089 my $oldsigpipe = $SIG{'PIPE'};
1090 # make sure the grandchild, if any,
1091 # doesn't run the success proc
1092 $SIG{'PIPE'} = sub {};
1093 print $write 1;
1094 close $write;
1095 close $read;
1096 $SIG{'PIPE'} = defined($oldsigpipe) ?
1097 $oldsigpipe : 'DEFAULT';
1098 $! = 255;
1099 $SIG{'CHLD'} = $oldsigchld;
1100 return 0;
1102 if ($result =~ /^:(\d+)$/) {
1103 # fork failed in child, there is no grandchild
1104 my $ec = $1;
1105 waitpid($child, 0);
1106 close $write;
1107 close $read;
1108 $! = $ec;
1109 $SIG{'CHLD'} = $oldsigchld;
1110 return 0;
1112 # reap the child and set $child to grandchild's pid
1113 waitpid($child, 0);
1114 $child = $result;
1116 if (!$child) {
1117 # grandchild that actually initiates the jobd.pl restart
1118 close $write;
1119 my $wait = 5;
1120 my $ufd = POSIX::open($devnull, O_RDWR);
1121 if (defined($ufd)) {
1122 dup2($ufd, 0) unless $ufd == 0;
1123 dup2($ufd, 1) unless $ufd == 1;
1124 dup2($ufd, 2) unless $ufd == 2;
1125 POSIX::close($ufd) unless $ufd == 0 || $ufd == 1 || $ufd == 2;
1127 chdir "/";
1128 if ($newpg) {
1129 my $makepg = sub {
1130 my $result = setpgid(0, 0);
1131 if (!defined($result)) {
1132 --$wait;
1133 sleep 1;
1135 $result;
1137 my $result = &$makepg;
1138 defined($result) or $result = &$makepg;
1139 defined($result) or $result = &$makepg;
1140 defined($result) or $result = &$makepg;
1142 sleep $wait;
1143 my $result = <$read>;
1144 close $read;
1145 chomp $result if defined($result);
1146 if (!defined($result) || $result eq 0) {
1147 open JDLF, '+<', $jdlf or _exit(1);
1148 select((select(JDLF),$|=1)[0]);
1149 print JDLF "restart\n";
1150 truncate JDLF, tell(JDLF);
1151 close JDLF;
1153 _exit(0);
1155 close $write;
1156 close $read;
1157 $SIG{'CHLD'} = $oldsigchld;
1158 return $child;
1161 sub cancel_jobd_restart {
1162 my $restarter = shift;
1163 return unless defined($restarter) && $restarter != 0;
1164 return -1 unless kill(0, $restarter);
1165 kill(9, $restarter) or die "failed to kill jobd restarter process (pid $restarter): $!\n";
1166 # we must not waitpid because $restarter was doubly forked and will
1167 # NOT send us a SIGCHLD when it terminates
1168 return $restarter;
1171 my $reexec = Girocco::ExecUtil->new;
1172 my $realpath0 = realpath($0);
1173 chdir "/";
1174 close(DATA) if fileno(DATA);
1175 my $sfac;
1176 Getopt::Long::Configure('bundling');
1177 my ($stiv, $idiv);
1178 my $parse_res = GetOptions(
1179 'help|?|h' => sub {
1180 pod2usage(-verbose => 2, -exitval => 0, -input => $realpath0)},
1181 'quiet|q' => \$quiet,
1182 'no-quiet' => sub {$quiet = 0},
1183 'progress|P' => \$progress,
1184 'inetd|i' => sub {$inetd = 1; $syslog = 1; $quiet = 1;},
1185 'idle-timeout|t=i' => \$idle_timeout,
1186 'daemon' => sub {$daemon = 1; $syslog = 1; $quiet = 1;},
1187 'max-lifetime=i' => \$max_lifetime,
1188 'syslog|s:s' => \$sfac,
1189 'no-syslog' => sub {$syslog = 0; $sfac = undef;},
1190 'stderr' => \$stderr,
1191 'abbrev=i' => \$abbrev,
1192 'show-fast-forward-info' => \$showff,
1193 'no-show-fast-forward-info' => sub {$showff = 0},
1194 'same-pid' => \$same_pid,
1195 'no-same-pid' => sub {$same_pid = 0},
1196 'status-interval=i' => \$stiv,
1197 'idle-status-interval=i' => \$idiv,
1198 ) || pod2usage(-exitval => 2, -input => $realpath0);
1199 $same_pid = !$daemon unless defined($same_pid);
1200 $syslog = 1 if defined($sfac);
1201 $progress = 1 unless $quiet;
1202 $abbrev = 128 unless $abbrev > 0;
1203 pod2usage(-msg => "--inetd and --daemon are incompatible") if ($inetd && $daemon);
1204 if (defined($idle_timeout)) {
1205 die "--idle-timeout must be a whole number\n" unless $idle_timeout =~ /^\d+$/;
1206 die "--idle-timeout may not be used without --inetd\n" unless $inetd;
1208 if (defined($max_lifetime)) {
1209 die "--max-lifetime must be a whole number\n" unless $max_lifetime =~ /^\d+$/;
1210 $max_lifetime += 0;
1212 defined($max_lifetime) or $max_lifetime = 604800; # 1 week
1213 if (defined($stiv)) {
1214 die "--status-interval must be a whole number\n" unless $stiv =~ /^\d+$/;
1215 $statusintv = $stiv * 60;
1217 if (defined($idiv)) {
1218 die "--idle-status-interval must be a whole number\n" unless $idiv =~ /^\d+$/;
1219 $idleintv = $idiv * 60;
1222 open STDIN, '<'.File::Spec->devnull or die "could not redirect STDIN to /dev/null\n" unless $inetd;
1223 open STDOUT, '>&STDERR' if $inetd;
1224 if ($syslog) {
1225 use Sys::Syslog qw();
1226 my $mode = 1;
1227 ++$mode if $stderr;
1228 $sfac = "user" unless defined($sfac) && $sfac ne "";
1229 my $ofac = $sfac;
1230 $sfac = uc($sfac);
1231 $sfac = 'LOG_'.$sfac unless $sfac =~ /^LOG_/;
1232 my $facility;
1233 my %badfac = map({("LOG_$_" => 1)}
1234 (qw(PID CONS ODELAY NDELAY NOWAIT PERROR FACMASK NFACILITIES PRIMASK LFMT)));
1235 eval "\$facility = Sys::Syslog::$sfac; 1" or die "invalid syslog facility: $ofac\n";
1236 die "invalid syslog facility: $ofac\n"
1237 if ($facility & ~0xf8) || ($facility >> 3) > 23 || $badfac{$sfac};
1238 tie *STDERR, 'OStream', $mode, $progname, $facility or die "tie failed";
1240 if ($quiet) {
1241 open STDOUT, '>', File::Spec->devnull;
1242 } elsif ($inetd) {
1243 *STDOUT = *STDERR;
1246 my ($NAME, $INO);
1248 my $restart_file = $Girocco::Config::chroot.'/etc/taskd.restart';
1249 my $restart_active = 1;
1250 my $resumefd = $ENV{(SOCKFDENV)};
1251 delete $ENV{(SOCKFDENV)};
1252 if (defined($resumefd)) {{
1253 unless ($resumefd =~ /^(\d+)(?::(-?\d+))?$/) {
1254 warn "ignoring invalid ".SOCKFDENV." environment value (\"$resumefd\") -- bad format\n";
1255 $resumefd = undef;
1256 last;
1258 my $resumeino;
1259 ($resumefd, $resumeino) = ($1, $2);
1260 $resumefd += 0;
1261 unless (isfdopen($resumefd)) {
1262 warn "ignoring invalid ".SOCKFDENV." environment value -- fd \"$resumefd\" not open\n";
1263 $resumefd = undef;
1264 last;
1266 unless ($inetd) {
1267 unless (defined($resumeino)) {
1268 warn "ignoring invalid ".SOCKFDENV." environment value (\"$resumefd\") -- missing inode\n";
1269 POSIX::close($resumefd);
1270 $resumefd = undef;
1271 last;
1273 $resumeino += 0;
1274 my $sockloc = $Girocco::Config::chroot.'/etc/taskd.socket';
1275 my $slinode = (stat($sockloc))[1];
1276 unless (defined($slinode) && -S _) {
1277 warn "ignoring ".SOCKFDENV." environment value; socket file does not exist: $sockloc\n";
1278 POSIX::close($resumefd);
1279 $resumefd = undef;
1280 last;
1282 open Test, "<&$resumefd" or die "open: $!";
1283 my $sockname = getsockname Test;
1284 my $sockpath;
1285 $sockpath = unpack_sockaddr_un $sockname if $sockname && sockaddr_family($sockname) == AF_UNIX;
1286 close Test;
1287 if (!defined($resumeino) || !defined($sockpath) || $resumeino != $slinode || realpath($sockloc) ne realpath($sockpath)) {
1288 warn "ignoring ".SOCKFDENV." environment value; does not match socket file: $sockloc\n";
1289 POSIX::close($resumefd);
1290 $resumefd = undef;
1292 $INO = $resumeino;
1295 if ($inetd || defined($resumefd)) {
1296 my $fdopen = defined($resumefd) ? $resumefd : 0;
1297 open Server, "<&=$fdopen" or die "open: $!";
1298 setcloexec(\*Server) if $fdopen > $^F;
1299 my $sockname = getsockname Server;
1300 die "getsockname: $!" unless $sockname;
1301 die "socket already connected! must be 'wait' socket\n" if getpeername Server;
1302 die "getpeername: $!" unless $!{ENOTCONN};
1303 my $st = getsockopt Server, SOL_SOCKET, SO_TYPE;
1304 die "getsockopt(SOL_SOCKET, SO_TYPE): $!" unless $st;
1305 my $socktype = unpack('i', $st);
1306 die "stream socket required\n" unless defined $socktype && $socktype == SOCK_STREAM;
1307 die "AF_UNIX socket required\n" unless sockaddr_family($sockname) == AF_UNIX;
1308 $NAME = unpack_sockaddr_un $sockname;
1309 my $expected = $Girocco::Config::chroot.'/etc/taskd.socket';
1310 if (realpath($NAME) ne realpath($expected)) {
1311 $restart_active = 0;
1312 warn "listening on \"$NAME\" but expected \"$expected\", restart file disabled\n";
1314 my $mode = (stat($NAME))[2];
1315 die "stat: $!" unless $mode;
1316 $mode &= 07777;
1317 if (($mode & 0660) != 0660) {
1318 chmod(($mode|0660), $NAME) == 1 or die "chmod ug+rw \"$NAME\" failed: $!";
1320 } else {
1321 $NAME = $Girocco::Config::chroot.'/etc/taskd.socket';
1322 my $uaddr = sockaddr_un($NAME);
1324 socket(Server, PF_UNIX, SOCK_STREAM, 0) or die "socket failed: $!";
1325 die "already exists but not a socket: $NAME\n" if -e $NAME && ! -S _;
1326 if (-e _) {
1327 # Do not unlink another instance's active listen socket!
1328 socket(my $sfd, PF_UNIX, SOCK_STREAM, 0) or die "socket failed: $!";
1329 connect($sfd, $uaddr) || $!{EPROTOTYPE} and
1330 die "Live socket '$NAME' exists. Please make sure no other instance of taskd is running.\n";
1331 close($sfd);
1332 unlink($NAME);
1334 bind(Server, $uaddr) or die "bind failed: $!";
1335 listen(Server, SOMAXCONN) or die "listen failed: $!";
1336 chmod 0666, $NAME or die "chmod failed: $!";
1337 $INO = (stat($NAME))[1] or die "stat failed: $!";
1340 foreach my $throttle (@Girocco::Config::throttle_classes, @throttle_defaults) {
1341 my $classname = $throttle->{"name"};
1342 $classname or next;
1343 Throttle::GetClassInfo($classname, $throttle);
1346 sub _min {
1347 return $_[0] <= $_[1] ? $_[0] : $_[1];
1350 pipe($piperead, $pipewrite) or die "pipe failed: $!";
1351 setnonblock($piperead);
1352 select((select($pipewrite), $|=1)[0]);
1353 my $pipebuff = '';
1354 my $fdset_both = '';
1355 vec($fdset_both, fileno($piperead), 1) = 1;
1356 my $fdset_pipe = $fdset_both;
1357 vec($fdset_both, fileno(Server), 1) = 1;
1358 my $penalty = 0;
1359 my $t = time;
1360 my $penaltytime = $t;
1361 my $nextwakeup = $t + 60;
1362 my $nextstatus = undef;
1363 $nextstatus = $t + $statusintv if $statusintv;
1364 if ($restart_active) {
1365 unless (unlink($restart_file) || $!{ENOENT}) {
1366 $restart_active = 0;
1367 statmsg "restart file disabled could not unlink \"$restart_file\": $!";
1370 daemon(1, 1) or die "failed to daemonize: $!\n" if $daemon;
1371 my $starttime = time;
1372 my $endtime = $max_lifetime ? $starttime + $max_lifetime : 0;
1373 statmsg "listening on $NAME";
1374 while (1) {
1375 my ($rout, $eout, $nfound);
1376 do {
1377 my $wait;
1378 my $now = time;
1379 my $adjustpenalty = sub {
1380 if ($penaltytime < $now) {
1381 my $credit = $now - $penaltytime;
1382 $penalty = $penalty > $credit ? $penalty - $credit : 0;
1383 $penaltytime = $now;
1386 if (defined($nextstatus) && $now >= $nextstatus) {
1387 unless ($idlestatus && !$children && (!$idleintv || $now - $idlestatus < $idleintv)) {
1388 my $statmsg = "STATUS: $children active";
1389 my @running = ();
1390 if ($children) {
1391 my @stats = ();
1392 my $cnt = 0;
1393 foreach my $cls (sort(Throttle::GetClassList())) {
1394 my $inf = Throttle::GetClassInfo($cls);
1395 if ($inf->{'total'}) {
1396 $cnt += $inf->{'total'};
1397 push(@stats, substr(lc($cls),0,1)."=".
1398 $inf->{'total'}.'/'.$inf->{'active'});
1401 push(@stats, "?=".($children-$cnt)) if @stats && $cnt < $children;
1402 $statmsg .= " (".join(" ",@stats).")" if @stats;
1403 foreach (Throttle::GetRunningPids()) {
1404 my ($cls, $ts, $desc) = Throttle::GetPidInfo($_);
1405 next unless $ts;
1406 push(@running, "[${cls}::$desc] ".duration($now-$ts));
1409 my $idlesecs;
1410 $statmsg .= ", idle " . duration($idlesecs)
1411 if !$children && ($idlesecs = $now - $idlestart) >= 2;
1412 statmsg $statmsg;
1413 statmsg "STATUS: currently running: ".join(", ", @running)
1414 if @running;
1415 $idlestatus = $now if !$children;
1417 $nextstatus += $statusintv while $nextstatus <= $now;
1419 $nextwakeup += 60, $now = time while ($wait = $nextwakeup - $now) <= 0;
1420 $wait = _min($wait, (Throttle::ServiceQueue()||60));
1421 &$adjustpenalty; # this prevents ignoring accept when we shouldn't
1422 my $fdset;
1423 if ($penalty <= $maxspawn) {
1424 $fdset = $fdset_both;
1425 } else {
1426 $fdset = $fdset_pipe;
1427 $wait = $penalty - $maxspawn if $wait > $penalty - $maxspawn;
1429 $nfound = select($rout=$fdset, undef, $eout=$fdset, $wait);
1430 logmsg("select failed: $!"), exit(1) unless $nfound >= 0 || $!{EINTR} || $!{EAGAIN};
1431 my $reaped;
1432 Throttle::RemoveSupplicant($reaped) while ($reaped = shift(@reapedpids));
1433 $now = time;
1434 &$adjustpenalty; # this prevents banking credits for elapsed time
1435 if (!$children && !$nfound && $restart_active && (($endtime && $now >= $endtime) || -e $restart_file)) {
1436 statmsg "RESTART: restart requested; max lifetime ($max_lifetime) exceeded" if $endtime && $now >= $endtime;
1437 $SIG{CHLD} = sub {};
1438 my $restarter = schedule_jobd_restart($inetd);
1439 if (defined($restarter) && !$restarter) {
1440 statmsg "RESTART: restart requested; retrying failed scheduling of jobd restart: $!";
1441 sleep 2; # *cough*
1442 $restarter = schedule_jobd_restart;
1443 if (!defined($restarter)) {
1444 statmsg "RESTART: restart requested; reschedule skipped jobd no longer running";
1445 } elsif (defined($restarter) && !$restarter) {
1446 statmsg "RESTART: restart requested; retry of jobd restart scheduling failed, skipping jobd restart: $!";
1447 $restarter = undef;
1450 if ($inetd) {
1451 statmsg "RESTART: restart requested; now exiting for inetd restart";
1452 statmsg "RESTART: restart requested; jobd restart scheduled in 5 seconds" if $restarter;
1453 sleep 2; # *cough*
1454 exit 0;
1455 } else {
1456 statmsg "RESTART: restart requested; now restarting";
1457 statmsg "RESTART: restart requested; jobd restart scheduled in 5 seconds" if $restarter;
1458 setnoncloexec(\*Server);
1459 $reexec->setenv(SOCKFDENV, fileno(Server).":$INO");
1460 $reexec->reexec($same_pid);
1461 setcloexec(\*Server) if fileno(Server) > $^F;
1462 statmsg "RESTART: continuing after failed restart: $!";
1463 chdir "/";
1464 cancel_jobd_restart($restarter) if $restarter;
1465 statmsg "RESTART: scheduled jobd restart has been cancelled" if $restarter;
1466 $SIG{CHLD} = \&REAPER;
1469 if ($idle_timeout && !$children && !$nfound && $now - $idlestart >= $idle_timeout) {
1470 statmsg "idle timeout (@{[duration($idle_timeout)]}) exceeded now exiting";
1471 exit 0;
1473 } while $nfound < 1;
1474 my $reout = $rout | $eout;
1475 if (vec($reout, fileno($piperead), 1)) {{
1476 my $nloff = -1;
1478 my $bytes;
1479 do {$bytes = sysread($piperead, $pipebuff, 512, length($pipebuff))}
1480 while (!defined($bytes) && $!{EINTR});
1481 last if !defined($bytes) && $!{EAGAIN};
1482 die "sysread failed: $!" unless defined $bytes;
1483 # since we always keep a copy of $pipewrite open EOF is fatal
1484 die "sysread returned EOF on pipe read" unless $bytes;
1485 $nloff = index($pipebuff, "\n", 0);
1486 if ($nloff < 0 && length($pipebuff) >= 512) {
1487 $pipebuff = '';
1488 print STDERR "discarding 512 bytes of control pipe data with no \\n found\n";
1490 redo unless $nloff >= 0;
1492 last unless $nloff >= 0;
1493 do {
1494 my $msg = substr($pipebuff, 0, $nloff);
1495 substr($pipebuff, 0, $nloff + 1) = '';
1496 $nloff = index($pipebuff, "\n", 0);
1497 process_pipe_msg($msg) if length($msg);
1498 } while $nloff >= 0;
1499 redo;
1501 next unless vec($reout, fileno(Server), 1);
1502 unless (accept(Client, Server)) {
1503 logmsg "accept failed: $!" unless $!{EINTR};
1504 next;
1506 logmsg "connection on $NAME";
1507 ++$penalty;
1508 spawn sub {
1509 my $inp = <STDIN>;
1510 $inp = <STDIN> if defined($inp) && $inp eq "\n";
1511 chomp $inp if defined($inp);
1512 # ignore empty and "nop" connects
1513 defined($inp) && $inp ne "" && $inp ne "nop" or exit 0;
1514 my ($cmd, $arg) = $inp =~ /^([a-zA-Z][a-zA-Z0-9._+-]*)(?:\s+(.*))?$/;
1515 defined($arg) or $arg = '';
1516 if ($cmd eq 'ref-changes') {
1517 ref_changes($arg);
1518 } elsif ($cmd eq 'clone') {
1519 clone($arg);
1520 } elsif ($cmd eq 'ref-change') {
1521 statmsg "processing obsolete ref-change message (please switch to ref-changes)";
1522 ref_change($arg);
1523 } elsif ($cmd eq 'throttle') {
1524 throttle($arg);
1525 } else {
1526 statmsg "ignoring unknown command: $cmd";
1527 exit 3;
1530 close Client;
1534 ## -------------
1535 ## Documentation
1536 ## -------------
1539 __END__
1541 =head1 NAME
1543 taskd.pl - Perform Girocco service tasks
1545 =head1 SYNOPSIS
1547 taskd.pl [options]
1549 Options:
1550 -h | --help detailed instructions
1551 -q | --quiet run quietly
1552 --no-quiet do not run quietly
1553 -P | --progress show occasional status updates
1554 -i | --inetd run as inetd unix stream wait service
1555 implies --quiet --syslog
1556 -t SECONDS | --idle-timeout=SECONDS how long to wait idle before exiting
1557 requires --inetd
1558 --daemon become a background daemon
1559 implies --quiet --syslog
1560 --max-lifetime=SECONDS how long before graceful restart
1561 default is 1 week, 0 disables
1562 -s | --syslog[=facility] send messages to syslog instead of
1563 stderr but see --stderr
1564 enabled by --inetd
1565 --no-syslog do not send message to syslog
1566 --stderr always send messages to stderr too
1567 --abbrev=n abbreviate hashes to n (default is 8)
1568 --show-fast-forward-info show fast-forward info (default is on)
1569 --no-show-fast-forward-info disable showing fast-forward info
1570 --same-pid keep same pid during graceful restart
1571 --no-same-pid do not keep same pid on graceful rstrt
1572 --status-interval=MINUTES status update interval (default 1)
1573 --idle-status-interval=IDLEMINUTES idle status interval (default 60)
1575 =head1 OPTIONS
1577 =over 8
1579 =item B<--help>
1581 Print the full description of taskd.pl's options.
1583 =item B<--quiet>
1585 Suppress non-error messages, e.g. for use when running this task as an inetd
1586 service. Enabled by default by --inetd.
1588 =item B<--no-quiet>
1590 Enable non-error messages. When running in --inetd mode these messages are
1591 sent to STDERR instead of STDOUT.
1593 =item B<--progress>
1595 Show information about the current status of the task operation occasionally.
1596 This is automatically enabled if --quiet is not given.
1598 =item B<--inetd>
1600 Run as an inetd wait service. File descriptor 0 must be an unconnected unix
1601 stream socket ready to have accept called on it. To be useful, the unix socket
1602 should be located at "$Girocco::Config::chroot/etc/taskd.socket". A warning
1603 will be issued if the socket is not in the expected location. Socket file
1604 permissions will be adjusted if necessary and if they cannot be taskd.pl will
1605 die. The --inetd option also enables the --quiet and --syslog options but
1606 --no-quiet and --no-syslog may be used to alter that.
1608 The correct specification for the inetd socket is a "unix" protocol "stream"
1609 socket in "wait" mode with user and group writable permissions (0660). An
1610 attempt will be made to alter the socket's file mode if needed and if that
1611 cannot be accomplished taskd.pl will die.
1613 Although most inetd stream services run in nowait mode, taskd.pl MUST be run
1614 in wait mode and will die if the passed in socket is already connected.
1616 Note that while *BSD's inetd happily supports unix sockets (and so does
1617 Darwin's launchd), neither xinetd nor GNU's inetd supports unix sockets.
1618 However, systemd does seem to.
1620 =item B<--idle-timeout=SECONDS>
1622 Only permitted when running in --inetd mode. After SECONDS of inactivity
1623 (i.e. all outstanding tasks have completed and no new requests have come in)
1624 exit normally. The default is no timeout at all (a SECONDS value of 0).
1625 Note that it may actually take up to SECONDS+60 for the idle exit to occur.
1627 =item B<--daemon>
1629 Fork and become a background daemon. Implies B<--syslog> and B<--quiet> (which
1630 can be altered by subsequent B<--no-syslog> and/or B<--no-quiet> options).
1631 Also implies B<--no-same-pid>, but since graceful restarts work by re-exec'ing
1632 taskd.pl with all of its original arguments, using B<--same-pid> won't really
1633 be effective with B<--daemon> since although it will cause the graceful restart
1634 exec to happen from the same pid, when the B<--daemon> option is subsequently
1635 processed it will end up in a new pid anyway.
1637 =item B<--max-lifetime=SECONDS>
1639 After taskd has been running for SECONDS of realtime, it will behave as though
1640 a graceful restart has been requested. A graceful restart takes place the
1641 next time taskd becomes idle (which may require up to 60 seconds to notice).
1642 If jobd is running when a graceful restart occurs, then jabd will also receive
1643 a graceful restart request at that time. The default value is 1 week (604800),
1644 set to 0 to disable.
1646 =item B<--syslog[=facility]>
1648 Normally error output is sent to STDERR. With this option it's sent to
1649 syslog instead. Note that when running in --inetd mode non-error output is
1650 also affected by this option as it's sent to STDERR in that case. If
1651 not specified, the default for facility is LOG_USER. Facility names are
1652 case-insensitive and the leading 'LOG_' is optional. Messages are logged
1653 with the LOG_NOTICE priority.
1655 =item B<--no-syslog>
1657 Send error message output to STDERR but not syslog.
1659 =item B<--stderr>
1661 Always send error message output to STDERR. If --syslog is in effect then
1662 a copy will also be sent to syslog. In --inetd mode this applies to non-error
1663 messages as well.
1665 =item B<--abbrev=n>
1667 Abbreviate displayed hash values to only the first n hexadecimal characters.
1668 The default is 8 characters. Set to 0 for no abbreviation at all.
1670 =item B<--show-fast-forward-info>
1672 Instead of showing ' -> ' in ref-change/ref-notify update messages, show either
1673 '..' for a fast-forward, creation or deletion or '...' for non-fast-forward.
1674 This requires running an extra git command for each ref update that is not a
1675 creation or deletion in order to determine whether or not it's a fast forward.
1677 =item B<--no-show-fast-forward-info>
1679 Disable showing of fast-forward information for ref-change/ref-notify update
1680 messages. Instead just show a ' -> ' indicator.
1682 =item B<--same-pid>
1684 When performing a graceful restart, perform the graceful restart exec from
1685 the same pid rather than switching to a new one. This is implied when
1686 I<--daemon> is I<NOT> used.
1688 =item B<--no-same-pid>
1690 When performing a graceful restart, perform the graceful restart exec after
1691 switching to a new pid. This is implied when I<--daemon> I<IS> used.
1693 =item B<--status-interval=MINUTES>
1695 If progress is enabled (with --progress or by default if no --inetd or --quiet)
1696 status updates are shown at each MINUTES interval. Setting the interval to 0
1697 disables them entirely even with --progress.
1699 =item B<--idle-status-interval=IDLEMINUTES>
1701 Two consecutive "idle" status updates with no intervening activity will not be
1702 shown unless IDLEMINUTES have elapsed between them. The default is 60 minutes.
1703 Setting the interval to 0 prevents any consecutive idle updates (with no
1704 activity between them) from appearing at all.
1706 =back
1708 =head1 DESCRIPTION
1710 taskd.pl is Girocco's service request servant; it listens for service requests
1711 such as new clone requests and ref update notifications and spawns a task to
1712 perform the requested action.
1714 =cut