Debian Codegraph @

stm/asyncTaskQueue.ml

raw symbols SCIP
1 (************************************************************************)
2 (* * The Rocq Prover / The Rocq Development Team *)
3 (* v * Copyright INRIA, CNRS and contributors *)
4 (* <O___,, * (see version control and CREDITS file for authors & dates) *)
5 (* \VV/ **************************************************************)
6 (* // * This file is distributed under the terms of the *)
7 (* * GNU Lesser General Public License Version 2.1 *)
8 (* * (see LICENSE file for the text of the license) *)
9 (************************************************************************)
10
11 open CErrors
12 open Pp
13 open Util
14
15 let stm_pr_err pp = Format.eprintf "%s] @[%a@]\n%!" (Spawned.process_id ()) Pp.pp_with pp
16 let stm_prerr_endline s = if CDebug.(get_flag misc) then begin stm_pr_err (str s) end else ()
17
18 type cancel_switch = bool ref
19 let async_proofs_flags_for_workers = ref []
20
21 module type Task = sig
22
23 type task
24 type competence
25
26 type worker_status = Fresh | Old of competence
27
28 (* Marshallable *)
29 type request
30 type response
31
32 val name : string (* UID of the task kind, for -toploop *)
33 val extra_env : unit -> string array
34
35 (* run by the master, on a thread *)
36 val request_of_task : worker_status -> task -> request option
37 val task_match : worker_status -> task -> bool
38 val use_response : worker_status -> task -> response ->
39 [ `Stay of competence * task list | `End ]
40 val on_marshal_error : string -> task -> unit
41 val on_task_cancellation_or_expiration_or_slave_death : task option -> unit
42 val forward_feedback : Feedback.feedback -> unit
43
44 (* run by the worker *)
45 val perform : request -> response
46
47 (* debugging *)
48 val name_of_task : task -> string
49 val name_of_request : request -> string
50
51 end
52
53 module Make(T : Task) () = struct
54
55 exception Die
56 type response =
57 | Response of T.response * (NewProfile.MiniJson.t list * NewProfile.sums) option
58 | RespFeedback of Feedback.feedback
59 type request = { request : T.request; profiling : bool }
60
61 let slave_respond { request = r; profiling } =
62 if profiling then
63 let events, sums, res =
64 NewProfile.with_profiling (fun () -> T.perform r)
65 in
66 Response (res, Some (events, sums))
67 else
68 let res = T.perform r in
69 Response (res, None)
70
71 exception MarshalError of string
72
73 let marshal_to_channel oc data =
74 Marshal.to_channel oc data [];
75 flush oc
76
77 let marshal_err s = raise (MarshalError s)
78
79 let marshal_request oc (req : request) =
80 try marshal_to_channel oc req
81 with Failure s | Invalid_argument s | Sys_error s ->
82 marshal_err ("marshal_request: "^s)
83
84 let unmarshal_request ic =
85 try (CThread.thread_friendly_input_value ic : request)
86 with Failure s | Invalid_argument s | Sys_error s ->
87 marshal_err ("unmarshal_request: "^s)
88
89 let marshal_response oc (res : response) =
90 try marshal_to_channel oc res
91 with Failure s | Invalid_argument s | Sys_error s ->
92 marshal_err ("marshal_response: "^s)
93
94 let unmarshal_response ic =
95 try (CThread.thread_friendly_input_value ic : response)
96 with Failure s | Invalid_argument s | Sys_error s ->
97 marshal_err ("unmarshal_response: "^s)
98
99 let report_status ?(id = !Flags.async_proofs_worker_id) s =
100 let open Feedback in
101 feedback ~id:Stateid.initial (WorkerStatus(id, s))
102
103 module Worker = Spawn.Sync ()
104
105 module Model = struct
106
107 type process = Worker.process
108 type extra = (T.task * cancel_switch) TQueue.t
109
110 let uid = ref 0
111
112 let get_toplevel_path top =
113 let dir = Findlib.package_directory "rocq-runtime" in
114 let exe = if Sys.(os_type = "Win32" || os_type = "Cygwin") then ".exe" else "" in
115 Filename.concat dir (top^exe)
116
117 let spawn ~spawn_args id priority =
118 let name = Printf.sprintf "%s:%d:%d" T.name id !uid in
119 incr uid;
120 let proc, ic, oc =
121 (* Filter arguments for slaves. *)
122 let args =
123 let wselect = "--kind=" ^ T.name in
124 let worker_opts =
125 !async_proofs_flags_for_workers @
126 ["-worker-id"; name;
127 "-async-proofs-worker-priority";
128 CoqworkmgrApi.(string_of_priority priority)]
129 in
130 Array.of_list (wselect :: spawn_args @ worker_opts) in
131 let env = Array.append (T.extra_env ()) (Unix.environment ()) in
132 let worker_name = get_toplevel_path "rocqworker" in
133 Worker.spawn ~env worker_name args in
134 name, proc, CThread.prepare_in_channel_for_thread_friendly_io ic, oc
135
136 let manager cpanel (id, proc, ic, oc) =
137 let { WorkerPool.extra = queue; exit; cancelled } = cpanel in
138 let exit () = report_status ~id "Dead"; exit () in
139 let last_task = ref None in
140 let worker_age = ref T.Fresh in
141 let got_token = ref false in
142 let giveback_exec_token () =
143 if !got_token then (CoqworkmgrApi.giveback 1; got_token := false) in
144 let stop_waiting = ref false in
145 let expiration_date = ref (ref false) in
146 let pick_task () =
147 stm_prerr_endline "waiting for a task";
148 let pick age (t, c) = not !c && T.task_match age t in
149 let task, task_expiration =
150 TQueue.pop ~picky:(pick !worker_age) ~destroy:stop_waiting queue in
151 expiration_date := task_expiration;
152 last_task := Some task;
153 stm_prerr_endline ("got task: " ^ T.name_of_task task);
154 task in
155 let add_tasks l =
156 List.iter (fun t -> TQueue.push queue (t,!expiration_date)) l in
157 let get_exec_token () =
158 ignore(CoqworkmgrApi.get 1);
159 got_token := true;
160 stm_prerr_endline ("got execution token") in
161 let kill proc =
162 Worker.kill proc;
163 stm_prerr_endline ("Worker exited: " ^
164 match Worker.wait proc with
165 | Unix.WEXITED 0x400 -> "exit code unavailable"
166 | Unix.WEXITED i -> Printf.sprintf "exit(%d)" i
167 | Unix.WSIGNALED sno -> Printf.sprintf "signalled(%d)" sno
168 | Unix.WSTOPPED sno -> Printf.sprintf "stopped(%d)" sno) in
169
170 let rec kill_if () =
171 if not (Worker.is_alive proc) then ()
172 else if cancelled () || !(!expiration_date) then
173 let () = stop_waiting := true in
174 let () = TQueue.broadcast queue in
175 Worker.kill proc
176 else
177 let () = Unix.sleep 1 in
178 kill_if ()
179 in
180 let kill_if () =
181 try kill_if ()
182 with Sys.Break ->
183 let () = stop_waiting := true in
184 let () = TQueue.broadcast queue in
185 Worker.kill proc
186 in
187 let _ = CThread.create kill_if () in
188
189 try while true do
190 report_status ~id "Idle";
191 let task = pick_task () in
192 match T.request_of_task !worker_age task with
193 | None -> stm_prerr_endline ("Task expired: " ^ T.name_of_task task)
194 | Some req ->
195 try
196 get_exec_token ();
197 marshal_request oc {request = req; profiling = NewProfile.is_profiling()};
198 let rec continue () =
199 match unmarshal_response ic with
200 | RespFeedback fbk -> T.forward_feedback fbk; continue ()
201 | Response (resp, prof) ->
202 Option.iter (fun (events,sums) -> NewProfile.insert_results events sums) prof;
203 match T.use_response !worker_age task resp with
204 | `End -> raise Die
205 | `Stay(competence, new_tasks) ->
206 last_task := None;
207 giveback_exec_token ();
208 worker_age := T.Old competence;
209 add_tasks new_tasks
210 in
211 continue ()
212 with
213 | (Sys_error _|Invalid_argument _|End_of_file|Die) as e ->
214 raise e (* we pass the exception to the external handler *)
215 | MarshalError s -> T.on_marshal_error s task; raise Die
216 | e ->
217 stm_pr_err Pp.(seq [str "Uncaught exception in worker manager: "; print e]);
218 flush_all (); raise Die
219 done with
220 | (Die | TQueue.BeingDestroyed) ->
221 giveback_exec_token (); kill proc; exit ()
222 | Sys_error _ | Invalid_argument _ | End_of_file ->
223 T.on_task_cancellation_or_expiration_or_slave_death !last_task;
224 giveback_exec_token (); kill proc; exit ()
225 end
226
227 module Pool = WorkerPool.Make(Model)
228
229 type queue = {
230 active : Pool.pool;
231 queue : (T.task * cancel_switch) TQueue.t;
232 cleaner : Thread.t option;
233 }
234
235 let create ~spawn_args size priority =
236 let cleaner queue =
237 while true do
238 try ignore(TQueue.pop ~picky:(fun (_,cancelled) -> !cancelled) queue)
239 with TQueue.BeingDestroyed -> (Thread.exit [@warning "-3"]) ()
240 done in
241 let queue = TQueue.create () in
242 {
243 active = Pool.create ~spawn_args queue ~size priority;
244 queue;
245 cleaner = if size > 0 then Some (CThread.create cleaner queue) else None;
246 }
247
248 let destroy { active; queue } =
249 Pool.destroy active;
250 TQueue.destroy queue
251
252 let broadcast { queue } = TQueue.broadcast queue
253
254 let enqueue_task { queue; active } t ~cancel_switch =
255 stm_prerr_endline ("Enqueue task "^T.name_of_task t);
256 TQueue.push queue (t, cancel_switch)
257
258 let cancel_worker { active } n = Pool.cancel n active
259
260 let name_of_request {request = r} = T.name_of_request r
261
262 let set_order { queue } cmp =
263 TQueue.set_order queue (fun (t1,_) (t2,_) -> cmp t1 t2)
264
265 let join { queue; active } =
266 if not (Pool.is_empty active) then
267 TQueue.wait_until_n_are_waiting_and_queue_empty
268 (Pool.n_workers active + 1(*cleaner*))
269 queue
270
271 let cancel_all { queue; active } =
272 TQueue.clear queue;
273 Pool.cancel_all active
274
275 let slave_ic = ref None
276 let slave_oc = ref None
277
278 let init_stdout () =
279 let ic, oc = Spawned.get_channels () in
280 slave_oc := Some oc; slave_ic := Some ic
281
282 let slave_handshake () =
283 Pool.worker_handshake (Option.get !slave_ic) (Option.get !slave_oc)
284
285 let pp_pid pp = Pp.(str (Spawned.process_id () ^ " ") ++ pp)
286
287 let debug_with_pid = Feedback.(function
288 | { contents = Message(Debug, loc, qf, pp) } as fb ->
289 { fb with contents = Message(Debug,loc, qf, pp_pid pp) }
290 | x -> x)
291
292 let main_loop () =
293 (* We pass feedback to master *)
294 let slave_feeder oc fb =
295 Control.protect_sigalrm (fun () ->
296 Marshal.to_channel oc (RespFeedback (debug_with_pid fb)) []; flush oc) ()
297 in
298 ignore (Feedback.add_feeder (fun x -> slave_feeder (Option.get !slave_oc) x));
299 let working = ref false in
300 slave_handshake ();
301 while true do
302 try
303 working := false;
304 let request = unmarshal_request (Option.get !slave_ic) in
305 working := true;
306 report_status (name_of_request request);
307 let response = slave_respond request in
308 report_status "Idle";
309 marshal_response (Option.get !slave_oc) response;
310 CEphemeron.clean ()
311 with
312 | MarshalError s ->
313 stm_pr_err Pp.(prlist str ["Fatal marshal error: "; s]); flush_all (); exit 2
314 | End_of_file ->
315 stm_prerr_endline "connection lost"; flush_all (); exit 2
316 | e ->
317 stm_pr_err Pp.(seq [str "Slave: critical exception: "; print e]);
318 flush_all (); exit 1
319 done
320
321 let clear { queue; active } =
322 assert(Pool.is_empty active); (* We allow that only if no slaves *)
323 TQueue.clear queue
324
325 let snapshot { queue; active } =
326 List.map fst
327 (TQueue.wait_until_n_are_waiting_then_snapshot
328 (Pool.n_workers active) queue)
329
330 let with_n_workers ~spawn_args n priority f =
331 let q = create ~spawn_args n priority in
332 try let rc = f q in destroy q; rc
333 with e -> let e = Exninfo.capture e in destroy q; Exninfo.iraise e
334
335 let n_workers { active } = Pool.n_workers active
336
337 end
338
339 module MakeQueue(T : Task) () = struct include Make(T) () end
340 module MakeWorker(T : Task) () = struct include Make(T) () end
341
342 exception RemoteException of Pp.t
343 let _ = CErrors.register_handler (function
344 | RemoteException ppcmd -> Some ppcmd
345 | _ -> None)