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"
34 * Note that whenever this is updated, you need to consider if you
35 * should call 'save_variables ()' (which persists the variables to a
36 * file). XXX We should replace this ref with an accessor
39 let state = ref Whenstate.empty
41 (* Format used to save variables. Note we can't allow any internal
42 * types to "escape" into this definition, else the file format will
43 * change when parts of the program change.
45 type variables_file_v1 = (string * variable_v1) list
49 | Vv1_string of string
53 let variable_of_variable_v1 = function
55 | Vv1_bool b -> T_bool b
56 | Vv1_string s -> T_string s
57 | Vv1_int i -> T_int i
58 | Vv1_float f -> T_float f
60 let variable_v1_of_variable = function
62 | T_bool b -> Vv1_bool b
63 | T_string s -> Vv1_string s
64 | T_int i -> Vv1_int i
65 | T_float f -> Vv1_float f
67 (* Jobs that are running: a map of PID -> (job, tmpdir, serial, start_time).
68 * Note that the job may no longer exist *OR* it may have been renamed,
69 * eg. if the jobs file was reloaded.
71 let runningmap = ref IntMap.empty
73 (* Serial numbers of running jobs. Map of serial -> PID (in runningmap). *)
74 let serialmap = ref BigIntMap.empty
76 (* Was debugging requested on the command line? *)
82 let esys = Unixqueue.standard_event_system ()
84 (* The timer. It's convenient to have this as a global variable
85 * because (a) there should only be one timer (which fires when the
86 * soonest every-job becomes ready), and (b) it's complicated to track
87 * that timer and avoid it getting double-scheduled (eg. when we
88 * reload the jobs file) without having a global variable.
90 let timer_group = ref None
96 Whenlock.create_lock !jobsdir;
98 (* Remove old socket if it exists. *)
99 let addr = sprintf "%s/socket" !jobsdir in
100 (try unlink addr with Unix_error _ -> ());
102 (* Create the Unix domain socket server. *)
104 Whenproto_srv.When.V1.create_server
108 ~proc_get_variable_names
118 ~proc_whisper_variables
119 (Rpc_server.Unix addr)
120 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
125 (* Handle SIGCHLD to clean up jobs. *)
126 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
128 (* Load or initialize the variables. *)
129 let variables_file = sprintf "%s/variables" !jobsdir in
132 let chan = open_in variables_file in
133 let r = load_variables !state chan in
138 Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
140 (* Try to load the variables from the file. If the file exists and
141 * cannot be read, raise an exception.
143 and load_variables state chan =
144 let signature = input_line chan in
145 if signature = "WHENJOBS VARIABLES VERSION 1" then (
146 let variables : variables_file_v1 = input_value chan in
149 Whenstate.set_variable state n (variable_of_variable_v1 v)
151 ) else (* in future, other signatures, but for now ... *)
152 failwith (sprintf "cannot read variables file: invalid signature: %s"
155 and save_variables () =
156 let variables_file = sprintf "%s/variables" !jobsdir in
157 let new_file = variables_file ^ ".new" in
158 let chan = open_out new_file in
159 fprintf chan "WHENJOBS VARIABLES VERSION 1\n";
160 let variables = Whenstate.get_variables !state in
162 List.map (fun (n, v) -> n, variable_v1_of_variable v) variables in
163 output_value chan variables;
165 (* Try to arrange that the new file is updated atomically. *)
167 Netsys_posix.fsync (descr_of_out_channel chan);
169 rename new_file variables_file
171 and proc_reload_file () =
172 if !debug then Syslog.notice "remote call: reload_file";
174 try reload_files (); `ok
175 with Failure err -> `error err
177 and proc_set_variable (name, value) =
178 if !debug then Syslog.notice "remote call: set_variable %s" name;
181 check_valid_variable_name name;
183 let value = variable_of_rpc value in
184 state := Whenstate.set_variable !state name value;
186 (* Which jobs need to be re-evaluated? *)
187 let jobs = Whenstate.get_dependencies !state [name] in
188 let jobnames, state' = reevaluate_whenjobs !state jobs in
189 let state' = run_whenjobs state' jobnames in
195 Failure msg -> `error msg
197 and proc_get_variable name =
198 if !debug then Syslog.notice "remote call: get_variable %s" name;
200 rpc_of_variable (Whenstate.get_variable !state name)
202 and proc_get_variable_names () =
203 if !debug then Syslog.notice "remote call: get_variable_names";
205 let vars = Whenstate.get_variable_names !state in
207 (* Return variable names as a sorted array. *)
208 let vars = Array.of_list vars in
209 Array.sort compare vars;
212 and proc_exit_daemon () =
213 if !debug then Syslog.notice "remote call: exit_daemon";
217 `error "exit_daemon: no server handle"
219 Rpc_server.stop_server ~graceful:true s;
221 Gc.compact (); (* force the server handle to get cleaned up now *)
224 and proc_get_jobs () =
225 let running = Array.of_list (IntMap.values !runningmap) in
227 fun (job, dir, serial, start_time) ->
228 { Whenproto_aux.job_name = job.job_name;
229 job_serial = string_of_big_int serial;
230 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
233 and proc_cancel_job serial =
235 let serial = big_int_of_string serial in
236 let pid = BigIntMap.find serial !serialmap in
240 | Not_found -> `error "job not found"
241 | exn -> `error (Printexc.to_string exn)
243 and proc_start_job jobname =
245 let job = Whenstate.get_job !state jobname in
246 let state' = run_job !state job in
251 | Not_found -> `error "job not found"
252 | exn -> `error (Printexc.to_string exn)
254 and proc_get_job serial =
256 let serial = big_int_of_string serial in
257 let pid = BigIntMap.find serial !serialmap in
258 let job, dir, serial, start_time = IntMap.find pid !runningmap in
259 { Whenproto_aux.job_name = job.job_name;
260 job_serial = string_of_big_int serial;
261 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
263 | Not_found -> failwith "job not found"
264 | exn -> failwith (Printexc.to_string exn)
266 and proc_set_variables vars =
268 let vars = Array.map (
269 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
270 name, variable_of_rpc value
272 let vars = Array.to_list vars in
275 Syslog.notice "remote call: set_variables (%s)"
279 sprintf "%s=%s" name (string_of_variable value)
282 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
284 (* Update all the variables atomically. *)
285 let s = List.fold_left (
286 fun s (name, value) -> Whenstate.set_variable s name value
290 (* Which jobs need to be re-evaluated? *)
291 let jobs = Whenstate.get_dependencies !state (List.map fst vars) in
292 let jobnames, state' = reevaluate_whenjobs !state jobs in
293 let state' = run_whenjobs state' jobnames in
299 Failure msg -> `error msg
301 and proc_get_job_names () =
302 Array.of_list (Whenstate.get_job_names !state)
304 and proc_test_variables vars =
305 (* This is the same as proc_set_variables, except that it doesn't
306 * update the state, it just returns the jobs that *would* run if
307 * these variables were set to these values.
309 let vars = Array.map (
310 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
311 name, variable_of_rpc value
313 let vars = Array.to_list vars in
316 Syslog.notice "remote call: test_variables (%s)"
320 sprintf "%s=%s" name (string_of_variable value)
323 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
325 (* Update all the variables atomically. *)
326 let state = List.fold_left (
327 fun s (name, value) -> Whenstate.set_variable s name value
330 (* Which jobs WOULD be re-evaluated? *)
331 let jobs = Whenstate.get_dependencies state (List.map fst vars) in
332 let jobnames, _ = reevaluate_whenjobs state jobs in
334 (* Return the names. *)
335 Array.of_list jobnames
337 and proc_ping_daemon () = `ok
339 and proc_whisper_variables vars =
341 let vars = Array.map (
342 fun { Whenproto_aux.sv_name = name; sv_value = value } ->
343 name, variable_of_rpc value
345 let vars = Array.to_list vars in
348 Syslog.notice "remote call: whisper_variables (%s)"
352 sprintf "%s=%s" name (string_of_variable value)
355 List.iter (fun (name, _) -> check_valid_variable_name name) vars;
357 (* Update all the variables atomically. *)
358 let s = List.fold_left (
359 fun s (name, value) -> Whenstate.set_variable s name value
364 (* .. but don't reevaluate or run jobs. *)
368 Failure msg -> `error msg
370 (* Reload the jobs file(s). *)
371 and reload_files () =
372 (* Get the highest numbered dir/jobs__*.cmo (bytecode) or
373 * dir/jobs__*.cmxs (native code) file and load it. Delete
374 * lower-numbered (== older) files.
378 if not Dynlink.is_native then ".cmo", 4 else ".cmxs", 5 in
379 let dir = !jobsdir in
380 let files = Array.to_list (Sys.readdir dir) in
381 let times = filter_map (
383 if not (string_startswith file "jobs__") ||
384 not (string_endswith file suffix) then
387 let len = String.length file in
388 let t = String.sub file 6 (len-slen-6) in
389 (* Use int64 because t won't necessarily fit into 31 bit int. *)
390 try Some (Int64.of_string t)
391 with Failure "int_of_string" -> assert false
394 let times = List.rev (List.sort compare times) in
398 (* Unlink the older files. *)
401 try unlink (dir // sprintf "jobs__%Ld%s" t suffix)
402 with Unix_error _ -> ()
404 (* Return the newest (highest numbered) file. *)
405 Some (dir // sprintf "jobs__%Ld%s" x suffix) in
407 (* As we are reloading the file, we want to create a new state
408 * that has no jobs, but has all the variables from the previous
411 let s = Whenstate.copy_variables !state Whenstate.empty in
417 (* no jobs file, return the same state *)
418 Syslog.notice "no jobs file found";
422 Dynlink.loadfile filename;
423 let s = Whenfile.get_state () in
424 Syslog.notice "loaded %d job(s)" (Whenstate.nr_jobs s);
427 | Dynlink.Error err ->
428 let err = Dynlink.error_message err in
429 Syslog.error "error loading jobs: %s" err;
432 failwith (Printexc.to_string exn) in
434 let s = Whenstate.copy_prev_state !state s in
437 (* Re-evaluate all when jobs. *)
438 let jobs = Whenstate.get_whenjobs !state in
439 let jobnames, state' = reevaluate_whenjobs ~onload:true !state jobs in
440 let state' = run_whenjobs state' jobnames in
444 (* Schedule the next every job to run. *)
445 schedule_next_everyjob ()
447 (* Re-evaluate each when-statement job, in a loop until we reach
448 * a fixpoint. Return the list of job names that should run and
451 and reevaluate_whenjobs ?onload state jobs =
452 let rec loop (set, state) jobs =
455 fun (set, state) job ->
457 try Whenstate.evaluate_whenjob ?onload state job
458 with Invalid_argument err | Failure err ->
459 Syslog.error "error evaluating job %s (at %s): %s"
460 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
464 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
466 (if r then StringSet.add job.job_name set else set), state'
467 ) (set, state) jobs in
468 (* reached a fixpoint? *)
469 if StringSet.compare set set' <> 0 then
470 loop (set', state') jobs
474 let set, state = loop (StringSet.empty, state) jobs in
475 let jobnames = StringSet.elements set in
477 (* Ensure the jobs always run in predictable (name) order. *)
478 let jobnames = List.sort compare_jobnames jobnames in
481 and run_whenjobs state jobnames =
483 let jobs = List.map (Whenstate.get_job state) jobnames in
484 List.fold_left run_job state jobs
486 (* Schedule the next every-statement job to run, if there is one. We
487 * look at the every jobs, work out the time that each must run at,
488 * pick the job(s) which must run soonest, and schedule a timer to run
489 * them. When the timer fires, it runs those jobs, then calls this
492 and schedule_next_everyjob () =
495 (* Get only everyjobs. *)
496 let jobs = Whenstate.get_everyjobs !state in
497 let jobs = List.map (
499 | { job_cond = Every_job period } as job -> (job, period)
500 | { job_cond = When_job _ } -> assert false
503 (* Map everyjob to next time it must run. *)
504 let jobs = List.map (
506 let t' = next_periodexpr t period in
507 assert (t' > t); (* serious bug in next_periodexpr if false *)
511 (* Sort, soonest first. *)
512 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
517 Syslog.notice "%s: next scheduled run at %s"
518 job.job_name (string_of_time_t t)
522 (* Pick the job(s) which run soonest. *)
523 let rec pick = function
526 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
527 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
529 let t, jobs = pick jobs in
533 (* Ensure the jobs always run in predictable (name) order. *)
535 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
539 Syslog.notice "scheduling job(s) %s to run at %s"
540 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
541 (string_of_time_t t);
543 (* Schedule them to run at time t. *)
544 let g = new_timer_group () in
545 let t_diff = t -. Unix.time () in
546 let t_diff = if t_diff < 0. then 0. else t_diff in
548 delete_timer_group (); (* Delete the timer. *)
549 let state' = List.fold_left run_job !state jobs in
552 schedule_next_everyjob ()
554 Unixqueue.weak_once esys g t_diff run_jobs;
558 and new_timer_group () =
559 delete_timer_group ();
560 let g = Unixqueue.new_group esys in
561 timer_group := Some g;
564 and delete_timer_group () =
565 match !timer_group with
568 Unixqueue.clear esys g;
571 and run_job state job =
572 (* Increment JOBSERIAL. *)
574 match Whenstate.get_variable state "JOBSERIAL" with
576 let serial = succ_big_int serial in
577 let state' = Whenstate.set_variable state "JOBSERIAL" (T_int serial) in
579 | _ -> assert false in
581 (* Call the pre-condition script. Note this may decide not to run
582 * the job by returning false.
584 let pre_condition () =
585 match job.job_pre with
590 fun pid (job, _, serial, start_time) ->
591 let r = { pirun_job_name = job.job_name;
592 pirun_serial = serial;
593 pirun_start_time = start_time;
598 pi_job_name = job.job_name;
600 pi_variables = Whenstate.get_variables state;
605 if pre_condition () then (
606 Syslog.notice "running %s (JOBSERIAL=%s)"
607 job.job_name (string_of_big_int serial);
609 (* Create a temporary directory. The current directory of the job
610 * will be in this directory. The directory is removed when the
611 * child process exits.
613 let dir = tmpdir () in
616 if pid = 0 then ( (* child process running the job *)
619 (* Set environment variables corresponding to each variable. *)
621 (fun (name, value) -> putenv name (string_of_variable value))
622 (Whenstate.get_variables state);
624 (* Set the $JOBNAME environment variable. *)
625 putenv "JOBNAME" job.job_name;
627 (* Create a temporary file containing the shell script fragment. *)
628 let script = dir // "script.sh" in
629 let chan = open_out script in
630 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
631 output_string chan job.job_script.sh_script;
635 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
637 (* Set output to file. *)
638 let output = dir // "output.txt" in
639 let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
644 (* Execute the shell script. *)
645 (try execvp shell [| shell; "-c"; script |];
646 with Unix_error (err, fn, _) ->
647 Syslog.error "%s failed: %s: %s" fn script (error_message err)
652 (* Remember this PID, the job and the temporary directory, so we
653 * can clean up when the child exits.
655 runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
656 serialmap := BigIntMap.add serial pid !serialmap;
661 Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
662 job.job_name (string_of_big_int serial);
668 let chan = open_in "/dev/urandom" in
669 let data = String.create 16 in
670 really_input chan data 0 (String.length data);
672 let data = Digest.to_hex (Digest.string data) in
673 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
677 (* This is called when a job (child process) exits. *)
678 and handle_sigchld _ =
680 let pid, status = waitpid [WNOHANG] 0 in
682 (* Look up the PID in the running jobs map. *)
683 let job, dir, serial, time = IntMap.find pid !runningmap in
684 runningmap := IntMap.remove pid !runningmap;
685 serialmap := BigIntMap.remove serial !serialmap;
686 post_job job dir serial time status
688 with Unix_error _ | Not_found -> ()
690 and post_job job dir serial time status =
691 (* If there is a post function, run it. *)
692 (match job.job_post with
698 | WSIGNALED s | WSTOPPED s -> 1 in
700 res_job_name = job.job_name;
704 res_output = dir // "output.txt";
705 res_start_time = time
710 Syslog.error "job %s post function failed: %s" job.job_name msg
712 Syslog.error "job %s post function exception: %s"
713 job.job_name (Printexc.to_string exn)
716 (* This should be safe because the path cannot contain shell metachars. *)
717 let cmd = sprintf "rm -rf '%s'" dir in
718 ignore (Sys.command cmd)
720 (* Intelligent comparison of job names. *)
721 and compare_jobnames name1 name2 =
723 let len1 = String.length name1
724 and len2 = String.length name2 in
725 if len1 > 4 && len2 > 4 &&
726 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
728 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
729 let i2 = int_of_string (String.sub name2 4 (len2-4)) in