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
82 (Rpc_server.Unix addr)
83 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
88 (* Handle SIGCHLD to clean up jobs. *)
89 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
91 (* Initialize the variables. *)
92 state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
94 and proc_reload_file () =
95 if !debug then Syslog.notice "remote call: reload_file";
97 try reload_file (); `ok
98 with Failure err -> `error err
100 and proc_set_variable (name, value) =
101 if !debug then Syslog.notice "remote call: set_variable %s" name;
104 check_valid_variable_name name;
106 let value = variable_of_rpc value in
107 state := Whenstate.set_variable !state name value;
109 (* Which jobs need to be re-evaluated? *)
110 let jobs = Whenstate.get_dependencies !state name in
111 reevaluate_whenjobs jobs;
115 Failure msg -> `error msg
117 and proc_get_variable name =
118 if !debug then Syslog.notice "remote call: get_variable %s" name;
120 rpc_of_variable (Whenstate.get_variable !state name)
122 and proc_get_variable_names () =
123 if !debug then Syslog.notice "remote call: get_variable_names";
125 let vars = Whenstate.get_variable_names !state in
127 (* Return variable names as a sorted array. *)
128 let vars = Array.of_list vars in
129 Array.sort compare vars;
132 and proc_exit_daemon () =
133 if !debug then Syslog.notice "remote call: exit_daemon";
137 `error "exit_daemon: no server handle"
139 Rpc_server.stop_server ~graceful:true s;
143 and proc_get_jobs () =
144 let running = Array.of_list (IntMap.values !runningmap) in
146 fun (job, dir, serial, start_time) ->
147 { Whenproto_aux.job_name = job.job_name;
148 job_serial = string_of_big_int serial;
149 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
152 and proc_cancel_job serial =
154 let serial = big_int_of_string serial in
155 let pid = BigIntMap.find serial !serialmap in
159 | Not_found -> `error "job not found"
160 | exn -> `error (Printexc.to_string exn)
162 and proc_start_job jobname =
164 let job = Whenstate.get_job !state jobname in
168 | Not_found -> `error "job not found"
169 | exn -> `error (Printexc.to_string exn)
171 and proc_get_job serial =
173 let serial = big_int_of_string serial in
174 let pid = BigIntMap.find serial !serialmap in
175 let job, dir, serial, start_time = IntMap.find pid !runningmap in
176 { Whenproto_aux.job_name = job.job_name;
177 job_serial = string_of_big_int serial;
178 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
180 | Not_found -> failwith "job not found"
181 | exn -> failwith (Printexc.to_string exn)
183 (* Reload the jobs file. *)
185 let file = sprintf "%s/jobs.cmo" !jobsdir in
187 (* As we are reloading the file, we want to create a new state
188 * that has no jobs, but has all the variables from the previous
191 let s = Whenstate.copy_variables !state Whenstate.empty in
196 Dynlink.loadfile file;
197 let s = Whenfile.get_state () in
198 Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
201 | Dynlink.Error err ->
202 let err = Dynlink.error_message err in
203 Syslog.error "error loading jobs: %s" err;
206 failwith (Printexc.to_string exn) in
208 let s = Whenstate.copy_prev_state !state s in
211 (* Re-evaluate all when jobs. *)
212 reevaluate_whenjobs ~onload:true (Whenstate.get_whenjobs !state);
214 (* Schedule the next every job to run. *)
215 schedule_next_everyjob ()
217 (* Re-evaluate each when-statement job, in a loop until we reach
218 * a fixpoint. Run those that need to be run.
220 and reevaluate_whenjobs ?onload jobs =
221 let rec loop set jobs =
226 try Whenstate.evaluate_whenjob ?onload !state job
227 with Invalid_argument err | Failure err ->
228 Syslog.error "error evaluating job %s (at %s): %s"
229 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
235 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
237 if r then StringSet.add job.job_name set else set
239 if StringSet.compare set set' <> 0 then
244 let set = loop StringSet.empty jobs in
245 let jobnames = StringSet.elements set in
247 (* Ensure the jobs always run in predictable (name) order. *)
248 let jobnames = List.sort compare_jobnames jobnames in
251 List.iter run_job (List.map (Whenstate.get_job !state) jobnames)
253 (* Schedule the next every-statement job to run, if there is one. We
254 * look at the every jobs, work out the time that each must run at,
255 * pick the job(s) which must run soonest, and schedule a timer to run
256 * them. When the timer fires, it runs those jobs, then calls this
259 and schedule_next_everyjob () =
262 (* Get only everyjobs. *)
263 let jobs = Whenstate.get_everyjobs !state in
264 let jobs = List.map (
266 | { job_cond = Every_job period } as job -> (job, period)
267 | { job_cond = When_job _ } -> assert false
270 (* Map everyjob to next time it must run. *)
271 let jobs = List.map (
273 let t' = next_periodexpr t period in
274 assert (t' > t); (* serious bug in next_periodexpr if false *)
278 (* Sort, soonest first. *)
279 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
284 Syslog.notice "%s: next scheduled run at %s"
285 job.job_name (string_of_time_t t)
289 (* Pick the job(s) which run soonest. *)
290 let rec pick = function
293 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
294 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
296 let t, jobs = pick jobs in
300 (* Ensure the jobs always run in predictable (name) order. *)
302 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
306 Syslog.notice "scheduling job(s) %s to run at %s"
307 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
308 (string_of_time_t t);
310 (* Schedule them to run at time t. *)
311 let g = new_timer_group () in
312 let t_diff = t -. Unix.time () in
313 let t_diff = if t_diff < 0. then 0. else t_diff in
315 delete_timer_group (); (* Delete the timer. *)
316 List.iter run_job jobs;
317 schedule_next_everyjob ()
319 Unixqueue.weak_once esys g t_diff run_jobs;
323 and new_timer_group () =
324 delete_timer_group ();
325 let g = Unixqueue.new_group esys in
326 timer_group := Some g;
329 and delete_timer_group () =
330 match !timer_group with
333 Unixqueue.clear esys g;
337 (* Increment JOBSERIAL. *)
339 match Whenstate.get_variable !state "JOBSERIAL" with
341 let serial = succ_big_int serial in
342 state := Whenstate.set_variable !state "JOBSERIAL" (T_int serial);
344 | _ -> assert false in
346 (* Call the pre-condition script. Note this may decide not to run
347 * the job by returning false.
349 let pre_condition () =
350 match job.job_pre with
355 fun pid (job, _, serial, start_time) ->
356 let r = { pirun_job_name = job.job_name;
357 pirun_serial = serial;
358 pirun_start_time = start_time;
363 pi_job_name = job.job_name;
365 pi_variables = Whenstate.get_variables !state;
370 if pre_condition () then (
371 Syslog.notice "running %s (JOBSERIAL=%s)"
372 job.job_name (string_of_big_int serial);
374 (* Create a temporary directory. The current directory of the job
375 * will be in this directory. The directory is removed when the
376 * child process exits.
378 let dir = tmpdir () in
381 if pid = 0 then ( (* child process running the job *)
384 (* Set environment variables corresponding to each variable. *)
386 (fun (name, value) -> putenv name (string_of_variable value))
387 (Whenstate.get_variables !state);
389 (* Set the $JOBNAME environment variable. *)
390 putenv "JOBNAME" job.job_name;
392 (* Create a temporary file containing the shell script fragment. *)
393 let script = dir // "script.sh" in
394 let chan = open_out script in
395 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
396 output_string chan job.job_script.sh_script;
400 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
402 (* Set output to file. *)
403 let output = dir // "output.txt" in
404 let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
409 (* Execute the shell script. *)
410 (try execvp shell [| shell; "-c"; script |];
411 with Unix_error (err, fn, _) ->
412 Syslog.error "%s failed: %s: %s" fn script (error_message err)
417 (* Remember this PID, the job and the temporary directory, so we
418 * can clean up when the child exits.
420 runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
421 serialmap := BigIntMap.add serial pid !serialmap
424 Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
425 job.job_name (string_of_big_int serial);
429 let chan = open_in "/dev/urandom" in
430 let data = String.create 16 in
431 really_input chan data 0 (String.length data);
433 let data = Digest.to_hex (Digest.string data) in
434 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
438 (* This is called when a job (child process) exits. *)
439 and handle_sigchld _ =
441 let pid, status = waitpid [WNOHANG] 0 in
443 (* Look up the PID in the running jobs map. *)
444 let job, dir, serial, time = IntMap.find pid !runningmap in
445 runningmap := IntMap.remove pid !runningmap;
446 serialmap := BigIntMap.remove serial !serialmap;
447 post_job job dir serial time status
449 with Unix_error _ | Not_found -> ()
451 and post_job job dir serial time status =
452 (* If there is a post function, run it. *)
453 (match job.job_post with
459 | WSIGNALED s | WSTOPPED s -> 1 in
461 res_job_name = job.job_name;
465 res_output = dir // "output.txt";
466 res_start_time = time
471 Syslog.error "job %s post function failed: %s" job.job_name msg
473 Syslog.error "job %s post function exception: %s"
474 job.job_name (Printexc.to_string exn)
477 (* This should be safe because the path cannot contain shell metachars. *)
478 let cmd = sprintf "rm -rf '%s'" dir in
479 ignore (Sys.command cmd)
481 (* Intelligent comparison of job names. *)
482 and compare_jobnames name1 name2 =
484 let len1 = String.length name1
485 and len2 = String.length name2 in
486 if len1 > 4 && len2 > 4 &&
487 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
489 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
490 let i2 = int_of_string (String.sub name2 4 (len2-4)) in