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