src/Pure/System/isabelle_process.scala
author wenzelm
Tue Aug 10 15:12:45 2010 +0200 (2010-08-10 ago)
changeset 38262 bb2df73fab2c
parent 38259 2b61c5e27399
child 38270 71bb3c273dd1
permissions -rw-r--r--
removed obsolete methods for (ML) commands;
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@28056
    12
  InputStream, OutputStream, 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@29648
    92
  @volatile private var proc: Process = null
wenzelm@29648
    93
  @volatile private var closing = false
wenzelm@29648
    94
  @volatile private var pid: String = null
wenzelm@27973
    95
wenzelm@27973
    96
wenzelm@27973
    97
  /* results */
wenzelm@27949
    98
wenzelm@37689
    99
  private def put_result(kind: String, props: List[(String, String)], body: List[XML.Tree])
wenzelm@29572
   100
  {
wenzelm@37689
   101
    if (kind == Markup.INIT) {
wenzelm@34214
   102
      for ((Markup.PID, p) <- props) pid = p
wenzelm@27963
   103
    }
wenzelm@38230
   104
    receiver ! new Result(XML.Elem(Markup(kind, props), body))
wenzelm@34100
   105
  }
wenzelm@34100
   106
wenzelm@37689
   107
  private def put_result(kind: String, text: String)
wenzelm@34100
   108
  {
wenzelm@34100
   109
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   110
  }
wenzelm@27992
   111
wenzelm@27973
   112
wenzelm@27973
   113
  /* signals */
wenzelm@27973
   114
wenzelm@38259
   115
  def interrupt() = synchronized {  // FIXME avoid synchronized
wenzelm@27993
   116
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@37689
   117
    if (pid == null) put_result(Markup.SYSTEM, "Cannot interrupt: unknown pid")
wenzelm@27973
   118
    else {
wenzelm@27973
   119
      try {
wenzelm@34100
   120
        if (system.execute(true, "kill", "-INT", pid).waitFor == 0)
wenzelm@37689
   121
          put_result(Markup.SIGNAL, "INT")
wenzelm@27990
   122
        else
wenzelm@37689
   123
          put_result(Markup.SYSTEM, "Cannot interrupt: kill command failed")
wenzelm@27973
   124
      }
wenzelm@27993
   125
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   126
    }
wenzelm@27973
   127
  }
wenzelm@27973
   128
wenzelm@38259
   129
  def kill() = synchronized {  // FIXME avoid synchronized
wenzelm@27993
   130
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   131
    else {
wenzelm@27973
   132
      try_close()
wenzelm@37132
   133
      Thread.sleep(500)  // FIXME property!?
wenzelm@37689
   134
      put_result(Markup.SIGNAL, "KILL")
wenzelm@27973
   135
      proc.destroy
wenzelm@27973
   136
      proc = null
wenzelm@27990
   137
      pid = null
wenzelm@27973
   138
    }
wenzelm@27973
   139
  }
wenzelm@27973
   140
wenzelm@27949
   141
wenzelm@27949
   142
wenzelm@38259
   143
  /** stream actors **/
wenzelm@27949
   144
wenzelm@38259
   145
  /* input */
wenzelm@27949
   146
wenzelm@38259
   147
  case class Input(cmd: String)
wenzelm@38259
   148
  case object Close
wenzelm@27949
   149
wenzelm@38259
   150
  private def input_actor(name: String, kind: String, stream: => OutputStream): Actor =
wenzelm@38259
   151
    Library.thread_actor(name) {
wenzelm@38253
   152
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   153
      var finished = false
wenzelm@27949
   154
      while (!finished) {
wenzelm@27949
   155
        try {
wenzelm@27949
   156
          //{{{
wenzelm@38259
   157
          receive {
wenzelm@38259
   158
            case Input(text) =>
wenzelm@38259
   159
              put_result(kind, text)
wenzelm@38259
   160
              writer.write(text)
wenzelm@38259
   161
              writer.flush
wenzelm@38259
   162
            case Close =>
wenzelm@38259
   163
              writer.close
wenzelm@38259
   164
              finished = true
wenzelm@38259
   165
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   166
          }
wenzelm@27949
   167
          //}}}
wenzelm@27949
   168
        }
wenzelm@27949
   169
        catch {
wenzelm@38259
   170
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   171
        }
wenzelm@27949
   172
      }
wenzelm@38259
   173
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   174
    }
wenzelm@27949
   175
wenzelm@27949
   176
wenzelm@38259
   177
  /* raw output */
wenzelm@27949
   178
wenzelm@38259
   179
  private def output_actor(name: String, kind: String, stream: => InputStream): Actor =
wenzelm@38259
   180
    Library.thread_actor(name) {
wenzelm@38253
   181
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   182
      var result = new StringBuilder(100)
wenzelm@27949
   183
wenzelm@27949
   184
      var finished = false
wenzelm@27949
   185
      while (!finished) {
wenzelm@27949
   186
        try {
wenzelm@28045
   187
          //{{{
wenzelm@28045
   188
          var c = -1
wenzelm@28045
   189
          var done = false
wenzelm@28045
   190
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   191
            c = reader.read
wenzelm@28045
   192
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   193
            else done = true
wenzelm@28045
   194
          }
wenzelm@28045
   195
          if (result.length > 0) {
wenzelm@38259
   196
            put_result(kind, result.toString)
wenzelm@28045
   197
            result.length = 0
wenzelm@27949
   198
          }
wenzelm@27949
   199
          else {
wenzelm@28045
   200
            reader.close
wenzelm@28045
   201
            finished = true
wenzelm@28045
   202
            try_close()
wenzelm@27949
   203
          }
wenzelm@28045
   204
          //}}}
wenzelm@27963
   205
        }
wenzelm@27963
   206
        catch {
wenzelm@38259
   207
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   208
        }
wenzelm@27949
   209
      }
wenzelm@38259
   210
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   211
    }
wenzelm@27949
   212
wenzelm@27949
   213
wenzelm@38259
   214
  /* message output */
wenzelm@27949
   215
wenzelm@38259
   216
  private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   217
wenzelm@38259
   218
  private def message_actor(name: String, stream: InputStream): Actor =
wenzelm@38259
   219
    Library.thread_actor(name) {
wenzelm@34100
   220
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   221
      var c = -1
wenzelm@27949
   222
wenzelm@34100
   223
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   224
      {
wenzelm@34100
   225
        //{{{
wenzelm@34100
   226
        // chunk size
wenzelm@34100
   227
        var n = 0
wenzelm@34100
   228
        c = stream.read
wenzelm@34100
   229
        while (48 <= c && c <= 57) {
wenzelm@34100
   230
          n = 10 * n + (c - 48)
wenzelm@34100
   231
          c = stream.read
wenzelm@34100
   232
        }
wenzelm@34100
   233
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   234
wenzelm@34100
   235
        // chunk content
wenzelm@34100
   236
        val buf =
wenzelm@34100
   237
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   238
          else new Array[Byte](n)
wenzelm@34100
   239
wenzelm@34100
   240
        var i = 0
wenzelm@34100
   241
        var m = 0
wenzelm@34100
   242
        do {
wenzelm@34100
   243
          m = stream.read(buf, i, n - i)
wenzelm@34100
   244
          i += m
wenzelm@34100
   245
        } while (m > 0 && n > i)
wenzelm@34100
   246
wenzelm@34100
   247
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   248
wenzelm@34100
   249
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   250
        //}}}
wenzelm@34100
   251
      }
wenzelm@34100
   252
wenzelm@34100
   253
      do {
wenzelm@27949
   254
        try {
wenzelm@34100
   255
          //{{{
wenzelm@34100
   256
          c = stream.read
wenzelm@34100
   257
          var non_sync = 0
wenzelm@34100
   258
          while (c >= 0 && c != 2) {
wenzelm@34100
   259
            non_sync += 1
wenzelm@34100
   260
            c = stream.read
wenzelm@28063
   261
          }
wenzelm@34100
   262
          if (non_sync > 0)
wenzelm@34100
   263
            throw new Protocol_Error("lost synchronization -- skipping " + non_sync + " bytes")
wenzelm@34100
   264
          if (c == 2) {
wenzelm@34100
   265
            val header = read_chunk()
wenzelm@34100
   266
            val body = read_chunk()
wenzelm@34100
   267
            header match {
wenzelm@38230
   268
              case List(XML.Elem(Markup(name, props), Nil))
wenzelm@37689
   269
                  if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@37689
   270
                put_result(Kind.markup(name(0)), props, body)
wenzelm@34100
   271
              case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   272
            }
wenzelm@27949
   273
          }
wenzelm@34100
   274
          //}}}
wenzelm@27963
   275
        }
wenzelm@28063
   276
        catch {
wenzelm@34100
   277
          case e: IOException =>
wenzelm@37689
   278
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   279
          case e: Protocol_Error =>
wenzelm@37689
   280
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   281
        }
wenzelm@34100
   282
      } while (c != -1)
wenzelm@34100
   283
      stream.close
wenzelm@34100
   284
      try_close()
wenzelm@34100
   285
wenzelm@38259
   286
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   287
    }
wenzelm@27949
   288
wenzelm@27949
   289
wenzelm@29192
   290
wenzelm@38259
   291
  /** init **/
wenzelm@38259
   292
wenzelm@38259
   293
  /* exec process */
wenzelm@27949
   294
wenzelm@38259
   295
  private val in_fifo = system.mk_fifo()
wenzelm@38259
   296
  private val out_fifo = system.mk_fifo()
wenzelm@38259
   297
  private def rm_fifos() = { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@28045
   298
wenzelm@38259
   299
  try {
wenzelm@38259
   300
    val cmdline =
wenzelm@38259
   301
      List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@38259
   302
    proc = system.execute(true, cmdline: _*)
wenzelm@38259
   303
  }
wenzelm@38259
   304
  catch {
wenzelm@38259
   305
    case e: IOException =>
wenzelm@38259
   306
      rm_fifos()
wenzelm@38259
   307
      error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@38259
   308
  }
wenzelm@28045
   309
wenzelm@38259
   310
wenzelm@38259
   311
  /* exit process */
wenzelm@38253
   312
wenzelm@38259
   313
  Library.thread_actor("process_exit") {
wenzelm@38259
   314
    val rc = proc.waitFor()
wenzelm@38259
   315
    Thread.sleep(300)  // FIXME property!?
wenzelm@38259
   316
    put_result(Markup.SYSTEM, "process_exit terminated")
wenzelm@38259
   317
    put_result(Markup.EXIT, rc.toString)
wenzelm@38259
   318
    rm_fifos()
wenzelm@38259
   319
  }
wenzelm@28045
   320
wenzelm@28045
   321
wenzelm@38259
   322
  /* I/O actors */
wenzelm@38259
   323
wenzelm@38259
   324
  private val standard_input =
wenzelm@38259
   325
    input_actor("standard_input", Markup.STDIN, proc.getOutputStream)
wenzelm@27963
   326
wenzelm@38259
   327
  private val command_input =
wenzelm@38259
   328
    input_actor("command_input", Markup.INPUT, system.fifo_output_stream(in_fifo))
wenzelm@38259
   329
wenzelm@38259
   330
  output_actor("standard_output", Markup.STDOUT, proc.getInputStream)
wenzelm@38259
   331
  message_actor("message_output", system.fifo_input_stream(out_fifo))
wenzelm@38259
   332
wenzelm@28045
   333
wenzelm@28045
   334
wenzelm@38259
   335
  /** main methods **/
wenzelm@38259
   336
wenzelm@38259
   337
  def input_raw(text: String) = standard_input ! Input(text)
wenzelm@38259
   338
wenzelm@38259
   339
  def input(text: String) = synchronized {  // FIXME avoid synchronized
wenzelm@38259
   340
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@38259
   341
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@38259
   342
    command_input ! Input(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@38259
   343
  }
wenzelm@38259
   344
wenzelm@38259
   345
  def close() = synchronized {    // FIXME avoid synchronized
wenzelm@38259
   346
    command_input ! Close
wenzelm@38259
   347
    closing = true
wenzelm@38259
   348
  }
wenzelm@38259
   349
wenzelm@38259
   350
  def try_close() = synchronized {
wenzelm@38259
   351
    if (proc != null && !closing) {
wenzelm@38259
   352
      try { close() }
wenzelm@38259
   353
      catch { case _: RuntimeException => }
wenzelm@38259
   354
    }
wenzelm@27949
   355
  }
wenzelm@27949
   356
}