src/Pure/System/isabelle_process.scala
author wenzelm
Mon Sep 20 11:38:14 2010 +0200 (2010-09-20 ago)
changeset 39530 16adc476348f
parent 39528 c01d89d18ff0
child 39572 bb3469024b6a
permissions -rw-r--r--
Isabelle_Process: more robust rendezvous, even without proper blocking on open (Cygwin);
     1 /*  Title:      Pure/System/isabelle_process.ML
     2     Author:     Makarius
     3     Options:    :folding=explicit:collapseFolds=1:
     4 
     5 Isabelle process management -- always reactive due to multi-threaded I/O.
     6 */
     7 
     8 package isabelle
     9 
    10 import java.util.concurrent.LinkedBlockingQueue
    11 import java.io.{BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter,
    12   InputStream, OutputStream, BufferedOutputStream, IOException}
    13 
    14 import scala.actors.Actor
    15 import Actor._
    16 
    17 
    18 object Isabelle_Process
    19 {
    20   /* results */
    21 
    22   object Kind
    23   {
    24     val message_markup = Map(
    25       ('A' : Int) -> Markup.INIT,
    26       ('B' : Int) -> Markup.STATUS,
    27       ('C' : Int) -> Markup.REPORT,
    28       ('D' : Int) -> Markup.WRITELN,
    29       ('E' : Int) -> Markup.TRACING,
    30       ('F' : Int) -> Markup.WARNING,
    31       ('G' : Int) -> Markup.ERROR)
    32   }
    33 
    34   class Result(val message: XML.Elem)
    35   {
    36     def kind = message.markup.name
    37     def properties = message.markup.properties
    38     def body = message.body
    39 
    40     def is_init = kind == Markup.INIT
    41     def is_exit = kind == Markup.EXIT
    42     def is_stdout = kind == Markup.STDOUT
    43     def is_system = kind == Markup.SYSTEM
    44     def is_status = kind == Markup.STATUS
    45     def is_report = kind == Markup.REPORT
    46     def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
    47 
    48     override def toString: String =
    49     {
    50       val res =
    51         if (is_status || is_report) message.body.map(_.toString).mkString
    52         else Pretty.string_of(message.body)
    53       if (properties.isEmpty)
    54         kind.toString + " [[" + res + "]]"
    55       else
    56         kind.toString + " " +
    57           (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
    58     }
    59   }
    60 }
    61 
    62 
    63 class Isabelle_Process(system: Isabelle_System, timeout: Int, receiver: Actor, args: String*)
    64 {
    65   import Isabelle_Process._
    66 
    67 
    68   /* demo constructor */
    69 
    70   def this(args: String*) =
    71     this(new Isabelle_System, 10000,
    72       actor { loop { react { case res => Console.println(res) } } }, args: _*)
    73 
    74 
    75   /* input actors */
    76 
    77   private case class Input_Text(text: String)
    78   private case class Input_Chunks(chunks: List[Array[Byte]])
    79 
    80   private case object Close
    81   private def close(a: Actor) { if (a != null) a ! Close }
    82 
    83   @volatile private var standard_input: Actor = null
    84   @volatile private var command_input: Actor = null
    85 
    86 
    87   /* process manager */
    88 
    89   private val in_fifo = system.mk_fifo()
    90   private val out_fifo = system.mk_fifo()
    91   private def rm_fifos() { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
    92 
    93   private val proc =
    94     try {
    95       val cmdline =
    96         List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
    97       system.execute(true, cmdline: _*)
    98     }
    99     catch { case e: IOException => rm_fifos(); throw(e) }
   100 
   101   private val stdout_reader =
   102     new BufferedReader(new InputStreamReader(proc.getInputStream, Standard_System.charset))
   103 
   104   private val stdin_writer =
   105     new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, Standard_System.charset))
   106 
   107   Simple_Thread.actor("process_manager") {
   108     val (startup_failed, startup_output) =
   109     {
   110       val expired = System.currentTimeMillis() + timeout
   111       val result = new StringBuilder(100)
   112 
   113       var finished = false
   114       while (!finished && System.currentTimeMillis() <= expired) {
   115         while (!finished && stdout_reader.ready) {
   116           val c = stdout_reader.read
   117           if (c == 2) finished = true
   118           else result += c.toChar
   119         }
   120         Thread.sleep(10)
   121       }
   122       (!finished, result.toString)
   123     }
   124     if (startup_failed) {
   125       put_result(Markup.STDOUT, startup_output)
   126       put_result(Markup.EXIT, "127")
   127       stdin_writer.close
   128       Thread.sleep(300)  // FIXME !?
   129       proc.destroy  // FIXME reliable!?
   130     }
   131     else {
   132       put_result(Markup.SYSTEM, startup_output)
   133 
   134       standard_input = stdin_actor()
   135       stdout_actor()
   136 
   137       // rendezvous
   138       val command_stream = system.fifo_output_stream(in_fifo)
   139       val message_stream = system.fifo_input_stream(out_fifo)
   140 
   141       command_input = input_actor(command_stream)
   142       message_actor(message_stream)
   143 
   144       val rc = proc.waitFor()
   145       Thread.sleep(300)  // FIXME !?
   146       system_result("Isabelle process terminated")
   147       put_result(Markup.EXIT, rc.toString)
   148     }
   149     rm_fifos()
   150   }
   151 
   152 
   153   /* results */
   154 
   155   private def system_result(text: String)
   156   {
   157     receiver ! new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text))))
   158   }
   159 
   160 
   161   private val xml_cache = new XML.Cache(131071)
   162 
   163   private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
   164   {
   165     if (pid.isEmpty && kind == Markup.INIT) {
   166       rm_fifos()
   167       props.find(_._1 == Markup.PID).map(_._1) match {
   168         case None => system_result("Bad Isabelle process initialization: missing pid")
   169         case p => pid = p
   170       }
   171     }
   172 
   173     val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
   174     xml_cache.cache_tree(msg)((message: XML.Tree) =>
   175       receiver ! new Result(message.asInstanceOf[XML.Elem]))
   176   }
   177 
   178   private def put_result(kind: String, text: String)
   179   {
   180     put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
   181   }
   182 
   183 
   184   /* signals */
   185 
   186   @volatile private var pid: Option[String] = None
   187 
   188   def interrupt()
   189   {
   190     pid match {
   191       case None => system_result("Cannot interrupt Isabelle: unknowd pid")
   192       case Some(i) =>
   193         try {
   194           if (system.execute(true, "kill", "-INT", i).waitFor == 0)
   195             system_result("Interrupt Isabelle")
   196           else
   197             system_result("Cannot interrupt Isabelle: kill command failed")
   198         }
   199         catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
   200     }
   201   }
   202 
   203   def kill()
   204   {
   205     val running =
   206       try { proc.exitValue; false }
   207       catch { case e: java.lang.IllegalThreadStateException => true }
   208     if (running) {
   209       close()
   210       Thread.sleep(500)  // FIXME !?
   211       system_result("Kill Isabelle")
   212       proc.destroy
   213     }
   214   }
   215 
   216 
   217 
   218   /** stream actors **/
   219 
   220   /* raw stdin */
   221 
   222   private def stdin_actor(): Actor =
   223   {
   224     val name = "standard_input"
   225     Simple_Thread.actor(name) {
   226       var finished = false
   227       while (!finished) {
   228         try {
   229           //{{{
   230           receive {
   231             case Input_Text(text) =>
   232               stdin_writer.write(text)
   233               stdin_writer.flush
   234             case Close =>
   235               stdin_writer.close
   236               finished = true
   237             case bad => System.err.println(name + ": ignoring bad message " + bad)
   238           }
   239           //}}}
   240         }
   241         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   242       }
   243       system_result(name + " terminated")
   244     }
   245   }
   246 
   247 
   248   /* raw stdout */
   249 
   250   private def stdout_actor(): Actor =
   251   {
   252     val name = "standard_output"
   253     Simple_Thread.actor(name) {
   254       var result = new StringBuilder(100)
   255 
   256       var finished = false
   257       while (!finished) {
   258         try {
   259           //{{{
   260           var c = -1
   261           var done = false
   262           while (!done && (result.length == 0 || stdout_reader.ready)) {
   263             c = stdout_reader.read
   264             if (c >= 0) result.append(c.asInstanceOf[Char])
   265             else done = true
   266           }
   267           if (result.length > 0) {
   268             put_result(Markup.STDOUT, result.toString)
   269             result.length = 0
   270           }
   271           else {
   272             stdout_reader.close
   273             finished = true
   274           }
   275           //}}}
   276         }
   277         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   278       }
   279       system_result(name + " terminated")
   280     }
   281   }
   282 
   283 
   284   /* command input */
   285 
   286   private def input_actor(raw_stream: OutputStream): Actor =
   287   {
   288     val name = "command_input"
   289     Simple_Thread.actor(name) {
   290       val stream = new BufferedOutputStream(raw_stream)
   291       var finished = false
   292       while (!finished) {
   293         try {
   294           //{{{
   295           receive {
   296             case Input_Chunks(chunks) =>
   297               stream.write(Standard_System.string_bytes(
   298                   chunks.map(_.length).mkString("", ",", "\n")));
   299               chunks.foreach(stream.write(_));
   300               stream.flush
   301             case Close =>
   302               stream.close
   303               finished = true
   304             case bad => System.err.println(name + ": ignoring bad message " + bad)
   305           }
   306           //}}}
   307         }
   308         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   309       }
   310       system_result(name + " terminated")
   311     }
   312   }
   313 
   314 
   315   /* message output */
   316 
   317   private def message_actor(stream: InputStream): Actor =
   318   {
   319     class EOF extends Exception
   320     class Protocol_Error(msg: String) extends Exception(msg)
   321 
   322     val name = "message_output"
   323     Simple_Thread.actor(name) {
   324       val default_buffer = new Array[Byte](65536)
   325       var c = -1
   326 
   327       def read_chunk(): XML.Body =
   328       {
   329         //{{{
   330         // chunk size
   331         var n = 0
   332         c = stream.read
   333         if (c == -1) throw new EOF
   334         while (48 <= c && c <= 57) {
   335           n = 10 * n + (c - 48)
   336           c = stream.read
   337         }
   338         if (c != 10) throw new Protocol_Error("bad message chunk header")
   339 
   340         // chunk content
   341         val buf =
   342           if (n <= default_buffer.size) default_buffer
   343           else new Array[Byte](n)
   344 
   345         var i = 0
   346         var m = 0
   347         do {
   348           m = stream.read(buf, i, n - i)
   349           i += m
   350         } while (m > 0 && n > i)
   351 
   352         if (i != n) throw new Protocol_Error("bad message chunk content")
   353 
   354         YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
   355         //}}}
   356       }
   357 
   358       do {
   359         try {
   360           val header = read_chunk()
   361           val body = read_chunk()
   362           header match {
   363             case List(XML.Elem(Markup(name, props), Nil))
   364                 if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
   365               put_result(Kind.message_markup(name(0)), props, body)
   366             case _ => throw new Protocol_Error("bad header: " + header.toString)
   367           }
   368         }
   369         catch {
   370           case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
   371           case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
   372           case _: EOF =>
   373         }
   374       } while (c != -1)
   375       stream.close
   376 
   377       system_result(name + " terminated")
   378     }
   379   }
   380 
   381 
   382   /** main methods **/
   383 
   384   def input_raw(text: String): Unit = standard_input ! Input_Text(text)
   385 
   386   def input_bytes(name: String, args: Array[Byte]*): Unit =
   387     command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
   388 
   389   def input(name: String, args: String*): Unit =
   390     input_bytes(name, args.map(Standard_System.string_bytes): _*)
   391 
   392   def close(): Unit = { close(command_input); close(standard_input) }
   393 }