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
81 (Rpc_server.Unix addr)
82 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
87 (* Handle SIGCHLD to clean up jobs. *)
88 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
90 (* Initialize the variables. *)
91 state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
93 and proc_reload_file () =
94 if !debug then Syslog.notice "remote call: reload_file";
96 try reload_file (); `ok
97 with Failure err -> `error err
99 and proc_set_variable (name, value) =
100 if !debug then Syslog.notice "remote call: set_variable %s" name;
103 check_valid_variable_name name;
105 let value = variable_of_rpc value in
106 state := Whenstate.set_variable !state name value;
108 (* Which jobs need to be re-evaluated? *)
109 let jobs = Whenstate.get_dependencies !state name in
110 reevaluate_whenjobs jobs;
114 Failure msg -> `error msg
116 and proc_get_variable name =
117 if !debug then Syslog.notice "remote call: get_variable %s" name;
119 rpc_of_variable (Whenstate.get_variable !state name)
121 and proc_get_variable_names () =
122 if !debug then Syslog.notice "remote call: get_variable_names";
124 let vars = Whenstate.get_variable_names !state in
126 (* Return variable names as a sorted array. *)
127 let vars = Array.of_list vars in
128 Array.sort compare vars;
131 and proc_exit_daemon () =
132 if !debug then Syslog.notice "remote call: exit_daemon";
136 `error "exit_daemon: no server handle"
138 Rpc_server.stop_server ~graceful:true s;
142 and proc_get_jobs () =
143 let running = Array.of_list (IntMap.values !runningmap) in
145 fun (job, dir, serial, start_time) ->
146 { Whenproto_aux.job_name = job.job_name;
147 job_serial = string_of_big_int serial;
148 job_tmpdir = dir; job_start_time = Int64.of_float start_time }
151 and proc_cancel_job serial =
153 let serial = big_int_of_string serial in
154 let pid = BigIntMap.find serial !serialmap in
158 | Not_found -> `error "job not found"
159 | exn -> `error (Printexc.to_string exn)
161 and proc_start_job jobname =
163 let job = Whenstate.get_job !state jobname in
167 | Not_found -> `error "job not found"
168 | exn -> `error (Printexc.to_string exn)
170 (* Reload the jobs file. *)
172 let file = sprintf "%s/jobs.cmo" !jobsdir in
174 (* As we are reloading the file, we want to create a new state
175 * that has no jobs, but has all the variables from the previous
178 let s = Whenstate.copy_variables !state Whenstate.empty in
183 Dynlink.loadfile file;
184 let s = Whenfile.get_state () in
185 Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
188 | Dynlink.Error err ->
189 let err = Dynlink.error_message err in
190 Syslog.error "error loading jobs: %s" err;
193 failwith (Printexc.to_string exn) in
195 let s = Whenstate.copy_prev_state !state s in
198 (* Re-evaluate all when jobs. *)
199 reevaluate_whenjobs ~onload:true (Whenstate.get_whenjobs !state);
201 (* Schedule the next every job to run. *)
202 schedule_next_everyjob ()
204 (* Re-evaluate each when-statement job, in a loop until we reach
205 * a fixpoint. Run those that need to be run.
207 and reevaluate_whenjobs ?onload jobs =
208 let rec loop set jobs =
213 try Whenstate.evaluate_whenjob ?onload !state job
214 with Invalid_argument err | Failure err ->
215 Syslog.error "error evaluating job %s (at %s): %s"
216 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
222 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
224 if r then StringSet.add job.job_name set else set
226 if StringSet.compare set set' <> 0 then
231 let set = loop StringSet.empty jobs in
232 let jobnames = StringSet.elements set in
234 (* Ensure the jobs always run in predictable (name) order. *)
235 let jobnames = List.sort compare_jobnames jobnames in
238 List.iter run_job (List.map (Whenstate.get_job !state) jobnames)
240 (* Schedule the next every-statement job to run, if there is one. We
241 * look at the every jobs, work out the time that each must run at,
242 * pick the job(s) which must run soonest, and schedule a timer to run
243 * them. When the timer fires, it runs those jobs, then calls this
246 and schedule_next_everyjob () =
249 (* Get only everyjobs. *)
250 let jobs = Whenstate.get_everyjobs !state in
251 let jobs = List.map (
253 | { job_cond = Every_job period } as job -> (job, period)
254 | { job_cond = When_job _ } -> assert false
257 (* Map everyjob to next time it must run. *)
258 let jobs = List.map (
260 let t' = next_periodexpr t period in
261 assert (t' > t); (* serious bug in next_periodexpr if false *)
265 (* Sort, soonest first. *)
266 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
271 Syslog.notice "%s: next scheduled run at %s"
272 job.job_name (string_of_time_t t)
276 (* Pick the job(s) which run soonest. *)
277 let rec pick = function
280 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
281 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
283 let t, jobs = pick jobs in
287 (* Ensure the jobs always run in predictable (name) order. *)
289 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
293 Syslog.notice "scheduling job(s) %s to run at %s"
294 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
295 (string_of_time_t t);
297 (* Schedule them to run at time t. *)
298 let g = new_timer_group () in
299 let t_diff = t -. Unix.time () in
300 let t_diff = if t_diff < 0. then 0. else t_diff in
302 delete_timer_group (); (* Delete the timer. *)
303 List.iter run_job jobs;
304 schedule_next_everyjob ()
306 Unixqueue.weak_once esys g t_diff run_jobs;
310 and new_timer_group () =
311 delete_timer_group ();
312 let g = Unixqueue.new_group esys in
313 timer_group := Some g;
316 and delete_timer_group () =
317 match !timer_group with
320 Unixqueue.clear esys g;
324 (* Increment JOBSERIAL. *)
326 match Whenstate.get_variable !state "JOBSERIAL" with
328 let serial = succ_big_int serial in
329 state := Whenstate.set_variable !state "JOBSERIAL" (T_int serial);
331 | _ -> assert false in
333 (* Call the pre-condition script. Note this may decide not to run
334 * the job by returning false.
336 let pre_condition () =
337 match job.job_pre with
342 fun pid (job, _, serial, start_time) ->
343 let r = { pirun_job_name = job.job_name;
344 pirun_serial = serial;
345 pirun_start_time = start_time;
350 pi_job_name = job.job_name;
352 pi_variables = Whenstate.get_variables !state;
357 if pre_condition () then (
358 Syslog.notice "running %s (JOBSERIAL=%s)"
359 job.job_name (string_of_big_int serial);
361 (* Create a temporary directory. The current directory of the job
362 * will be in this directory. The directory is removed when the
363 * child process exits.
365 let dir = tmpdir () in
368 if pid = 0 then ( (* child process running the job *)
371 (* Set environment variables corresponding to each variable. *)
373 (fun (name, value) -> putenv name (string_of_variable value))
374 (Whenstate.get_variables !state);
376 (* Set the $JOBNAME environment variable. *)
377 putenv "JOBNAME" job.job_name;
379 (* Create a temporary file containing the shell script fragment. *)
380 let script = dir // "script.sh" in
381 let chan = open_out script in
382 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
383 output_string chan job.job_script.sh_script;
387 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
389 (* Set output to file. *)
390 let output = dir // "output.txt" in
391 let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
396 (* Execute the shell script. *)
397 (try execvp shell [| shell; "-c"; script |];
398 with Unix_error (err, fn, _) ->
399 Syslog.error "%s failed: %s: %s" fn script (error_message err)
404 (* Remember this PID, the job and the temporary directory, so we
405 * can clean up when the child exits.
407 runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
408 serialmap := BigIntMap.add serial pid !serialmap
411 Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
412 job.job_name (string_of_big_int serial);
416 let chan = open_in "/dev/urandom" in
417 let data = String.create 16 in
418 really_input chan data 0 (String.length data);
420 let data = Digest.to_hex (Digest.string data) in
421 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
425 (* This is called when a job (child process) exits. *)
426 and handle_sigchld _ =
428 let pid, status = waitpid [WNOHANG] 0 in
430 (* Look up the PID in the running jobs map. *)
431 let job, dir, serial, time = IntMap.find pid !runningmap in
432 runningmap := IntMap.remove pid !runningmap;
433 serialmap := BigIntMap.remove serial !serialmap;
434 post_job job dir serial time status
436 with Unix_error _ | Not_found -> ()
438 and post_job job dir serial time status =
439 (* If there is a post function, run it. *)
440 (match job.job_post with
446 | WSIGNALED s | WSTOPPED s -> 1 in
448 res_job_name = job.job_name;
452 res_output = dir // "output.txt";
453 res_start_time = time
458 Syslog.error "job %s post function failed: %s" job.job_name msg
460 Syslog.error "job %s post function exception: %s"
461 job.job_name (Printexc.to_string exn)
464 (* This should be safe because the path cannot contain shell metachars. *)
465 let cmd = sprintf "rm -rf '%s'" dir in
466 ignore (Sys.command cmd)
468 (* Intelligent comparison of job names. *)
469 and compare_jobnames name1 name2 =
471 let len1 = String.length name1
472 and len2 = String.length name2 in
473 if len1 > 4 && len2 > 4 &&
474 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
476 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
477 let i2 = int_of_string (String.sub name2 4 (len2-4)) in