2 * Copyright (C) 2012 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 external _exit : int -> 'a = "whenjobs__exit"
33 let state = ref Whenstate.empty
35 (* Jobs that are running: a map of PID -> (job, tmpdir, serial, start_time).
36 * Note that the job may no longer exist *OR* it may have been renamed,
37 * eg. if the jobs file was reloaded.
39 let runningmap = ref IntMap.empty
41 (* Serial numbers of running jobs. Map of serial -> PID (in runningmap). *)
42 let serialmap = ref BigIntMap.empty
44 (* Was debugging requested on the command line? *)
50 let esys = Unixqueue.standard_event_system ()
52 (* The timer. It's convenient to have this as a global variable
53 * because (a) there should only be one timer (which fires when the
54 * soonest every-job becomes ready), and (b) it's complicated to track
55 * that timer and avoid it getting double-scheduled (eg. when we
56 * reload the jobs file) without having a global variable.
58 let timer_group = ref None
64 Whenlock.create_lock !jobsdir;
66 (* Remove old socket if it exists. *)
67 let addr = sprintf "%s/socket" !jobsdir in
68 (try unlink addr with Unix_error _ -> ());
70 (* Create the Unix domain socket server. *)
72 Whenproto_srv.When.V1.create_server
76 ~proc_get_variable_names
86 ~proc_whisper_variables
87 (Rpc_server.Unix addr)
88 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
93 (* Handle SIGCHLD to clean up jobs. *)
94 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
96 (* Initialize the variables. *)
97 state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
99 and proc_reload_file () =
100 if !debug then Syslog.notice "remote call: reload_file";
102 try reload_files (); `ok
103 with Failure err -> `error err
105 and proc_set_variable (name, value) =
106 if !debug then Syslog.notice "remote call: set_variable %s" name;
109 check_valid_variable_name name;
111 let value = variable_of_rpc value in
112 state := Whenstate.set_variable !state name value;
114 (* Which jobs need to be re-evaluated? *)
115 let jobs = Whenstate.get_dependencies !state [name] in
116 let jobnames, state' = reevaluate_whenjobs !state jobs in
117 let state' = run_whenjobs state' jobnames in
122 Failure msg -> `error msg
124 and proc_get_variable name =
125 if !debug then Syslog.notice "remote call: get_variable %s" name;
127 rpc_of_variable (Whenstate.get_variable !state name)
129 and proc_get_variable_names () =
130 if !debug then Syslog.notice "remote call: get_variable_names";
132 let vars = Whenstate.get_variable_names !state in
134 (* Return variable names as a sorted array. *)
135 let vars = Array.of_list vars in
136 Array.sort compare vars;
139 and proc_exit_daemon () =
140 if !debug then Syslog.notice "remote call: exit_daemon";
144 `error "exit_daemon: no server handle"
146 Rpc_server.stop_server ~graceful:true s;
150 and proc_get_jobs () =
151 let running = Array.of_list (IntMap.values !runningmap) in
153 fun (job, dir, serial, start_time) ->
154 { Whenproto_aux.job_name = job.job_name;
155 job_serial = string_of_big_int serial;
156 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
159 and proc_cancel_job serial =
161 let serial = big_int_of_string serial in
162 let pid = BigIntMap.find serial !serialmap in
166 | Not_found -> `error "job not found"
167 | exn -> `error (Printexc.to_string exn)
169 and proc_start_job jobname =
171 let job = Whenstate.get_job !state jobname in
172 let state' = run_job !state job in
176 | Not_found -> `error "job not found"
177 | exn -> `error (Printexc.to_string exn)
179 and proc_get_job serial =
181 let serial = big_int_of_string serial in
182 let pid = BigIntMap.find serial !serialmap in
183 let job, dir, serial, start_time = IntMap.find pid !runningmap in
184 { Whenproto_aux.job_name = job.job_name;
185 job_serial = string_of_big_int serial;
186 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
188 | Not_found -> failwith "job not found"
189 | exn -> failwith (Printexc.to_string exn)
191 and proc_set_variables vars =
193 let vars = Array.map (
194 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
195 name, variable_of_rpc value
197 let vars = Array.to_list vars in
200 Syslog.notice "remote call: set_variables (%s)"
204 sprintf "%s=%s" name (string_of_variable value)
207 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
209 (* Update all the variables atomically. *)
210 let s = List.fold_left (
211 fun s (name, value) -> Whenstate.set_variable s name value
215 (* Which jobs need to be re-evaluated? *)
216 let jobs = Whenstate.get_dependencies !state (List.map fst vars) in
217 let jobnames, state' = reevaluate_whenjobs !state jobs in
218 let state' = run_whenjobs state' jobnames in
223 Failure msg -> `error msg
225 and proc_get_job_names () =
226 Array.of_list (Whenstate.get_job_names !state)
228 and proc_test_variables vars =
229 (* This is the same as proc_set_variables, except that it doesn't
230 * update the state, it just returns the jobs that *would* run if
231 * these variables were set to these values.
233 let vars = Array.map (
234 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
235 name, variable_of_rpc value
237 let vars = Array.to_list vars in
240 Syslog.notice "remote call: test_variables (%s)"
244 sprintf "%s=%s" name (string_of_variable value)
247 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
249 (* Update all the variables atomically. *)
250 let state = List.fold_left (
251 fun s (name, value) -> Whenstate.set_variable s name value
254 (* Which jobs WOULD be re-evaluated? *)
255 let jobs = Whenstate.get_dependencies state (List.map fst vars) in
256 let jobnames, _ = reevaluate_whenjobs state jobs in
258 (* Return the names. *)
259 Array.of_list jobnames
261 and proc_ping_daemon () = `ok
263 and proc_whisper_variables vars =
265 let vars = Array.map (
266 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
267 name, variable_of_rpc value
269 let vars = Array.to_list vars in
272 Syslog.notice "remote call: whisper_variables (%s)"
276 sprintf "%s=%s" name (string_of_variable value)
279 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
281 (* Update all the variables atomically. *)
282 let s = List.fold_left (
283 fun s (name, value) -> Whenstate.set_variable s name value
287 (* .. but don't reevaluate or run jobs. *)
291 Failure msg -> `error msg
293 (* Reload the jobs file(s). *)
294 and reload_files () =
295 (* Get dir/*.cmo (bytecode) or dir/*.cmxs (native code) *)
296 let suffix = if not Dynlink.is_native then ".cmo" else ".cmxs" in
297 let dir = !jobsdir in
298 let files = Array.to_list (Sys.readdir dir) in
299 let files = List.filter (fun file -> string_endswith file suffix) files in
300 let files = List.map (fun file -> dir // file) files in
301 let files = List.sort compare files in
303 (* As we are reloading the file, we want to create a new state
304 * that has no jobs, but has all the variables from the previous
307 let s = Whenstate.copy_variables !state Whenstate.empty in
312 List.iter Dynlink.loadfile files;
313 let s = Whenfile.get_state () in
314 Syslog.notice "loaded %d job(s) from %d file(s)"
315 (Whenstate.nr_jobs s) (List.length files);
318 | Dynlink.Error err ->
319 let err = Dynlink.error_message err in
320 Syslog.error "error loading jobs: %s" err;
323 failwith (Printexc.to_string exn) in
325 let s = Whenstate.copy_prev_state !state s in
328 (* Re-evaluate all when jobs. *)
329 let jobs = Whenstate.get_whenjobs !state in
330 let jobnames, state' = reevaluate_whenjobs ~onload:true !state jobs in
331 let state' = run_whenjobs state' jobnames in
334 (* Schedule the next every job to run. *)
335 schedule_next_everyjob ()
337 (* Re-evaluate each when-statement job, in a loop until we reach
338 * a fixpoint. Return the list of job names that should run and
341 and reevaluate_whenjobs ?onload state jobs =
342 let rec loop (set, state) jobs =
345 fun (set, state) job ->
347 try Whenstate.evaluate_whenjob ?onload state job
348 with Invalid_argument err | Failure err ->
349 Syslog.error "error evaluating job %s (at %s): %s"
350 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
354 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
356 (if r then StringSet.add job.job_name set else set), state'
357 ) (set, state) jobs in
358 (* reached a fixpoint? *)
359 if StringSet.compare set set' <> 0 then
360 loop (set', state') jobs
364 let set, state = loop (StringSet.empty, state) jobs in
365 let jobnames = StringSet.elements set in
367 (* Ensure the jobs always run in predictable (name) order. *)
368 let jobnames = List.sort compare_jobnames jobnames in
371 and run_whenjobs state jobnames =
373 let jobs = List.map (Whenstate.get_job state) jobnames in
374 List.fold_left run_job state jobs
376 (* Schedule the next every-statement job to run, if there is one. We
377 * look at the every jobs, work out the time that each must run at,
378 * pick the job(s) which must run soonest, and schedule a timer to run
379 * them. When the timer fires, it runs those jobs, then calls this
382 and schedule_next_everyjob () =
385 (* Get only everyjobs. *)
386 let jobs = Whenstate.get_everyjobs !state in
387 let jobs = List.map (
389 | { job_cond = Every_job period } as job -> (job, period)
390 | { job_cond = When_job _ } -> assert false
393 (* Map everyjob to next time it must run. *)
394 let jobs = List.map (
396 let t' = next_periodexpr t period in
397 assert (t' > t); (* serious bug in next_periodexpr if false *)
401 (* Sort, soonest first. *)
402 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
407 Syslog.notice "%s: next scheduled run at %s"
408 job.job_name (string_of_time_t t)
412 (* Pick the job(s) which run soonest. *)
413 let rec pick = function
416 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
417 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
419 let t, jobs = pick jobs in
423 (* Ensure the jobs always run in predictable (name) order. *)
425 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
429 Syslog.notice "scheduling job(s) %s to run at %s"
430 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
431 (string_of_time_t t);
433 (* Schedule them to run at time t. *)
434 let g = new_timer_group () in
435 let t_diff = t -. Unix.time () in
436 let t_diff = if t_diff < 0. then 0. else t_diff in
438 delete_timer_group (); (* Delete the timer. *)
439 let state' = List.fold_left run_job !state jobs in
441 schedule_next_everyjob ()
443 Unixqueue.weak_once esys g t_diff run_jobs;
447 and new_timer_group () =
448 delete_timer_group ();
449 let g = Unixqueue.new_group esys in
450 timer_group := Some g;
453 and delete_timer_group () =
454 match !timer_group with
457 Unixqueue.clear esys g;
460 and run_job state job =
461 (* Increment JOBSERIAL. *)
463 match Whenstate.get_variable state "JOBSERIAL" with
465 let serial = succ_big_int serial in
466 let state' = Whenstate.set_variable state "JOBSERIAL" (T_int serial) in
468 | _ -> assert false in
470 (* Call the pre-condition script. Note this may decide not to run
471 * the job by returning false.
473 let pre_condition () =
474 match job.job_pre with
479 fun pid (job, _, serial, start_time) ->
480 let r = { pirun_job_name = job.job_name;
481 pirun_serial = serial;
482 pirun_start_time = start_time;
487 pi_job_name = job.job_name;
489 pi_variables = Whenstate.get_variables state;
494 if pre_condition () then (
495 Syslog.notice "running %s (JOBSERIAL=%s)"
496 job.job_name (string_of_big_int serial);
498 (* Create a temporary directory. The current directory of the job
499 * will be in this directory. The directory is removed when the
500 * child process exits.
502 let dir = tmpdir () in
505 if pid = 0 then ( (* child process running the job *)
508 (* Set environment variables corresponding to each variable. *)
510 (fun (name, value) -> putenv name (string_of_variable value))
511 (Whenstate.get_variables state);
513 (* Set the $JOBNAME environment variable. *)
514 putenv "JOBNAME" job.job_name;
516 (* Create a temporary file containing the shell script fragment. *)
517 let script = dir // "script.sh" in
518 let chan = open_out script in
519 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
520 output_string chan job.job_script.sh_script;
524 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
526 (* Set output to file. *)
527 let output = dir // "output.txt" in
528 let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
533 (* Execute the shell script. *)
534 (try execvp shell [| shell; "-c"; script |];
535 with Unix_error (err, fn, _) ->
536 Syslog.error "%s failed: %s: %s" fn script (error_message err)
541 (* Remember this PID, the job and the temporary directory, so we
542 * can clean up when the child exits.
544 runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
545 serialmap := BigIntMap.add serial pid !serialmap;
550 Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
551 job.job_name (string_of_big_int serial);
557 let chan = open_in "/dev/urandom" in
558 let data = String.create 16 in
559 really_input chan data 0 (String.length data);
561 let data = Digest.to_hex (Digest.string data) in
562 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
566 (* This is called when a job (child process) exits. *)
567 and handle_sigchld _ =
569 let pid, status = waitpid [WNOHANG] 0 in
571 (* Look up the PID in the running jobs map. *)
572 let job, dir, serial, time = IntMap.find pid !runningmap in
573 runningmap := IntMap.remove pid !runningmap;
574 serialmap := BigIntMap.remove serial !serialmap;
575 post_job job dir serial time status
577 with Unix_error _ | Not_found -> ()
579 and post_job job dir serial time status =
580 (* If there is a post function, run it. *)
581 (match job.job_post with
587 | WSIGNALED s | WSTOPPED s -> 1 in
589 res_job_name = job.job_name;
593 res_output = dir // "output.txt";
594 res_start_time = time
599 Syslog.error "job %s post function failed: %s" job.job_name msg
601 Syslog.error "job %s post function exception: %s"
602 job.job_name (Printexc.to_string exn)
605 (* This should be safe because the path cannot contain shell metachars. *)
606 let cmd = sprintf "rm -rf '%s'" dir in
607 ignore (Sys.command cmd)
609 (* Intelligent comparison of job names. *)
610 and compare_jobnames name1 name2 =
612 let len1 = String.length name1
613 and len2 = String.length name2 in
614 if len1 > 4 && len2 > 4 &&
615 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
617 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
618 let i2 = int_of_string (String.sub name2 4 (len2-4)) in