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