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