src/Pure/System/isabelle_process.ML
author wenzelm
Wed, 10 Jul 2013 22:56:48 +0200
changeset 53720 0a7240d88e09
parent 53719 31467a4b1466
child 53721 5cad4a5f5615
permissions -rw-r--r--
explicit shutdown of message output thread;
     1 (*  Title:      Pure/System/isabelle_process.ML
     2     Author:     Makarius
     3 
     4 Isabelle process wrapper, based on private fifos for maximum
     5 robustness and performance, or local socket for maximum portability.
     6 
     7 Startup phases:
     8   - raw Posix process startup with uncontrolled output on stdout/stderr
     9   - stderr \002: ML running
    10   - stdin/stdout/stderr freely available (raw ML loop)
    11   - protocol thread initialization
    12   - rendezvous on system channel
    13   - message INIT: channels ready
    14 *)
    15 
    16 signature ISABELLE_PROCESS =
    17 sig
    18   val is_active: unit -> bool
    19   val protocol_command: string -> (string list -> unit) -> unit
    20   val reset_tracing: unit -> unit
    21   val crashes: exn list Synchronized.var
    22   val init_fifos: string -> string -> unit
    23   val init_socket: string -> unit
    24 end;
    25 
    26 structure Isabelle_Process: ISABELLE_PROCESS =
    27 struct
    28 
    29 (* print mode *)
    30 
    31 val isabelle_processN = "isabelle_process";
    32 
    33 fun is_active () = Print_Mode.print_mode_active isabelle_processN;
    34 
    35 val _ = Output.add_mode isabelle_processN Output.default_output Output.default_escape;
    36 val _ = Markup.add_mode isabelle_processN YXML.output_markup;
    37 
    38 
    39 (* protocol commands *)
    40 
    41 local
    42 
    43 val commands =
    44   Synchronized.var "Isabelle_Process.commands" (Symtab.empty: (string list -> unit) Symtab.table);
    45 
    46 in
    47 
    48 fun protocol_command name cmd =
    49   Synchronized.change commands (fn cmds =>
    50    (if not (Symtab.defined cmds name) then ()
    51     else warning ("Redefining Isabelle protocol command " ^ quote name);
    52     Symtab.update (name, cmd) cmds));
    53 
    54 fun run_command name args =
    55   (case Symtab.lookup (Synchronized.value commands) name of
    56     NONE => error ("Undefined Isabelle protocol command " ^ quote name)
    57   | SOME cmd =>
    58       (Runtime.debugging cmd args handle exn =>
    59         error ("Isabelle protocol command failure: " ^ quote name ^ "\n" ^
    60           ML_Compiler.exn_message exn)));
    61 
    62 end;
    63 
    64 
    65 (* restricted tracing messages *)
    66 
    67 val tracing_messages =
    68   Synchronized.var "tracing_messages" (Inttab.empty: int Inttab.table);
    69 
    70 fun reset_tracing () =
    71   Synchronized.change tracing_messages (K Inttab.empty);
    72 
    73 fun update_tracing () =
    74   (case Position.parse_id (Position.thread_data ()) of
    75     NONE => ()
    76   | SOME id =>
    77       let
    78         val ok =
    79           Synchronized.change_result tracing_messages (fn tab =>
    80             let
    81               val n = the_default 0 (Inttab.lookup tab id) + 1;
    82               val ok = n <= Options.default_int "editor_tracing_messages";
    83             in (ok, Inttab.update (id, n) tab) end);
    84       in
    85         if ok then ()
    86         else
    87           let
    88             val (text, promise) = Active.dialog_text ();
    89             val _ =
    90               writeln ("Tracing paused.  " ^ text "Stop" ^ ", or continue with next " ^
    91                 text "100" ^ ", " ^ text "1000" ^ ", " ^ text "10000" ^ " messages?")
    92             val m = Markup.parse_int (Future.join promise)
    93               handle Fail _ => error "Stopped";
    94           in
    95             Synchronized.change tracing_messages
    96               (Inttab.map_default (id, 0) (fn k => k - m))
    97           end
    98       end);
    99 
   100 
   101 (* message channels *)
   102 
   103 local
   104 
   105 fun chunk s = [string_of_int (size s), "\n", s];
   106 fun flush channel = ignore (try System_Channel.flush channel);
   107 
   108 datatype target =
   109   Sync of {send: string list -> unit} |
   110   Async of {send: string list -> bool -> unit, shutdown: unit -> unit};
   111 
   112 fun message do_flush target name raw_props body =
   113   let
   114     val robust_props = map (pairself YXML.embed_controls) raw_props;
   115     val header = YXML.string_of (XML.Elem ((name, robust_props), []));
   116     val msg = chunk header @ chunk body;
   117   in (case target of Sync {send} => send msg | Async {send, ...} => send msg do_flush) end;
   118 
   119 fun message_output mbox channel =
   120   let
   121     fun loop receive =
   122       (case receive mbox of
   123         SOME NONE => flush channel
   124       | SOME (SOME (msg, do_flush)) =>
   125          (List.app (fn s => System_Channel.output channel s) msg;
   126           if do_flush then flush channel else ();
   127           loop (Mailbox.receive_timeout (seconds 0.02)))
   128       | NONE => (flush channel; loop (SOME o Mailbox.receive)));
   129   in fn () => loop (SOME o Mailbox.receive) end;
   130 
   131 fun make_target channel =
   132   if Multithreading.available then
   133     let
   134       val mbox = Mailbox.create ();
   135       val thread = Simple_Thread.fork false (message_output mbox channel);
   136     in
   137       Async {
   138         send = fn msg => fn do_flush => Mailbox.send mbox (SOME (msg, do_flush)),
   139         shutdown = fn () =>
   140           (Mailbox.send mbox NONE; Mailbox.await_empty mbox; Simple_Thread.join thread)
   141       }
   142     end
   143   else
   144     Sync {send = fn msg => (List.app (fn s => System_Channel.output channel s) msg; flush channel)};
   145 
   146 in
   147 
   148 fun init_channels channel =
   149   let
   150     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdOut, IO.LINE_BUF);
   151     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream TextIO.stdErr, IO.LINE_BUF);
   152 
   153     val target = make_target channel;
   154 
   155     fun standard_message opt_serial name body =
   156       if body = "" then ()
   157       else
   158         message false target name
   159           ((case opt_serial of SOME i => cons (Markup.serialN, Markup.print_int i) | _ => I)
   160             (Position.properties_of (Position.thread_data ()))) body;
   161   in
   162     Output.Private_Hooks.status_fn := standard_message NONE Markup.statusN;
   163     Output.Private_Hooks.report_fn := standard_message NONE Markup.reportN;
   164     Output.Private_Hooks.result_fn := (fn (i, s) => standard_message (SOME i) Markup.resultN s);
   165     Output.Private_Hooks.writeln_fn :=
   166       (fn s => standard_message (SOME (serial ())) Markup.writelnN s);
   167     Output.Private_Hooks.tracing_fn :=
   168       (fn s => (update_tracing (); standard_message (SOME (serial ())) Markup.tracingN s));
   169     Output.Private_Hooks.warning_fn :=
   170       (fn s => standard_message (SOME (serial ())) Markup.warningN s);
   171     Output.Private_Hooks.error_fn :=
   172       (fn (i, s) => standard_message (SOME i) Markup.errorN s);
   173     Output.Private_Hooks.protocol_message_fn := message true target Markup.protocolN;
   174     Output.Private_Hooks.urgent_message_fn := ! Output.Private_Hooks.writeln_fn;
   175     Output.Private_Hooks.prompt_fn := ignore;
   176     message true target Markup.initN [] (Session.welcome ());
   177     (case target of Async {shutdown, ...} => shutdown | _ => fn () => ())
   178   end;
   179 
   180 end;
   181 
   182 
   183 (* protocol loop -- uninterruptible *)
   184 
   185 val crashes = Synchronized.var "Isabelle_Process.crashes" ([]: exn list);
   186 
   187 local
   188 
   189 fun recover crash =
   190   (Synchronized.change crashes (cons crash);
   191     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   192 
   193 fun read_chunk channel len =
   194   let
   195     val n =
   196       (case Int.fromString len of
   197         SOME n => n
   198       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   199     val chunk = System_Channel.inputN channel n;
   200     val m = size chunk;
   201   in
   202     if m = n then chunk
   203     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   204   end;
   205 
   206 fun read_command channel =
   207   (case System_Channel.input_line channel of
   208     NONE => raise Runtime.TERMINATE
   209   | SOME line => map (read_chunk channel) (space_explode "," line));
   210 
   211 fun worker_guest e =
   212   Future.worker_guest "Isabelle_Process.loop" (Future.new_group NONE) e ();
   213 
   214 in
   215 
   216 fun loop channel =
   217   let val continue =
   218     (case read_command channel of
   219       [] => (Output.error_msg "Isabelle process: no input"; true)
   220     | name :: args => (worker_guest (fn () => run_command name args); true))
   221     handle Runtime.TERMINATE => false
   222       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   223   in if continue then loop channel else () end;
   224 
   225 end;
   226 
   227 
   228 (* init *)
   229 
   230 val default_modes1 =
   231   [Syntax_Trans.no_bracketsN, Syntax_Trans.no_type_bracketsN, Graph_Display.active_graphN];
   232 val default_modes2 = [Symbol.xsymbolsN, isabelle_processN, Pretty.symbolicN];
   233 
   234 val init = uninterruptible (fn _ => fn rendezvous =>
   235   let
   236     val _ = Output.physical_stderr Symbol.STX;
   237 
   238     val _ = Printer.show_markup_default := true;
   239     val _ = Context.set_thread_data NONE;
   240     val _ =
   241       Unsynchronized.change print_mode
   242         (fn mode => (mode @ default_modes1) |> fold (update op =) default_modes2);
   243 
   244     val channel = rendezvous ();
   245     val shutdown_channels = init_channels channel;
   246     val _ = Session.init_protocol_handlers ();
   247     val _ = loop channel;
   248   in shutdown_channels () end);
   249 
   250 fun init_fifos fifo1 fifo2 = init (fn () => System_Channel.fifo_rendezvous fifo1 fifo2);
   251 fun init_socket name = init (fn () => System_Channel.socket_rendezvous name);
   252 
   253 
   254 (* options *)
   255 
   256 val _ =
   257   protocol_command "Isabelle_Process.options"
   258     (fn [options_yxml] =>
   259       let val options = Options.decode (YXML.parse_body options_yxml) in
   260         Options.set_default options;
   261         Future.ML_statistics := true;
   262         Multithreading.trace := Options.int options "threads_trace";
   263         Multithreading.max_threads := Options.int options "threads";
   264         Goal.skip_proofs := Options.bool options "editor_skip_proofs";
   265         Goal.parallel_proofs := (if Options.int options "parallel_proofs" > 0 then 3 else 0)
   266       end);
   267 
   268 end;
   269