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