(* whenjobs * Copyright (C) 2012 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) open Whenutils open Unix open Printf (* All jobs that are loaded. Maps name -> [job] structure. *) let jobs = ref StringMap.empty (* Map variable names to jobs which depend on that variable. This * gives us a quick way to tell which jobs might need to be reevaluated * when a variable is set. *) let dependencies = ref StringMap.empty (* Current values of variables. Using the referentially transparent * type Map is very useful here because it lets us cheaply keep * previous values of variables. *) let variables : variables ref = ref StringMap.empty (* Last time that an every job ran. See schedule_next_everyjob below. *) let last_t = ref (time ()) (* $HOME/.whenjobs *) let jobsdir = ref "" (* Was debugging requested on the command line? *) let debug = ref false let esys = Unixqueue.standard_event_system () let timer_group = ref None let rec init j d = jobsdir := j; debug := d; Whenlock.create_lock !jobsdir; (* Remove old socket if it exists. *) let addr = sprintf "%s/socket" !jobsdir in (try unlink addr with Unix_error _ -> ()); ignore ( Whenproto_srv.When.V1.create_server ~proc_reload_file ~proc_set_variable ~proc_get_variable ~proc_get_variable_names (Rpc_server.Unix addr) Rpc.Tcp (* not TCP, this is the same as SOCK_STREAM *) Rpc.Socket esys ) and proc_reload_file () = if !debug then Syslog.notice "remote call: reload_file"; try reload_file (); `ok with Failure err -> `error err and proc_set_variable (name, value) = if !debug then Syslog.notice "remote call: set_variable %s" name; let value = variable_of_rpc value in variables := StringMap.add name value !variables; (* Which jobs need to be re-evaluated? *) let jobnames = try StringMap.find name !dependencies with Not_found -> [] in reevaluate_whenjobs jobnames and proc_get_variable name = if !debug then Syslog.notice "remote call: get_variable %s" name; try rpc_of_variable (StringMap.find name !variables) with (* all non-existent variables are empty strings *) Not_found -> `string_t "" and proc_get_variable_names () = if !debug then Syslog.notice "remote call: get_variable_names"; (* Only return variables that are non-empty. *) let vars = StringMap.fold ( fun name value xs -> if value <> T_string "" then name :: xs else xs ) !variables [] in let vars = Array.of_list vars in Array.sort compare vars; vars (* Reload the jobs file. *) and reload_file () = let file = sprintf "%s/jobs.cmo" !jobsdir in Whenfile.init (); let js = try Dynlink.loadfile file; let jobs = Whenfile.get_jobs () in Syslog.notice "loaded %d job(s) from %s" (List.length jobs) file; jobs with | Dynlink.Error err -> let err = Dynlink.error_message err in Syslog.error "error loading jobs: %s" err; failwith err | exn -> failwith (Printexc.to_string exn) in (* Set 'jobs' and related global variables. *) let () = let map = List.fold_left ( fun map j -> let name = j.job_name in StringMap.add name j map ) StringMap.empty js in jobs := map in let () = let map = List.fold_left ( fun map j -> let deps = dependencies_of_job j in let name = j.job_name in List.fold_left ( fun map d -> let names = try StringMap.find d map with Not_found -> [] in StringMap.add d (name :: names) map ) map deps ) StringMap.empty js in dependencies := map in (* Re-evaluate all when jobs. *) reevaluate_whenjobs (StringMap.keys !jobs); (* Schedule the next every job to run. *) last_t := time (); schedule_next_everyjob () (* Re-evaluate each named when-statement job, in a loop until we reach * a fixpoint. Run those that need to be run. every-statement jobs * are ignored here. *) and reevaluate_whenjobs jobnames = let rec loop set jobnames = let set' = List.fold_left ( fun set jobname -> let job = try StringMap.find jobname !jobs with Not_found -> assert false in assert (jobname = job.job_name); let r, job' = try job_evaluate job !variables with Invalid_argument err | Failure err -> Syslog.error "error evaluating job %s (at %s): %s" jobname (Camlp4.PreCast.Ast.Loc.to_string job.job_loc) err; false, job in jobs := StringMap.add jobname job' !jobs; if !debug then Syslog.notice "evaluate %s -> %b\n" jobname r; if r then StringSet.add jobname set else set ) set jobnames in if StringSet.compare set set' <> 0 then loop set' jobnames else set' in let set = loop StringSet.empty jobnames in let jobnames = StringSet.elements set in (* Ensure the jobs always run in predictable (name) order. *) let jobnames = List.sort compare jobnames in List.iter run_job (List.map (fun jobname -> StringMap.find jobname !jobs) jobnames) (* Schedule the next every-statement job to run, if there is one. We * look at the every jobs, work out the time that each must run at, * pick the job(s) which must run soonest, and schedule a timer to run * them. When the timer fires, it runs those jobs, then call this * function again. 'last_t' is the base time used for scheduling (or * the time that the file was last reloaded). *) and schedule_next_everyjob () = (* Get only everyjobs. *) let jobs = StringMap.values !jobs in let jobs = filter_map ( function | { job_cond = Every_job period } as job -> Some (job, period) | { job_cond = When_job _ } -> None ) jobs in (* Map everyjob to next time it must run. *) let jobs = List.map ( fun (job, period) -> let t' = next_periodexpr !last_t period in assert (t' > !last_t); (* serious bug in next_periodexpr if false *) job, t' ) jobs in (* Sort, soonest first. *) let jobs = List.sort (fun (_,a) (_,b) -> compare a b) jobs in if !debug then ( List.iter ( fun (job, t) -> Syslog.notice "%s: next scheduled run at %s" job.job_name (string_of_time_t t) ) jobs ); (* Pick the job(s) which run soonest. *) let rec pick = function | [] -> 0., [] | [j, t] -> t, [j] | (j1, t) :: (j2, t') :: _ when t < t' -> t, [j1] | (j1, t) :: (((j2, t') :: _) as rest) -> t, (j1 :: snd (pick rest)) in let t, jobs = pick jobs in if t > 0. then ( last_t := t; if jobs <> [] then ( if !debug then Syslog.notice "scheduling job(s) %s to run at %s" (String.concat ", " (List.map (fun { job_name = name } -> name) jobs)) (string_of_time_t t); (* Schedule them to run at time t. *) let g = new_timer_group () in let w = Unixqueue.new_wait_id esys in let t_diff = t -. Unix.time () in let t_diff = if t_diff < 0. then 0. else t_diff in Unixqueue.add_resource esys g (Unixqueue.Wait w, t_diff); let run_jobs _ _ _ = List.iter run_job jobs; delete_timer (); schedule_next_everyjob (); in Unixqueue.add_handler esys g run_jobs; ) ) and string_of_time_t t = let tm = gmtime t in sprintf "%04d-%02d-%02d %02d:%02d:%02d UTC" (1900+tm.tm_year) (1+tm.tm_mon) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec and new_timer_group () = delete_timer (); let g = Unixqueue.new_group esys in timer_group := Some g; g and delete_timer () = match !timer_group with | None -> () | Some g -> Unixqueue.clear esys g; timer_group := None and run_job job = Syslog.notice "running %s" job.job_name; () (* XXX *) let main_loop () = Unixqueue.run esys