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