src/Pure/System/isabelle_process.scala
author wenzelm
Sun Sep 19 20:11:51 2010 +0200 (2010-09-19 ago)
changeset 39526 f1296795a8dc
parent 39525 72e949a0425b
child 39528 c01d89d18ff0
permissions -rw-r--r--
message_actor: more robust treatment of EOF;
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@34100
    63
class Isabelle_Process(system: Isabelle_System, 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@32474
    71
    this(new Isabelle_System,
wenzelm@34213
    72
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    73
wenzelm@29174
    74
wenzelm@27973
    75
  /* process information */
wenzelm@27973
    76
wenzelm@38270
    77
  @volatile private var proc: Option[Process] = None
wenzelm@38270
    78
  @volatile private var pid: Option[String] = None
wenzelm@27973
    79
wenzelm@27973
    80
wenzelm@27973
    81
  /* results */
wenzelm@27949
    82
wenzelm@39525
    83
  private def system_result(text: String)
wenzelm@39525
    84
  {
wenzelm@39525
    85
    receiver ! new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text))))
wenzelm@39525
    86
  }
wenzelm@39525
    87
wenzelm@39525
    88
wenzelm@38446
    89
  private val xml_cache = new XML.Cache(131071)
wenzelm@38446
    90
wenzelm@38573
    91
  private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
wenzelm@29572
    92
  {
wenzelm@39525
    93
    if (pid.isEmpty && kind == Markup.INIT) {
wenzelm@39525
    94
      props.find(_._1 == Markup.PID).map(_._1) match {
wenzelm@39525
    95
        case None => system_result("Bad Isabelle process initialization: missing pid")
wenzelm@39525
    96
        case p => pid = p
wenzelm@39525
    97
      }
wenzelm@39525
    98
    }
wenzelm@38446
    99
wenzelm@39439
   100
    val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@39439
   101
    xml_cache.cache_tree(msg)((message: XML.Tree) =>
wenzelm@38446
   102
      receiver ! new Result(message.asInstanceOf[XML.Elem]))
wenzelm@34100
   103
  }
wenzelm@34100
   104
wenzelm@37689
   105
  private def put_result(kind: String, text: String)
wenzelm@34100
   106
  {
wenzelm@34100
   107
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   108
  }
wenzelm@27992
   109
wenzelm@27973
   110
wenzelm@27973
   111
  /* signals */
wenzelm@27973
   112
wenzelm@38270
   113
  def interrupt()
wenzelm@38270
   114
  {
wenzelm@39525
   115
    if (proc.isEmpty) system_result("Cannot interrupt Isabelle: no process")
wenzelm@38270
   116
    else
wenzelm@38270
   117
      pid match {
wenzelm@39525
   118
        case None => system_result("Cannot interrupt Isabelle: unknowd pid")
wenzelm@38270
   119
        case Some(i) =>
wenzelm@38270
   120
          try {
wenzelm@38270
   121
            if (system.execute(true, "kill", "-INT", i).waitFor == 0)
wenzelm@39525
   122
              system_result("Interrupt Isabelle")
wenzelm@38270
   123
            else
wenzelm@39525
   124
              system_result("Cannot interrupt Isabelle: kill command failed")
wenzelm@38270
   125
          }
wenzelm@38270
   126
          catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   127
      }
wenzelm@27973
   128
  }
wenzelm@27973
   129
wenzelm@38270
   130
  def kill()
wenzelm@38270
   131
  {
wenzelm@38270
   132
    proc match {
wenzelm@39525
   133
      case None => system_result("Cannot kill Isabelle: no process")
wenzelm@38270
   134
      case Some(p) =>
wenzelm@38270
   135
        close()
wenzelm@38270
   136
        Thread.sleep(500)  // FIXME !?
wenzelm@39525
   137
        system_result("Kill Isabelle")
wenzelm@38270
   138
        p.destroy
wenzelm@38270
   139
        proc = None
wenzelm@38270
   140
        pid = None
wenzelm@27973
   141
    }
wenzelm@27973
   142
  }
wenzelm@27973
   143
wenzelm@27949
   144
wenzelm@27949
   145
wenzelm@38259
   146
  /** stream actors **/
wenzelm@27949
   147
wenzelm@39519
   148
  private case class Input_Text(text: String)
wenzelm@39519
   149
  private case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@39519
   150
  private case object Close
wenzelm@27949
   151
wenzelm@38270
   152
wenzelm@38270
   153
  /* raw stdin */
wenzelm@38270
   154
wenzelm@38270
   155
  private def stdin_actor(name: String, stream: OutputStream): Actor =
wenzelm@38636
   156
    Simple_Thread.actor(name) {
wenzelm@38253
   157
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   158
      var finished = false
wenzelm@27949
   159
      while (!finished) {
wenzelm@27949
   160
        try {
wenzelm@27949
   161
          //{{{
wenzelm@38259
   162
          receive {
wenzelm@38270
   163
            case Input_Text(text) =>
wenzelm@38259
   164
              writer.write(text)
wenzelm@38259
   165
              writer.flush
wenzelm@38259
   166
            case Close =>
wenzelm@38259
   167
              writer.close
wenzelm@38259
   168
              finished = true
wenzelm@38259
   169
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   170
          }
wenzelm@27949
   171
          //}}}
wenzelm@27949
   172
        }
wenzelm@39525
   173
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   174
      }
wenzelm@39525
   175
      system_result(name + " terminated")
wenzelm@27949
   176
    }
wenzelm@27949
   177
wenzelm@27949
   178
wenzelm@38270
   179
  /* raw stdout */
wenzelm@27949
   180
wenzelm@38270
   181
  private def stdout_actor(name: String, stream: InputStream): Actor =
wenzelm@38636
   182
    Simple_Thread.actor(name) {
wenzelm@38253
   183
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   184
      var result = new StringBuilder(100)
wenzelm@27949
   185
wenzelm@27949
   186
      var finished = false
wenzelm@27949
   187
      while (!finished) {
wenzelm@27949
   188
        try {
wenzelm@28045
   189
          //{{{
wenzelm@28045
   190
          var c = -1
wenzelm@28045
   191
          var done = false
wenzelm@28045
   192
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   193
            c = reader.read
wenzelm@28045
   194
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   195
            else done = true
wenzelm@28045
   196
          }
wenzelm@28045
   197
          if (result.length > 0) {
wenzelm@38270
   198
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   199
            result.length = 0
wenzelm@27949
   200
          }
wenzelm@27949
   201
          else {
wenzelm@28045
   202
            reader.close
wenzelm@28045
   203
            finished = true
wenzelm@38270
   204
            close()
wenzelm@38270
   205
          }
wenzelm@38270
   206
          //}}}
wenzelm@38270
   207
        }
wenzelm@39525
   208
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@38270
   209
      }
wenzelm@39525
   210
      system_result(name + " terminated")
wenzelm@38270
   211
    }
wenzelm@38270
   212
wenzelm@38270
   213
wenzelm@38270
   214
  /* command input */
wenzelm@38270
   215
wenzelm@39523
   216
  private def input_actor(name: String, fifo: String): Actor =
wenzelm@38636
   217
    Simple_Thread.actor(name) {
wenzelm@39523
   218
      val stream = new BufferedOutputStream(system.fifo_output_stream(fifo))  // FIXME potentially blocking forever
wenzelm@38270
   219
      var finished = false
wenzelm@38270
   220
      while (!finished) {
wenzelm@38270
   221
        try {
wenzelm@38270
   222
          //{{{
wenzelm@38270
   223
          receive {
wenzelm@38270
   224
            case Input_Chunks(chunks) =>
wenzelm@38270
   225
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   226
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   227
              chunks.foreach(stream.write(_));
wenzelm@38270
   228
              stream.flush
wenzelm@38270
   229
            case Close =>
wenzelm@38270
   230
              stream.close
wenzelm@38270
   231
              finished = true
wenzelm@38270
   232
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   233
          }
wenzelm@28045
   234
          //}}}
wenzelm@27963
   235
        }
wenzelm@39525
   236
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   237
      }
wenzelm@39525
   238
      system_result(name + " terminated")
wenzelm@27949
   239
    }
wenzelm@27949
   240
wenzelm@27949
   241
wenzelm@38259
   242
  /* message output */
wenzelm@27949
   243
wenzelm@39526
   244
  private def message_actor(name: String, fifo: String): Actor =
wenzelm@39526
   245
  {
wenzelm@39526
   246
    class EOF extends Exception
wenzelm@39526
   247
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   248
wenzelm@38636
   249
    Simple_Thread.actor(name) {
wenzelm@39523
   250
      val stream = system.fifo_input_stream(fifo)  // FIXME potentially blocking forever
wenzelm@34100
   251
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   252
      var c = -1
wenzelm@27949
   253
wenzelm@38573
   254
      def read_chunk(): XML.Body =
wenzelm@34100
   255
      {
wenzelm@34100
   256
        //{{{
wenzelm@34100
   257
        // chunk size
wenzelm@34100
   258
        var n = 0
wenzelm@34100
   259
        c = stream.read
wenzelm@39526
   260
        if (c == -1) throw new EOF
wenzelm@34100
   261
        while (48 <= c && c <= 57) {
wenzelm@34100
   262
          n = 10 * n + (c - 48)
wenzelm@34100
   263
          c = stream.read
wenzelm@34100
   264
        }
wenzelm@34100
   265
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   266
wenzelm@34100
   267
        // chunk content
wenzelm@34100
   268
        val buf =
wenzelm@34100
   269
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   270
          else new Array[Byte](n)
wenzelm@34100
   271
wenzelm@34100
   272
        var i = 0
wenzelm@34100
   273
        var m = 0
wenzelm@34100
   274
        do {
wenzelm@34100
   275
          m = stream.read(buf, i, n - i)
wenzelm@34100
   276
          i += m
wenzelm@34100
   277
        } while (m > 0 && n > i)
wenzelm@34100
   278
wenzelm@34100
   279
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   280
wenzelm@34100
   281
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   282
        //}}}
wenzelm@34100
   283
      }
wenzelm@34100
   284
wenzelm@34100
   285
      do {
wenzelm@27949
   286
        try {
wenzelm@38445
   287
          val header = read_chunk()
wenzelm@38445
   288
          val body = read_chunk()
wenzelm@38445
   289
          header match {
wenzelm@38445
   290
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@39525
   291
                if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
wenzelm@39525
   292
              put_result(Kind.message_markup(name(0)), props, body)
wenzelm@38445
   293
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   294
          }
wenzelm@27963
   295
        }
wenzelm@28063
   296
        catch {
wenzelm@39525
   297
          case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
wenzelm@39525
   298
          case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
wenzelm@39526
   299
          case _: EOF =>
wenzelm@28063
   300
        }
wenzelm@34100
   301
      } while (c != -1)
wenzelm@34100
   302
      stream.close
wenzelm@38270
   303
      close()
wenzelm@34100
   304
wenzelm@39525
   305
      system_result(name + " terminated")
wenzelm@27949
   306
    }
wenzelm@39526
   307
  }
wenzelm@27949
   308
wenzelm@27949
   309
wenzelm@29192
   310
wenzelm@38259
   311
  /** init **/
wenzelm@38259
   312
wenzelm@38259
   313
  /* exec process */
wenzelm@27949
   314
wenzelm@39523
   315
  private val in_fifo = system.mk_fifo()
wenzelm@39523
   316
  private val out_fifo = system.mk_fifo()
wenzelm@39523
   317
  private def rm_fifos() { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@39523
   318
wenzelm@38259
   319
  try {
wenzelm@38259
   320
    val cmdline =
wenzelm@38259
   321
      List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@38270
   322
    proc = Some(system.execute(true, cmdline: _*))
wenzelm@38259
   323
  }
wenzelm@39523
   324
  catch { case e: IOException => rm_fifos(); throw(e) }
wenzelm@28045
   325
wenzelm@38259
   326
wenzelm@38270
   327
  /* I/O actors */
wenzelm@38270
   328
wenzelm@39523
   329
  private val command_input = input_actor("command_input", in_fifo)
wenzelm@39523
   330
  message_actor("message_output", out_fifo)
wenzelm@39519
   331
wenzelm@38270
   332
  private val standard_input = stdin_actor("standard_input", proc.get.getOutputStream)
wenzelm@38270
   333
  stdout_actor("standard_output", proc.get.getInputStream)
wenzelm@38270
   334
wenzelm@38270
   335
wenzelm@38259
   336
  /* exit process */
wenzelm@38253
   337
wenzelm@38636
   338
  Simple_Thread.actor("process_exit") {
wenzelm@38270
   339
    proc match {
wenzelm@38270
   340
      case None =>
wenzelm@38270
   341
      case Some(p) =>
wenzelm@38270
   342
        val rc = p.waitFor()
wenzelm@38270
   343
        Thread.sleep(300)  // FIXME property!?
wenzelm@39525
   344
        system_result("Isabelle process terminated")
wenzelm@38270
   345
        put_result(Markup.EXIT, rc.toString)
wenzelm@38270
   346
    }
wenzelm@38259
   347
    rm_fifos()
wenzelm@38259
   348
  }
wenzelm@28045
   349
wenzelm@28045
   350
wenzelm@28045
   351
wenzelm@38259
   352
  /** main methods **/
wenzelm@38259
   353
wenzelm@38270
   354
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   355
wenzelm@38372
   356
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   357
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   358
wenzelm@38270
   359
  def input(name: String, args: String*): Unit =
wenzelm@38372
   360
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   361
wenzelm@39524
   362
  def close(): Unit = { standard_input ! Close; command_input ! Close }
wenzelm@27949
   363
}