src/Pure/System/isabelle_process.scala
author wenzelm
Sun Sep 19 22:40:22 2010 +0200 (2010-09-19 ago)
changeset 39528 c01d89d18ff0
parent 39526 f1296795a8dc
child 39530 16adc476348f
permissions -rw-r--r--
refined Isabelle_Process startup: emit \002 before rendezvous on fifos, more robust treatment of startup failure with timeout, do not quit() after main loop;
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@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@39528
   136
      command_input = input_actor()
wenzelm@39528
   137
      message_actor()
wenzelm@39528
   138
wenzelm@39528
   139
      val rc = proc.waitFor()
wenzelm@39528
   140
      Thread.sleep(300)  // FIXME !?
wenzelm@39528
   141
      system_result("Isabelle process terminated")
wenzelm@39528
   142
      put_result(Markup.EXIT, rc.toString)
wenzelm@39528
   143
    }
wenzelm@39528
   144
    rm_fifos()
wenzelm@39528
   145
  }
wenzelm@27973
   146
wenzelm@27973
   147
wenzelm@27973
   148
  /* results */
wenzelm@27949
   149
wenzelm@39525
   150
  private def system_result(text: String)
wenzelm@39525
   151
  {
wenzelm@39525
   152
    receiver ! new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text))))
wenzelm@39525
   153
  }
wenzelm@39525
   154
wenzelm@39525
   155
wenzelm@38446
   156
  private val xml_cache = new XML.Cache(131071)
wenzelm@38446
   157
wenzelm@38573
   158
  private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
wenzelm@29572
   159
  {
wenzelm@39525
   160
    if (pid.isEmpty && kind == Markup.INIT) {
wenzelm@39525
   161
      props.find(_._1 == Markup.PID).map(_._1) match {
wenzelm@39525
   162
        case None => system_result("Bad Isabelle process initialization: missing pid")
wenzelm@39525
   163
        case p => pid = p
wenzelm@39525
   164
      }
wenzelm@39525
   165
    }
wenzelm@38446
   166
wenzelm@39439
   167
    val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@39439
   168
    xml_cache.cache_tree(msg)((message: XML.Tree) =>
wenzelm@38446
   169
      receiver ! new Result(message.asInstanceOf[XML.Elem]))
wenzelm@34100
   170
  }
wenzelm@34100
   171
wenzelm@37689
   172
  private def put_result(kind: String, text: String)
wenzelm@34100
   173
  {
wenzelm@34100
   174
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   175
  }
wenzelm@27992
   176
wenzelm@27973
   177
wenzelm@27973
   178
  /* signals */
wenzelm@27973
   179
wenzelm@39528
   180
  @volatile private var pid: Option[String] = None
wenzelm@39528
   181
wenzelm@38270
   182
  def interrupt()
wenzelm@38270
   183
  {
wenzelm@39528
   184
    pid match {
wenzelm@39528
   185
      case None => system_result("Cannot interrupt Isabelle: unknowd pid")
wenzelm@39528
   186
      case Some(i) =>
wenzelm@39528
   187
        try {
wenzelm@39528
   188
          if (system.execute(true, "kill", "-INT", i).waitFor == 0)
wenzelm@39528
   189
            system_result("Interrupt Isabelle")
wenzelm@39528
   190
          else
wenzelm@39528
   191
            system_result("Cannot interrupt Isabelle: kill command failed")
wenzelm@39528
   192
        }
wenzelm@39528
   193
        catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@39528
   194
    }
wenzelm@27973
   195
  }
wenzelm@27973
   196
wenzelm@38270
   197
  def kill()
wenzelm@38270
   198
  {
wenzelm@39528
   199
    val running =
wenzelm@39528
   200
      try { proc.exitValue; false }
wenzelm@39528
   201
      catch { case e: java.lang.IllegalThreadStateException => true }
wenzelm@39528
   202
    if (running) {
wenzelm@39528
   203
      close()
wenzelm@39528
   204
      Thread.sleep(500)  // FIXME !?
wenzelm@39528
   205
      system_result("Kill Isabelle")
wenzelm@39528
   206
      proc.destroy
wenzelm@27973
   207
    }
wenzelm@27973
   208
  }
wenzelm@27973
   209
wenzelm@27949
   210
wenzelm@27949
   211
wenzelm@38259
   212
  /** stream actors **/
wenzelm@27949
   213
wenzelm@38270
   214
  /* raw stdin */
wenzelm@38270
   215
wenzelm@39528
   216
  private def stdin_actor(): Actor =
wenzelm@39528
   217
  {
wenzelm@39528
   218
    val name = "standard_input"
wenzelm@38636
   219
    Simple_Thread.actor(name) {
wenzelm@27949
   220
      var finished = false
wenzelm@27949
   221
      while (!finished) {
wenzelm@27949
   222
        try {
wenzelm@27949
   223
          //{{{
wenzelm@38259
   224
          receive {
wenzelm@38270
   225
            case Input_Text(text) =>
wenzelm@39528
   226
              stdin_writer.write(text)
wenzelm@39528
   227
              stdin_writer.flush
wenzelm@38259
   228
            case Close =>
wenzelm@39528
   229
              stdin_writer.close
wenzelm@38259
   230
              finished = true
wenzelm@38259
   231
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   232
          }
wenzelm@27949
   233
          //}}}
wenzelm@27949
   234
        }
wenzelm@39525
   235
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   236
      }
wenzelm@39525
   237
      system_result(name + " terminated")
wenzelm@27949
   238
    }
wenzelm@39528
   239
  }
wenzelm@27949
   240
wenzelm@27949
   241
wenzelm@38270
   242
  /* raw stdout */
wenzelm@27949
   243
wenzelm@39528
   244
  private def stdout_actor(): Actor =
wenzelm@39528
   245
  {
wenzelm@39528
   246
    val name = "standard_output"
wenzelm@38636
   247
    Simple_Thread.actor(name) {
wenzelm@28045
   248
      var result = new StringBuilder(100)
wenzelm@27949
   249
wenzelm@27949
   250
      var finished = false
wenzelm@27949
   251
      while (!finished) {
wenzelm@27949
   252
        try {
wenzelm@28045
   253
          //{{{
wenzelm@28045
   254
          var c = -1
wenzelm@28045
   255
          var done = false
wenzelm@39528
   256
          while (!done && (result.length == 0 || stdout_reader.ready)) {
wenzelm@39528
   257
            c = stdout_reader.read
wenzelm@28045
   258
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   259
            else done = true
wenzelm@28045
   260
          }
wenzelm@28045
   261
          if (result.length > 0) {
wenzelm@38270
   262
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   263
            result.length = 0
wenzelm@27949
   264
          }
wenzelm@27949
   265
          else {
wenzelm@39528
   266
            stdout_reader.close
wenzelm@28045
   267
            finished = true
wenzelm@38270
   268
          }
wenzelm@38270
   269
          //}}}
wenzelm@38270
   270
        }
wenzelm@39525
   271
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@38270
   272
      }
wenzelm@39525
   273
      system_result(name + " terminated")
wenzelm@38270
   274
    }
wenzelm@39528
   275
  }
wenzelm@38270
   276
wenzelm@38270
   277
wenzelm@38270
   278
  /* command input */
wenzelm@38270
   279
wenzelm@39528
   280
  private def input_actor(): Actor =
wenzelm@39528
   281
  {
wenzelm@39528
   282
    val name = "command_input"
wenzelm@38636
   283
    Simple_Thread.actor(name) {
wenzelm@39528
   284
      val stream = new BufferedOutputStream(system.fifo_output_stream(in_fifo))
wenzelm@38270
   285
      var finished = false
wenzelm@38270
   286
      while (!finished) {
wenzelm@38270
   287
        try {
wenzelm@38270
   288
          //{{{
wenzelm@38270
   289
          receive {
wenzelm@38270
   290
            case Input_Chunks(chunks) =>
wenzelm@38270
   291
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   292
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   293
              chunks.foreach(stream.write(_));
wenzelm@38270
   294
              stream.flush
wenzelm@38270
   295
            case Close =>
wenzelm@38270
   296
              stream.close
wenzelm@38270
   297
              finished = true
wenzelm@38270
   298
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   299
          }
wenzelm@28045
   300
          //}}}
wenzelm@27963
   301
        }
wenzelm@39525
   302
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   303
      }
wenzelm@39525
   304
      system_result(name + " terminated")
wenzelm@27949
   305
    }
wenzelm@39528
   306
  }
wenzelm@27949
   307
wenzelm@27949
   308
wenzelm@38259
   309
  /* message output */
wenzelm@27949
   310
wenzelm@39528
   311
  private def message_actor(): Actor =
wenzelm@39526
   312
  {
wenzelm@39526
   313
    class EOF extends Exception
wenzelm@39526
   314
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   315
wenzelm@39528
   316
    val name = "message_output"
wenzelm@38636
   317
    Simple_Thread.actor(name) {
wenzelm@39528
   318
      val stream = system.fifo_input_stream(out_fifo)
wenzelm@34100
   319
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   320
      var c = -1
wenzelm@27949
   321
wenzelm@38573
   322
      def read_chunk(): XML.Body =
wenzelm@34100
   323
      {
wenzelm@34100
   324
        //{{{
wenzelm@34100
   325
        // chunk size
wenzelm@34100
   326
        var n = 0
wenzelm@34100
   327
        c = stream.read
wenzelm@39526
   328
        if (c == -1) throw new EOF
wenzelm@34100
   329
        while (48 <= c && c <= 57) {
wenzelm@34100
   330
          n = 10 * n + (c - 48)
wenzelm@34100
   331
          c = stream.read
wenzelm@34100
   332
        }
wenzelm@34100
   333
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   334
wenzelm@34100
   335
        // chunk content
wenzelm@34100
   336
        val buf =
wenzelm@34100
   337
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   338
          else new Array[Byte](n)
wenzelm@34100
   339
wenzelm@34100
   340
        var i = 0
wenzelm@34100
   341
        var m = 0
wenzelm@34100
   342
        do {
wenzelm@34100
   343
          m = stream.read(buf, i, n - i)
wenzelm@34100
   344
          i += m
wenzelm@34100
   345
        } while (m > 0 && n > i)
wenzelm@34100
   346
wenzelm@34100
   347
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   348
wenzelm@34100
   349
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   350
        //}}}
wenzelm@34100
   351
      }
wenzelm@34100
   352
wenzelm@34100
   353
      do {
wenzelm@27949
   354
        try {
wenzelm@38445
   355
          val header = read_chunk()
wenzelm@38445
   356
          val body = read_chunk()
wenzelm@38445
   357
          header match {
wenzelm@38445
   358
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@39525
   359
                if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
wenzelm@39525
   360
              put_result(Kind.message_markup(name(0)), props, body)
wenzelm@38445
   361
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   362
          }
wenzelm@27963
   363
        }
wenzelm@28063
   364
        catch {
wenzelm@39525
   365
          case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
wenzelm@39525
   366
          case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
wenzelm@39526
   367
          case _: EOF =>
wenzelm@28063
   368
        }
wenzelm@34100
   369
      } while (c != -1)
wenzelm@34100
   370
      stream.close
wenzelm@34100
   371
wenzelm@39525
   372
      system_result(name + " terminated")
wenzelm@27949
   373
    }
wenzelm@39526
   374
  }
wenzelm@27949
   375
wenzelm@27949
   376
wenzelm@38259
   377
  /** main methods **/
wenzelm@38259
   378
wenzelm@38270
   379
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   380
wenzelm@38372
   381
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   382
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   383
wenzelm@38270
   384
  def input(name: String, args: String*): Unit =
wenzelm@38372
   385
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   386
wenzelm@39528
   387
  def close(): Unit = { close(command_input); close(standard_input) }
wenzelm@27949
   388
}