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