a4993a8543e06c32ddec5d71d4929f9ece3e2d41
[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: a map of PID -> (job, tmpdir, serial, start_time).
36  * Note that the job may no longer exist *OR* it may have been renamed,
37  * eg. if the jobs file was reloaded.
38  *)
39 let runningmap = ref IntMap.empty
40
41 (* Serial numbers of running jobs.  Map of serial -> PID (in runningmap). *)
42 let serialmap = ref BigIntMap.empty
43
44 (* Was debugging requested on the command line? *)
45 let debug = ref false
46
47 (* The server. *)
48 let server = ref None
49
50 let esys = Unixqueue.standard_event_system ()
51
52 (* The timer.  It's convenient to have this as a global variable
53  * because (a) there should only be one timer (which fires when the
54  * soonest every-job becomes ready), and (b) it's complicated to track
55  * that timer and avoid it getting double-scheduled (eg.  when we
56  * reload the jobs file) without having a global variable.
57  *)
58 let timer_group = ref None
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   (* Create the Unix domain socket server. *)
71   server := Some (
72     Whenproto_srv.When.V1.create_server
73       ~proc_reload_file
74       ~proc_set_variable
75       ~proc_get_variable
76       ~proc_get_variable_names
77       ~proc_exit_daemon
78       ~proc_get_jobs
79       ~proc_cancel_job
80       ~proc_start_job
81       ~proc_get_job
82       ~proc_set_variables
83       ~proc_get_job_names
84       (Rpc_server.Unix addr)
85       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
86       Rpc.Socket
87       esys
88   );
89
90   (* Handle SIGCHLD to clean up jobs. *)
91   Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
92
93   (* Initialize the variables. *)
94   state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
95
96 and proc_reload_file () =
97   if !debug then Syslog.notice "remote call: reload_file";
98
99   try reload_file (); `ok
100   with Failure err -> `error err
101
102 and proc_set_variable (name, value) =
103   if !debug then Syslog.notice "remote call: set_variable %s" name;
104
105   try
106     check_valid_variable_name name;
107
108     let value = variable_of_rpc value in
109     state := Whenstate.set_variable !state name value;
110
111     (* Which jobs need to be re-evaluated? *)
112     let jobs = Whenstate.get_dependencies !state [name] in
113     reevaluate_whenjobs jobs;
114
115     `ok
116   with
117     Failure msg -> `error msg
118
119 and proc_get_variable name =
120   if !debug then Syslog.notice "remote call: get_variable %s" name;
121
122   rpc_of_variable (Whenstate.get_variable !state name)
123
124 and proc_get_variable_names () =
125   if !debug then Syslog.notice "remote call: get_variable_names";
126
127   let vars = Whenstate.get_variable_names !state in
128
129   (* Return variable names as a sorted array. *)
130   let vars = Array.of_list vars in
131   Array.sort compare vars;
132   vars
133
134 and proc_exit_daemon () =
135   if !debug then Syslog.notice "remote call: exit_daemon";
136
137   match !server with
138   | None ->
139     `error "exit_daemon: no server handle"
140   | Some s ->
141     Rpc_server.stop_server ~graceful:true s;
142     server := None;
143     `ok
144
145 and proc_get_jobs () =
146   let running = Array.of_list (IntMap.values !runningmap) in
147   Array.map (
148     fun (job, dir, serial, start_time) ->
149       { Whenproto_aux.job_name = job.job_name;
150         job_serial = string_of_big_int serial;
151         job_tmpdir = dir; job_start_time = Int64.of_float start_time }
152   ) running
153
154 and proc_cancel_job serial =
155   try
156     let serial = big_int_of_string serial in
157     let pid = BigIntMap.find serial !serialmap in
158     kill pid 15;
159     `ok
160   with
161   | Not_found -> `error "job not found"
162   | exn -> `error (Printexc.to_string exn)
163
164 and proc_start_job jobname =
165   try
166     let job = Whenstate.get_job !state jobname in
167     run_job job;
168     `ok
169   with
170   | Not_found -> `error "job not found"
171   | exn -> `error (Printexc.to_string exn)
172
173 and proc_get_job serial =
174   try
175     let serial = big_int_of_string serial in
176     let pid = BigIntMap.find serial !serialmap in
177     let job, dir, serial, start_time = IntMap.find pid !runningmap in
178     { Whenproto_aux.job_name = job.job_name;
179       job_serial = string_of_big_int serial;
180       job_tmpdir = dir; job_start_time = Int64.of_float start_time }
181   with
182   | Not_found -> failwith "job not found"
183   | exn -> failwith (Printexc.to_string exn)
184
185 and proc_set_variables vars =
186   try
187     let vars = Array.map (
188       fun { Whenproto_aux.sv_name = name; sv_value = value } ->
189         name, variable_of_rpc value
190     ) vars in
191     let vars = Array.to_list vars in
192
193     if !debug then
194       Syslog.notice "remote call: set_variables (%s)"
195         (String.concat " "
196            (List.map (
197              fun (name, value) ->
198                sprintf "%s=%s" name (string_of_variable value)
199             ) vars));
200
201     List.iter (fun (name, _) -> check_valid_variable_name name) vars;
202
203     (* Update all the variables atomically. *)
204     let s = List.fold_left (
205       fun s (name, value) -> Whenstate.set_variable s name value
206     ) !state vars in
207     state := s;
208
209     (* Which jobs need to be re-evaluated? *)
210     let jobs = Whenstate.get_dependencies !state (List.map fst vars) in
211     reevaluate_whenjobs jobs;
212
213     `ok
214   with
215     Failure msg -> `error msg
216
217 and proc_get_job_names () =
218   Array.of_list (Whenstate.get_job_names !state)
219
220 (* Reload the jobs file. *)
221 and reload_file () =
222   let file = sprintf "%s/jobs.cmo" !jobsdir in
223
224   (* As we are reloading the file, we want to create a new state
225    * that has no jobs, but has all the variables from the previous
226    * state.
227    *)
228   let s = Whenstate.copy_variables !state Whenstate.empty in
229   Whenfile.init s;
230
231   let s =
232     try
233       Dynlink.loadfile file;
234       let s = Whenfile.get_state () in
235       Syslog.notice "loaded %d job(s) from %s" (Whenstate.nr_jobs s) file;
236       s
237     with
238     | Dynlink.Error err ->
239       let err = Dynlink.error_message err in
240       Syslog.error "error loading jobs: %s" err;
241       failwith err
242     | exn ->
243       failwith (Printexc.to_string exn) in
244
245   let s = Whenstate.copy_prev_state !state s in
246   state := s;
247
248   (* Re-evaluate all when jobs. *)
249   reevaluate_whenjobs ~onload:true (Whenstate.get_whenjobs !state);
250
251   (* Schedule the next every job to run. *)
252   schedule_next_everyjob ()
253
254 (* Re-evaluate each when-statement job, in a loop until we reach
255  * a fixpoint.  Run those that need to be run.
256  *)
257 and reevaluate_whenjobs ?onload jobs =
258   let rec loop set jobs =
259     let set' =
260       List.fold_left (
261         fun set job ->
262           let r, state' =
263             try Whenstate.evaluate_whenjob ?onload !state job
264             with Invalid_argument err | Failure err ->
265               Syslog.error "error evaluating job %s (at %s): %s"
266                 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
267               false, !state in
268
269           state := state';
270
271           if !debug then
272             Syslog.notice "evaluate %s -> %b\n" job.job_name r;
273
274           if r then StringSet.add job.job_name set else set
275       ) set jobs in
276     if StringSet.compare set set' <> 0 then
277       loop set' jobs
278     else
279       set'
280   in
281   let set = loop StringSet.empty jobs in
282   let jobnames = StringSet.elements set in
283
284   (* Ensure the jobs always run in predictable (name) order. *)
285   let jobnames = List.sort compare_jobnames jobnames in
286
287   (* Run the jobs. *)
288   List.iter run_job (List.map (Whenstate.get_job !state) jobnames)
289
290 (* Schedule the next every-statement job to run, if there is one.  We
291  * look at the every jobs, work out the time that each must run at,
292  * pick the job(s) which must run soonest, and schedule a timer to run
293  * them.  When the timer fires, it runs those jobs, then calls this
294  * function again.
295  *)
296 and schedule_next_everyjob () =
297   let t = time () in
298
299   (* Get only everyjobs. *)
300   let jobs = Whenstate.get_everyjobs !state in
301   let jobs = List.map (
302     function
303     | { job_cond = Every_job period } as job -> (job, period)
304     | { job_cond = When_job _ } -> assert false
305   ) jobs in
306
307   (* Map everyjob to next time it must run. *)
308   let jobs = List.map (
309     fun (job, period) ->
310       let t' = next_periodexpr t period in
311       assert (t' > t); (* serious bug in next_periodexpr if false *)
312       job, t'
313   ) jobs in
314
315   (* Sort, soonest first. *)
316   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
317
318   if !debug then (
319     List.iter (
320       fun (job, t) ->
321         Syslog.notice "%s: next scheduled run at %s"
322           job.job_name (string_of_time_t t)
323     ) jobs
324   );
325
326   (* Pick the job(s) which run soonest. *)
327   let rec pick = function
328     | [] -> 0., []
329     | [j, t] -> t, [j]
330     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
331     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
332   in
333   let t, jobs = pick jobs in
334
335   if t > 0. then (
336     if jobs <> [] then (
337       (* Ensure the jobs always run in predictable (name) order. *)
338       let jobs =
339         List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
340           jobs in
341
342       if !debug then
343         Syslog.notice "scheduling job(s) %s to run at %s"
344           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
345           (string_of_time_t t);
346
347       (* Schedule them to run at time t. *)
348       let g = new_timer_group () in
349       let t_diff = t -. Unix.time () in
350       let t_diff = if t_diff < 0. then 0. else t_diff in
351       let run_jobs () =
352         delete_timer_group ();          (* Delete the timer. *)
353         List.iter run_job jobs;
354         schedule_next_everyjob ()
355       in
356       Unixqueue.weak_once esys g t_diff run_jobs;
357     )
358   )
359
360 and new_timer_group () =
361   delete_timer_group ();
362   let g = Unixqueue.new_group esys in
363   timer_group := Some g;
364   g
365
366 and delete_timer_group () =
367   match !timer_group with
368   | None -> ()
369   | Some g ->
370     Unixqueue.clear esys g;
371     timer_group := None
372
373 and run_job job =
374   (* Increment JOBSERIAL. *)
375   let serial =
376     match Whenstate.get_variable !state "JOBSERIAL" with
377     | T_int serial ->
378       let serial = succ_big_int serial in
379       state := Whenstate.set_variable !state "JOBSERIAL" (T_int serial);
380       serial
381     | _ -> assert false in
382
383   (* Call the pre-condition script.  Note this may decide not to run
384    * the job by returning false.
385    *)
386   let pre_condition () =
387     match job.job_pre with
388     | None -> true
389     | Some pre ->
390       let rs = ref [] in
391       IntMap.iter (
392         fun pid (job, _, serial, start_time) ->
393           let r = { pirun_job_name = job.job_name;
394                     pirun_serial = serial;
395                     pirun_start_time = start_time;
396                     pirun_pid = pid } in
397           rs := r :: !rs
398       ) !runningmap;
399       let preinfo = {
400         pi_job_name = job.job_name;
401         pi_serial = serial;
402         pi_variables = Whenstate.get_variables !state;
403         pi_running = !rs;
404       } in
405       pre preinfo
406   in
407   if pre_condition () then (
408     Syslog.notice "running %s (JOBSERIAL=%s)"
409       job.job_name (string_of_big_int serial);
410
411     (* Create a temporary directory.  The current directory of the job
412      * will be in this directory.  The directory is removed when the
413      * child process exits.
414      *)
415     let dir = tmpdir () in
416
417     let pid = fork () in
418     if pid = 0 then ( (* child process running the job *)
419       chdir dir;
420
421       (* Set environment variables corresponding to each variable. *)
422       List.iter
423         (fun (name, value) -> putenv name (string_of_variable value))
424         (Whenstate.get_variables !state);
425
426       (* Set the $JOBNAME environment variable. *)
427       putenv "JOBNAME" job.job_name;
428
429       (* Create a temporary file containing the shell script fragment. *)
430       let script = dir // "script.sh" in
431       let chan = open_out script in
432       fprintf chan "set -e\n"; (* So that jobs exit on error. *)
433       output_string chan job.job_script.sh_script;
434       close_out chan;
435       chmod script 0o700;
436
437       let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
438
439       (* Set output to file. *)
440       let output = dir // "output.txt" in
441       let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
442       dup2 fd stdout;
443       dup2 fd stderr;
444       close fd;
445
446       (* Execute the shell script. *)
447       (try execvp shell [| shell; "-c"; script |];
448        with Unix_error (err, fn, _) ->
449          Syslog.error "%s failed: %s: %s" fn script (error_message err)
450       );
451       _exit 1
452     );
453
454     (* Remember this PID, the job and the temporary directory, so we
455      * can clean up when the child exits.
456      *)
457     runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
458     serialmap := BigIntMap.add serial pid !serialmap
459   )
460   else (
461     Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
462       job.job_name (string_of_big_int serial);
463   )
464
465 and tmpdir () =
466   let chan = open_in "/dev/urandom" in
467   let data = String.create 16 in
468   really_input chan data 0 (String.length data);
469   close_in chan;
470   let data = Digest.to_hex (Digest.string data) in
471   let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
472   mkdir dir 0o700;
473   dir
474
475 (* This is called when a job (child process) exits. *)
476 and handle_sigchld _ =
477   try
478     let pid, status = waitpid [WNOHANG] 0 in
479     if pid > 0 then (
480       (* Look up the PID in the running jobs map. *)
481       let job, dir, serial, time = IntMap.find pid !runningmap in
482       runningmap := IntMap.remove pid !runningmap;
483       serialmap := BigIntMap.remove serial !serialmap;
484       post_job job dir serial time status
485     )
486   with Unix_error _ | Not_found -> ()
487
488 and post_job job dir serial time status =
489   (* If there is a post function, run it. *)
490   (match job.job_post with
491   | None -> ()
492   | Some post ->
493     let code =
494       match status with
495       | WEXITED c -> c
496       | WSIGNALED s | WSTOPPED s -> 1 in
497     let result = {
498       res_job_name = job.job_name;
499       res_serial = serial;
500       res_code = code;
501       res_tmpdir = dir;
502       res_output = dir // "output.txt";
503       res_start_time = time
504     } in
505     try post result
506     with
507     | Failure msg ->
508       Syslog.error "job %s post function failed: %s" job.job_name msg
509     | exn ->
510       Syslog.error "job %s post function exception: %s"
511         job.job_name (Printexc.to_string exn)
512   );
513
514   (* This should be safe because the path cannot contain shell metachars. *)
515   let cmd = sprintf "rm -rf '%s'" dir in
516   ignore (Sys.command cmd)
517
518 (* Intelligent comparison of job names. *)
519 and compare_jobnames name1 name2 =
520   try
521     let len1 = String.length name1
522     and len2 = String.length name2 in
523     if len1 > 4 && len2 > 4 &&
524       String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
525     then (
526       let i1 = int_of_string (String.sub name1 4 (len1-4)) in
527       let i2 = int_of_string (String.sub name2 4 (len2-4)) in
528       compare i1 i2
529     )
530     else raise Not_found
531   with _ ->
532     compare name1 name2
533
534 let main_loop () =
535   Unixqueue.run esys