jobd: shotgun fixes for new job handling
[girocco.git] / jobd / jobd.pl
blob3ca416e6c853397490acf8a6e52cddf70bb52a2b
1 #!/usr/bin/perl
3 # jobd - perform Girocco maintenance jobs
5 # Run with --help for details
7 use strict;
8 use warnings;
10 use Getopt::Long;
11 use Pod::Usage;
12 use POSIX ":sys_wait_h";
14 use Girocco::Config;
15 use Girocco::Project;
16 use Girocco::User;
18 # Options
19 my $quiet;
20 my $progress;
21 my $kill_after = 900;
22 my $max_par = 20;
23 my $lockfile = "/tmp/jobd.lock";
24 my $all_once;
25 my $one;
27 ######### Jobs {{{1
29 sub update_project {
30 my $job = shift;
31 my $p = $job->{'project'};
32 check_project_exists($job) || return;
33 (-e "$Girocco::Config::reporoot/$p.git/.nofetch") && do {
34 job_skip($job);
35 setup_gc($job);
36 return;
38 exec_job_command($job, ["$Girocco::Config::basedir/jobd/update.sh", $p], $quiet);
41 sub gc_project {
42 my $job = shift;
43 my $p = $job->{'project'};
44 check_project_exists($job) || return;
45 exec_job_command($job, ["$Girocco::Config::basedir/jobd/gc.sh", $p], $quiet);
48 sub setup_gc {
49 my $job = shift;
50 queue_job(
51 project => $job->{'project'},
52 type => 'gc',
53 command => \&gc_project,
54 intensive => 1,
58 sub check_project_exists {
59 my $job = shift;
60 my $p = $job->{'project'};
61 if (!-d "$Girocco::Config::reporoot/$p.git") {
62 error("Warning: skipping non-existent project: $job->{project}")
63 unless $quiet;
64 job_skip();
65 return 0;
70 sub queue_one {
71 my $project = shift;
72 queue_job(
73 project => $project,
74 type => 'update',
75 command => \&update_project,
76 on_success => \&setup_gc,
77 on_error => \&setup_gc,
81 sub queue_all {
82 queue_one($_) for (Girocco::Project->get_full_list());
85 ######### Daemon operation {{{1
87 my @queue;
88 my @running;
89 my $perpetual = 1;
90 my $locked = 0;
91 my $jobs_executed;
92 my $jobs_skipped;
93 my @jobs_killed;
95 sub handle_softexit {
96 error("Waiting for outstanding jobs to finish... ".
97 "^C again to exit immediately");
98 @queue = ();
99 $perpetual = 0;
100 $SIG{'INT'} = \&handle_exit;
103 sub handle_exit {
104 error("Killing outstanding jobs...");
105 $SIG{'TERM'} = 'IGNORE';
106 for (@running) {
107 kill 'KILL', $_->{'pid'};
109 unlink $lockfile if ($locked);
110 exit(0);
113 sub queue_job {
114 my %opts = @_;
115 $opts{'queued_at'} = time;
116 $opts{'dont_run'} = 0;
117 $opts{'intensive'} = 0 unless exists $opts{'intensive'};
118 push @queue, \%opts;
121 sub run_job {
122 my $job = shift;
124 push @running, $job;
125 $job->{'command'}->($job);
126 if ($job->{'dont_run'}) {
127 pop @running;
128 $jobs_skipped++;
129 return;
133 sub _job_name {
134 my $job = shift;
135 "[".$job->{'type'}."::".$job->{'project'}."]";
138 # Only one of those per job!
139 sub exec_job_command {
140 my ($job, $command, $err_only) = @_;
142 my $pid;
143 if (!defined($pid = fork)) {
144 error(_job_name($job) ." Can't fork job: $!");
145 $job->{'finished'} = 1;
146 return;
148 if (!$pid) {
149 open STDIN, '/dev/null' || do {
150 error(_job_name($job) ."Can't read from /dev/null: $!");
151 $job->{'finished'} = 1;
152 return;
154 if ($err_only) {
155 open STDOUT, '>/dev/null' || do {
156 error(_job_name($job) ." Can't write to /dev/null: $!");
157 $job->{'finished'} = 1;
158 return;
161 # "Prevent" races
162 select(undef, undef, undef, 0.1);
163 exec @$command;
164 # Stop perl from complaining
165 exit $?;
167 $job->{'pid'} = $pid;
168 $job->{'finished'} = 0;
169 $job->{'started_at'} = time;
172 sub job_skip {
173 my $job = shift;
174 $job->{'dont_run'} = 1;
177 sub reap_hanging_jobs {
178 for (@running) {
179 if (defined($_->{'started_at'}) && (time - $_->{'started_at'}) > $kill_after) {
180 $_->{'finished'} = 1;
181 kill 'KILL', $_->{'pid'};
182 print STDERR _job_name($_) ." KILLED due to timeout\n";
183 push @jobs_killed, _job_name($_);
188 sub reap_finished_jobs {
189 my $pid;
190 while (1) {
191 $pid = waitpid(-1, WNOHANG);
192 last if $pid == -1;
194 my @child = grep { $_->{'pid'} && $_->{'pid'} == $pid } @running;
195 if ($?) {
196 # XXX- we currently don't care
198 if (@child && !$child[0]->{'finished'}) {
199 $child[0]->{'on_success'}->($_) if defined($child[0]->{'on_success'});
200 $jobs_executed++;
201 } elsif (@child) {
202 $child[0]->{'on_error'}->($_) if defined($child[0]->{'on_error'});
205 @running = grep { $_->{'finished'} == 0 } @running;
208 sub have_intensive_jobs {
209 grep { $_->{'intensive'} == 1 } @running;
212 sub run_queue {
213 my $last_progress = time;
214 $jobs_executed = 0;
215 $jobs_skipped = 0;
216 @jobs_killed = ();
217 if ($progress) {
218 printf STDERR "--- Processing %d queued jobs\n", scalar(@queue);
220 $SIG{'INT'} = \&handle_softexit;
221 $SIG{'TERM'} = \&handle_exit;
222 while (@queue || @running) {
223 reap_hanging_jobs();
224 reap_finished_jobs();
225 # Back off if we're too busy
226 if (@running >= $max_par || have_intensive_jobs() || !@queue) {
227 sleep 1;
228 if ($progress && (time - $last_progress) >= 60) {
229 printf STDERR "STATUS: %d queued, %d running, %d finished, %d skipped, %d killed\n", scalar(@queue), scalar(@running), $jobs_executed, $jobs_skipped, scalar(@jobs_killed);
230 if (@running) {
231 my @run_status;
232 for (@running) {
233 push @run_status, _job_name($_)." ". (time - $_->{'started_at'}) ."s";
235 error("STATUS: currently running: ". join(', ', @run_status));
237 $last_progress = time;
239 next;
241 # Run next
242 run_job(shift(@queue)) if @queue;
244 if ($progress) {
245 printf STDERR "--- Queue processed. %d jobs executed, %d skipped, %d killed. Now restarting.\n", $jobs_executed, $jobs_skipped, scalar(@jobs_killed);
249 sub run_perpetually {
250 if (-e $lockfile) {
251 die "Lockfile exists. Please make sure no other instance of jobd is running.";
253 open LOCK, '>', $lockfile || die "Cannot create lockfile $lockfile: $!";
254 print LOCK $$;
255 close LOCK;
256 $locked = 1;
258 while ($perpetual) {
259 queue_all();
260 run_queue();
262 unlink $lockfile;
265 ######### Helpers {{{1
267 sub error($) {
268 print STDERR shift()."\n";
270 sub fatal($) {
271 error(shift);
272 exit 1;
275 ######### Main {{{1
277 # Parse options
278 Getopt::Long::Configure('bundling');
279 my $parse_res = GetOptions(
280 'help|?' => sub { pod2usage(-verbose => 1, -exitval => 0); },
281 'quiet|q' => \$quiet,
282 'progress|P' => \$progress,
283 'kill-after|k=i' => \$kill_after,
284 'max-parallel|p=i' => \$max_par,
285 'lockfile|l=s' => \$lockfile,
286 'all-once|a' => \$all_once,
287 'one|o=s' => \$one,
288 ) || pod2usage(2);
289 fatal("Error: can only use one out of --all-once and --one")
290 if ($all_once && $one);
292 unless ($quiet) {
293 $ENV{'show_progress'} = '1';
294 $progress = 1;
297 if ($one) {
298 queue_one($one);
299 run_queue();
300 exit;
303 if ($all_once) {
304 queue_all();
305 run_queue();
306 exit;
309 run_perpetually();
311 ########## Documentation {{{1
313 __END__
315 =head1 NAME
317 jobd - Perform Girocco maintenance jobs
319 =head1 SYNOPSIS
321 jobd [options]
323 Options:
324 -h | --help detailed instructions
325 -q | --quiet run quietly
326 -P | --progress show occasional status updates
327 -k SECONDS | --kill-after=SECONDS how long to wait before killing jobs
328 -p NUM | --max-parallel=NUM how many jobs to run at the same time
329 -l FILE | --lockfile=FILE create a lockfile in the given location
330 -a | --all-once process the list only once
331 -o PRJNAME | --one=PRJNAME process only one project
333 =head1 OPTIONS
335 =over 8
337 =item B<--help>
339 Print the full description of jobd's options.
341 =item B<--quiet>
343 Suppress non-error messages, e.g. for use when running this task as a cronjob.
345 =item B<--progress>
347 Show information about the current status of the job queue occasionally. This
348 is automatically enabled if --quiet is not given.
350 =item B<--kill-after=SECONDS>
352 Kill supervised jobs after a certain time to avoid hanging the daemon.
354 =item B<--max-parallel=NUM>
356 Run no more than that many jobs at the same time.
358 =item B<--lockfile=FILE>
360 For perpetual operation, create a lockfile in that place and clean it up after
361 finishing/aborting.
363 =item B<--all-once>
365 Instead of perpetuously processing all projects over and over again, process
366 them just once and then exit.
368 =item B<--one=PRJNAME>
370 Process only the given project (given as just the project name without C<.git>
371 suffix) and then exit.
373 =back
375 =head1 DESCRIPTION
377 jobd is Girocco's repositories maintenance servant; it periodically checks all
378 the repositories and updates mirrored repositories and repacks push-mode
379 repositories when needed.
381 =cut