src/Pure/System/isabelle_process.scala
author wenzelm
Sat Aug 07 22:09:52 2010 +0200 (2010-08-07 ago)
changeset 38230 ed147003de4b
parent 37712 7f25bf4b4bca
child 38231 968844caaff9
permissions -rw-r--r--
simplified type XML.Tree: embed Markup directly, avoid slightly odd triple;
XML.cache_tree: actually store XML.Text as well;
added Isabelle_Process.Result.properties;
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@38230
    48
    def kind = message.markup.name
wenzelm@38230
    49
    def properties = message.markup.properties
wenzelm@37689
    50
    def body = message.body
wenzelm@37689
    51
wenzelm@37689
    52
    def is_raw = Kind.is_raw(kind)
wenzelm@37689
    53
    def is_control = Kind.is_control(kind)
wenzelm@37689
    54
    def is_system = Kind.is_system(kind)
wenzelm@37689
    55
    def is_status = kind == Markup.STATUS
wenzelm@38230
    56
    def is_ready = is_status && body == List(XML.Elem(Markup(Markup.READY, Nil), Nil))
wenzelm@34100
    57
wenzelm@34100
    58
    override def toString: String =
wenzelm@34100
    59
    {
wenzelm@29522
    60
      val res =
wenzelm@37689
    61
        if (is_status) message.body.map(_.toString).mkString
wenzelm@37689
    62
        else Pretty.string_of(message.body)
wenzelm@38230
    63
      if (properties.isEmpty)
wenzelm@29572
    64
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    65
      else
wenzelm@29572
    66
        kind.toString + " " +
wenzelm@38230
    67
          (for ((x, y) <- properties) 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@38230
   101
    receiver ! new Result(XML.Elem(Markup(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@37712
   160
  def ML_val(text: String) =
wenzelm@32448
   161
    output_sync("ML_val " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   162
wenzelm@37712
   163
  def ML_command(text: String) =
wenzelm@37712
   164
    output_sync("ML_command " + Isabelle_Syntax.encode_string(text))
wenzelm@37712
   165
wenzelm@27949
   166
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   167
    output_raw("\u0000")
wenzelm@27949
   168
    closing = true
wenzelm@27949
   169
  }
wenzelm@27949
   170
wenzelm@27949
   171
  def try_close() = synchronized {
wenzelm@27949
   172
    if (proc != null && !closing) {
wenzelm@27949
   173
      try { close() }
wenzelm@27993
   174
      catch { case _: RuntimeException => }
wenzelm@27949
   175
    }
wenzelm@27949
   176
  }
wenzelm@27949
   177
wenzelm@27949
   178
wenzelm@27949
   179
  /* stdin */
wenzelm@27949
   180
wenzelm@34213
   181
  private class Stdin_Thread(out_stream: OutputStream) extends Thread("isabelle: stdin") {
wenzelm@27949
   182
    override def run() = {
wenzelm@34201
   183
      val writer = new BufferedWriter(new OutputStreamWriter(out_stream, Standard_System.charset))
wenzelm@27949
   184
      var finished = false
wenzelm@27949
   185
      while (!finished) {
wenzelm@27949
   186
        try {
wenzelm@27949
   187
          //{{{
wenzelm@27955
   188
          val s = output.take
wenzelm@27949
   189
          if (s == "\u0000") {
wenzelm@27949
   190
            writer.close
wenzelm@27949
   191
            finished = true
wenzelm@27949
   192
          }
wenzelm@27949
   193
          else {
wenzelm@37689
   194
            put_result(Markup.STDIN, s)
wenzelm@27949
   195
            writer.write(s)
wenzelm@27949
   196
            writer.flush
wenzelm@27949
   197
          }
wenzelm@27949
   198
          //}}}
wenzelm@27949
   199
        }
wenzelm@27949
   200
        catch {
wenzelm@37689
   201
          case e: IOException => put_result(Markup.SYSTEM, "Stdin thread: " + e.getMessage)
wenzelm@27949
   202
        }
wenzelm@27949
   203
      }
wenzelm@37689
   204
      put_result(Markup.SYSTEM, "Stdin thread terminated")
wenzelm@27949
   205
    }
wenzelm@27949
   206
  }
wenzelm@27949
   207
wenzelm@27949
   208
wenzelm@27949
   209
  /* stdout */
wenzelm@27949
   210
wenzelm@34213
   211
  private class Stdout_Thread(in_stream: InputStream) extends Thread("isabelle: stdout") {
wenzelm@27949
   212
    override def run() = {
wenzelm@34201
   213
      val reader = new BufferedReader(new InputStreamReader(in_stream, Standard_System.charset))
wenzelm@28045
   214
      var result = new StringBuilder(100)
wenzelm@27949
   215
wenzelm@27949
   216
      var finished = false
wenzelm@27949
   217
      while (!finished) {
wenzelm@27949
   218
        try {
wenzelm@28045
   219
          //{{{
wenzelm@28045
   220
          var c = -1
wenzelm@28045
   221
          var done = false
wenzelm@28045
   222
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   223
            c = reader.read
wenzelm@28045
   224
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   225
            else done = true
wenzelm@28045
   226
          }
wenzelm@28045
   227
          if (result.length > 0) {
wenzelm@37689
   228
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   229
            result.length = 0
wenzelm@27949
   230
          }
wenzelm@27949
   231
          else {
wenzelm@28045
   232
            reader.close
wenzelm@28045
   233
            finished = true
wenzelm@28045
   234
            try_close()
wenzelm@27949
   235
          }
wenzelm@28045
   236
          //}}}
wenzelm@27963
   237
        }
wenzelm@27963
   238
        catch {
wenzelm@37689
   239
          case e: IOException => put_result(Markup.SYSTEM, "Stdout thread: " + e.getMessage)
wenzelm@27949
   240
        }
wenzelm@27949
   241
      }
wenzelm@37689
   242
      put_result(Markup.SYSTEM, "Stdout thread terminated")
wenzelm@27949
   243
    }
wenzelm@27949
   244
  }
wenzelm@27949
   245
wenzelm@27949
   246
wenzelm@28045
   247
  /* messages */
wenzelm@27949
   248
wenzelm@34213
   249
  private class Message_Thread(fifo: String) extends Thread("isabelle: messages")
wenzelm@34100
   250
  {
wenzelm@34100
   251
    private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@34100
   252
    override def run()
wenzelm@34100
   253
    {
wenzelm@34100
   254
      val stream = system.fifo_stream(fifo)
wenzelm@34100
   255
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   256
      var c = -1
wenzelm@27949
   257
wenzelm@34100
   258
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   259
      {
wenzelm@34100
   260
        //{{{
wenzelm@34100
   261
        // chunk size
wenzelm@34100
   262
        var n = 0
wenzelm@34100
   263
        c = stream.read
wenzelm@34100
   264
        while (48 <= c && c <= 57) {
wenzelm@34100
   265
          n = 10 * n + (c - 48)
wenzelm@34100
   266
          c = stream.read
wenzelm@34100
   267
        }
wenzelm@34100
   268
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   269
wenzelm@34100
   270
        // chunk content
wenzelm@34100
   271
        val buf =
wenzelm@34100
   272
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   273
          else new Array[Byte](n)
wenzelm@34100
   274
wenzelm@34100
   275
        var i = 0
wenzelm@34100
   276
        var m = 0
wenzelm@34100
   277
        do {
wenzelm@34100
   278
          m = stream.read(buf, i, n - i)
wenzelm@34100
   279
          i += m
wenzelm@34100
   280
        } while (m > 0 && n > i)
wenzelm@34100
   281
wenzelm@34100
   282
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   283
wenzelm@34100
   284
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   285
        //}}}
wenzelm@34100
   286
      }
wenzelm@34100
   287
wenzelm@34100
   288
      do {
wenzelm@27949
   289
        try {
wenzelm@34100
   290
          //{{{
wenzelm@34100
   291
          c = stream.read
wenzelm@34100
   292
          var non_sync = 0
wenzelm@34100
   293
          while (c >= 0 && c != 2) {
wenzelm@34100
   294
            non_sync += 1
wenzelm@34100
   295
            c = stream.read
wenzelm@28063
   296
          }
wenzelm@34100
   297
          if (non_sync > 0)
wenzelm@34100
   298
            throw new Protocol_Error("lost synchronization -- skipping " + non_sync + " bytes")
wenzelm@34100
   299
          if (c == 2) {
wenzelm@34100
   300
            val header = read_chunk()
wenzelm@34100
   301
            val body = read_chunk()
wenzelm@34100
   302
            header match {
wenzelm@38230
   303
              case List(XML.Elem(Markup(name, props), Nil))
wenzelm@37689
   304
                  if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@37689
   305
                put_result(Kind.markup(name(0)), props, body)
wenzelm@34100
   306
              case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   307
            }
wenzelm@27949
   308
          }
wenzelm@34100
   309
          //}}}
wenzelm@27963
   310
        }
wenzelm@28063
   311
        catch {
wenzelm@34100
   312
          case e: IOException =>
wenzelm@37689
   313
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   314
          case e: Protocol_Error =>
wenzelm@37689
   315
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   316
        }
wenzelm@34100
   317
      } while (c != -1)
wenzelm@34100
   318
      stream.close
wenzelm@34100
   319
      try_close()
wenzelm@34100
   320
wenzelm@37689
   321
      put_result(Markup.SYSTEM, "Message thread terminated")
wenzelm@27949
   322
    }
wenzelm@27949
   323
  }
wenzelm@27949
   324
wenzelm@27949
   325
wenzelm@29192
   326
wenzelm@27949
   327
  /** main **/
wenzelm@27949
   328
wenzelm@27949
   329
  {
wenzelm@29192
   330
    /* messages */
wenzelm@28045
   331
wenzelm@34100
   332
    val message_fifo = system.mk_fifo()
wenzelm@34100
   333
    def rm_fifo() = system.rm_fifo(message_fifo)
wenzelm@28045
   334
wenzelm@34213
   335
    val message_thread = new Message_Thread(message_fifo)
wenzelm@28063
   336
    message_thread.start
wenzelm@28045
   337
wenzelm@28045
   338
wenzelm@27973
   339
    /* exec process */
wenzelm@27963
   340
wenzelm@27973
   341
    try {
wenzelm@34100
   342
      val cmdline = List(system.getenv_strict("ISABELLE_PROCESS"), "-W", message_fifo) ++ args
wenzelm@34100
   343
      proc = system.execute(true, cmdline: _*)
wenzelm@27949
   344
    }
wenzelm@27993
   345
    catch {
wenzelm@28063
   346
      case e: IOException =>
wenzelm@28063
   347
        rm_fifo()
wenzelm@28063
   348
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   349
    }
wenzelm@27949
   350
wenzelm@27949
   351
wenzelm@28045
   352
    /* stdin/stdout */
wenzelm@28045
   353
wenzelm@34213
   354
    new Stdin_Thread(proc.getOutputStream).start
wenzelm@34213
   355
    new Stdout_Thread(proc.getInputStream).start
wenzelm@28045
   356
wenzelm@28045
   357
wenzelm@28045
   358
    /* exit */
wenzelm@27949
   359
wenzelm@28063
   360
    new Thread("isabelle: exit") {
wenzelm@28045
   361
      override def run() = {
wenzelm@28045
   362
        val rc = proc.waitFor()
wenzelm@37132
   363
        Thread.sleep(300)  // FIXME property!?
wenzelm@37689
   364
        put_result(Markup.SYSTEM, "Exit thread terminated")
wenzelm@37689
   365
        put_result(Markup.EXIT, rc.toString)
wenzelm@28063
   366
        rm_fifo()
wenzelm@28045
   367
      }
wenzelm@28063
   368
    }.start
wenzelm@27949
   369
  }
wenzelm@27949
   370
}