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