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