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