src/Pure/System/isabelle_process.ML
author wenzelm
Sun Sep 19 22:40:22 2010 +0200 (2010-09-19 ago)
changeset 39528 c01d89d18ff0
parent 39513 fce2202892c4
child 39530 16adc476348f
permissions -rw-r--r--
refined Isabelle_Process startup: emit \002 before rendezvous on fifos, more robust treatment of startup failure with timeout, do not quit() after main loop;
tuned;
     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.
     6 
     7 Startup phases:
     8   . raw Posix process startup with uncontrolled output on stdout/stderr
     9   . stdout \002: ML running
    10   .. stdin/stdout/stderr freely available (raw ML loop)
    11   .. protocol thread initialization
    12   ... switch to in_fifo/out_fifo channels (rendezvous via open)
    13   ... out_fifo INIT(pid): channels ready
    14   ... out_fifo STATUS(keywords)
    15   ... out_fifo READY: main loop ready
    16 *)
    17 
    18 signature ISABELLE_PROCESS =
    19 sig
    20   val isabelle_processN: string
    21   val add_command: string -> (string list -> unit) -> unit
    22   val command: string -> string list -> unit
    23   val crashes: exn list Unsynchronized.ref
    24   val init: string -> string -> unit
    25 end;
    26 
    27 structure Isabelle_Process: ISABELLE_PROCESS =
    28 struct
    29 
    30 (* print modes *)
    31 
    32 val isabelle_processN = "isabelle_process";
    33 
    34 val _ = Output.add_mode isabelle_processN Output.default_output Output.default_escape;
    35 val _ = Markup.add_mode isabelle_processN YXML.output_markup;
    36 
    37 
    38 (* commands *)
    39 
    40 local
    41 
    42 val global_commands = Unsynchronized.ref (Symtab.empty: (string list -> unit) Symtab.table);
    43 
    44 in
    45 
    46 fun add_command name cmd = CRITICAL (fn () =>
    47   Unsynchronized.change global_commands (fn cmds =>
    48    (if not (Symtab.defined cmds name) then ()
    49     else warning ("Redefining Isabelle process command " ^ quote name);
    50     Symtab.update (name, cmd) cmds)));
    51 
    52 fun command name args =
    53   (case Symtab.lookup (! global_commands) name of
    54     NONE => error ("Undefined Isabelle process command " ^ quote name)
    55   | SOME cmd => cmd args);
    56 
    57 end;
    58 
    59 
    60 (* message markup *)
    61 
    62 local
    63 
    64 fun chunk s = string_of_int (size s) ^ "\n" ^ s;
    65 
    66 fun message _ _ _ "" = ()
    67   | message out_stream ch raw_props body =
    68       let
    69         val robust_props = map (pairself YXML.escape_controls) raw_props;
    70         val header = YXML.string_of (XML.Elem ((ch, robust_props), []));
    71       in TextIO.output (out_stream, chunk header ^ chunk body) (*atomic output!*) end;
    72 
    73 in
    74 
    75 fun standard_message out_stream with_serial ch body =
    76   message out_stream ch
    77     ((if with_serial then cons (Markup.serialN, serial_string ()) else I)
    78       (Position.properties_of (Position.thread_data ()))) body;
    79 
    80 fun init_message out_stream =
    81   message out_stream "A" [(Markup.pidN, process_id ())] (Session.welcome ());
    82 
    83 end;
    84 
    85 
    86 (* channels *)
    87 
    88 local
    89 
    90 fun auto_flush stream =
    91   let
    92     val _ = TextIO.StreamIO.setBufferMode (TextIO.getOutstream stream, IO.BLOCK_BUF);
    93     fun loop () =
    94       (OS.Process.sleep (Time.fromMilliseconds 20); try TextIO.flushOut stream; loop ());
    95   in loop end;
    96 
    97 fun rendezvous f fifo =
    98   let
    99     val path = File.platform_path (Path.explode fifo);
   100     val result = f fifo;  (*should block until peer is ready*)
   101     val _ =
   102       if String.isSuffix "cygwin" ml_platform then ()  (*Cygwin 1.7: no proper blocking on open*)
   103       else OS.FileSys.remove path;  (*prevent future access*)
   104   in result end;
   105 
   106 in
   107 
   108 fun setup_channels in_fifo out_fifo =
   109   let
   110     val in_stream = rendezvous TextIO.openIn in_fifo;
   111     val out_stream = rendezvous TextIO.openOut out_fifo;
   112     val _ = Simple_Thread.fork false (auto_flush out_stream);
   113     val _ = Simple_Thread.fork false (auto_flush TextIO.stdOut);
   114     val _ = Simple_Thread.fork false (auto_flush TextIO.stdErr);
   115   in
   116     Output.status_fn   := standard_message out_stream false "B";
   117     Output.report_fn   := standard_message out_stream false "C";
   118     Output.writeln_fn  := standard_message out_stream true "D";
   119     Output.tracing_fn  := standard_message out_stream true "E";
   120     Output.warning_fn  := standard_message out_stream true "F";
   121     Output.error_fn    := standard_message out_stream true "G";
   122     Output.priority_fn := ! Output.writeln_fn;
   123     Output.prompt_fn   := ignore;
   124     (in_stream, out_stream)
   125   end;
   126 
   127 end;
   128 
   129 
   130 (* protocol loop -- uninterruptible *)
   131 
   132 val crashes = Unsynchronized.ref ([]: exn list);
   133 
   134 local
   135 
   136 fun recover crash =
   137   (CRITICAL (fn () => Unsynchronized.change crashes (cons crash));
   138     warning "Recovering from Isabelle process crash -- see also Isabelle_Process.crashes");
   139 
   140 fun read_chunk stream len =
   141   let
   142     val n =
   143       (case Int.fromString len of
   144         SOME n => n
   145       | NONE => error ("Isabelle process: malformed chunk header " ^ quote len));
   146     val chunk = TextIO.inputN (stream, n);
   147     val m = size chunk;
   148   in
   149     if m = n then chunk
   150     else error ("Isabelle process: bad chunk (" ^ string_of_int m ^ " vs. " ^ string_of_int n ^ ")")
   151   end;
   152 
   153 fun read_command stream =
   154   (case TextIO.inputLine stream of
   155     NONE => raise Runtime.TERMINATE
   156   | SOME line => map (read_chunk stream) (space_explode "," line));
   157 
   158 fun run_command name args =
   159   Runtime.debugging (command name) args
   160     handle exn =>
   161       error ("Isabelle process command failure: " ^ name ^ "\n" ^ ML_Compiler.exn_message exn);
   162 
   163 in
   164 
   165 fun loop stream =
   166   let val continue =
   167     (case read_command stream of
   168       [] => (Output.error_msg "Isabelle process: no input"; true)
   169     | name :: args => (run_command name args; true))
   170     handle Runtime.TERMINATE => false
   171       | exn => (Output.error_msg (ML_Compiler.exn_message exn) handle crash => recover crash; true);
   172   in if continue then loop stream else () end;
   173 
   174 end;
   175 
   176 
   177 (* init *)
   178 
   179 fun init in_fifo out_fifo = ignore (Simple_Thread.fork false (fn () =>
   180   let
   181     val _ = OS.Process.sleep (Time.fromMilliseconds 500);  (*yield to raw ML toplevel*)
   182     val _ = Output.std_output Symbol.STX;
   183 
   184     val _ = quick_and_dirty := true;  (* FIXME !? *)
   185     val _ = Context.set_thread_data NONE;
   186     val _ = Unsynchronized.change print_mode
   187       (fold (update op =) [isabelle_processN, Keyword.keyword_statusN, Pretty.symbolicN]);
   188 
   189     val (in_stream, out_stream) = setup_channels in_fifo out_fifo;
   190     val _ = init_message out_stream;
   191     val _ = Keyword.status ();
   192     val _ = Output.status (Markup.markup Markup.ready "");
   193   in loop in_stream end));
   194 
   195 end;
   196