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 (* Don't permit certain names. *)
98 if name = "JOBSERIAL" then
99 failwith "JOBSERIAL variable cannot be set";
101 let len = String.length name in
103 failwith "variable name is an empty string";
104 if name.[0] <> '_' && not (isalpha name.[0]) then
105 failwith "variable name must start with alphabetic character or underscore";
109 else if name.[i] <> '_' && not (isalnum name.[i]) then
110 failwith "variable name contains non-alphanumeric non-underscore character"
115 let value = variable_of_rpc value in
116 state := Whenstate.set_variable !state name value;
118 (* Which jobs need to be re-evaluated? *)
119 let jobs = Whenstate.get_dependencies !state name in
120 reevaluate_whenjobs jobs;
124 Failure msg -> `error msg
126 and proc_get_variable name =
127 if !debug then Syslog.notice "remote call: get_variable %s" name;
129 rpc_of_variable (Whenstate.get_variable !state name)
131 and proc_get_variable_names () =
132 if !debug then Syslog.notice "remote call: get_variable_names";
134 let vars = Whenstate.get_variable_names !state in
136 (* Return variable names as a sorted array. *)
137 let vars = Array.of_list vars in
138 Array.sort compare vars;
141 and proc_exit_daemon () =
142 if !debug then Syslog.notice "remote call: exit_daemon";
146 `error "exit_daemon: no server handle"
148 Rpc_server.stop_server ~graceful:true s;
152 (* Reload the jobs file. *)
154 let file = sprintf "%s/jobs.cmo" !jobsdir in
156 (* As we are reloading the file, we want to create a new state
157 * that has no jobs, but has all the variables from the previous
160 let s = Whenstate.copy_variables !state Whenstate.empty in
165 Dynlink.loadfile file;
166 let s = Whenfile.get_state () in
167 Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
170 | Dynlink.Error err ->
171 let err = Dynlink.error_message err in
172 Syslog.error "error loading jobs: %s" err;
175 failwith (Printexc.to_string exn) in
179 (* Re-evaluate all when jobs. *)
180 reevaluate_whenjobs ~onload:true (Whenstate.get_whenjobs !state);
182 (* Schedule the next every job to run. *)
183 schedule_next_everyjob ()
185 (* Re-evaluate each when-statement job, in a loop until we reach
186 * a fixpoint. Run those that need to be run.
188 and reevaluate_whenjobs ?onload jobs =
189 let rec loop set jobs =
194 try Whenstate.evaluate_whenjob ?onload !state job
195 with Invalid_argument err | Failure err ->
196 Syslog.error "error evaluating job %s (at %s): %s"
197 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
203 Syslog.notice "evaluate %s -> %b\n" job.job_name r;
205 if r then StringSet.add job.job_name set else set
207 if StringSet.compare set set' <> 0 then
212 let set = loop StringSet.empty jobs in
213 let jobnames = StringSet.elements set in
215 (* Ensure the jobs always run in predictable (name) order. *)
216 let jobnames = List.sort compare_jobnames jobnames in
219 List.iter run_job (List.map (Whenstate.get_job !state) jobnames)
221 (* Schedule the next every-statement job to run, if there is one. We
222 * look at the every jobs, work out the time that each must run at,
223 * pick the job(s) which must run soonest, and schedule a timer to run
224 * them. When the timer fires, it runs those jobs, then calls this
227 and schedule_next_everyjob () =
230 (* Get only everyjobs. *)
231 let jobs = Whenstate.get_everyjobs !state in
232 let jobs = List.map (
234 | { job_cond = Every_job period } as job -> (job, period)
235 | { job_cond = When_job _ } -> assert false
238 (* Map everyjob to next time it must run. *)
239 let jobs = List.map (
241 let t' = next_periodexpr t period in
242 assert (t' > t); (* serious bug in next_periodexpr if false *)
246 (* Sort, soonest first. *)
247 let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
252 Syslog.notice "%s: next scheduled run at %s"
253 job.job_name (string_of_time_t t)
257 (* Pick the job(s) which run soonest. *)
258 let rec pick = function
261 | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
262 | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
264 let t, jobs = pick jobs in
268 (* Ensure the jobs always run in predictable (name) order. *)
270 List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
274 Syslog.notice "scheduling job(s) %s to run at %s"
275 (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
276 (string_of_time_t t);
278 (* Schedule them to run at time t. *)
279 let g = new_timer_group () in
280 let t_diff = t -. Unix.time () in
281 let t_diff = if t_diff < 0. then 0. else t_diff in
283 delete_timer_group (); (* Delete the timer. *)
284 List.iter run_job jobs;
285 schedule_next_everyjob ()
287 Unixqueue.weak_once esys g t_diff run_jobs;
291 and new_timer_group () =
292 delete_timer_group ();
293 let g = Unixqueue.new_group esys in
294 timer_group := Some g;
297 and delete_timer_group () =
298 match !timer_group with
301 Unixqueue.clear esys g;
304 and string_of_time_t t =
306 sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
307 (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
308 tm.tm_hour tm.tm_min tm.tm_sec
312 (* Increment JOBSERIAL. *)
314 match Whenstate.get_variable !state "JOBSERIAL" with
316 let serial = succ_big_int serial in
317 state := Whenstate.set_variable !state "JOBSERIAL" (T_int serial);
319 | _ -> assert false in
321 Syslog.notice "running %s (JOBSERIAL=%s)"
322 job.job_name (string_of_big_int serial) in
324 (* Create a temporary directory. The current directory of the job
325 * will be in this directory. The directory is removed when the
326 * child process exits.
328 let dir = tmpdir () in
331 if pid = 0 then ( (* child process running the job *)
334 (* Set environment variables corresponding to each variable. *)
336 (fun (name, value) -> putenv name (string_of_variable value))
337 (Whenstate.get_variables !state);
339 (* Set the $JOBNAME environment variable. *)
340 putenv "JOBNAME" job.job_name;
342 (* Create a temporary file containing the shell script fragment. *)
343 let script = dir // "script" in
344 let chan = open_out script in
345 fprintf chan "set -e\n"; (* So that jobs exit on error. *)
346 output_string chan job.job_script.sh_script;
350 let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
352 (* Execute the shell script. *)
353 (try execvp shell [| shell; "-c"; script |];
354 with Unix_error (err, fn, _) ->
355 Syslog.error "%s failed: %s: %s" fn script (error_message err)
360 (* Remember this PID, the job and the temporary directory, so we
361 * can clean up when the child exits.
363 running := IntMap.add pid (job, dir) !running
366 let chan = open_in "/dev/urandom" in
367 let data = String.create 16 in
368 really_input chan data 0 (String.length data);
370 let data = Digest.to_hex (Digest.string data) in
371 let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
375 (* This is called when a job (child process) exits. *)
376 and handle_sigchld _ =
378 let pid, status = waitpid [WNOHANG] 0 in
380 (* Look up the PID in the running jobs map. *)
381 let job, dir = IntMap.find pid !running in
382 running := IntMap.remove pid !running;
385 with Unix_error _ | Not_found -> ()
387 and cleanup_job job dir =
388 (* This should be safe because the path cannot contain shell metachars. *)
389 let cmd = sprintf "rm -rf '%s'" dir in
390 ignore (Sys.command cmd)
392 (* Intelligent comparison of job names. *)
393 and compare_jobnames name1 name2 =
395 let len1 = String.length name1
396 and len2 = String.length name2 in
397 if len1 > 4 && len2 > 4 &&
398 String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
400 let i1 = int_of_string (String.sub name1 4 (len1-4)) in
401 let i2 = int_of_string (String.sub name2 4 (len2-4)) in