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