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; map of PID -> (job, other data). Note that
36 * the job may no longer exist *OR* it may have been renamed,
37 * eg. if the jobs file was reloaded.
39 let running = ref IntMap.empty
41 (* Was debugging requested on the command line? *)
47 let esys = Unixqueue.standard_event_system ()
49 (* The timer. It's convenient to have this as a global variable
50 * because (a) there should only be one timer (which fires when the
51 * soonest every-job becomes ready), and (b) it's complicated to track
52 * that timer and avoid it getting double-scheduled (eg. when we
53 * reload the jobs file) without having a global variable.
55 let timer_group = ref None
61 Whenlock.create_lock !jobsdir;
63 (* Remove old socket if it exists. *)
64 let addr = sprintf "%s/socket" !jobsdir in
65 (try unlink addr with Unix_error _ -> ());
67 (* Create the Unix domain socket server. *)
69 Whenproto_srv.When.V1.create_server
73 ~proc_get_variable_names
75 (Rpc_server.Unix addr)
76 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
81 (* Handle SIGCHLD to clean up jobs. *)
82 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
84 (* Initialize the variables. *)
85 state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
87 and proc_reload_file () =
88 if !debug then Syslog.notice "remote call: reload_file";
90 try reload_file (); `ok
91 with Failure err -> `error err
93 and proc_set_variable (name, value) =
94 if !debug then Syslog.notice "remote call: set_variable %s" name;
97 check_valid_variable_name name;
99 let value = variable_of_rpc value in
100 state := Whenstate.set_variable !state name value;
102 (* Which jobs need to be re-evaluated? *)
103 let jobs = Whenstate.get_dependencies !state name in
104 reevaluate_whenjobs jobs;
108 Failure msg -> `error msg
110 and proc_get_variable name =
111 if !debug then Syslog.notice "remote call: get_variable %s" name;
113 rpc_of_variable (Whenstate.get_variable !state name)
115 and proc_get_variable_names () =
116 if !debug then Syslog.notice "remote call: get_variable_names";
118 let vars = Whenstate.get_variable_names !state in
120 (* Return variable names as a sorted array. *)
121 let vars = Array.of_list vars in
122 Array.sort compare vars;
125 and proc_exit_daemon () =
126 if !debug then Syslog.notice "remote call: exit_daemon";
130 `error "exit_daemon: no server handle"
132 Rpc_server.stop_server ~graceful:true s;
136 (* Reload the jobs file. *)
138 let file = sprintf "%s/jobs.cmo" !jobsdir in
140 (* As we are reloading the file, we want to create a new state
141 * that has no jobs, but has all the variables from the previous
144 let s = Whenstate.copy_variables !state Whenstate.empty in
149 Dynlink.loadfile file;
150 let s = Whenfile.get_state () in
151 Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
154 | Dynlink.Error err ->
155 let err = Dynlink.error_message err in
156 Syslog.error "error loading jobs: %s" err;
159 failwith (Printexc.to_string exn) in
163 (* Re-evaluate all when jobs. *)
164 reevaluate_whenjobs ~onload:true (Whenstate.get_whenjobs !state);
166 (* Schedule the next every job to run. *)
167 schedule_next_everyjob ()
169 (* Re-evaluate each when-statement job, in a loop until we reach
170 * a fixpoint. Run those that need to be run.
172 and reevaluate_whenjobs ?onload jobs =
173 let rec loop set jobs =
178 try Whenstate.evaluate_whenjob ?onload !state job
179 with Invalid_argument err | Failure err ->
180 Syslog.error "error evaluating job %s (at %s): %s"
181 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
187 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
189 if r then StringSet.add job.job_name set else set
191 if StringSet.compare set set' <> 0 then
196 let set = loop StringSet.empty jobs in
197 let jobnames = StringSet.elements set in
199 (* Ensure the jobs always run in predictable (name) order. *)
200 let jobnames = List.sort compare_jobnames jobnames in
203 List.iter run_job (List.map (Whenstate.get_job !state) jobnames)
205 (* Schedule the next every-statement job to run, if there is one. We
206 * look at the every jobs, work out the time that each must run at,
207 * pick the job(s) which must run soonest, and schedule a timer to run
208 * them. When the timer fires, it runs those jobs, then calls this
211 and schedule_next_everyjob () =
214 (* Get only everyjobs. *)
215 let jobs = Whenstate.get_everyjobs !state in
216 let jobs = List.map (
218 | { job_cond = Every_job period } as job -> (job, period)
219 | { job_cond = When_job _ } -> assert false
222 (* Map everyjob to next time it must run. *)
223 let jobs = List.map (
225 let t' = next_periodexpr t period in
226 assert (t' > t); (* serious bug in next_periodexpr if false *)
230 (* Sort, soonest first. *)
231 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
236 Syslog.notice "%s: next scheduled run at %s"
237 job.job_name (string_of_time_t t)
241 (* Pick the job(s) which run soonest. *)
242 let rec pick = function
245 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
246 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
248 let t, jobs = pick jobs in
252 (* Ensure the jobs always run in predictable (name) order. *)
254 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
258 Syslog.notice "scheduling job(s) %s to run at %s"
259 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
260 (string_of_time_t t);
262 (* Schedule them to run at time t. *)
263 let g = new_timer_group () in
264 let t_diff = t -. Unix.time () in
265 let t_diff = if t_diff < 0. then 0. else t_diff in
267 delete_timer_group (); (* Delete the timer. *)
268 List.iter run_job jobs;
269 schedule_next_everyjob ()
271 Unixqueue.weak_once esys g t_diff run_jobs;
275 and new_timer_group () =
276 delete_timer_group ();
277 let g = Unixqueue.new_group esys in
278 timer_group := Some g;
281 and delete_timer_group () =
282 match !timer_group with
285 Unixqueue.clear esys g;
288 and string_of_time_t t =
290 sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
291 (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
292 tm.tm_hour tm.tm_min tm.tm_sec
296 (* Increment JOBSERIAL. *)
298 match Whenstate.get_variable !state "JOBSERIAL" with
300 let serial = succ_big_int serial in
301 state := Whenstate.set_variable !state "JOBSERIAL" (T_int serial);
303 | _ -> assert false in
305 Syslog.notice "running %s (JOBSERIAL=%s)"
306 job.job_name (string_of_big_int serial) in
308 (* Create a temporary directory. The current directory of the job
309 * will be in this directory. The directory is removed when the
310 * child process exits.
312 let dir = tmpdir () in
315 if pid = 0 then ( (* child process running the job *)
318 (* Set environment variables corresponding to each variable. *)
320 (fun (name, value) -> putenv name (string_of_variable value))
321 (Whenstate.get_variables !state);
323 (* Set the $JOBNAME environment variable. *)
324 putenv "JOBNAME" job.job_name;
326 (* Create a temporary file containing the shell script fragment. *)
327 let script = dir // "script" in
328 let chan = open_out script in
329 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
330 output_string chan job.job_script.sh_script;
334 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
336 (* Execute the shell script. *)
337 (try execvp shell [| shell; "-c"; script |];
338 with Unix_error (err, fn, _) ->
339 Syslog.error "%s failed: %s: %s" fn script (error_message err)
344 (* Remember this PID, the job and the temporary directory, so we
345 * can clean up when the child exits.
347 running := IntMap.add pid (job, dir) !running
350 let chan = open_in "/dev/urandom" in
351 let data = String.create 16 in
352 really_input chan data 0 (String.length data);
354 let data = Digest.to_hex (Digest.string data) in
355 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
359 (* This is called when a job (child process) exits. *)
360 and handle_sigchld _ =
362 let pid, status = waitpid [WNOHANG] 0 in
364 (* Look up the PID in the running jobs map. *)
365 let job, dir = IntMap.find pid !running in
366 running := IntMap.remove pid !running;
369 with Unix_error _ | Not_found -> ()
371 and cleanup_job job dir =
372 (* This should be safe because the path cannot contain shell metachars. *)
373 let cmd = sprintf "rm -rf '%s'" dir in
374 ignore (Sys.command cmd)
376 (* Intelligent comparison of job names. *)
377 and compare_jobnames name1 name2 =
379 let len1 = String.length name1
380 and len2 = String.length name2 in
381 if len1 > 4 && len2 > 4 &&
382 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
384 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
385 let i2 = int_of_string (String.sub name2 4 (len2-4)) in