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