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