src/Pure/System/isabelle_process.scala
author wenzelm
Mon Sep 20 11:38:14 2010 +0200 (2010-09-20 ago)
changeset 39530 16adc476348f
parent 39528 c01d89d18ff0
child 39572 bb3469024b6a
permissions -rw-r--r--
Isabelle_Process: more robust rendezvous, even without proper blocking on open (Cygwin);
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@38270
    12
  InputStream, OutputStream, BufferedOutputStream, 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@39525
    22
  object Kind
wenzelm@39525
    23
  {
wenzelm@39525
    24
    val message_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@39513
    31
      ('G' : Int) -> Markup.ERROR)
wenzelm@27949
    32
  }
wenzelm@27949
    33
wenzelm@37689
    34
  class Result(val message: XML.Elem)
wenzelm@34100
    35
  {
wenzelm@38230
    36
    def kind = message.markup.name
wenzelm@38230
    37
    def properties = message.markup.properties
wenzelm@37689
    38
    def body = message.body
wenzelm@37689
    39
wenzelm@39525
    40
    def is_init = kind == Markup.INIT
wenzelm@39525
    41
    def is_exit = kind == Markup.EXIT
wenzelm@39525
    42
    def is_stdout = kind == Markup.STDOUT
wenzelm@39525
    43
    def is_system = kind == Markup.SYSTEM
wenzelm@37689
    44
    def is_status = kind == Markup.STATUS
wenzelm@38236
    45
    def is_report = kind == Markup.REPORT
wenzelm@38231
    46
    def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
wenzelm@34100
    47
wenzelm@34100
    48
    override def toString: String =
wenzelm@34100
    49
    {
wenzelm@29522
    50
      val res =
wenzelm@38236
    51
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@37689
    52
        else Pretty.string_of(message.body)
wenzelm@38230
    53
      if (properties.isEmpty)
wenzelm@29572
    54
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    55
      else
wenzelm@29572
    56
        kind.toString + " " +
wenzelm@38230
    57
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    58
    }
wenzelm@27973
    59
  }
wenzelm@27973
    60
}
wenzelm@27973
    61
wenzelm@27973
    62
wenzelm@39528
    63
class Isabelle_Process(system: Isabelle_System, timeout: Int, receiver: Actor, args: String*)
wenzelm@29192
    64
{
wenzelm@31797
    65
  import Isabelle_Process._
wenzelm@29194
    66
wenzelm@27973
    67
wenzelm@29192
    68
  /* demo constructor */
wenzelm@27973
    69
wenzelm@29192
    70
  def this(args: String*) =
wenzelm@39528
    71
    this(new Isabelle_System, 10000,
wenzelm@34213
    72
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    73
wenzelm@29174
    74
wenzelm@39528
    75
  /* input actors */
wenzelm@39528
    76
wenzelm@39528
    77
  private case class Input_Text(text: String)
wenzelm@39528
    78
  private case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@39528
    79
wenzelm@39528
    80
  private case object Close
wenzelm@39528
    81
  private def close(a: Actor) { if (a != null) a ! Close }
wenzelm@39528
    82
wenzelm@39528
    83
  @volatile private var standard_input: Actor = null
wenzelm@39528
    84
  @volatile private var command_input: Actor = null
wenzelm@39528
    85
wenzelm@39528
    86
wenzelm@39528
    87
  /* process manager */
wenzelm@39528
    88
wenzelm@39528
    89
  private val in_fifo = system.mk_fifo()
wenzelm@39528
    90
  private val out_fifo = system.mk_fifo()
wenzelm@39528
    91
  private def rm_fifos() { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@39528
    92
wenzelm@39528
    93
  private val proc =
wenzelm@39528
    94
    try {
wenzelm@39528
    95
      val cmdline =
wenzelm@39528
    96
        List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@39528
    97
      system.execute(true, cmdline: _*)
wenzelm@39528
    98
    }
wenzelm@39528
    99
    catch { case e: IOException => rm_fifos(); throw(e) }
wenzelm@39528
   100
wenzelm@39528
   101
  private val stdout_reader =
wenzelm@39528
   102
    new BufferedReader(new InputStreamReader(proc.getInputStream, Standard_System.charset))
wenzelm@39528
   103
wenzelm@39528
   104
  private val stdin_writer =
wenzelm@39528
   105
    new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, Standard_System.charset))
wenzelm@27973
   106
wenzelm@39528
   107
  Simple_Thread.actor("process_manager") {
wenzelm@39528
   108
    val (startup_failed, startup_output) =
wenzelm@39528
   109
    {
wenzelm@39528
   110
      val expired = System.currentTimeMillis() + timeout
wenzelm@39528
   111
      val result = new StringBuilder(100)
wenzelm@39528
   112
wenzelm@39528
   113
      var finished = false
wenzelm@39528
   114
      while (!finished && System.currentTimeMillis() <= expired) {
wenzelm@39528
   115
        while (!finished && stdout_reader.ready) {
wenzelm@39528
   116
          val c = stdout_reader.read
wenzelm@39528
   117
          if (c == 2) finished = true
wenzelm@39528
   118
          else result += c.toChar
wenzelm@39528
   119
        }
wenzelm@39528
   120
        Thread.sleep(10)
wenzelm@39528
   121
      }
wenzelm@39528
   122
      (!finished, result.toString)
wenzelm@39528
   123
    }
wenzelm@39528
   124
    if (startup_failed) {
wenzelm@39528
   125
      put_result(Markup.STDOUT, startup_output)
wenzelm@39528
   126
      put_result(Markup.EXIT, "127")
wenzelm@39528
   127
      stdin_writer.close
wenzelm@39528
   128
      Thread.sleep(300)  // FIXME !?
wenzelm@39528
   129
      proc.destroy  // FIXME reliable!?
wenzelm@39528
   130
    }
wenzelm@39528
   131
    else {
wenzelm@39528
   132
      put_result(Markup.SYSTEM, startup_output)
wenzelm@39528
   133
wenzelm@39528
   134
      standard_input = stdin_actor()
wenzelm@39528
   135
      stdout_actor()
wenzelm@39530
   136
wenzelm@39530
   137
      // rendezvous
wenzelm@39530
   138
      val command_stream = system.fifo_output_stream(in_fifo)
wenzelm@39530
   139
      val message_stream = system.fifo_input_stream(out_fifo)
wenzelm@39530
   140
wenzelm@39530
   141
      command_input = input_actor(command_stream)
wenzelm@39530
   142
      message_actor(message_stream)
wenzelm@39528
   143
wenzelm@39528
   144
      val rc = proc.waitFor()
wenzelm@39528
   145
      Thread.sleep(300)  // FIXME !?
wenzelm@39528
   146
      system_result("Isabelle process terminated")
wenzelm@39528
   147
      put_result(Markup.EXIT, rc.toString)
wenzelm@39528
   148
    }
wenzelm@39528
   149
    rm_fifos()
wenzelm@39528
   150
  }
wenzelm@27973
   151
wenzelm@27973
   152
wenzelm@27973
   153
  /* results */
wenzelm@27949
   154
wenzelm@39525
   155
  private def system_result(text: String)
wenzelm@39525
   156
  {
wenzelm@39525
   157
    receiver ! new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text))))
wenzelm@39525
   158
  }
wenzelm@39525
   159
wenzelm@39525
   160
wenzelm@38446
   161
  private val xml_cache = new XML.Cache(131071)
wenzelm@38446
   162
wenzelm@38573
   163
  private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
wenzelm@29572
   164
  {
wenzelm@39525
   165
    if (pid.isEmpty && kind == Markup.INIT) {
wenzelm@39530
   166
      rm_fifos()
wenzelm@39525
   167
      props.find(_._1 == Markup.PID).map(_._1) match {
wenzelm@39525
   168
        case None => system_result("Bad Isabelle process initialization: missing pid")
wenzelm@39525
   169
        case p => pid = p
wenzelm@39525
   170
      }
wenzelm@39525
   171
    }
wenzelm@38446
   172
wenzelm@39439
   173
    val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@39439
   174
    xml_cache.cache_tree(msg)((message: XML.Tree) =>
wenzelm@38446
   175
      receiver ! new Result(message.asInstanceOf[XML.Elem]))
wenzelm@34100
   176
  }
wenzelm@34100
   177
wenzelm@37689
   178
  private def put_result(kind: String, text: String)
wenzelm@34100
   179
  {
wenzelm@34100
   180
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   181
  }
wenzelm@27992
   182
wenzelm@27973
   183
wenzelm@27973
   184
  /* signals */
wenzelm@27973
   185
wenzelm@39528
   186
  @volatile private var pid: Option[String] = None
wenzelm@39528
   187
wenzelm@38270
   188
  def interrupt()
wenzelm@38270
   189
  {
wenzelm@39528
   190
    pid match {
wenzelm@39528
   191
      case None => system_result("Cannot interrupt Isabelle: unknowd pid")
wenzelm@39528
   192
      case Some(i) =>
wenzelm@39528
   193
        try {
wenzelm@39528
   194
          if (system.execute(true, "kill", "-INT", i).waitFor == 0)
wenzelm@39528
   195
            system_result("Interrupt Isabelle")
wenzelm@39528
   196
          else
wenzelm@39528
   197
            system_result("Cannot interrupt Isabelle: kill command failed")
wenzelm@39528
   198
        }
wenzelm@39528
   199
        catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@39528
   200
    }
wenzelm@27973
   201
  }
wenzelm@27973
   202
wenzelm@38270
   203
  def kill()
wenzelm@38270
   204
  {
wenzelm@39528
   205
    val running =
wenzelm@39528
   206
      try { proc.exitValue; false }
wenzelm@39528
   207
      catch { case e: java.lang.IllegalThreadStateException => true }
wenzelm@39528
   208
    if (running) {
wenzelm@39528
   209
      close()
wenzelm@39528
   210
      Thread.sleep(500)  // FIXME !?
wenzelm@39528
   211
      system_result("Kill Isabelle")
wenzelm@39528
   212
      proc.destroy
wenzelm@27973
   213
    }
wenzelm@27973
   214
  }
wenzelm@27973
   215
wenzelm@27949
   216
wenzelm@27949
   217
wenzelm@38259
   218
  /** stream actors **/
wenzelm@27949
   219
wenzelm@38270
   220
  /* raw stdin */
wenzelm@38270
   221
wenzelm@39528
   222
  private def stdin_actor(): Actor =
wenzelm@39528
   223
  {
wenzelm@39528
   224
    val name = "standard_input"
wenzelm@38636
   225
    Simple_Thread.actor(name) {
wenzelm@27949
   226
      var finished = false
wenzelm@27949
   227
      while (!finished) {
wenzelm@27949
   228
        try {
wenzelm@27949
   229
          //{{{
wenzelm@38259
   230
          receive {
wenzelm@38270
   231
            case Input_Text(text) =>
wenzelm@39528
   232
              stdin_writer.write(text)
wenzelm@39528
   233
              stdin_writer.flush
wenzelm@38259
   234
            case Close =>
wenzelm@39528
   235
              stdin_writer.close
wenzelm@38259
   236
              finished = true
wenzelm@38259
   237
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   238
          }
wenzelm@27949
   239
          //}}}
wenzelm@27949
   240
        }
wenzelm@39525
   241
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   242
      }
wenzelm@39525
   243
      system_result(name + " terminated")
wenzelm@27949
   244
    }
wenzelm@39528
   245
  }
wenzelm@27949
   246
wenzelm@27949
   247
wenzelm@38270
   248
  /* raw stdout */
wenzelm@27949
   249
wenzelm@39528
   250
  private def stdout_actor(): Actor =
wenzelm@39528
   251
  {
wenzelm@39528
   252
    val name = "standard_output"
wenzelm@38636
   253
    Simple_Thread.actor(name) {
wenzelm@28045
   254
      var result = new StringBuilder(100)
wenzelm@27949
   255
wenzelm@27949
   256
      var finished = false
wenzelm@27949
   257
      while (!finished) {
wenzelm@27949
   258
        try {
wenzelm@28045
   259
          //{{{
wenzelm@28045
   260
          var c = -1
wenzelm@28045
   261
          var done = false
wenzelm@39528
   262
          while (!done && (result.length == 0 || stdout_reader.ready)) {
wenzelm@39528
   263
            c = stdout_reader.read
wenzelm@28045
   264
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   265
            else done = true
wenzelm@28045
   266
          }
wenzelm@28045
   267
          if (result.length > 0) {
wenzelm@38270
   268
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   269
            result.length = 0
wenzelm@27949
   270
          }
wenzelm@27949
   271
          else {
wenzelm@39528
   272
            stdout_reader.close
wenzelm@28045
   273
            finished = true
wenzelm@38270
   274
          }
wenzelm@38270
   275
          //}}}
wenzelm@38270
   276
        }
wenzelm@39525
   277
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@38270
   278
      }
wenzelm@39525
   279
      system_result(name + " terminated")
wenzelm@38270
   280
    }
wenzelm@39528
   281
  }
wenzelm@38270
   282
wenzelm@38270
   283
wenzelm@38270
   284
  /* command input */
wenzelm@38270
   285
wenzelm@39530
   286
  private def input_actor(raw_stream: OutputStream): Actor =
wenzelm@39528
   287
  {
wenzelm@39528
   288
    val name = "command_input"
wenzelm@38636
   289
    Simple_Thread.actor(name) {
wenzelm@39530
   290
      val stream = new BufferedOutputStream(raw_stream)
wenzelm@38270
   291
      var finished = false
wenzelm@38270
   292
      while (!finished) {
wenzelm@38270
   293
        try {
wenzelm@38270
   294
          //{{{
wenzelm@38270
   295
          receive {
wenzelm@38270
   296
            case Input_Chunks(chunks) =>
wenzelm@38270
   297
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   298
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   299
              chunks.foreach(stream.write(_));
wenzelm@38270
   300
              stream.flush
wenzelm@38270
   301
            case Close =>
wenzelm@38270
   302
              stream.close
wenzelm@38270
   303
              finished = true
wenzelm@38270
   304
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   305
          }
wenzelm@28045
   306
          //}}}
wenzelm@27963
   307
        }
wenzelm@39525
   308
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   309
      }
wenzelm@39525
   310
      system_result(name + " terminated")
wenzelm@27949
   311
    }
wenzelm@39528
   312
  }
wenzelm@27949
   313
wenzelm@27949
   314
wenzelm@38259
   315
  /* message output */
wenzelm@27949
   316
wenzelm@39530
   317
  private def message_actor(stream: InputStream): Actor =
wenzelm@39526
   318
  {
wenzelm@39526
   319
    class EOF extends Exception
wenzelm@39526
   320
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   321
wenzelm@39528
   322
    val name = "message_output"
wenzelm@38636
   323
    Simple_Thread.actor(name) {
wenzelm@34100
   324
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   325
      var c = -1
wenzelm@27949
   326
wenzelm@38573
   327
      def read_chunk(): XML.Body =
wenzelm@34100
   328
      {
wenzelm@34100
   329
        //{{{
wenzelm@34100
   330
        // chunk size
wenzelm@34100
   331
        var n = 0
wenzelm@34100
   332
        c = stream.read
wenzelm@39526
   333
        if (c == -1) throw new EOF
wenzelm@34100
   334
        while (48 <= c && c <= 57) {
wenzelm@34100
   335
          n = 10 * n + (c - 48)
wenzelm@34100
   336
          c = stream.read
wenzelm@34100
   337
        }
wenzelm@34100
   338
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   339
wenzelm@34100
   340
        // chunk content
wenzelm@34100
   341
        val buf =
wenzelm@34100
   342
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   343
          else new Array[Byte](n)
wenzelm@34100
   344
wenzelm@34100
   345
        var i = 0
wenzelm@34100
   346
        var m = 0
wenzelm@34100
   347
        do {
wenzelm@34100
   348
          m = stream.read(buf, i, n - i)
wenzelm@34100
   349
          i += m
wenzelm@34100
   350
        } while (m > 0 && n > i)
wenzelm@34100
   351
wenzelm@34100
   352
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   353
wenzelm@34100
   354
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   355
        //}}}
wenzelm@34100
   356
      }
wenzelm@34100
   357
wenzelm@34100
   358
      do {
wenzelm@27949
   359
        try {
wenzelm@38445
   360
          val header = read_chunk()
wenzelm@38445
   361
          val body = read_chunk()
wenzelm@38445
   362
          header match {
wenzelm@38445
   363
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@39525
   364
                if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
wenzelm@39525
   365
              put_result(Kind.message_markup(name(0)), props, body)
wenzelm@38445
   366
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   367
          }
wenzelm@27963
   368
        }
wenzelm@28063
   369
        catch {
wenzelm@39525
   370
          case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
wenzelm@39525
   371
          case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
wenzelm@39526
   372
          case _: EOF =>
wenzelm@28063
   373
        }
wenzelm@34100
   374
      } while (c != -1)
wenzelm@34100
   375
      stream.close
wenzelm@34100
   376
wenzelm@39525
   377
      system_result(name + " terminated")
wenzelm@27949
   378
    }
wenzelm@39526
   379
  }
wenzelm@27949
   380
wenzelm@27949
   381
wenzelm@38259
   382
  /** main methods **/
wenzelm@38259
   383
wenzelm@38270
   384
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   385
wenzelm@38372
   386
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   387
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   388
wenzelm@38270
   389
  def input(name: String, args: String*): Unit =
wenzelm@38372
   390
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   391
wenzelm@39528
   392
  def close(): Unit = { close(command_input); close(standard_input) }
wenzelm@27949
   393
}