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