src/Pure/System/isabelle_process.scala
author wenzelm
Sun Jul 04 00:05:32 2010 +0200 (2010-07-04 ago)
changeset 37689 628eabe2213a
parent 37132 10ef4da1c314
child 37712 7f25bf4b4bca
permissions -rw-r--r--
simplified Isabelle_Process.Result: use markup directly;
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@37689
    27
      ('C' : Int) -> Markup.WRITELN,
wenzelm@37689
    28
      ('D' : Int) -> Markup.TRACING,
wenzelm@37689
    29
      ('E' : Int) -> Markup.WARNING,
wenzelm@37689
    30
      ('F' : Int) -> Markup.ERROR,
wenzelm@37689
    31
      ('G' : Int) -> Markup.DEBUG)
wenzelm@37689
    32
    def is_raw(kind: String) =
wenzelm@37689
    33
      kind == Markup.STDOUT
wenzelm@37689
    34
    def is_control(kind: String) =
wenzelm@37689
    35
      kind == Markup.SYSTEM ||
wenzelm@37689
    36
      kind == Markup.SIGNAL ||
wenzelm@37689
    37
      kind == Markup.EXIT
wenzelm@37689
    38
    def is_system(kind: String) =
wenzelm@37689
    39
      kind == Markup.SYSTEM ||
wenzelm@37689
    40
      kind == Markup.STDIN ||
wenzelm@37689
    41
      kind == Markup.SIGNAL ||
wenzelm@37689
    42
      kind == Markup.EXIT ||
wenzelm@37689
    43
      kind == Markup.STATUS
wenzelm@27949
    44
  }
wenzelm@27949
    45
wenzelm@37689
    46
  class Result(val message: XML.Elem)
wenzelm@34100
    47
  {
wenzelm@37689
    48
    def kind = message.name
wenzelm@37689
    49
    def body = message.body
wenzelm@37689
    50
wenzelm@37689
    51
    def is_raw = Kind.is_raw(kind)
wenzelm@37689
    52
    def is_control = Kind.is_control(kind)
wenzelm@37689
    53
    def is_system = Kind.is_system(kind)
wenzelm@37689
    54
    def is_status = kind == Markup.STATUS
wenzelm@37689
    55
    def is_ready = is_status && body == List(XML.Elem(Markup.READY, Nil, Nil))
wenzelm@34100
    56
wenzelm@34100
    57
    override def toString: String =
wenzelm@34100
    58
    {
wenzelm@29522
    59
      val res =
wenzelm@37689
    60
        if (is_status) message.body.map(_.toString).mkString
wenzelm@37689
    61
        else Pretty.string_of(message.body)
wenzelm@37689
    62
      val props = message.attributes
wenzelm@29572
    63
      if (props.isEmpty)
wenzelm@29572
    64
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    65
      else
wenzelm@29572
    66
        kind.toString + " " +
wenzelm@29572
    67
          (for ((x, y) <- props) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    68
    }
wenzelm@34109
    69
wenzelm@37689
    70
    def cache(c: XML.Cache): Result = new Result(c.cache_tree(message).asInstanceOf[XML.Elem])
wenzelm@27973
    71
  }
wenzelm@27973
    72
}
wenzelm@27973
    73
wenzelm@27973
    74
wenzelm@34100
    75
class Isabelle_Process(system: Isabelle_System, receiver: Actor, args: String*)
wenzelm@29192
    76
{
wenzelm@31797
    77
  import Isabelle_Process._
wenzelm@29194
    78
wenzelm@27973
    79
wenzelm@29192
    80
  /* demo constructor */
wenzelm@27973
    81
wenzelm@29192
    82
  def this(args: String*) =
wenzelm@32474
    83
    this(new Isabelle_System,
wenzelm@34213
    84
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    85
wenzelm@29174
    86
wenzelm@27973
    87
  /* process information */
wenzelm@27973
    88
wenzelm@29648
    89
  @volatile private var proc: Process = null
wenzelm@29648
    90
  @volatile private var closing = false
wenzelm@29648
    91
  @volatile private var pid: String = null
wenzelm@27973
    92
wenzelm@27973
    93
wenzelm@27973
    94
  /* results */
wenzelm@27949
    95
wenzelm@37689
    96
  private def put_result(kind: String, props: List[(String, String)], body: List[XML.Tree])
wenzelm@29572
    97
  {
wenzelm@37689
    98
    if (kind == Markup.INIT) {
wenzelm@34214
    99
      for ((Markup.PID, p) <- props) pid = p
wenzelm@27963
   100
    }
wenzelm@37689
   101
    receiver ! new Result(XML.Elem(kind, props, body))
wenzelm@34100
   102
  }
wenzelm@34100
   103
wenzelm@37689
   104
  private def put_result(kind: String, text: String)
wenzelm@34100
   105
  {
wenzelm@34100
   106
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   107
  }
wenzelm@27992
   108
wenzelm@27973
   109
wenzelm@27973
   110
  /* signals */
wenzelm@27973
   111
wenzelm@27973
   112
  def interrupt() = synchronized {
wenzelm@27993
   113
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@37689
   114
    if (pid == null) put_result(Markup.SYSTEM, "Cannot interrupt: unknown pid")
wenzelm@27973
   115
    else {
wenzelm@27973
   116
      try {
wenzelm@34100
   117
        if (system.execute(true, "kill", "-INT", pid).waitFor == 0)
wenzelm@37689
   118
          put_result(Markup.SIGNAL, "INT")
wenzelm@27990
   119
        else
wenzelm@37689
   120
          put_result(Markup.SYSTEM, "Cannot interrupt: kill command failed")
wenzelm@27973
   121
      }
wenzelm@27993
   122
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   123
    }
wenzelm@27973
   124
  }
wenzelm@27973
   125
wenzelm@27973
   126
  def kill() = synchronized {
wenzelm@27993
   127
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   128
    else {
wenzelm@27973
   129
      try_close()
wenzelm@37132
   130
      Thread.sleep(500)  // FIXME property!?
wenzelm@37689
   131
      put_result(Markup.SIGNAL, "KILL")
wenzelm@27973
   132
      proc.destroy
wenzelm@27973
   133
      proc = null
wenzelm@27990
   134
      pid = null
wenzelm@27973
   135
    }
wenzelm@27973
   136
  }
wenzelm@27973
   137
wenzelm@27949
   138
wenzelm@27949
   139
  /* output being piped into the process */
wenzelm@27949
   140
wenzelm@27990
   141
  private val output = new LinkedBlockingQueue[String]
wenzelm@27949
   142
wenzelm@28045
   143
  private def output_raw(text: String) = synchronized {
wenzelm@27993
   144
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@27993
   145
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@27955
   146
    output.put(text)
wenzelm@27949
   147
  }
wenzelm@27949
   148
wenzelm@28303
   149
  def output_sync(text: String) =
wenzelm@28045
   150
    output_raw(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@27949
   151
wenzelm@27963
   152
wenzelm@27963
   153
  def command(text: String) =
wenzelm@32448
   154
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   155
wenzelm@29572
   156
  def command(props: List[(String, String)], text: String) =
wenzelm@32448
   157
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_properties(props) + " " +
wenzelm@32448
   158
      Isabelle_Syntax.encode_string(text))
wenzelm@27949
   159
wenzelm@27963
   160
  def ML(text: String) =
wenzelm@32448
   161
    output_sync("ML_val " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   162
wenzelm@27949
   163
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   164
    output_raw("\u0000")
wenzelm@27949
   165
    closing = true
wenzelm@27949
   166
  }
wenzelm@27949
   167
wenzelm@27949
   168
  def try_close() = synchronized {
wenzelm@27949
   169
    if (proc != null && !closing) {
wenzelm@27949
   170
      try { close() }
wenzelm@27993
   171
      catch { case _: RuntimeException => }
wenzelm@27949
   172
    }
wenzelm@27949
   173
  }
wenzelm@27949
   174
wenzelm@27949
   175
wenzelm@27949
   176
  /* stdin */
wenzelm@27949
   177
wenzelm@34213
   178
  private class Stdin_Thread(out_stream: OutputStream) extends Thread("isabelle: stdin") {
wenzelm@27949
   179
    override def run() = {
wenzelm@34201
   180
      val writer = new BufferedWriter(new OutputStreamWriter(out_stream, Standard_System.charset))
wenzelm@27949
   181
      var finished = false
wenzelm@27949
   182
      while (!finished) {
wenzelm@27949
   183
        try {
wenzelm@27949
   184
          //{{{
wenzelm@27955
   185
          val s = output.take
wenzelm@27949
   186
          if (s == "\u0000") {
wenzelm@27949
   187
            writer.close
wenzelm@27949
   188
            finished = true
wenzelm@27949
   189
          }
wenzelm@27949
   190
          else {
wenzelm@37689
   191
            put_result(Markup.STDIN, s)
wenzelm@27949
   192
            writer.write(s)
wenzelm@27949
   193
            writer.flush
wenzelm@27949
   194
          }
wenzelm@27949
   195
          //}}}
wenzelm@27949
   196
        }
wenzelm@27949
   197
        catch {
wenzelm@37689
   198
          case e: IOException => put_result(Markup.SYSTEM, "Stdin thread: " + e.getMessage)
wenzelm@27949
   199
        }
wenzelm@27949
   200
      }
wenzelm@37689
   201
      put_result(Markup.SYSTEM, "Stdin thread terminated")
wenzelm@27949
   202
    }
wenzelm@27949
   203
  }
wenzelm@27949
   204
wenzelm@27949
   205
wenzelm@27949
   206
  /* stdout */
wenzelm@27949
   207
wenzelm@34213
   208
  private class Stdout_Thread(in_stream: InputStream) extends Thread("isabelle: stdout") {
wenzelm@27949
   209
    override def run() = {
wenzelm@34201
   210
      val reader = new BufferedReader(new InputStreamReader(in_stream, Standard_System.charset))
wenzelm@28045
   211
      var result = new StringBuilder(100)
wenzelm@27949
   212
wenzelm@27949
   213
      var finished = false
wenzelm@27949
   214
      while (!finished) {
wenzelm@27949
   215
        try {
wenzelm@28045
   216
          //{{{
wenzelm@28045
   217
          var c = -1
wenzelm@28045
   218
          var done = false
wenzelm@28045
   219
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   220
            c = reader.read
wenzelm@28045
   221
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   222
            else done = true
wenzelm@28045
   223
          }
wenzelm@28045
   224
          if (result.length > 0) {
wenzelm@37689
   225
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   226
            result.length = 0
wenzelm@27949
   227
          }
wenzelm@27949
   228
          else {
wenzelm@28045
   229
            reader.close
wenzelm@28045
   230
            finished = true
wenzelm@28045
   231
            try_close()
wenzelm@27949
   232
          }
wenzelm@28045
   233
          //}}}
wenzelm@27963
   234
        }
wenzelm@27963
   235
        catch {
wenzelm@37689
   236
          case e: IOException => put_result(Markup.SYSTEM, "Stdout thread: " + e.getMessage)
wenzelm@27949
   237
        }
wenzelm@27949
   238
      }
wenzelm@37689
   239
      put_result(Markup.SYSTEM, "Stdout thread terminated")
wenzelm@27949
   240
    }
wenzelm@27949
   241
  }
wenzelm@27949
   242
wenzelm@27949
   243
wenzelm@28045
   244
  /* messages */
wenzelm@27949
   245
wenzelm@34213
   246
  private class Message_Thread(fifo: String) extends Thread("isabelle: messages")
wenzelm@34100
   247
  {
wenzelm@34100
   248
    private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@34100
   249
    override def run()
wenzelm@34100
   250
    {
wenzelm@34100
   251
      val stream = system.fifo_stream(fifo)
wenzelm@34100
   252
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   253
      var c = -1
wenzelm@27949
   254
wenzelm@34100
   255
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   256
      {
wenzelm@34100
   257
        //{{{
wenzelm@34100
   258
        // chunk size
wenzelm@34100
   259
        var n = 0
wenzelm@34100
   260
        c = stream.read
wenzelm@34100
   261
        while (48 <= c && c <= 57) {
wenzelm@34100
   262
          n = 10 * n + (c - 48)
wenzelm@34100
   263
          c = stream.read
wenzelm@34100
   264
        }
wenzelm@34100
   265
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   266
wenzelm@34100
   267
        // chunk content
wenzelm@34100
   268
        val buf =
wenzelm@34100
   269
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   270
          else new Array[Byte](n)
wenzelm@34100
   271
wenzelm@34100
   272
        var i = 0
wenzelm@34100
   273
        var m = 0
wenzelm@34100
   274
        do {
wenzelm@34100
   275
          m = stream.read(buf, i, n - i)
wenzelm@34100
   276
          i += m
wenzelm@34100
   277
        } while (m > 0 && n > i)
wenzelm@34100
   278
wenzelm@34100
   279
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   280
wenzelm@34100
   281
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   282
        //}}}
wenzelm@34100
   283
      }
wenzelm@34100
   284
wenzelm@34100
   285
      do {
wenzelm@27949
   286
        try {
wenzelm@34100
   287
          //{{{
wenzelm@34100
   288
          c = stream.read
wenzelm@34100
   289
          var non_sync = 0
wenzelm@34100
   290
          while (c >= 0 && c != 2) {
wenzelm@34100
   291
            non_sync += 1
wenzelm@34100
   292
            c = stream.read
wenzelm@28063
   293
          }
wenzelm@34100
   294
          if (non_sync > 0)
wenzelm@34100
   295
            throw new Protocol_Error("lost synchronization -- skipping " + non_sync + " bytes")
wenzelm@34100
   296
          if (c == 2) {
wenzelm@34100
   297
            val header = read_chunk()
wenzelm@34100
   298
            val body = read_chunk()
wenzelm@34100
   299
            header match {
wenzelm@34100
   300
              case List(XML.Elem(name, props, Nil))
wenzelm@37689
   301
                  if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@37689
   302
                put_result(Kind.markup(name(0)), props, body)
wenzelm@34100
   303
              case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   304
            }
wenzelm@27949
   305
          }
wenzelm@34100
   306
          //}}}
wenzelm@27963
   307
        }
wenzelm@28063
   308
        catch {
wenzelm@34100
   309
          case e: IOException =>
wenzelm@37689
   310
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   311
          case e: Protocol_Error =>
wenzelm@37689
   312
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   313
        }
wenzelm@34100
   314
      } while (c != -1)
wenzelm@34100
   315
      stream.close
wenzelm@34100
   316
      try_close()
wenzelm@34100
   317
wenzelm@37689
   318
      put_result(Markup.SYSTEM, "Message thread terminated")
wenzelm@27949
   319
    }
wenzelm@27949
   320
  }
wenzelm@27949
   321
wenzelm@27949
   322
wenzelm@29192
   323
wenzelm@27949
   324
  /** main **/
wenzelm@27949
   325
wenzelm@27949
   326
  {
wenzelm@29192
   327
    /* messages */
wenzelm@28045
   328
wenzelm@34100
   329
    val message_fifo = system.mk_fifo()
wenzelm@34100
   330
    def rm_fifo() = system.rm_fifo(message_fifo)
wenzelm@28045
   331
wenzelm@34213
   332
    val message_thread = new Message_Thread(message_fifo)
wenzelm@28063
   333
    message_thread.start
wenzelm@28045
   334
wenzelm@28045
   335
wenzelm@27973
   336
    /* exec process */
wenzelm@27963
   337
wenzelm@27973
   338
    try {
wenzelm@34100
   339
      val cmdline = List(system.getenv_strict("ISABELLE_PROCESS"), "-W", message_fifo) ++ args
wenzelm@34100
   340
      proc = system.execute(true, cmdline: _*)
wenzelm@27949
   341
    }
wenzelm@27993
   342
    catch {
wenzelm@28063
   343
      case e: IOException =>
wenzelm@28063
   344
        rm_fifo()
wenzelm@28063
   345
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   346
    }
wenzelm@27949
   347
wenzelm@27949
   348
wenzelm@28045
   349
    /* stdin/stdout */
wenzelm@28045
   350
wenzelm@34213
   351
    new Stdin_Thread(proc.getOutputStream).start
wenzelm@34213
   352
    new Stdout_Thread(proc.getInputStream).start
wenzelm@28045
   353
wenzelm@28045
   354
wenzelm@28045
   355
    /* exit */
wenzelm@27949
   356
wenzelm@28063
   357
    new Thread("isabelle: exit") {
wenzelm@28045
   358
      override def run() = {
wenzelm@28045
   359
        val rc = proc.waitFor()
wenzelm@37132
   360
        Thread.sleep(300)  // FIXME property!?
wenzelm@37689
   361
        put_result(Markup.SYSTEM, "Exit thread terminated")
wenzelm@37689
   362
        put_result(Markup.EXIT, rc.toString)
wenzelm@28063
   363
        rm_fifo()
wenzelm@28045
   364
      }
wenzelm@28063
   365
    }.start
wenzelm@27949
   366
  }
wenzelm@27949
   367
}