Ensure when-stmt jobs always run in predictable (name) order.
[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 Unix
22 open Printf
23
24 (* All jobs that are loaded.  Maps name -> [job] structure. *)
25 let jobs = ref StringMap.empty
26
27 (* Map variable names to jobs which depend on that variable.  This
28  * gives us a quick way to tell which jobs might need to be reevaluated
29  * when a variable is set.
30  *)
31 let dependencies = ref StringMap.empty
32
33 (* Current values of variables.  Using the referentially transparent
34  * type Map is very useful here because it lets us cheaply keep
35  * previous values of variables.
36  *)
37 let variables : variables ref = ref StringMap.empty
38
39 (* Last time that an every job ran.  See schedule_next_everyjob below. *)
40 let last_t = ref (time ())
41
42 (* $HOME/.whenjobs *)
43 let jobsdir = ref ""
44
45 (* Was debugging requested on the command line? *)
46 let debug = ref false
47
48 let esys = Unixqueue.standard_event_system ()
49 let timer_group = ref None
50
51 let rec init j d =
52   jobsdir := j;
53   debug := d;
54
55   Whenlock.create_lock !jobsdir;
56
57   (* Remove old socket if it exists. *)
58   let addr = sprintf "%s/socket" !jobsdir in
59   (try unlink addr with Unix_error _ -> ());
60
61   ignore (
62     Whenproto_srv.When.V1.create_server
63       ~proc_reload_file
64       ~proc_set_variable
65       ~proc_get_variable
66       ~proc_get_variable_names
67       (Rpc_server.Unix addr)
68       Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *)
69       Rpc.Socket
70       esys
71   )
72
73 and proc_reload_file () =
74   if !debug then Syslog.notice "remote call: reload_file";
75
76   try reload_file (); `ok
77   with Failure err -> `error err
78
79 and proc_set_variable (name, value) =
80   if !debug then Syslog.notice "remote call: set_variable %s" name;
81
82   let value = variable_of_rpc value in
83   variables := StringMap.add name value !variables;
84
85   (* Which jobs need to be re-evaluated? *)
86   let jobnames = try StringMap.find name !dependencies with Not_found -> [] in
87   reevaluate_whenjobs jobnames
88
89 and proc_get_variable name =
90   if !debug then Syslog.notice "remote call: get_variable %s" name;
91
92   try rpc_of_variable (StringMap.find name !variables)
93   with (* all non-existent variables are empty strings *)
94     Not_found -> `string_t ""
95
96 and proc_get_variable_names () =
97   if !debug then Syslog.notice "remote call: get_variable_names";
98
99   (* Only return variables that are non-empty. *)
100   let vars = StringMap.fold (
101     fun name value xs -> if value <> T_string "" then name :: xs else xs
102   ) !variables [] in
103   let vars = Array.of_list vars in
104   Array.sort compare vars;
105   vars
106
107 (* Reload the jobs file. *)
108 and reload_file () =
109   let file = sprintf "%s/jobs.cmo" !jobsdir in
110   Whenfile.init ();
111
112   let js =
113     try
114       Dynlink.loadfile file;
115       let jobs = Whenfile.get_jobs () in
116       Syslog.notice "loaded %d job(s) from %s" (List.length jobs) file;
117       jobs
118     with
119     | Dynlink.Error err ->
120       let err = Dynlink.error_message err in
121       Syslog.error "error loading jobs: %s" err;
122       failwith err
123     | exn ->
124       failwith (Printexc.to_string exn) in
125
126   (* Set 'jobs' and related global variables. *)
127   let () =
128     let map = List.fold_left (
129       fun map j ->
130         let name = j.job_name in
131         StringMap.add name j map
132     ) StringMap.empty js in
133     jobs := map in
134
135   let () =
136     let map = List.fold_left (
137       fun map j ->
138         let deps = dependencies_of_job j in
139         let name = j.job_name in
140         List.fold_left (
141           fun map d ->
142             let names = try StringMap.find d map with Not_found -> [] in
143             StringMap.add d (name :: names) map
144         ) map deps
145     ) StringMap.empty js in
146     dependencies := map in
147
148   (* Re-evaluate all when jobs. *)
149   reevaluate_whenjobs (StringMap.keys !jobs);
150
151   (* Schedule the next every job to run. *)
152   last_t := time ();
153   schedule_next_everyjob ()
154
155 (* Re-evaluate each named when-statement job, in a loop until we reach
156  * a fixpoint.  Run those that need to be run.  every-statement jobs
157  * are ignored here.
158  *)
159 and reevaluate_whenjobs jobnames =
160   let rec loop set jobnames =
161     let set' =
162       List.fold_left (
163         fun set jobname ->
164           let job =
165             try StringMap.find jobname !jobs
166             with Not_found -> assert false in
167           assert (jobname = job.job_name);
168
169           let r, job' = job_evaluate job !variables in
170           jobs := StringMap.add jobname job' !jobs;
171
172           if !debug then
173             Syslog.notice "evaluate %s -> %b\n" jobname r;
174
175           if r then StringSet.add jobname set else set
176       ) set jobnames in
177     if StringSet.compare set set' <> 0 then
178       loop set' jobnames
179     else
180       set'
181   in
182   let set = loop StringSet.empty jobnames in
183   let jobnames = StringSet.elements set in
184   (* Ensure the jobs always run in predictable (name) order. *)
185   let jobnames = List.sort compare jobnames in
186   List.iter run_job
187     (List.map (fun jobname -> StringMap.find jobname !jobs) jobnames)
188
189 (* Schedule the next every-statement job to run, if there is one.  We
190  * look at the every jobs, work out the time that each must run at,
191  * pick the job(s) which must run soonest, and schedule a timer to run
192  * them.  When the timer fires, it runs those jobs, then call this
193  * function again.  'last_t' is the base time used for scheduling (or
194  * the time that the file was last reloaded).
195  *)
196 and schedule_next_everyjob () =
197   (* Get only everyjobs. *)
198   let jobs = StringMap.values !jobs in
199   let jobs = filter_map (
200     function
201     | { job_cond = Every_job period } as job -> Some (job, period)
202     | { job_cond = When_job _ } -> None
203   ) jobs in
204
205   (* Map everyjob to next time it must run. *)
206   let jobs = List.map (
207     fun (job, period) ->
208       let t' = next_periodexpr !last_t period in
209       assert (t' > !last_t); (* serious bug in next_periodexpr if false *)
210       job, t'
211   ) jobs in
212
213   (* Sort, soonest first. *)
214   let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in
215
216   if !debug then (
217     List.iter (
218       fun (job, t) ->
219         Syslog.notice "%s: next scheduled run at %s"
220           job.job_name (string_of_time_t t)
221     ) jobs
222   );
223
224   (* Pick the job(s) which run soonest. *)
225   let rec pick = function
226     | [] -> 0., []
227     | [j, t] -> t, [j]
228     | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1]
229     | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest))
230   in
231   let t, jobs = pick jobs in
232
233   if t > 0. then (
234     last_t := t;
235
236     if jobs <> [] then (
237       if !debug then
238         Syslog.notice "scheduling job(s) %s to run at %s"
239           (String.concat ", " (List.map (fun { job_name = name } -> name) jobs))
240           (string_of_time_t t);
241
242       (* Schedule them to run at time t. *)
243       let g = new_timer_group () in
244       let w = Unixqueue.new_wait_id esys in
245       let t_diff = t -. Unix.time () in
246       let t_diff = if t_diff < 0. then 0. else t_diff in
247       Unixqueue.add_resource esys g (Unixqueue.Wait w, t_diff);
248       let run_jobs _ _ _ =
249         List.iter run_job jobs;
250         delete_timer ();
251         schedule_next_everyjob ();
252       in
253       Unixqueue.add_handler esys g run_jobs;
254     )
255   )
256
257 and string_of_time_t t =
258   let tm = gmtime t in
259   sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC"
260     (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday
261     tm.tm_hour tm.tm_min tm.tm_sec
262
263 and new_timer_group () =
264   delete_timer ();
265   let g = Unixqueue.new_group esys in
266   timer_group := Some g;
267   g
268
269 and delete_timer () =
270   match !timer_group with
271   | None -> ()
272   | Some g ->
273     Unixqueue.clear esys g;
274     timer_group := None
275
276 and run_job job =
277   Syslog.notice "running %s" job.job_name;
278   () (* XXX *)
279
280 let main_loop () =
281   Unixqueue.run esys