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