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