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