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