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