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.
26 external _exit : int -> 'a = "whenjobs__exit"
28 (* All jobs that are loaded. Maps name -> [job] structure. *)
29 let jobs = ref StringMap.empty
31 (* Map variable names to jobs which depend on that variable. This
32 * gives us a quick way to tell which jobs might need to be reevaluated
33 * when a variable is set.
35 let dependencies = ref StringMap.empty
37 (* Current values of variables. Using the referentially transparent
38 * type Map is very useful here because it lets us cheaply keep
39 * previous values of variables.
41 let variables : variables ref = ref StringMap.empty
46 (* Jobs that are running; map of PID -> (job, other data). Note that
47 * the job may no longer exist *OR* it may have been renamed,
48 * eg. if the jobs file was reloaded.
50 let running = ref IntMap.empty
52 (* Was debugging requested on the command line? *)
58 let esys = Unixqueue.standard_event_system ()
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 _ -> ());
71 Whenproto_srv.When.V1.create_server
75 ~proc_get_variable_names
77 (Rpc_server.Unix addr)
78 Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
83 (* Handle SIGCHLD to clean up jobs. *)
84 Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
86 (* Initialize the variables. XXX Eventually this will be saved
87 * and loaded from a persistent store.
89 variables := StringMap.add "JOBSERIAL" (T_int zero_big_int) !variables
91 and proc_reload_file () =
92 if !debug then Syslog.notice "remote call: reload_file";
94 try reload_file (); `ok
95 with Failure err -> `error err
97 and proc_set_variable (name, value) =
98 if !debug then Syslog.notice "remote call: set_variable %s" name;
100 let value = variable_of_rpc value in
101 variables := StringMap.add name value !variables;
103 (* Which jobs need to be re-evaluated? *)
104 let jobnames = try StringMap.find name !dependencies with Not_found -> [] in
105 reevaluate_whenjobs jobnames
107 and proc_get_variable name =
108 if !debug then Syslog.notice "remote call: get_variable %s" name;
110 try rpc_of_variable (StringMap.find name !variables)
111 with (* all non-existent variables are empty strings *)
112 Not_found -> `string_t ""
114 and proc_get_variable_names () =
115 if !debug then Syslog.notice "remote call: get_variable_names";
117 (* Only return variables that are non-empty. *)
118 let vars = StringMap.fold (
119 fun name value xs -> if value <> T_string "" then name :: xs else xs
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
143 Dynlink.loadfile file;
144 let jobs = Whenfile.get_jobs () in
145 Syslog.notice "loaded %d job(s) from %s" (List.length jobs) file;
148 | Dynlink.Error err ->
149 let err = Dynlink.error_message err in
150 Syslog.error "error loading jobs: %s" err;
153 failwith (Printexc.to_string exn) in
155 (* Set 'jobs' and related global variables. *)
157 let map = List.fold_left (
159 let name = j.job_name in
160 StringMap.add name j map
161 ) StringMap.empty js in
165 let map = List.fold_left (
167 let deps = dependencies_of_job j in
168 let name = j.job_name in
171 let names = try StringMap.find d map with Not_found -> [] in
172 StringMap.add d (name :: names) map
174 ) StringMap.empty js in
175 dependencies := map in
177 (* Re-evaluate all when jobs. *)
178 reevaluate_whenjobs (StringMap.keys !jobs);
180 (* Schedule the next every job to run. *)
181 schedule_next_everyjob ()
183 (* Re-evaluate each named when-statement job, in a loop until we reach
184 * a fixpoint. Run those that need to be run. every-statement jobs
187 and reevaluate_whenjobs jobnames =
188 let rec loop set jobnames =
193 try StringMap.find jobname !jobs
194 with Not_found -> assert false in
195 assert (jobname = job.job_name);
198 try job_evaluate job !variables
199 with Invalid_argument err | Failure err ->
200 Syslog.error "error evaluating job %s (at %s): %s"
201 jobname (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
204 jobs := StringMap.add jobname job' !jobs;
207 Syslog.notice "evaluate %s -> %b\n" jobname r;
209 if r then StringSet.add jobname set else set
211 if StringSet.compare set set' <> 0 then
216 let set = loop StringSet.empty jobnames in
217 let jobnames = StringSet.elements set in
218 (* Ensure the jobs always run in predictable (name) order. *)
219 let jobnames = List.sort compare_jobnames jobnames in
221 (List.map (fun jobname -> StringMap.find jobname !jobs) jobnames)
223 (* Schedule the next every-statement job to run, if there is one. We
224 * look at the every jobs, work out the time that each must run at,
225 * pick the job(s) which must run soonest, and schedule a timer to run
226 * them. When the timer fires, it runs those jobs, then calls this
229 and schedule_next_everyjob () =
232 (* Get only everyjobs. *)
233 let jobs = StringMap.values !jobs in
234 let jobs = filter_map (
236 | { job_cond = Every_job period } as job -> Some (job, period)
237 | { job_cond = When_job _ } -> None
240 (* Map everyjob to next time it must run. *)
241 let jobs = List.map (
243 let t' = next_periodexpr t period in
244 assert (t' > t); (* serious bug in next_periodexpr if false *)
248 (* Sort, soonest first. *)
249 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
254 Syslog.notice "%s: next scheduled run at %s"
255 job.job_name (string_of_time_t t)
259 (* Pick the job(s) which run soonest. *)
260 let rec pick = function
263 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
264 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
266 let t, jobs = pick jobs in
270 (* Ensure the jobs always run in predictable (name) order. *)
272 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
276 Syslog.notice "scheduling job(s) %s to run at %s"
277 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
278 (string_of_time_t t);
280 (* Schedule them to run at time t. *)
281 let g = Unixqueue.new_group esys in
282 let t_diff = t -. Unix.time () in
283 let t_diff = if t_diff < 0. then 0. else t_diff in
285 Unixqueue.clear esys g; (* Delete the timer. *)
286 List.iter run_job jobs;
287 schedule_next_everyjob ()
289 Unixqueue.weak_once esys g t_diff run_jobs;
293 and string_of_time_t t =
295 sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
296 (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
297 tm.tm_hour tm.tm_min tm.tm_sec
301 (* Increment JOBSERIAL. *)
303 match StringMap.find "JOBSERIAL" !variables with
305 let serial = succ_big_int serial in
306 variables := StringMap.add "JOBSERIAL" (T_int serial) !variables;
308 | _ -> assert false in
310 Syslog.notice "running %s (JOBSERIAL=%s)"
311 job.job_name (string_of_big_int serial) in
313 (* Create a temporary directory. The current directory of the job
314 * will be in this directory. The directory is removed when the
315 * child process exits.
317 let dir = tmpdir () in
320 if pid = 0 then ( (* child process running the job *)
323 (* Set environment variables corresponding to each variable. *)
325 (fun name value -> putenv name (string_of_variable value)) !variables;
327 (* Set the $JOBNAME environment variable. *)
328 putenv "JOBNAME" job.job_name;
330 (* Create a temporary file containing the shell script fragment. *)
331 let script = dir // "script" in
332 let chan = open_out script in
333 output_string chan job.job_script.sh_script;
337 (* Execute the shell script. *)
338 (try execvp "bash" [| "bash"; "-c"; script |];
339 with Unix_error (err, fn, _) ->
340 Syslog.error "%s failed: %s: %s" fn script (error_message err)
345 (* Remember this PID, the job and the temporary directory, so we
346 * can clean up when the child exits.
348 running := IntMap.add pid (job, dir) !running
351 let chan = open_in "/dev/urandom" in
352 let data = String.create 16 in
353 really_input chan data 0 (String.length data);
355 let data = Digest.to_hex (Digest.string data) in
356 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
360 (* This is called when a job (child process) exits. *)
361 and handle_sigchld _ =
363 let pid, status = waitpid [WNOHANG] 0 in
365 (* Look up the PID in the running jobs map. *)
366 let job, dir = IntMap.find pid !running in
367 running := IntMap.remove pid !running;
370 with Unix_error _ | Not_found -> ()
372 and cleanup_job job dir =
373 (* This should be safe because the path cannot contain shell metachars. *)
374 let cmd = sprintf "rm -rf '%s'" dir in
375 ignore (Sys.command cmd)
377 (* Intelligent comparison of job names. *)
378 and compare_jobnames name1 name2 =
380 let len1 = String.length name1
381 and len2 = String.length name2 in
382 if len1 > 4 && len2 > 4 &&
383 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
385 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
386 let i2 = int_of_string (String.sub name2 4 (len2-4)) in