Add a $JOBSERIAL environment variable when jobs run.
[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
21 open Big_int
22 open Unix
23 open Printf
24
25 (* See [exit.c]. *)
26 external _exit : int -> 'a = "whenjobs__exit"
27
28 (* All jobs that are loaded.  Maps name -> [job] structure. *)
29 let jobs = ref StringMap.empty
30
31 (* Map variable names to jobs which depend on that variable.  This
32  * gives us a quick way to tell which jobs might need to be reevaluated
33  * when a variable is set.
34  *)
35 let dependencies = ref StringMap.empty
36
37 (* Current values of variables.  Using the referentially transparent
38  * type Map is very useful here because it lets us cheaply keep
39  * previous values of variables.
40  *)
41 let variables : variables ref = ref StringMap.empty
42
43 (* $HOME/.whenjobs *)
44 let jobsdir = ref ""
45
46 (* Jobs that are running; map of PID -> (job, other data).  Note that
47  * the job may no longer exist *OR* it may have been renamed,
48  * eg. if the jobs file was reloaded.
49  *)
50 let running = ref IntMap.empty
51
52 (* Was debugging requested on the command line? *)
53 let debug = ref false
54
55 (* The server. *)
56 let server = ref None
57
58 let esys = Unixqueue.standard_event_system ()
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   server := Some (
71     Whenproto_srv.When.V1.create_server
72       ~proc_reload_file
73       ~proc_set_variable
74       ~proc_get_variable
75       ~proc_get_variable_names
76       ~proc_exit_daemon
77       (Rpc_server.Unix addr)
78       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
79       Rpc.Socket
80       esys
81   );
82
83   (* Handle SIGCHLD to clean up jobs. *)
84   Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
85
86   (* Initialize the variables.  XXX Eventually this will be saved
87    * and loaded from a persistent store.
88    *)
89   variables := StringMap.add "JOBSERIAL" (T_int zero_big_int) !variables
90
91 and proc_reload_file () =
92   if !debug then Syslog.notice "remote call: reload_file";
93
94   try reload_file (); `ok
95   with Failure err -> `error err
96
97 and proc_set_variable (name, value) =
98   if !debug then Syslog.notice "remote call: set_variable %s" name;
99
100   let value = variable_of_rpc value in
101   variables := StringMap.add name value !variables;
102
103   (* Which jobs need to be re-evaluated? *)
104   let jobnames = try StringMap.find name !dependencies with Not_found -> [] in
105   reevaluate_whenjobs jobnames
106
107 and proc_get_variable name =
108   if !debug then Syslog.notice "remote call: get_variable %s" name;
109
110   try rpc_of_variable (StringMap.find name !variables)
111   with (* all non-existent variables are empty strings *)
112     Not_found -> `string_t ""
113
114 and proc_get_variable_names () =
115   if !debug then Syslog.notice "remote call: get_variable_names";
116
117   (* Only return variables that are non-empty. *)
118   let vars = StringMap.fold (
119     fun name value xs -> if value <> T_string "" then name :: xs else xs
120   ) !variables [] in
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   Whenfile.init ();
140
141   let js =
142     try
143       Dynlink.loadfile file;
144       let jobs = Whenfile.get_jobs () in
145       Syslog.notice "loaded %d job(s) from %s" (List.length jobs) file;
146       jobs
147     with
148     | Dynlink.Error err ->
149       let err = Dynlink.error_message err in
150       Syslog.error "error loading jobs: %s" err;
151       failwith err
152     | exn ->
153       failwith (Printexc.to_string exn) in
154
155   (* Set 'jobs' and related global variables. *)
156   let () =
157     let map = List.fold_left (
158       fun map j ->
159         let name = j.job_name in
160         StringMap.add name j map
161     ) StringMap.empty js in
162     jobs := map in
163
164   let () =
165     let map = List.fold_left (
166       fun map j ->
167         let deps = dependencies_of_job j in
168         let name = j.job_name in
169         List.fold_left (
170           fun map d ->
171             let names = try StringMap.find d map with Not_found -> [] in
172             StringMap.add d (name :: names) map
173         ) map deps
174     ) StringMap.empty js in
175     dependencies := map in
176
177   (* Re-evaluate all when jobs. *)
178   reevaluate_whenjobs (StringMap.keys !jobs);
179
180   (* Schedule the next every job to run. *)
181   schedule_next_everyjob ()
182
183 (* Re-evaluate each named when-statement job, in a loop until we reach
184  * a fixpoint.  Run those that need to be run.  every-statement jobs
185  * are ignored here.
186  *)
187 and reevaluate_whenjobs jobnames =
188   let rec loop set jobnames =
189     let set' =
190       List.fold_left (
191         fun set jobname ->
192           let job =
193             try StringMap.find jobname !jobs
194             with Not_found -> assert false in
195           assert (jobname = job.job_name);
196
197           let r, job' =
198             try job_evaluate job !variables
199             with Invalid_argument err | Failure err ->
200               Syslog.error "error evaluating job %s (at %s): %s"
201                 jobname (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
202               false, job in
203
204           jobs := StringMap.add jobname job' !jobs;
205
206           if !debug then
207             Syslog.notice "evaluate %s -> %b\n" jobname r;
208
209           if r then StringSet.add jobname set else set
210       ) set jobnames in
211     if StringSet.compare set set' <> 0 then
212       loop set' jobnames
213     else
214       set'
215   in
216   let set = loop StringSet.empty jobnames in
217   let jobnames = StringSet.elements set in
218   (* Ensure the jobs always run in predictable (name) order. *)
219   let jobnames = List.sort compare_jobnames jobnames in
220   List.iter run_job
221     (List.map (fun jobname -> StringMap.find jobname !jobs) jobnames)
222
223 (* Schedule the next every-statement job to run, if there is one.  We
224  * look at the every jobs, work out the time that each must run at,
225  * pick the job(s) which must run soonest, and schedule a timer to run
226  * them.  When the timer fires, it runs those jobs, then calls this
227  * function again.
228  *)
229 and schedule_next_everyjob () =
230   let t = time () in
231
232   (* Get only everyjobs. *)
233   let jobs = StringMap.values !jobs in
234   let jobs = filter_map (
235     function
236     | { job_cond = Every_job period } as job -> Some (job, period)
237     | { job_cond = When_job _ } -> None
238   ) jobs in
239
240   (* Map everyjob to next time it must run. *)
241   let jobs = List.map (
242     fun (job, period) ->
243       let t' = next_periodexpr t period in
244       assert (t' > t); (* serious bug in next_periodexpr if false *)
245       job, t'
246   ) jobs in
247
248   (* Sort, soonest first. *)
249   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
250
251   if !debug then (
252     List.iter (
253       fun (job, t) ->
254         Syslog.notice "%s: next scheduled run at %s"
255           job.job_name (string_of_time_t t)
256     ) jobs
257   );
258
259   (* Pick the job(s) which run soonest. *)
260   let rec pick = function
261     | [] -> 0., []
262     | [j, t] -> t, [j]
263     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
264     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
265   in
266   let t, jobs = pick jobs in
267
268   if t > 0. then (
269     if jobs <> [] then (
270       (* Ensure the jobs always run in predictable (name) order. *)
271       let jobs =
272         List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
273           jobs in
274
275       if !debug then
276         Syslog.notice "scheduling job(s) %s to run at %s"
277           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
278           (string_of_time_t t);
279
280       (* Schedule them to run at time t. *)
281       let g = Unixqueue.new_group esys in
282       let t_diff = t -. Unix.time () in
283       let t_diff = if t_diff < 0. then 0. else t_diff in
284       let run_jobs () =
285         Unixqueue.clear esys g;         (* Delete the timer. *)
286         List.iter run_job jobs;
287         schedule_next_everyjob ()
288       in
289       Unixqueue.weak_once esys g t_diff run_jobs;
290     )
291   )
292
293 and string_of_time_t t =
294   let tm = gmtime t in
295   sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
296     (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
297     tm.tm_hour tm.tm_min tm.tm_sec
298
299 and run_job job =
300   let () =
301     (* Increment JOBSERIAL. *)
302     let serial =
303       match StringMap.find "JOBSERIAL" !variables with
304       | T_int serial ->
305         let serial = succ_big_int serial in
306         variables := StringMap.add "JOBSERIAL" (T_int serial) !variables;
307         serial
308       | _ -> assert false in
309
310     Syslog.notice "running %s (JOBSERIAL=%s)"
311       job.job_name (string_of_big_int serial) in
312
313   (* Create a temporary directory.  The current directory of the job
314    * will be in this directory.  The directory is removed when the
315    * child process exits.
316    *)
317   let dir = tmpdir () in
318
319   let pid = fork () in
320   if pid = 0 then ( (* child process running the job *)
321     chdir dir;
322
323     (* Set environment variables corresponding to each variable. *)
324     StringMap.iter
325       (fun name value -> putenv name (string_of_variable value)) !variables;
326
327     (* Set the $JOBNAME environment variable. *)
328     putenv "JOBNAME" job.job_name;
329
330     (* Create a temporary file containing the shell script fragment. *)
331     let script = dir // "script" in
332     let chan = open_out script in
333     output_string chan job.job_script.sh_script;
334     close_out chan;
335     chmod script 0o700;
336
337     (* Execute the shell script. *)
338     (try execvp "bash" [| "bash"; "-c"; script |];
339      with Unix_error (err, fn, _) ->
340        Syslog.error "%s failed: %s: %s" fn script (error_message err)
341     );
342     _exit 1
343   );
344
345   (* Remember this PID, the job and the temporary directory, so we
346    * can clean up when the child exits.
347    *)
348   running := IntMap.add pid (job, dir) !running
349
350 and tmpdir () =
351   let chan = open_in "/dev/urandom" in
352   let data = String.create 16 in
353   really_input chan data 0 (String.length data);
354   close_in chan;
355   let data = Digest.to_hex (Digest.string data) in
356   let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
357   mkdir dir 0o700;
358   dir
359
360 (* This is called when a job (child process) exits. *)
361 and handle_sigchld _ =
362   try
363     let pid, status = waitpid [WNOHANG] 0 in
364     if pid > 0 then (
365       (* Look up the PID in the running jobs map. *)
366       let job, dir = IntMap.find pid !running in
367       running := IntMap.remove pid !running;
368       cleanup_job job dir
369     )
370   with Unix_error _ | Not_found -> ()
371
372 and cleanup_job job dir =
373   (* This should be safe because the path cannot contain shell metachars. *)
374   let cmd = sprintf "rm -rf '%s'" dir in
375   ignore (Sys.command cmd)
376
377 (* Intelligent comparison of job names. *)
378 and compare_jobnames name1 name2 =
379   try
380     let len1 = String.length name1
381     and len2 = String.length name2 in
382     if len1 > 4 && len2 > 4 &&
383       String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
384     then (
385       let i1 = int_of_string (String.sub name1 4 (len1-4)) in
386       let i2 = int_of_string (String.sub name2 4 (len2-4)) in
387       compare i1 i2
388     )
389     else raise Not_found
390   with _ ->
391     compare name1 name2
392
393 let main_loop () =
394   Unixqueue.run esys