Pass the state through reevaluate_whenjobs and run_job.
[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 open Whenexpr
21
22 open Big_int
23 open Unix
24 open Printf
25
26 (* See [exit.c]. *)
27 external _exit : int -> 'a = "whenjobs__exit"
28
29 (* $HOME/.whenjobs *)
30 let jobsdir = ref ""
31
32 (* The state. *)
33 let state = ref Whenstate.empty
34
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.
38  *)
39 let runningmap = ref IntMap.empty
40
41 (* Serial numbers of running jobs.  Map of serial -> PID (in runningmap). *)
42 let serialmap = ref BigIntMap.empty
43
44 (* Was debugging requested on the command line? *)
45 let debug = ref false
46
47 (* The server. *)
48 let server = ref None
49
50 let esys = Unixqueue.standard_event_system ()
51
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.
57  *)
58 let timer_group = ref None
59
60 let rec init j d =
61   jobsdir := j;
62   debug := d;
63
64   Whenlock.create_lock !jobsdir;
65
66   (* Remove old socket if it exists. *)
67   let addr = sprintf "%s/socket" !jobsdir in
68   (try unlink addr with Unix_error _ -> ());
69
70   (* Create the Unix domain socket server. *)
71   server := Some (
72     Whenproto_srv.When.V1.create_server
73       ~proc_reload_file
74       ~proc_set_variable
75       ~proc_get_variable
76       ~proc_get_variable_names
77       ~proc_exit_daemon
78       ~proc_get_jobs
79       ~proc_cancel_job
80       ~proc_start_job
81       ~proc_get_job
82       ~proc_set_variables
83       ~proc_get_job_names
84       (Rpc_server.Unix addr)
85       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
86       Rpc.Socket
87       esys
88   );
89
90   (* Handle SIGCHLD to clean up jobs. *)
91   Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
92
93   (* Initialize the variables. *)
94   state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
95
96 and proc_reload_file () =
97   if !debug then Syslog.notice "remote call: reload_file";
98
99   try reload_file (); `ok
100   with Failure err -> `error err
101
102 and proc_set_variable (name, value) =
103   if !debug then Syslog.notice "remote call: set_variable %s" name;
104
105   try
106     check_valid_variable_name name;
107
108     let value = variable_of_rpc value in
109     state := Whenstate.set_variable !state name value;
110
111     (* Which jobs need to be re-evaluated? *)
112     let jobs = Whenstate.get_dependencies !state [name] in
113     let state' = reevaluate_whenjobs !state jobs in
114     state := state';
115
116     `ok
117   with
118     Failure msg -> `error msg
119
120 and proc_get_variable name =
121   if !debug then Syslog.notice "remote call: get_variable %s" name;
122
123   rpc_of_variable (Whenstate.get_variable !state name)
124
125 and proc_get_variable_names () =
126   if !debug then Syslog.notice "remote call: get_variable_names";
127
128   let vars = Whenstate.get_variable_names !state in
129
130   (* Return variable names as a sorted array. *)
131   let vars = Array.of_list vars in
132   Array.sort compare vars;
133   vars
134
135 and proc_exit_daemon () =
136   if !debug then Syslog.notice "remote call: exit_daemon";
137
138   match !server with
139   | None ->
140     `error "exit_daemon: no server handle"
141   | Some s ->
142     Rpc_server.stop_server ~graceful:true s;
143     server := None;
144     `ok
145
146 and proc_get_jobs () =
147   let running = Array.of_list (IntMap.values !runningmap) in
148   Array.map (
149     fun (job, dir, serial, start_time) ->
150       { Whenproto_aux.job_name = job.job_name;
151         job_serial = string_of_big_int serial;
152         job_tmpdir = dir; job_start_time = Int64.of_float start_time }
153   ) running
154
155 and proc_cancel_job serial =
156   try
157     let serial = big_int_of_string serial in
158     let pid = BigIntMap.find serial !serialmap in
159     kill pid 15;
160     `ok
161   with
162   | Not_found -> `error "job not found"
163   | exn -> `error (Printexc.to_string exn)
164
165 and proc_start_job jobname =
166   try
167     let job = Whenstate.get_job !state jobname in
168     let state' = run_job !state job in
169     state := state';
170     `ok
171   with
172   | Not_found -> `error "job not found"
173   | exn -> `error (Printexc.to_string exn)
174
175 and proc_get_job serial =
176   try
177     let serial = big_int_of_string serial in
178     let pid = BigIntMap.find serial !serialmap in
179     let job, dir, serial, start_time = IntMap.find pid !runningmap in
180     { Whenproto_aux.job_name = job.job_name;
181       job_serial = string_of_big_int serial;
182       job_tmpdir = dir; job_start_time = Int64.of_float start_time }
183   with
184   | Not_found -> failwith "job not found"
185   | exn -> failwith (Printexc.to_string exn)
186
187 and proc_set_variables vars =
188   try
189     let vars = Array.map (
190       fun { Whenproto_aux.sv_name = name; sv_value = value } ->
191         name, variable_of_rpc value
192     ) vars in
193     let vars = Array.to_list vars in
194
195     if !debug then
196       Syslog.notice "remote call: set_variables (%s)"
197         (String.concat " "
198            (List.map (
199              fun (name, value) ->
200                sprintf "%s=%s" name (string_of_variable value)
201             ) vars));
202
203     List.iter (fun (name, _) -> check_valid_variable_name name) vars;
204
205     (* Update all the variables atomically. *)
206     let s = List.fold_left (
207       fun s (name, value) -> Whenstate.set_variable s name value
208     ) !state vars in
209     state := s;
210
211     (* Which jobs need to be re-evaluated? *)
212     let jobs = Whenstate.get_dependencies !state (List.map fst vars) in
213     let state' = reevaluate_whenjobs !state jobs in
214     state := state';
215
216     `ok
217   with
218     Failure msg -> `error msg
219
220 and proc_get_job_names () =
221   Array.of_list (Whenstate.get_job_names !state)
222
223 (* Reload the jobs file. *)
224 and reload_file () =
225   let file = sprintf "%s/jobs.cmo" !jobsdir in
226
227   (* As we are reloading the file, we want to create a new state
228    * that has no jobs, but has all the variables from the previous
229    * state.
230    *)
231   let s = Whenstate.copy_variables !state Whenstate.empty in
232   Whenfile.init s;
233
234   let s =
235     try
236       Dynlink.loadfile file;
237       let s = Whenfile.get_state () in
238       Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
239       s
240     with
241     | Dynlink.Error err ->
242       let err = Dynlink.error_message err in
243       Syslog.error "error loading jobs: %s" err;
244       failwith err
245     | exn ->
246       failwith (Printexc.to_string exn) in
247
248   let s = Whenstate.copy_prev_state !state s in
249   state := s;
250
251   (* Re-evaluate all when jobs. *)
252   let jobs = Whenstate.get_whenjobs !state in
253   let state' = reevaluate_whenjobs ~onload:true !state jobs in
254   state := state';
255
256   (* Schedule the next every job to run. *)
257   schedule_next_everyjob ()
258
259 (* Re-evaluate each when-statement job, in a loop until we reach
260  * a fixpoint.  Run the jobs and return the updated state.
261  *)
262 and reevaluate_whenjobs ?onload state jobs =
263   let rec loop (set, state) jobs =
264     let set', state' =
265       List.fold_left (
266         fun (set, state) job ->
267           let r, state' =
268             try Whenstate.evaluate_whenjob ?onload state job
269             with Invalid_argument err | Failure err ->
270               Syslog.error "error evaluating job %s (at %s): %s"
271                 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
272               false, state in
273
274           if !debug then
275             Syslog.notice "evaluate %s -> %b\n" job.job_name r;
276
277           (if r then StringSet.add job.job_name set else set), state'
278       ) (set, state) jobs in
279     (* reached a fixpoint? *)
280     if StringSet.compare set set' <> 0 then
281       loop (set', state') jobs
282     else
283       (set', state')
284   in
285   let set, state = loop (StringSet.empty, state) jobs in
286   let jobnames = StringSet.elements set in
287
288   (* Ensure the jobs always run in predictable (name) order. *)
289   let jobnames = List.sort compare_jobnames jobnames in
290
291   (* Run the jobs. *)
292   let jobs = List.map (Whenstate.get_job state) jobnames in
293   List.fold_left run_job state jobs
294
295 (* Schedule the next every-statement job to run, if there is one.  We
296  * look at the every jobs, work out the time that each must run at,
297  * pick the job(s) which must run soonest, and schedule a timer to run
298  * them.  When the timer fires, it runs those jobs, then calls this
299  * function again.
300  *)
301 and schedule_next_everyjob () =
302   let t = time () in
303
304   (* Get only everyjobs. *)
305   let jobs = Whenstate.get_everyjobs !state in
306   let jobs = List.map (
307     function
308     | { job_cond = Every_job period } as job -> (job, period)
309     | { job_cond = When_job _ } -> assert false
310   ) jobs in
311
312   (* Map everyjob to next time it must run. *)
313   let jobs = List.map (
314     fun (job, period) ->
315       let t' = next_periodexpr t period in
316       assert (t' > t); (* serious bug in next_periodexpr if false *)
317       job, t'
318   ) jobs in
319
320   (* Sort, soonest first. *)
321   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
322
323   if !debug then (
324     List.iter (
325       fun (job, t) ->
326         Syslog.notice "%s: next scheduled run at %s"
327           job.job_name (string_of_time_t t)
328     ) jobs
329   );
330
331   (* Pick the job(s) which run soonest. *)
332   let rec pick = function
333     | [] -> 0., []
334     | [j, t] -> t, [j]
335     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
336     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
337   in
338   let t, jobs = pick jobs in
339
340   if t > 0. then (
341     if jobs <> [] then (
342       (* Ensure the jobs always run in predictable (name) order. *)
343       let jobs =
344         List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
345           jobs in
346
347       if !debug then
348         Syslog.notice "scheduling job(s) %s to run at %s"
349           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
350           (string_of_time_t t);
351
352       (* Schedule them to run at time t. *)
353       let g = new_timer_group () in
354       let t_diff = t -. Unix.time () in
355       let t_diff = if t_diff < 0. then 0. else t_diff in
356       let run_jobs () =
357         delete_timer_group ();          (* Delete the timer. *)
358         let state' = List.fold_left run_job !state jobs in
359         state := state';
360         schedule_next_everyjob ()
361       in
362       Unixqueue.weak_once esys g t_diff run_jobs;
363     )
364   )
365
366 and new_timer_group () =
367   delete_timer_group ();
368   let g = Unixqueue.new_group esys in
369   timer_group := Some g;
370   g
371
372 and delete_timer_group () =
373   match !timer_group with
374   | None -> ()
375   | Some g ->
376     Unixqueue.clear esys g;
377     timer_group := None
378
379 and run_job state job =
380   (* Increment JOBSERIAL. *)
381   let serial, state =
382     match Whenstate.get_variable state "JOBSERIAL" with
383     | T_int serial ->
384       let serial = succ_big_int serial in
385       let state' = Whenstate.set_variable state "JOBSERIAL" (T_int serial) in
386       serial, state'
387     | _ -> assert false in
388
389   (* Call the pre-condition script.  Note this may decide not to run
390    * the job by returning false.
391    *)
392   let pre_condition () =
393     match job.job_pre with
394     | None -> true
395     | Some pre ->
396       let rs = ref [] in
397       IntMap.iter (
398         fun pid (job, _, serial, start_time) ->
399           let r = { pirun_job_name = job.job_name;
400                     pirun_serial = serial;
401                     pirun_start_time = start_time;
402                     pirun_pid = pid } in
403           rs := r :: !rs
404       ) !runningmap;
405       let preinfo = {
406         pi_job_name = job.job_name;
407         pi_serial = serial;
408         pi_variables = Whenstate.get_variables state;
409         pi_running = !rs;
410       } in
411       pre preinfo
412   in
413   if pre_condition () then (
414     Syslog.notice "running %s (JOBSERIAL=%s)"
415       job.job_name (string_of_big_int serial);
416
417     (* Create a temporary directory.  The current directory of the job
418      * will be in this directory.  The directory is removed when the
419      * child process exits.
420      *)
421     let dir = tmpdir () in
422
423     let pid = fork () in
424     if pid = 0 then ( (* child process running the job *)
425       chdir dir;
426
427       (* Set environment variables corresponding to each variable. *)
428       List.iter
429         (fun (name, value) -> putenv name (string_of_variable value))
430         (Whenstate.get_variables state);
431
432       (* Set the $JOBNAME environment variable. *)
433       putenv "JOBNAME" job.job_name;
434
435       (* Create a temporary file containing the shell script fragment. *)
436       let script = dir // "script.sh" in
437       let chan = open_out script in
438       fprintf chan "set -e\n"; (* So that jobs exit on error. *)
439       output_string chan job.job_script.sh_script;
440       close_out chan;
441       chmod script 0o700;
442
443       let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
444
445       (* Set output to file. *)
446       let output = dir // "output.txt" in
447       let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
448       dup2 fd stdout;
449       dup2 fd stderr;
450       close fd;
451
452       (* Execute the shell script. *)
453       (try execvp shell [| shell; "-c"; script |];
454        with Unix_error (err, fn, _) ->
455          Syslog.error "%s failed: %s: %s" fn script (error_message err)
456       );
457       _exit 1
458     );
459
460     (* Remember this PID, the job and the temporary directory, so we
461      * can clean up when the child exits.
462      *)
463     runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
464     serialmap := BigIntMap.add serial pid !serialmap;
465
466     state
467   )
468   else (
469     Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
470       job.job_name (string_of_big_int serial);
471
472     state
473   )
474
475 and tmpdir () =
476   let chan = open_in "/dev/urandom" in
477   let data = String.create 16 in
478   really_input chan data 0 (String.length data);
479   close_in chan;
480   let data = Digest.to_hex (Digest.string data) in
481   let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
482   mkdir dir 0o700;
483   dir
484
485 (* This is called when a job (child process) exits. *)
486 and handle_sigchld _ =
487   try
488     let pid, status = waitpid [WNOHANG] 0 in
489     if pid > 0 then (
490       (* Look up the PID in the running jobs map. *)
491       let job, dir, serial, time = IntMap.find pid !runningmap in
492       runningmap := IntMap.remove pid !runningmap;
493       serialmap := BigIntMap.remove serial !serialmap;
494       post_job job dir serial time status
495     )
496   with Unix_error _ | Not_found -> ()
497
498 and post_job job dir serial time status =
499   (* If there is a post function, run it. *)
500   (match job.job_post with
501   | None -> ()
502   | Some post ->
503     let code =
504       match status with
505       | WEXITED c -> c
506       | WSIGNALED s | WSTOPPED s -> 1 in
507     let result = {
508       res_job_name = job.job_name;
509       res_serial = serial;
510       res_code = code;
511       res_tmpdir = dir;
512       res_output = dir // "output.txt";
513       res_start_time = time
514     } in
515     try post result
516     with
517     | Failure msg ->
518       Syslog.error "job %s post function failed: %s" job.job_name msg
519     | exn ->
520       Syslog.error "job %s post function exception: %s"
521         job.job_name (Printexc.to_string exn)
522   );
523
524   (* This should be safe because the path cannot contain shell metachars. *)
525   let cmd = sprintf "rm -rf '%s'" dir in
526   ignore (Sys.command cmd)
527
528 (* Intelligent comparison of job names. *)
529 and compare_jobnames name1 name2 =
530   try
531     let len1 = String.length name1
532     and len2 = String.length name2 in
533     if len1 > 4 && len2 > 4 &&
534       String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
535     then (
536       let i1 = int_of_string (String.sub name1 4 (len1-4)) in
537       let i2 = int_of_string (String.sub name2 4 (len2-4)) in
538       compare i1 i2
539     )
540     else raise Not_found
541   with _ ->
542     compare name1 name2
543
544 let main_loop () =
545   Unixqueue.run esys