32 bit: Fix for 31 bit int overflow in time_t.
[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       ~proc_test_variables
85       ~proc_ping_daemon
86       ~proc_whisper_variables
87       (Rpc_server.Unix addr)
88       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
89       Rpc.Socket
90       esys
91   );
92
93   (* Handle SIGCHLD to clean up jobs. *)
94   Sys.set_signal Sys.sigchld (Sys.Signal_handle handle_sigchld);
95
96   (* Initialize the variables. *)
97   state := Whenstate.set_variable !state "JOBSERIAL" (T_int zero_big_int)
98
99 and proc_reload_file () =
100   if !debug then Syslog.notice "remote call: reload_file";
101
102   try reload_files (); `ok
103   with Failure err -> `error err
104
105 and proc_set_variable (name, value) =
106   if !debug then Syslog.notice "remote call: set_variable %s" name;
107
108   try
109     check_valid_variable_name name;
110
111     let value = variable_of_rpc value in
112     state := Whenstate.set_variable !state name value;
113
114     (* Which jobs need to be re-evaluated? *)
115     let jobs = Whenstate.get_dependencies !state [name] in
116     let jobnames, state' = reevaluate_whenjobs !state jobs in
117     let state' = run_whenjobs state' jobnames in
118     state := state';
119
120     `ok
121   with
122     Failure msg -> `error msg
123
124 and proc_get_variable name =
125   if !debug then Syslog.notice "remote call: get_variable %s" name;
126
127   rpc_of_variable (Whenstate.get_variable !state name)
128
129 and proc_get_variable_names () =
130   if !debug then Syslog.notice "remote call: get_variable_names";
131
132   let vars = Whenstate.get_variable_names !state in
133
134   (* Return variable names as a sorted array. *)
135   let vars = Array.of_list vars in
136   Array.sort compare vars;
137   vars
138
139 and proc_exit_daemon () =
140   if !debug then Syslog.notice "remote call: exit_daemon";
141
142   match !server with
143   | None ->
144     `error "exit_daemon: no server handle"
145   | Some s ->
146     Rpc_server.stop_server ~graceful:true s;
147     server := None;
148     `ok
149
150 and proc_get_jobs () =
151   let running = Array.of_list (IntMap.values !runningmap) in
152   Array.map (
153     fun (job, dir, serial, start_time) ->
154       { Whenproto_aux.job_name = job.job_name;
155         job_serial = string_of_big_int serial;
156         job_tmpdir = dir; job_start_time = Int64.of_float start_time }
157   ) running
158
159 and proc_cancel_job serial =
160   try
161     let serial = big_int_of_string serial in
162     let pid = BigIntMap.find serial !serialmap in
163     kill pid 15;
164     `ok
165   with
166   | Not_found -> `error "job not found"
167   | exn -> `error (Printexc.to_string exn)
168
169 and proc_start_job jobname =
170   try
171     let job = Whenstate.get_job !state jobname in
172     let state' = run_job !state job in
173     state := state';
174     `ok
175   with
176   | Not_found -> `error "job not found"
177   | exn -> `error (Printexc.to_string exn)
178
179 and proc_get_job serial =
180   try
181     let serial = big_int_of_string serial in
182     let pid = BigIntMap.find serial !serialmap in
183     let job, dir, serial, start_time = IntMap.find pid !runningmap in
184     { Whenproto_aux.job_name = job.job_name;
185       job_serial = string_of_big_int serial;
186       job_tmpdir = dir; job_start_time = Int64.of_float start_time }
187   with
188   | Not_found -> failwith "job not found"
189   | exn -> failwith (Printexc.to_string exn)
190
191 and proc_set_variables vars =
192   try
193     let vars = Array.map (
194       fun { Whenproto_aux.sv_name = name; sv_value = value } ->
195         name, variable_of_rpc value
196     ) vars in
197     let vars = Array.to_list vars in
198
199     if !debug then
200       Syslog.notice "remote call: set_variables (%s)"
201         (String.concat " "
202            (List.map (
203              fun (name, value) ->
204                sprintf "%s=%s" name (string_of_variable value)
205             ) vars));
206
207     List.iter (fun (name, _) -> check_valid_variable_name name) vars;
208
209     (* Update all the variables atomically. *)
210     let s = List.fold_left (
211       fun s (name, value) -> Whenstate.set_variable s name value
212     ) !state vars in
213     state := s;
214
215     (* Which jobs need to be re-evaluated? *)
216     let jobs = Whenstate.get_dependencies !state (List.map fst vars) in
217     let jobnames, state' = reevaluate_whenjobs !state jobs in
218     let state' = run_whenjobs state' jobnames in
219     state := state';
220
221     `ok
222   with
223     Failure msg -> `error msg
224
225 and proc_get_job_names () =
226   Array.of_list (Whenstate.get_job_names !state)
227
228 and proc_test_variables vars =
229   (* This is the same as proc_set_variables, except that it doesn't
230    * update the state, it just returns the jobs that *would* run if
231    * these variables were set to these values.
232    *)
233   let vars = Array.map (
234     fun { Whenproto_aux.sv_name = name; sv_value = value } ->
235       name, variable_of_rpc value
236   ) vars in
237   let vars = Array.to_list vars in
238
239   if !debug then
240     Syslog.notice "remote call: test_variables (%s)"
241       (String.concat " "
242          (List.map (
243            fun (name, value) ->
244              sprintf "%s=%s" name (string_of_variable value)
245           ) vars));
246
247   List.iter (fun (name, _) -> check_valid_variable_name name) vars;
248
249   (* Update all the variables atomically. *)
250   let state = List.fold_left (
251     fun s (name, value) -> Whenstate.set_variable s name value
252   ) !state vars in
253
254   (* Which jobs WOULD be re-evaluated? *)
255   let jobs = Whenstate.get_dependencies state (List.map fst vars) in
256   let jobnames, _ = reevaluate_whenjobs state jobs in
257
258   (* Return the names. *)
259   Array.of_list jobnames
260
261 and proc_ping_daemon () = `ok
262
263 and proc_whisper_variables vars =
264   try
265     let vars = Array.map (
266       fun { Whenproto_aux.sv_name = name; sv_value = value } ->
267         name, variable_of_rpc value
268     ) vars in
269     let vars = Array.to_list vars in
270
271     if !debug then
272       Syslog.notice "remote call: whisper_variables (%s)"
273         (String.concat " "
274            (List.map (
275              fun (name, value) ->
276                sprintf "%s=%s" name (string_of_variable value)
277             ) vars));
278
279     List.iter (fun (name, _) -> check_valid_variable_name name) vars;
280
281     (* Update all the variables atomically. *)
282     let s = List.fold_left (
283       fun s (name, value) -> Whenstate.set_variable s name value
284     ) !state vars in
285     state := s;
286
287     (* .. but don't reevaluate or run jobs. *)
288
289     `ok
290   with
291     Failure msg -> `error msg
292
293 (* Reload the jobs file(s). *)
294 and reload_files () =
295   (* Get the highest numbered dir/jobs__*.cmo (bytecode) or
296    * dir/jobs__*.cmxs (native code) file and load it.  Delete
297    * lower-numbered (== older) files.
298    *)
299   let filename =
300     let suffix, slen =
301       if not Dynlink.is_native then ".cmo", 4 else ".cmxs", 5 in
302     let dir = !jobsdir in
303     let files = Array.to_list (Sys.readdir dir) in
304     let times = filter_map (
305       fun file ->
306         if not (string_startswith file "jobs__") ||
307           not (string_endswith file suffix) then
308           None
309         else (
310           let len = String.length file in
311           let t = String.sub file 6 (len-slen-6) in
312           (* Use int64 because t won't necessarily fit into 31 bit int. *)
313           try Some (Int64.of_string t)
314           with Failure "int_of_string" -> assert false
315         )
316     ) files in
317     let times = List.rev (List.sort compare times) in
318     match times with
319     | [] -> None
320     | x::xs ->
321       (* Unlink the older files. *)
322       List.iter (
323         fun t ->
324           try unlink (dir // sprintf "jobs__%Ld%s" t suffix)
325           with Unix_error _ -> ()
326       ) xs;
327       (* Return the newest (highest numbered) file. *)
328       Some (dir // sprintf "jobs__%Ld%s" x suffix) in
329
330   (* As we are reloading the file, we want to create a new state
331    * that has no jobs, but has all the variables from the previous
332    * state.
333    *)
334   let s = Whenstate.copy_variables !state Whenstate.empty in
335   Whenfile.init s;
336
337   let s =
338     match filename with
339     | None ->
340       (* no jobs file, return the same state *)
341       Syslog.notice "no jobs file found";
342       s
343     | Some filename ->
344       try
345         Dynlink.loadfile filename;
346         let s = Whenfile.get_state () in
347         Syslog.notice "loaded %d job(s)" (Whenstate.nr_jobs s);
348         s
349       with
350       | Dynlink.Error err ->
351         let err = Dynlink.error_message err in
352         Syslog.error "error loading jobs: %s" err;
353         failwith err
354       | exn ->
355         failwith (Printexc.to_string exn) in
356
357   let s = Whenstate.copy_prev_state !state s in
358   state := s;
359
360   (* Re-evaluate all when jobs. *)
361   let jobs = Whenstate.get_whenjobs !state in
362   let jobnames, state' = reevaluate_whenjobs ~onload:true !state jobs in
363   let state' = run_whenjobs state' jobnames in
364   state := state';
365
366   (* Schedule the next every job to run. *)
367   schedule_next_everyjob ()
368
369 (* Re-evaluate each when-statement job, in a loop until we reach
370  * a fixpoint.  Return the list of job names that should run and
371  * the updated state.
372  *)
373 and reevaluate_whenjobs ?onload state jobs =
374   let rec loop (set, state) jobs =
375     let set', state' =
376       List.fold_left (
377         fun (set, state) job ->
378           let r, state' =
379             try Whenstate.evaluate_whenjob ?onload state job
380             with Invalid_argument err | Failure err ->
381               Syslog.error "error evaluating job %s (at %s): %s"
382                 job.job_name (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err;
383               false, state in
384
385           if !debug then
386             Syslog.notice "evaluate %s -> %b\n" job.job_name r;
387
388           (if r then StringSet.add job.job_name set else set), state'
389       ) (set, state) jobs in
390     (* reached a fixpoint? *)
391     if StringSet.compare set set' <> 0 then
392       loop (set', state') jobs
393     else
394       (set', state')
395   in
396   let set, state = loop (StringSet.empty, state) jobs in
397   let jobnames = StringSet.elements set in
398
399   (* Ensure the jobs always run in predictable (name) order. *)
400   let jobnames = List.sort compare_jobnames jobnames in
401   jobnames, state
402
403 and run_whenjobs state jobnames =
404   (* Run the jobs. *)
405   let jobs = List.map (Whenstate.get_job state) jobnames in
406   List.fold_left run_job state jobs
407
408 (* Schedule the next every-statement job to run, if there is one.  We
409  * look at the every jobs, work out the time that each must run at,
410  * pick the job(s) which must run soonest, and schedule a timer to run
411  * them.  When the timer fires, it runs those jobs, then calls this
412  * function again.
413  *)
414 and schedule_next_everyjob () =
415   let t = time () in
416
417   (* Get only everyjobs. *)
418   let jobs = Whenstate.get_everyjobs !state in
419   let jobs = List.map (
420     function
421     | { job_cond = Every_job period } as job -> (job, period)
422     | { job_cond = When_job _ } -> assert false
423   ) jobs in
424
425   (* Map everyjob to next time it must run. *)
426   let jobs = List.map (
427     fun (job, period) ->
428       let t' = next_periodexpr t period in
429       assert (t' > t); (* serious bug in next_periodexpr if false *)
430       job, t'
431   ) jobs in
432
433   (* Sort, soonest first. *)
434   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
435
436   if !debug then (
437     List.iter (
438       fun (job, t) ->
439         Syslog.notice "%s: next scheduled run at %s"
440           job.job_name (string_of_time_t t)
441     ) jobs
442   );
443
444   (* Pick the job(s) which run soonest. *)
445   let rec pick = function
446     | [] -> 0., []
447     | [j, t] -> t, [j]
448     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
449     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
450   in
451   let t, jobs = pick jobs in
452
453   if t > 0. then (
454     if jobs <> [] then (
455       (* Ensure the jobs always run in predictable (name) order. *)
456       let jobs =
457         List.sort (fun {job_name = a} {job_name = b} -> compare_jobnames a b)
458           jobs in
459
460       if !debug then
461         Syslog.notice "scheduling job(s) %s to run at %s"
462           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
463           (string_of_time_t t);
464
465       (* Schedule them to run at time t. *)
466       let g = new_timer_group () in
467       let t_diff = t -. Unix.time () in
468       let t_diff = if t_diff < 0. then 0. else t_diff in
469       let run_jobs () =
470         delete_timer_group ();          (* Delete the timer. *)
471         let state' = List.fold_left run_job !state jobs in
472         state := state';
473         schedule_next_everyjob ()
474       in
475       Unixqueue.weak_once esys g t_diff run_jobs;
476     )
477   )
478
479 and new_timer_group () =
480   delete_timer_group ();
481   let g = Unixqueue.new_group esys in
482   timer_group := Some g;
483   g
484
485 and delete_timer_group () =
486   match !timer_group with
487   | None -> ()
488   | Some g ->
489     Unixqueue.clear esys g;
490     timer_group := None
491
492 and run_job state job =
493   (* Increment JOBSERIAL. *)
494   let serial, state =
495     match Whenstate.get_variable state "JOBSERIAL" with
496     | T_int serial ->
497       let serial = succ_big_int serial in
498       let state' = Whenstate.set_variable state "JOBSERIAL" (T_int serial) in
499       serial, state'
500     | _ -> assert false in
501
502   (* Call the pre-condition script.  Note this may decide not to run
503    * the job by returning false.
504    *)
505   let pre_condition () =
506     match job.job_pre with
507     | None -> true
508     | Some pre ->
509       let rs = ref [] in
510       IntMap.iter (
511         fun pid (job, _, serial, start_time) ->
512           let r = { pirun_job_name = job.job_name;
513                     pirun_serial = serial;
514                     pirun_start_time = start_time;
515                     pirun_pid = pid } in
516           rs := r :: !rs
517       ) !runningmap;
518       let preinfo = {
519         pi_job_name = job.job_name;
520         pi_serial = serial;
521         pi_variables = Whenstate.get_variables state;
522         pi_running = !rs;
523       } in
524       pre preinfo
525   in
526   if pre_condition () then (
527     Syslog.notice "running %s (JOBSERIAL=%s)"
528       job.job_name (string_of_big_int serial);
529
530     (* Create a temporary directory.  The current directory of the job
531      * will be in this directory.  The directory is removed when the
532      * child process exits.
533      *)
534     let dir = tmpdir () in
535
536     let pid = fork () in
537     if pid = 0 then ( (* child process running the job *)
538       chdir dir;
539
540       (* Set environment variables corresponding to each variable. *)
541       List.iter
542         (fun (name, value) -> putenv name (string_of_variable value))
543         (Whenstate.get_variables state);
544
545       (* Set the $JOBNAME environment variable. *)
546       putenv "JOBNAME" job.job_name;
547
548       (* Create a temporary file containing the shell script fragment. *)
549       let script = dir // "script.sh" in
550       let chan = open_out script in
551       fprintf chan "set -e\n"; (* So that jobs exit on error. *)
552       output_string chan job.job_script.sh_script;
553       close_out chan;
554       chmod script 0o700;
555
556       let shell = try getenv "SHELL" with Not_found -> "/bin/sh" in
557
558       (* Set output to file. *)
559       let output = dir // "output.txt" in
560       let fd = openfile output [O_WRONLY; O_CREAT; O_TRUNC; O_NOCTTY] 0o600 in
561       dup2 fd stdout;
562       dup2 fd stderr;
563       close fd;
564
565       (* Execute the shell script. *)
566       (try execvp shell [| shell; "-c"; script |];
567        with Unix_error (err, fn, _) ->
568          Syslog.error "%s failed: %s: %s" fn script (error_message err)
569       );
570       _exit 1
571     );
572
573     (* Remember this PID, the job and the temporary directory, so we
574      * can clean up when the child exits.
575      *)
576     runningmap := IntMap.add pid (job, dir, serial, time ()) !runningmap;
577     serialmap := BigIntMap.add serial pid !serialmap;
578
579     state
580   )
581   else (
582     Syslog.notice "not running %s (JOBSERIAL=%s) because pre() condition returned false"
583       job.job_name (string_of_big_int serial);
584
585     state
586   )
587
588 and tmpdir () =
589   let chan = open_in "/dev/urandom" in
590   let data = String.create 16 in
591   really_input chan data 0 (String.length data);
592   close_in chan;
593   let data = Digest.to_hex (Digest.string data) in
594   let dir = Filename.temp_dir_name // sprintf "whenjobs%s" data in
595   mkdir dir 0o700;
596   dir
597
598 (* This is called when a job (child process) exits. *)
599 and handle_sigchld _ =
600   try
601     let pid, status = waitpid [WNOHANG] 0 in
602     if pid > 0 then (
603       (* Look up the PID in the running jobs map. *)
604       let job, dir, serial, time = IntMap.find pid !runningmap in
605       runningmap := IntMap.remove pid !runningmap;
606       serialmap := BigIntMap.remove serial !serialmap;
607       post_job job dir serial time status
608     )
609   with Unix_error _ | Not_found -> ()
610
611 and post_job job dir serial time status =
612   (* If there is a post function, run it. *)
613   (match job.job_post with
614   | None -> ()
615   | Some post ->
616     let code =
617       match status with
618       | WEXITED c -> c
619       | WSIGNALED s | WSTOPPED s -> 1 in
620     let result = {
621       res_job_name = job.job_name;
622       res_serial = serial;
623       res_code = code;
624       res_tmpdir = dir;
625       res_output = dir // "output.txt";
626       res_start_time = time
627     } in
628     try post result
629     with
630     | Failure msg ->
631       Syslog.error "job %s post function failed: %s" job.job_name msg
632     | exn ->
633       Syslog.error "job %s post function exception: %s"
634         job.job_name (Printexc.to_string exn)
635   );
636
637   (* This should be safe because the path cannot contain shell metachars. *)
638   let cmd = sprintf "rm -rf '%s'" dir in
639   ignore (Sys.command cmd)
640
641 (* Intelligent comparison of job names. *)
642 and compare_jobnames name1 name2 =
643   try
644     let len1 = String.length name1
645     and len2 = String.length name2 in
646     if len1 > 4 && len2 > 4 &&
647       String.sub name1 0 4 = "job$" && String.sub name2 0 4 = "job$"
648     then (
649       let i1 = int_of_string (String.sub name1 4 (len1-4)) in
650       let i2 = int_of_string (String.sub name2 4 (len2-4)) in
651       compare i1 i2
652     )
653     else raise Not_found
654   with _ ->
655     compare name1 name2
656
657 let main_loop () =
658   Unixqueue.run esys