src/Pure/System/isabelle_process.scala
author wenzelm
Mon Aug 16 17:04:22 2010 +0200 (2010-08-16 ago)
changeset 38445 ba9ea6b9b75c
parent 38372 e753f71b6b34
child 38446 9d59dab38fef
permissions -rw-r--r--
simplified internal message format: dropped special Symbol.STX header;
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@27949
    16
wenzelm@27973
    17
wenzelm@32474
    18
object Isabelle_Process
wenzelm@32474
    19
{
wenzelm@27949
    20
  /* results */
wenzelm@27949
    21
wenzelm@37689
    22
  object Kind {
wenzelm@29522
    23
    // message markup
wenzelm@29522
    24
    val markup = Map(
wenzelm@37689
    25
      ('A' : Int) -> Markup.INIT,
wenzelm@37689
    26
      ('B' : Int) -> Markup.STATUS,
wenzelm@38236
    27
      ('C' : Int) -> Markup.REPORT,
wenzelm@38236
    28
      ('D' : Int) -> Markup.WRITELN,
wenzelm@38236
    29
      ('E' : Int) -> Markup.TRACING,
wenzelm@38236
    30
      ('F' : Int) -> Markup.WARNING,
wenzelm@38236
    31
      ('G' : Int) -> Markup.ERROR,
wenzelm@38236
    32
      ('H' : Int) -> Markup.DEBUG)
wenzelm@37689
    33
    def is_raw(kind: String) =
wenzelm@37689
    34
      kind == Markup.STDOUT
wenzelm@37689
    35
    def is_control(kind: String) =
wenzelm@37689
    36
      kind == Markup.SYSTEM ||
wenzelm@37689
    37
      kind == Markup.SIGNAL ||
wenzelm@37689
    38
      kind == Markup.EXIT
wenzelm@37689
    39
    def is_system(kind: String) =
wenzelm@37689
    40
      kind == Markup.SYSTEM ||
wenzelm@38259
    41
      kind == Markup.INPUT ||
wenzelm@37689
    42
      kind == Markup.STDIN ||
wenzelm@37689
    43
      kind == Markup.SIGNAL ||
wenzelm@37689
    44
      kind == Markup.EXIT ||
wenzelm@37689
    45
      kind == Markup.STATUS
wenzelm@27949
    46
  }
wenzelm@27949
    47
wenzelm@37689
    48
  class Result(val message: XML.Elem)
wenzelm@34100
    49
  {
wenzelm@38230
    50
    def kind = message.markup.name
wenzelm@38230
    51
    def properties = message.markup.properties
wenzelm@37689
    52
    def body = message.body
wenzelm@37689
    53
wenzelm@37689
    54
    def is_raw = Kind.is_raw(kind)
wenzelm@37689
    55
    def is_control = Kind.is_control(kind)
wenzelm@37689
    56
    def is_system = Kind.is_system(kind)
wenzelm@37689
    57
    def is_status = kind == Markup.STATUS
wenzelm@38236
    58
    def is_report = kind == Markup.REPORT
wenzelm@38231
    59
    def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
wenzelm@34100
    60
wenzelm@34100
    61
    override def toString: String =
wenzelm@34100
    62
    {
wenzelm@29522
    63
      val res =
wenzelm@38236
    64
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@37689
    65
        else Pretty.string_of(message.body)
wenzelm@38230
    66
      if (properties.isEmpty)
wenzelm@29572
    67
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    68
      else
wenzelm@29572
    69
        kind.toString + " " +
wenzelm@38230
    70
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    71
    }
wenzelm@34109
    72
wenzelm@37689
    73
    def cache(c: XML.Cache): Result = new Result(c.cache_tree(message).asInstanceOf[XML.Elem])
wenzelm@27973
    74
  }
wenzelm@27973
    75
}
wenzelm@27973
    76
wenzelm@27973
    77
wenzelm@34100
    78
class Isabelle_Process(system: Isabelle_System, 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@32474
    86
    this(new Isabelle_System,
wenzelm@34213
    87
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    88
wenzelm@29174
    89
wenzelm@27973
    90
  /* process information */
wenzelm@27973
    91
wenzelm@38270
    92
  @volatile private var proc: Option[Process] = None
wenzelm@38270
    93
  @volatile private var pid: Option[String] = None
wenzelm@27973
    94
wenzelm@27973
    95
wenzelm@27973
    96
  /* results */
wenzelm@27949
    97
wenzelm@37689
    98
  private def put_result(kind: String, props: List[(String, String)], body: List[XML.Tree])
wenzelm@29572
    99
  {
wenzelm@37689
   100
    if (kind == Markup.INIT) {
wenzelm@38270
   101
      for ((Markup.PID, p) <- props) pid = Some(p)
wenzelm@27963
   102
    }
wenzelm@38230
   103
    receiver ! new Result(XML.Elem(Markup(kind, props), body))
wenzelm@34100
   104
  }
wenzelm@34100
   105
wenzelm@37689
   106
  private def put_result(kind: String, text: String)
wenzelm@34100
   107
  {
wenzelm@34100
   108
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   109
  }
wenzelm@27992
   110
wenzelm@27973
   111
wenzelm@27973
   112
  /* signals */
wenzelm@27973
   113
wenzelm@38270
   114
  def interrupt()
wenzelm@38270
   115
  {
wenzelm@38270
   116
    if (proc.isEmpty) put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: no process")
wenzelm@38270
   117
    else
wenzelm@38270
   118
      pid match {
wenzelm@38270
   119
        case None => put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: unknowd pid")
wenzelm@38270
   120
        case Some(i) =>
wenzelm@38270
   121
          try {
wenzelm@38270
   122
            if (system.execute(true, "kill", "-INT", i).waitFor == 0)
wenzelm@38270
   123
              put_result(Markup.SIGNAL, "INT")
wenzelm@38270
   124
            else
wenzelm@38270
   125
              put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: kill command failed")
wenzelm@38270
   126
          }
wenzelm@38270
   127
          catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   128
      }
wenzelm@27973
   129
  }
wenzelm@27973
   130
wenzelm@38270
   131
  def kill()
wenzelm@38270
   132
  {
wenzelm@38270
   133
    proc match {
wenzelm@38270
   134
      case None => put_result(Markup.SYSTEM, "Cannot kill Isabelle: no process")
wenzelm@38270
   135
      case Some(p) =>
wenzelm@38270
   136
        close()
wenzelm@38270
   137
        Thread.sleep(500)  // FIXME !?
wenzelm@38270
   138
        put_result(Markup.SIGNAL, "KILL")
wenzelm@38270
   139
        p.destroy
wenzelm@38270
   140
        proc = None
wenzelm@38270
   141
        pid = None
wenzelm@27973
   142
    }
wenzelm@27973
   143
  }
wenzelm@27973
   144
wenzelm@27949
   145
wenzelm@27949
   146
wenzelm@38259
   147
  /** stream actors **/
wenzelm@27949
   148
wenzelm@38270
   149
  case class Input_Text(text: String)
wenzelm@38270
   150
  case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@38259
   151
  case object Close
wenzelm@27949
   152
wenzelm@38270
   153
wenzelm@38270
   154
  /* raw stdin */
wenzelm@38270
   155
wenzelm@38270
   156
  private def stdin_actor(name: String, stream: OutputStream): Actor =
wenzelm@38259
   157
    Library.thread_actor(name) {
wenzelm@38253
   158
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   159
      var finished = false
wenzelm@27949
   160
      while (!finished) {
wenzelm@27949
   161
        try {
wenzelm@27949
   162
          //{{{
wenzelm@38259
   163
          receive {
wenzelm@38270
   164
            case Input_Text(text) =>
wenzelm@38270
   165
              // FIXME echo input?!
wenzelm@38259
   166
              writer.write(text)
wenzelm@38259
   167
              writer.flush
wenzelm@38259
   168
            case Close =>
wenzelm@38259
   169
              writer.close
wenzelm@38259
   170
              finished = true
wenzelm@38259
   171
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   172
          }
wenzelm@27949
   173
          //}}}
wenzelm@27949
   174
        }
wenzelm@27949
   175
        catch {
wenzelm@38259
   176
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   177
        }
wenzelm@27949
   178
      }
wenzelm@38259
   179
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   180
    }
wenzelm@27949
   181
wenzelm@27949
   182
wenzelm@38270
   183
  /* raw stdout */
wenzelm@27949
   184
wenzelm@38270
   185
  private def stdout_actor(name: String, stream: InputStream): Actor =
wenzelm@38259
   186
    Library.thread_actor(name) {
wenzelm@38253
   187
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   188
      var result = new StringBuilder(100)
wenzelm@27949
   189
wenzelm@27949
   190
      var finished = false
wenzelm@27949
   191
      while (!finished) {
wenzelm@27949
   192
        try {
wenzelm@28045
   193
          //{{{
wenzelm@28045
   194
          var c = -1
wenzelm@28045
   195
          var done = false
wenzelm@28045
   196
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   197
            c = reader.read
wenzelm@28045
   198
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   199
            else done = true
wenzelm@28045
   200
          }
wenzelm@28045
   201
          if (result.length > 0) {
wenzelm@38270
   202
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   203
            result.length = 0
wenzelm@27949
   204
          }
wenzelm@27949
   205
          else {
wenzelm@28045
   206
            reader.close
wenzelm@28045
   207
            finished = true
wenzelm@38270
   208
            close()
wenzelm@38270
   209
          }
wenzelm@38270
   210
          //}}}
wenzelm@38270
   211
        }
wenzelm@38270
   212
        catch {
wenzelm@38270
   213
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@38270
   214
        }
wenzelm@38270
   215
      }
wenzelm@38270
   216
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@38270
   217
    }
wenzelm@38270
   218
wenzelm@38270
   219
wenzelm@38270
   220
  /* command input */
wenzelm@38270
   221
wenzelm@38270
   222
  private def input_actor(name: String, raw_stream: OutputStream): Actor =
wenzelm@38270
   223
    Library.thread_actor(name) {
wenzelm@38270
   224
      val stream = new BufferedOutputStream(raw_stream)
wenzelm@38270
   225
      var finished = false
wenzelm@38270
   226
      while (!finished) {
wenzelm@38270
   227
        try {
wenzelm@38270
   228
          //{{{
wenzelm@38270
   229
          receive {
wenzelm@38270
   230
            case Input_Chunks(chunks) =>
wenzelm@38270
   231
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   232
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   233
              chunks.foreach(stream.write(_));
wenzelm@38270
   234
              stream.flush
wenzelm@38270
   235
            case Close =>
wenzelm@38270
   236
              stream.close
wenzelm@38270
   237
              finished = true
wenzelm@38270
   238
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   239
          }
wenzelm@28045
   240
          //}}}
wenzelm@27963
   241
        }
wenzelm@27963
   242
        catch {
wenzelm@38259
   243
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   244
        }
wenzelm@27949
   245
      }
wenzelm@38259
   246
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   247
    }
wenzelm@27949
   248
wenzelm@27949
   249
wenzelm@38259
   250
  /* message output */
wenzelm@27949
   251
wenzelm@38259
   252
  private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   253
wenzelm@38259
   254
  private def message_actor(name: String, stream: InputStream): Actor =
wenzelm@38259
   255
    Library.thread_actor(name) {
wenzelm@34100
   256
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   257
      var c = -1
wenzelm@27949
   258
wenzelm@34100
   259
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   260
      {
wenzelm@34100
   261
        //{{{
wenzelm@34100
   262
        // chunk size
wenzelm@34100
   263
        var n = 0
wenzelm@34100
   264
        c = stream.read
wenzelm@34100
   265
        while (48 <= c && c <= 57) {
wenzelm@34100
   266
          n = 10 * n + (c - 48)
wenzelm@34100
   267
          c = stream.read
wenzelm@34100
   268
        }
wenzelm@34100
   269
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   270
wenzelm@34100
   271
        // chunk content
wenzelm@34100
   272
        val buf =
wenzelm@34100
   273
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   274
          else new Array[Byte](n)
wenzelm@34100
   275
wenzelm@34100
   276
        var i = 0
wenzelm@34100
   277
        var m = 0
wenzelm@34100
   278
        do {
wenzelm@34100
   279
          m = stream.read(buf, i, n - i)
wenzelm@34100
   280
          i += m
wenzelm@34100
   281
        } while (m > 0 && n > i)
wenzelm@34100
   282
wenzelm@34100
   283
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   284
wenzelm@34100
   285
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   286
        //}}}
wenzelm@34100
   287
      }
wenzelm@34100
   288
wenzelm@34100
   289
      do {
wenzelm@27949
   290
        try {
wenzelm@38445
   291
          val header = read_chunk()
wenzelm@38445
   292
          val body = read_chunk()
wenzelm@38445
   293
          header match {
wenzelm@38445
   294
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@38445
   295
                if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@38445
   296
              put_result(Kind.markup(name(0)), props, body)
wenzelm@38445
   297
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   298
          }
wenzelm@27963
   299
        }
wenzelm@28063
   300
        catch {
wenzelm@34100
   301
          case e: IOException =>
wenzelm@37689
   302
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   303
          case e: Protocol_Error =>
wenzelm@37689
   304
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   305
        }
wenzelm@34100
   306
      } while (c != -1)
wenzelm@34100
   307
      stream.close
wenzelm@38270
   308
      close()
wenzelm@34100
   309
wenzelm@38259
   310
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   311
    }
wenzelm@27949
   312
wenzelm@27949
   313
wenzelm@29192
   314
wenzelm@38259
   315
  /** init **/
wenzelm@38259
   316
wenzelm@38259
   317
  /* exec process */
wenzelm@27949
   318
wenzelm@38259
   319
  private val in_fifo = system.mk_fifo()
wenzelm@38259
   320
  private val out_fifo = system.mk_fifo()
wenzelm@38259
   321
  private def rm_fifos() = { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@28045
   322
wenzelm@38259
   323
  try {
wenzelm@38259
   324
    val cmdline =
wenzelm@38259
   325
      List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@38270
   326
    proc = Some(system.execute(true, cmdline: _*))
wenzelm@38259
   327
  }
wenzelm@38259
   328
  catch {
wenzelm@38259
   329
    case e: IOException =>
wenzelm@38259
   330
      rm_fifos()
wenzelm@38259
   331
      error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@38259
   332
  }
wenzelm@28045
   333
wenzelm@38259
   334
wenzelm@38270
   335
  /* I/O actors */
wenzelm@38270
   336
wenzelm@38270
   337
  private val standard_input = stdin_actor("standard_input", proc.get.getOutputStream)
wenzelm@38270
   338
  stdout_actor("standard_output", proc.get.getInputStream)
wenzelm@38270
   339
wenzelm@38270
   340
  private val command_input = input_actor("command_input", system.fifo_output_stream(in_fifo))
wenzelm@38270
   341
  message_actor("message_output", system.fifo_input_stream(out_fifo))
wenzelm@38270
   342
wenzelm@38270
   343
wenzelm@38259
   344
  /* exit process */
wenzelm@38253
   345
wenzelm@38259
   346
  Library.thread_actor("process_exit") {
wenzelm@38270
   347
    proc match {
wenzelm@38270
   348
      case None =>
wenzelm@38270
   349
      case Some(p) =>
wenzelm@38270
   350
        val rc = p.waitFor()
wenzelm@38270
   351
        Thread.sleep(300)  // FIXME property!?
wenzelm@38270
   352
        put_result(Markup.SYSTEM, "process_exit terminated")
wenzelm@38270
   353
        put_result(Markup.EXIT, rc.toString)
wenzelm@38270
   354
    }
wenzelm@38259
   355
    rm_fifos()
wenzelm@38259
   356
  }
wenzelm@28045
   357
wenzelm@28045
   358
wenzelm@28045
   359
wenzelm@38259
   360
  /** main methods **/
wenzelm@38259
   361
wenzelm@38270
   362
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   363
wenzelm@38372
   364
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   365
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   366
wenzelm@38270
   367
  def input(name: String, args: String*): Unit =
wenzelm@38372
   368
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   369
wenzelm@38270
   370
  def close(): Unit = command_input ! Close
wenzelm@27949
   371
}