src/Pure/System/isabelle_process.scala
author wenzelm
Sun Sep 25 13:48:59 2011 +0200 (2011-09-25 ago)
changeset 45075 6c66e268f8eb
parent 45055 55274f7e306b
child 45158 db4bf4fb5492
permissions -rw-r--r--
more uniform defaults;
     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   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(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: Properties.T = 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(
    79     timeout: Time = Time.seconds(25),
    80     use_socket: Boolean = false,
    81     receiver: Isabelle_Process.Message => Unit = Console.println(_),
    82     args: List[String] = Nil)
    83 {
    84   import Isabelle_Process._
    85 
    86 
    87   /* results */
    88 
    89   private def system_result(text: String)
    90   {
    91     receiver(new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text)))))
    92   }
    93 
    94   private val xml_cache = new XML.Cache()
    95 
    96   private def put_result(kind: String, props: Properties.T, body: XML.Body)
    97   {
    98     if (kind == Markup.INIT) system_channel.accepted()
    99     if (kind == Markup.RAW)
   100       receiver(new Result(XML.Elem(Markup(kind, props), body)))
   101     else {
   102       val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
   103       receiver(new Result(xml_cache.cache_tree(msg).asInstanceOf[XML.Elem]))
   104     }
   105   }
   106 
   107   private def put_result(kind: String, text: String)
   108   {
   109     put_result(kind, Nil, List(XML.Text(Symbol.decode(text))))
   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(use_socket)
   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(true, 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_result("Failed to terminate Isabelle: " + e.getMessage) }
   151   }
   152 
   153   private val process_manager = Simple_Thread.fork("process_manager")
   154   {
   155     val (startup_failed, startup_output) =
   156     {
   157       val expired = System.currentTimeMillis() + timeout.ms
   158       val result = new StringBuilder(100)
   159 
   160       var finished: Option[Boolean] = None
   161       while (finished.isEmpty && System.currentTimeMillis() <= expired) {
   162         while (finished.isEmpty && process.stdout.ready) {
   163           val c = process.stdout.read
   164           if (c == 2) finished = Some(true)
   165           else result += c.toChar
   166         }
   167         if (process_result.is_finished) finished = Some(false)
   168         else Thread.sleep(10)
   169       }
   170       (finished.isEmpty || !finished.get, result.toString.trim)
   171     }
   172     system_result(startup_output)
   173 
   174     if (startup_failed) {
   175       put_result(Markup.EXIT, "Return code: 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 = stdout_actor()
   186       command_input = input_actor(command_stream)
   187       val message = message_actor(message_stream)
   188 
   189       val rc = process_result.join
   190       system_result("process terminated")
   191       for ((thread, _) <- List(standard_input, stdout, command_input, message)) thread.join
   192       system_result("process_manager terminated")
   193       put_result(Markup.EXIT, "Return code: " + rc.toString)
   194     }
   195     system_channel.accepted()
   196   }
   197 
   198 
   199   /* management methods */
   200 
   201   def join() { process_manager.join() }
   202 
   203   def terminate()
   204   {
   205     close()
   206     system_result("Terminating Isabelle process")
   207     terminate_process()
   208   }
   209 
   210 
   211 
   212   /** stream actors **/
   213 
   214   /* raw stdin */
   215 
   216   private def stdin_actor(): (Thread, Actor) =
   217   {
   218     val name = "standard_input"
   219     Simple_Thread.actor(name) {
   220       var finished = false
   221       while (!finished) {
   222         try {
   223           //{{{
   224           receive {
   225             case Input_Text(text) =>
   226               process.stdin.write(text)
   227               process.stdin.flush
   228             case Close =>
   229               process.stdin.close
   230               finished = true
   231             case bad => System.err.println(name + ": ignoring bad message " + bad)
   232           }
   233           //}}}
   234         }
   235         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   236       }
   237       system_result(name + " terminated")
   238     }
   239   }
   240 
   241 
   242   /* raw stdout */
   243 
   244   private def stdout_actor(): (Thread, Actor) =
   245   {
   246     val name = "standard_output"
   247     Simple_Thread.actor(name) {
   248       var result = new StringBuilder(100)
   249 
   250       var finished = false
   251       while (!finished) {
   252         try {
   253           //{{{
   254           var c = -1
   255           var done = false
   256           while (!done && (result.length == 0 || process.stdout.ready)) {
   257             c = process.stdout.read
   258             if (c >= 0) result.append(c.asInstanceOf[Char])
   259             else done = true
   260           }
   261           if (result.length > 0) {
   262             put_result(Markup.STDOUT, result.toString)
   263             result.length = 0
   264           }
   265           else {
   266             process.stdout.close
   267             finished = true
   268           }
   269           //}}}
   270         }
   271         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   272       }
   273       system_result(name + " terminated")
   274     }
   275   }
   276 
   277 
   278   /* command input */
   279 
   280   private def input_actor(raw_stream: OutputStream): (Thread, Actor) =
   281   {
   282     val name = "command_input"
   283     Simple_Thread.actor(name) {
   284       val stream = new BufferedOutputStream(raw_stream)
   285       var finished = false
   286       while (!finished) {
   287         try {
   288           //{{{
   289           receive {
   290             case Input_Chunks(chunks) =>
   291               stream.write(Standard_System.string_bytes(
   292                   chunks.map(_.length).mkString("", ",", "\n")));
   293               chunks.foreach(stream.write(_));
   294               stream.flush
   295             case Close =>
   296               stream.close
   297               finished = true
   298             case bad => System.err.println(name + ": ignoring bad message " + bad)
   299           }
   300           //}}}
   301         }
   302         catch { case e: IOException => system_result(name + ": " + e.getMessage) }
   303       }
   304       system_result(name + " terminated")
   305     }
   306   }
   307 
   308 
   309   /* message output */
   310 
   311   private def message_actor(stream: InputStream): (Thread, Actor) =
   312   {
   313     class EOF extends Exception
   314     class Protocol_Error(msg: String) extends Exception(msg)
   315 
   316     val name = "message_output"
   317     Simple_Thread.actor(name) {
   318       val default_buffer = new Array[Byte](65536)
   319       var c = -1
   320 
   321       def read_chunk(decode: Boolean): XML.Body =
   322       {
   323         //{{{
   324         // chunk size
   325         var n = 0
   326         c = stream.read
   327         if (c == -1) throw new EOF
   328         while (48 <= c && c <= 57) {
   329           n = 10 * n + (c - 48)
   330           c = stream.read
   331         }
   332         if (c != 10) throw new Protocol_Error("bad message chunk header")
   333 
   334         // chunk content
   335         val buf =
   336           if (n <= default_buffer.size) default_buffer
   337           else new Array[Byte](n)
   338 
   339         var i = 0
   340         var m = 0
   341         do {
   342           m = stream.read(buf, i, n - i)
   343           if (m != -1) i += m
   344         } while (m != -1 && n > i)
   345 
   346         if (i != n) throw new Protocol_Error("bad message chunk content")
   347 
   348         if (decode)
   349           YXML.parse_body_failsafe(Standard_System.decode_chars(Symbol.decode, buf, 0, n))
   350         else List(XML.Text(Standard_System.decode_chars(s => s, buf, 0, n).toString))
   351         //}}}
   352       }
   353 
   354       do {
   355         try {
   356           val header = read_chunk(true)
   357           header match {
   358             case List(XML.Elem(Markup(name, props), Nil))
   359                 if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
   360               val kind = Kind.message_markup(name(0))
   361               val body = read_chunk(kind != Markup.RAW)
   362               put_result(kind, props, body)
   363             case _ =>
   364               read_chunk(false)
   365               throw new Protocol_Error("bad header: " + header.toString)
   366           }
   367         }
   368         catch {
   369           case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
   370           case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
   371           case _: EOF =>
   372         }
   373       } while (c != -1)
   374       stream.close
   375 
   376       system_result(name + " terminated")
   377     }
   378   }
   379 
   380 
   381   /** main methods **/
   382 
   383   def input_raw(text: String): Unit = standard_input._2 ! Input_Text(text)
   384 
   385   def input_bytes(name: String, args: Array[Byte]*): Unit =
   386     command_input._2 ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
   387 
   388   def input(name: String, args: String*): Unit =
   389   {
   390     receiver(new Input(name, args.toList))
   391     input_bytes(name, args.map(Standard_System.string_bytes): _*)
   392   }
   393 
   394   def close(): Unit = { close(command_input); close(standard_input) }
   395 }