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