Fix double-scheduled timer problem caused by reloading the jobs file.
[whenjobs.git] / daemon / daemon.ml
1 (* whenjobs
2  * Copyright (C) 2012 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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.
17  *)
18
19 open Whenutils
20
21 open Big_int
22 open Unix
23 open Printf
24
25 (* See [exit.c]. *)
26 external _exit : int -> 'a = "whenjobs__exit"
27
28 (* All jobs that are loaded.  Maps name -> [job] structure. *)
29 let jobs = ref StringMap.empty
30
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.
34  *)
35 let dependencies = ref StringMap.empty
36
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.
40  *)
41 let variables : variables ref = ref StringMap.empty
42
43 (* $HOME/.whenjobs *)
44 let jobsdir = ref ""
45
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.
49  *)
50 let running = ref IntMap.empty
51
52 (* Was debugging requested on the command line? *)
53 let debug = ref false
54
55 (* The server. *)
56 let server = ref None
57
58 let esys = Unixqueue.standard_event_system ()
59
60 (* The timer.  It's convenient to have this as a global variable
61  * because (a) there should only be one timer (which fires when the
62  * soonest every-job becomes ready), and (b) it's complicated to track
63  * that timer and avoid it getting double-scheduled (eg.  when we
64  * reload the jobs file) without having a global variable.
65  *)
66 let timer_group = ref None
67
68 let rec init j d =
69   jobsdir := j;
70   debug := d;
71
72   Whenlock.create_lock !jobsdir;
73
74   (* Remove old socket if it exists. *)
75   let addr = sprintf "%s/socket" !jobsdir in
76   (try unlink addr with Unix_error _ -> ());
77
78   server := Some (
79     Whenproto_srv.When.V1.create_server
80       ~proc_reload_file
81       ~proc_set_variable
82       ~proc_get_variable
83       ~proc_get_variable_names
84       ~proc_exit_daemon
85       (Rpc_server.Unix addr)
86       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
87       Rpc.Socket
88       esys
89   );
90
91   (* Handle SIGCHLD to clean up jobs. *)
92   Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
93
94   (* Initialize the variables.  XXX Eventually this will be saved
95    * and loaded from a persistent store.
96    *)
97   variables := StringMap.add "JOBSERIAL" (T_int zero_big_int) !variables
98
99 and proc_reload_file () =
100   if !debug then Syslog.notice "remote call: reload_file";
101
102   try reload_file (); `ok
103   with Failure err -> `error err
104
105 and proc_set_variable (name, value) =
106   if !debug then Syslog.notice "remote call: set_variable %s" name;
107
108   try
109     (* Don't permit certain names. *)
110     if name = "JOBSERIAL" then
111       failwith "JOBSERIAL variable cannot be set";
112
113     let len = String.length name in
114     if len = 0 then
115       failwith "variable name is an empty string";
116     if name.[0] <> '_' && not (isalpha name.[0]) then
117       failwith "variable name must start with alphabetic character or underscore";
118
119     let rec loop i =
120       if i >= len then ()
121       else if name.[i] <> '_' && not (isalnum name.[i]) then
122         failwith "variable name contains non-alphanumeric non-underscore character"
123       else loop (i+1)
124     in
125     loop 1;
126
127     let value = variable_of_rpc value in
128     variables := StringMap.add name value !variables;
129
130     (* Which jobs need to be re-evaluated? *)
131     let jobnames = try StringMap.find name !dependencies with Not_found -> [] in
132     reevaluate_whenjobs jobnames;
133
134     `ok
135   with
136     Failure msg -> `error msg
137
138 and proc_get_variable name =
139   if !debug then Syslog.notice "remote call: get_variable %s" name;
140
141   try rpc_of_variable (StringMap.find name !variables)
142   with (* all non-existent variables are empty strings *)
143     Not_found -> `string_t ""
144
145 and proc_get_variable_names () =
146   if !debug then Syslog.notice "remote call: get_variable_names";
147
148   (* Only return variables that are non-empty. *)
149   let vars = StringMap.fold (
150     fun name value xs -> if value <> T_string "" then name :: xs else xs
151   ) !variables [] in
152   let vars = Array.of_list vars in
153   Array.sort compare vars;
154   vars
155
156 and proc_exit_daemon () =
157   if !debug then Syslog.notice "remote call: exit_daemon";
158
159   match !server with
160   | None ->
161     `error "exit_daemon: no server handle"
162   | Some s ->
163     Rpc_server.stop_server ~graceful:true s;
164     server := None;
165     `ok
166
167 (* Reload the jobs file. *)
168 and reload_file () =
169   let file = sprintf "%s/jobs.cmo" !jobsdir in
170   Whenfile.init ();
171
172   let js =
173     try
174       Dynlink.loadfile file;
175       let jobs = Whenfile.get_jobs () in
176       Syslog.notice "loaded %d job(s) from %s" (List.length jobs) file;
177       jobs
178     with
179     | Dynlink.Error err ->
180       let err = Dynlink.error_message err in
181       Syslog.error "error loading jobs: %s" err;
182       failwith err
183     | exn ->
184       failwith (Printexc.to_string exn) in
185
186   (* Set 'jobs' and related global variables. *)
187   let () =
188     let map = List.fold_left (
189       fun map j ->
190         let name = j.job_name in
191         StringMap.add name j map
192     ) StringMap.empty js in
193     jobs := map in
194
195   let () =
196     let map = List.fold_left (
197       fun map j ->
198         let deps = dependencies_of_job j in
199         let name = j.job_name in
200         List.fold_left (
201           fun map d ->
202             let names = try StringMap.find d map with Not_found -> [] in
203             StringMap.add d (name :: names) map
204         ) map deps
205     ) StringMap.empty js in
206     dependencies := map in
207
208   (* Re-evaluate all when jobs. *)
209   reevaluate_whenjobs ~onload:true (StringMap.keys !jobs);
210
211   (* Schedule the next every job to run. *)
212   schedule_next_everyjob ()
213
214 (* Re-evaluate each named when-statement job, in a loop until we reach
215  * a fixpoint.  Run those that need to be run.  every-statement jobs
216  * are ignored here.
217  *)
218 and reevaluate_whenjobs ?(onload=false) jobnames =
219   let rec loop set jobnames =
220     let set' =
221       List.fold_left (
222         fun set jobname ->
223           let job =
224             try StringMap.find jobname !jobs
225             with Not_found -> assert false in
226           assert (jobname = job.job_name);
227
228           let r, job' =
229             try job_evaluate job !variables onload
230             with Invalid_argument err | Failure err ->
231               Syslog.error "error evaluating job %s (at %s): %s"
232                 jobname (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
233               false, job in
234
235           jobs := StringMap.add jobname job' !jobs;
236
237           if !debug then
238             Syslog.notice "evaluate %s -> %b\n" jobname r;
239
240           if r then StringSet.add jobname set else set
241       ) set jobnames in
242     if StringSet.compare set set' <> 0 then
243       loop set' jobnames
244     else
245       set'
246   in
247   let set = loop StringSet.empty jobnames in
248   let jobnames = StringSet.elements set in
249   (* Ensure the jobs always run in predictable (name) order. *)
250   let jobnames = List.sort compare_jobnames jobnames in
251   List.iter run_job
252     (List.map (fun jobname -> StringMap.find jobname !jobs) jobnames)
253
254 (* Schedule the next every-statement job to run, if there is one.  We
255  * look at the every jobs, work out the time that each must run at,
256  * pick the job(s) which must run soonest, and schedule a timer to run
257  * them.  When the timer fires, it runs those jobs, then calls this
258  * function again.
259  *)
260 and schedule_next_everyjob () =
261   let t = time () in
262
263   (* Get only everyjobs. *)
264   let jobs = StringMap.values !jobs in
265   let jobs = filter_map (
266     function
267     | { job_cond = Every_job period } as job -> Some (job, period)
268     | { job_cond = When_job _ } -> None
269   ) jobs in
270
271   (* Map everyjob to next time it must run. *)
272   let jobs = List.map (
273     fun (job, period) ->
274       let t' = next_periodexpr t period in
275       assert (t' > t); (* serious bug in next_periodexpr if false *)
276       job, t'
277   ) jobs in
278
279   (* Sort, soonest first. *)
280   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
281
282   if !debug then (
283     List.iter (
284       fun (job, t) ->
285         Syslog.notice "%s: next scheduled run at %s"
286           job.job_name (string_of_time_t t)
287     ) jobs
288   );
289
290   (* Pick the job(s) which run soonest. *)
291   let rec pick = function
292     | [] -> 0., []
293     | [j, t] -> t, [j]
294     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
295     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
296   in
297   let t, jobs = pick jobs in
298
299   if t > 0. then (
300     if jobs <> [] then (
301       (* Ensure the jobs always run in predictable (name) order. *)
302       let jobs =
303         List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
304           jobs in
305
306       if !debug then
307         Syslog.notice "scheduling job(s) %s to run at %s"
308           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
309           (string_of_time_t t);
310
311       (* Schedule them to run at time t. *)
312       let g = new_timer_group () in
313       let t_diff = t -. Unix.time () in
314       let t_diff = if t_diff < 0. then 0. else t_diff in
315       let run_jobs () =
316         delete_timer_group ();          (* Delete the timer. *)
317         List.iter run_job jobs;
318         schedule_next_everyjob ()
319       in
320       Unixqueue.weak_once esys g t_diff run_jobs;
321     )
322   )
323
324 and new_timer_group () =
325   delete_timer_group ();
326   let g = Unixqueue.new_group esys in
327   timer_group := Some g;
328   g
329
330 and delete_timer_group () =
331   match !timer_group with
332   | None -> ()
333   | Some g ->
334     Unixqueue.clear esys g;
335     timer_group := None
336
337 and string_of_time_t t =
338   let tm = gmtime t in
339   sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
340     (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
341     tm.tm_hour tm.tm_min tm.tm_sec
342
343 and run_job job =
344   let () =
345     (* Increment JOBSERIAL. *)
346     let serial =
347       match StringMap.find "JOBSERIAL" !variables with
348       | T_int serial ->
349         let serial = succ_big_int serial in
350         variables := StringMap.add "JOBSERIAL" (T_int serial) !variables;
351         serial
352       | _ -> assert false in
353
354     Syslog.notice "running %s (JOBSERIAL=%s)"
355       job.job_name (string_of_big_int serial) in
356
357   (* Create a temporary directory.  The current directory of the job
358    * will be in this directory.  The directory is removed when the
359    * child process exits.
360    *)
361   let dir = tmpdir () in
362
363   let pid = fork () in
364   if pid = 0 then ( (* child process running the job *)
365     chdir dir;
366
367     (* Set environment variables corresponding to each variable. *)
368     StringMap.iter
369       (fun name value -> putenv name (string_of_variable value)) !variables;
370
371     (* Set the $JOBNAME environment variable. *)
372     putenv "JOBNAME" job.job_name;
373
374     (* Create a temporary file containing the shell script fragment. *)
375     let script = dir // "script" in
376     let chan = open_out script in
377     fprintf chan "set -e\n"; (* So that jobs exit on error. *)
378     output_string chan job.job_script.sh_script;
379     close_out chan;
380     chmod script 0o700;
381
382     let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
383
384     (* Execute the shell script. *)
385     (try execvp shell [| shell; "-c"; script |];
386      with Unix_error (err, fn, _) ->
387        Syslog.error "%s failed: %s: %s" fn script (error_message err)
388     );
389     _exit 1
390   );
391
392   (* Remember this PID, the job and the temporary directory, so we
393    * can clean up when the child exits.
394    *)
395   running := IntMap.add pid (job, dir) !running
396
397 and tmpdir () =
398   let chan = open_in "/dev/urandom" in
399   let data = String.create 16 in
400   really_input chan data 0 (String.length data);
401   close_in chan;
402   let data = Digest.to_hex (Digest.string data) in
403   let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
404   mkdir dir 0o700;
405   dir
406
407 (* This is called when a job (child process) exits. *)
408 and handle_sigchld _ =
409   try
410     let pid, status = waitpid [WNOHANG] 0 in
411     if pid > 0 then (
412       (* Look up the PID in the running jobs map. *)
413       let job, dir = IntMap.find pid !running in
414       running := IntMap.remove pid !running;
415       cleanup_job job dir
416     )
417   with Unix_error _ | Not_found -> ()
418
419 and cleanup_job job dir =
420   (* This should be safe because the path cannot contain shell metachars. *)
421   let cmd = sprintf "rm -rf '%s'" dir in
422   ignore (Sys.command cmd)
423
424 (* Intelligent comparison of job names. *)
425 and compare_jobnames name1 name2 =
426   try
427     let len1 = String.length name1
428     and len2 = String.length name2 in
429     if len1 > 4 && len2 > 4 &&
430       String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
431     then (
432       let i1 = int_of_string (String.sub name1 4 (len1-4)) in
433       let i2 = int_of_string (String.sub name2 4 (len2-4)) in
434       compare i1 i2
435     )
436     else raise Not_found
437   with _ ->
438     compare name1 name2
439
440 let main_loop () =
441   Unixqueue.run esys