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