src/Pure/System/isabelle_process.scala
author wenzelm
Fri Sep 17 15:51:11 2010 +0200 (2010-09-17 ago)
changeset 39439 1c294d150ded
parent 38636 b7647ca7de5a
child 39513 fce2202892c4
permissions -rw-r--r--
eliminated markup "location" in favour of more explicit "no_report", which is actually deleted from messages;
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@38236
    31
      ('G' : Int) -> Markup.ERROR,
wenzelm@38236
    32
      ('H' : Int) -> Markup.DEBUG)
wenzelm@37689
    33
    def is_raw(kind: String) =
wenzelm@37689
    34
      kind == Markup.STDOUT
wenzelm@37689
    35
    def is_control(kind: String) =
wenzelm@37689
    36
      kind == Markup.SYSTEM ||
wenzelm@37689
    37
      kind == Markup.SIGNAL ||
wenzelm@37689
    38
      kind == Markup.EXIT
wenzelm@37689
    39
    def is_system(kind: String) =
wenzelm@37689
    40
      kind == Markup.SYSTEM ||
wenzelm@38259
    41
      kind == Markup.INPUT ||
wenzelm@37689
    42
      kind == Markup.STDIN ||
wenzelm@37689
    43
      kind == Markup.SIGNAL ||
wenzelm@37689
    44
      kind == Markup.EXIT ||
wenzelm@37689
    45
      kind == Markup.STATUS
wenzelm@27949
    46
  }
wenzelm@27949
    47
wenzelm@37689
    48
  class Result(val message: XML.Elem)
wenzelm@34100
    49
  {
wenzelm@38230
    50
    def kind = message.markup.name
wenzelm@38230
    51
    def properties = message.markup.properties
wenzelm@37689
    52
    def body = message.body
wenzelm@37689
    53
wenzelm@37689
    54
    def is_raw = Kind.is_raw(kind)
wenzelm@37689
    55
    def is_control = Kind.is_control(kind)
wenzelm@37689
    56
    def is_system = Kind.is_system(kind)
wenzelm@37689
    57
    def is_status = kind == Markup.STATUS
wenzelm@38236
    58
    def is_report = kind == Markup.REPORT
wenzelm@38231
    59
    def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
wenzelm@34100
    60
wenzelm@34100
    61
    override def toString: String =
wenzelm@34100
    62
    {
wenzelm@29522
    63
      val res =
wenzelm@38236
    64
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@37689
    65
        else Pretty.string_of(message.body)
wenzelm@38230
    66
      if (properties.isEmpty)
wenzelm@29572
    67
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    68
      else
wenzelm@29572
    69
        kind.toString + " " +
wenzelm@38230
    70
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    71
    }
wenzelm@27973
    72
  }
wenzelm@27973
    73
}
wenzelm@27973
    74
wenzelm@27973
    75
wenzelm@34100
    76
class Isabelle_Process(system: Isabelle_System, receiver: Actor, args: String*)
wenzelm@29192
    77
{
wenzelm@31797
    78
  import Isabelle_Process._
wenzelm@29194
    79
wenzelm@27973
    80
wenzelm@29192
    81
  /* demo constructor */
wenzelm@27973
    82
wenzelm@29192
    83
  def this(args: String*) =
wenzelm@32474
    84
    this(new Isabelle_System,
wenzelm@34213
    85
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    86
wenzelm@29174
    87
wenzelm@27973
    88
  /* process information */
wenzelm@27973
    89
wenzelm@38270
    90
  @volatile private var proc: Option[Process] = None
wenzelm@38270
    91
  @volatile private var pid: Option[String] = None
wenzelm@27973
    92
wenzelm@27973
    93
wenzelm@27973
    94
  /* results */
wenzelm@27949
    95
wenzelm@38446
    96
  private val xml_cache = new XML.Cache(131071)
wenzelm@38446
    97
wenzelm@38573
    98
  private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
wenzelm@29572
    99
  {
wenzelm@38446
   100
    if (pid.isEmpty && kind == Markup.INIT)
wenzelm@38446
   101
      pid = props.find(_._1 == Markup.PID).map(_._1)
wenzelm@38446
   102
wenzelm@39439
   103
    val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@39439
   104
    xml_cache.cache_tree(msg)((message: XML.Tree) =>
wenzelm@38446
   105
      receiver ! new Result(message.asInstanceOf[XML.Elem]))
wenzelm@34100
   106
  }
wenzelm@34100
   107
wenzelm@37689
   108
  private def put_result(kind: String, text: String)
wenzelm@34100
   109
  {
wenzelm@34100
   110
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   111
  }
wenzelm@27992
   112
wenzelm@27973
   113
wenzelm@27973
   114
  /* signals */
wenzelm@27973
   115
wenzelm@38270
   116
  def interrupt()
wenzelm@38270
   117
  {
wenzelm@38270
   118
    if (proc.isEmpty) put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: no process")
wenzelm@38270
   119
    else
wenzelm@38270
   120
      pid match {
wenzelm@38270
   121
        case None => put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: unknowd pid")
wenzelm@38270
   122
        case Some(i) =>
wenzelm@38270
   123
          try {
wenzelm@38270
   124
            if (system.execute(true, "kill", "-INT", i).waitFor == 0)
wenzelm@38270
   125
              put_result(Markup.SIGNAL, "INT")
wenzelm@38270
   126
            else
wenzelm@38270
   127
              put_result(Markup.SYSTEM, "Cannot interrupt Isabelle: kill command failed")
wenzelm@38270
   128
          }
wenzelm@38270
   129
          catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   130
      }
wenzelm@27973
   131
  }
wenzelm@27973
   132
wenzelm@38270
   133
  def kill()
wenzelm@38270
   134
  {
wenzelm@38270
   135
    proc match {
wenzelm@38270
   136
      case None => put_result(Markup.SYSTEM, "Cannot kill Isabelle: no process")
wenzelm@38270
   137
      case Some(p) =>
wenzelm@38270
   138
        close()
wenzelm@38270
   139
        Thread.sleep(500)  // FIXME !?
wenzelm@38270
   140
        put_result(Markup.SIGNAL, "KILL")
wenzelm@38270
   141
        p.destroy
wenzelm@38270
   142
        proc = None
wenzelm@38270
   143
        pid = None
wenzelm@27973
   144
    }
wenzelm@27973
   145
  }
wenzelm@27973
   146
wenzelm@27949
   147
wenzelm@27949
   148
wenzelm@38259
   149
  /** stream actors **/
wenzelm@27949
   150
wenzelm@38270
   151
  case class Input_Text(text: String)
wenzelm@38270
   152
  case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@38259
   153
  case object Close
wenzelm@27949
   154
wenzelm@38270
   155
wenzelm@38270
   156
  /* raw stdin */
wenzelm@38270
   157
wenzelm@38270
   158
  private def stdin_actor(name: String, stream: OutputStream): Actor =
wenzelm@38636
   159
    Simple_Thread.actor(name) {
wenzelm@38253
   160
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   161
      var finished = false
wenzelm@27949
   162
      while (!finished) {
wenzelm@27949
   163
        try {
wenzelm@27949
   164
          //{{{
wenzelm@38259
   165
          receive {
wenzelm@38270
   166
            case Input_Text(text) =>
wenzelm@38270
   167
              // FIXME echo input?!
wenzelm@38259
   168
              writer.write(text)
wenzelm@38259
   169
              writer.flush
wenzelm@38259
   170
            case Close =>
wenzelm@38259
   171
              writer.close
wenzelm@38259
   172
              finished = true
wenzelm@38259
   173
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   174
          }
wenzelm@27949
   175
          //}}}
wenzelm@27949
   176
        }
wenzelm@27949
   177
        catch {
wenzelm@38259
   178
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   179
        }
wenzelm@27949
   180
      }
wenzelm@38259
   181
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   182
    }
wenzelm@27949
   183
wenzelm@27949
   184
wenzelm@38270
   185
  /* raw stdout */
wenzelm@27949
   186
wenzelm@38270
   187
  private def stdout_actor(name: String, stream: InputStream): Actor =
wenzelm@38636
   188
    Simple_Thread.actor(name) {
wenzelm@38253
   189
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   190
      var result = new StringBuilder(100)
wenzelm@27949
   191
wenzelm@27949
   192
      var finished = false
wenzelm@27949
   193
      while (!finished) {
wenzelm@27949
   194
        try {
wenzelm@28045
   195
          //{{{
wenzelm@28045
   196
          var c = -1
wenzelm@28045
   197
          var done = false
wenzelm@28045
   198
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   199
            c = reader.read
wenzelm@28045
   200
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   201
            else done = true
wenzelm@28045
   202
          }
wenzelm@28045
   203
          if (result.length > 0) {
wenzelm@38270
   204
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   205
            result.length = 0
wenzelm@27949
   206
          }
wenzelm@27949
   207
          else {
wenzelm@28045
   208
            reader.close
wenzelm@28045
   209
            finished = true
wenzelm@38270
   210
            close()
wenzelm@38270
   211
          }
wenzelm@38270
   212
          //}}}
wenzelm@38270
   213
        }
wenzelm@38270
   214
        catch {
wenzelm@38270
   215
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@38270
   216
        }
wenzelm@38270
   217
      }
wenzelm@38270
   218
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@38270
   219
    }
wenzelm@38270
   220
wenzelm@38270
   221
wenzelm@38270
   222
  /* command input */
wenzelm@38270
   223
wenzelm@38270
   224
  private def input_actor(name: String, raw_stream: OutputStream): Actor =
wenzelm@38636
   225
    Simple_Thread.actor(name) {
wenzelm@38270
   226
      val stream = new BufferedOutputStream(raw_stream)
wenzelm@38270
   227
      var finished = false
wenzelm@38270
   228
      while (!finished) {
wenzelm@38270
   229
        try {
wenzelm@38270
   230
          //{{{
wenzelm@38270
   231
          receive {
wenzelm@38270
   232
            case Input_Chunks(chunks) =>
wenzelm@38270
   233
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   234
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   235
              chunks.foreach(stream.write(_));
wenzelm@38270
   236
              stream.flush
wenzelm@38270
   237
            case Close =>
wenzelm@38270
   238
              stream.close
wenzelm@38270
   239
              finished = true
wenzelm@38270
   240
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   241
          }
wenzelm@28045
   242
          //}}}
wenzelm@27963
   243
        }
wenzelm@27963
   244
        catch {
wenzelm@38259
   245
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   246
        }
wenzelm@27949
   247
      }
wenzelm@38259
   248
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   249
    }
wenzelm@27949
   250
wenzelm@27949
   251
wenzelm@38259
   252
  /* message output */
wenzelm@27949
   253
wenzelm@38259
   254
  private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   255
wenzelm@38259
   256
  private def message_actor(name: String, stream: InputStream): Actor =
wenzelm@38636
   257
    Simple_Thread.actor(name) {
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@38259
   321
  private val in_fifo = system.mk_fifo()
wenzelm@38259
   322
  private val out_fifo = system.mk_fifo()
wenzelm@38259
   323
  private def rm_fifos() = { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@28045
   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@38259
   330
  catch {
wenzelm@38259
   331
    case e: IOException =>
wenzelm@38259
   332
      rm_fifos()
wenzelm@38259
   333
      error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@38259
   334
  }
wenzelm@28045
   335
wenzelm@38259
   336
wenzelm@38270
   337
  /* I/O actors */
wenzelm@38270
   338
wenzelm@38270
   339
  private val standard_input = stdin_actor("standard_input", proc.get.getOutputStream)
wenzelm@38270
   340
  stdout_actor("standard_output", proc.get.getInputStream)
wenzelm@38270
   341
wenzelm@38270
   342
  private val command_input = input_actor("command_input", system.fifo_output_stream(in_fifo))
wenzelm@38270
   343
  message_actor("message_output", system.fifo_input_stream(out_fifo))
wenzelm@38270
   344
wenzelm@38270
   345
wenzelm@38259
   346
  /* exit process */
wenzelm@38253
   347
wenzelm@38636
   348
  Simple_Thread.actor("process_exit") {
wenzelm@38270
   349
    proc match {
wenzelm@38270
   350
      case None =>
wenzelm@38270
   351
      case Some(p) =>
wenzelm@38270
   352
        val rc = p.waitFor()
wenzelm@38270
   353
        Thread.sleep(300)  // FIXME property!?
wenzelm@38270
   354
        put_result(Markup.SYSTEM, "process_exit terminated")
wenzelm@38270
   355
        put_result(Markup.EXIT, rc.toString)
wenzelm@38270
   356
    }
wenzelm@38259
   357
    rm_fifos()
wenzelm@38259
   358
  }
wenzelm@28045
   359
wenzelm@28045
   360
wenzelm@28045
   361
wenzelm@38259
   362
  /** main methods **/
wenzelm@38259
   363
wenzelm@38270
   364
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   365
wenzelm@38372
   366
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   367
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   368
wenzelm@38270
   369
  def input(name: String, args: String*): Unit =
wenzelm@38372
   370
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   371
wenzelm@38270
   372
  def close(): Unit = command_input ! Close
wenzelm@27949
   373
}