src/Pure/System/isabelle_process.scala
author wenzelm
Sat Sep 18 21:33:56 2010 +0200 (2010-09-18 ago)
changeset 39524 59ebce09ce6e
parent 39523 d8971680b0fc
child 39525 72e949a0425b
permissions -rw-r--r--
recovered basic session stop/restart;
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@38259
   166
              writer.write(text)
wenzelm@38259
   167
              writer.flush
wenzelm@38259
   168
            case Close =>
wenzelm@38259
   169
              writer.close
wenzelm@38259
   170
              finished = true
wenzelm@38259
   171
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   172
          }
wenzelm@27949
   173
          //}}}
wenzelm@27949
   174
        }
wenzelm@27949
   175
        catch {
wenzelm@38259
   176
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   177
        }
wenzelm@27949
   178
      }
wenzelm@38259
   179
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   180
    }
wenzelm@27949
   181
wenzelm@27949
   182
wenzelm@38270
   183
  /* raw stdout */
wenzelm@27949
   184
wenzelm@38270
   185
  private def stdout_actor(name: String, stream: InputStream): Actor =
wenzelm@38636
   186
    Simple_Thread.actor(name) {
wenzelm@38253
   187
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   188
      var result = new StringBuilder(100)
wenzelm@27949
   189
wenzelm@27949
   190
      var finished = false
wenzelm@27949
   191
      while (!finished) {
wenzelm@27949
   192
        try {
wenzelm@28045
   193
          //{{{
wenzelm@28045
   194
          var c = -1
wenzelm@28045
   195
          var done = false
wenzelm@28045
   196
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   197
            c = reader.read
wenzelm@28045
   198
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   199
            else done = true
wenzelm@28045
   200
          }
wenzelm@28045
   201
          if (result.length > 0) {
wenzelm@38270
   202
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   203
            result.length = 0
wenzelm@27949
   204
          }
wenzelm@27949
   205
          else {
wenzelm@28045
   206
            reader.close
wenzelm@28045
   207
            finished = true
wenzelm@38270
   208
            close()
wenzelm@38270
   209
          }
wenzelm@38270
   210
          //}}}
wenzelm@38270
   211
        }
wenzelm@38270
   212
        catch {
wenzelm@38270
   213
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@38270
   214
        }
wenzelm@38270
   215
      }
wenzelm@38270
   216
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@38270
   217
    }
wenzelm@38270
   218
wenzelm@38270
   219
wenzelm@38270
   220
  /* command input */
wenzelm@38270
   221
wenzelm@39523
   222
  private def input_actor(name: String, fifo: String): Actor =
wenzelm@38636
   223
    Simple_Thread.actor(name) {
wenzelm@39523
   224
      val stream = new BufferedOutputStream(system.fifo_output_stream(fifo))  // FIXME potentially blocking forever
wenzelm@38270
   225
      var finished = false
wenzelm@38270
   226
      while (!finished) {
wenzelm@38270
   227
        try {
wenzelm@38270
   228
          //{{{
wenzelm@38270
   229
          receive {
wenzelm@38270
   230
            case Input_Chunks(chunks) =>
wenzelm@38270
   231
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   232
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   233
              chunks.foreach(stream.write(_));
wenzelm@38270
   234
              stream.flush
wenzelm@38270
   235
            case Close =>
wenzelm@38270
   236
              stream.close
wenzelm@38270
   237
              finished = true
wenzelm@38270
   238
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   239
          }
wenzelm@28045
   240
          //}}}
wenzelm@27963
   241
        }
wenzelm@27963
   242
        catch {
wenzelm@38259
   243
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   244
        }
wenzelm@27949
   245
      }
wenzelm@38259
   246
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   247
    }
wenzelm@27949
   248
wenzelm@27949
   249
wenzelm@38259
   250
  /* message output */
wenzelm@27949
   251
wenzelm@38259
   252
  private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   253
wenzelm@39523
   254
  private def message_actor(name: String, fifo: String): Actor =
wenzelm@38636
   255
    Simple_Thread.actor(name) {
wenzelm@39523
   256
      val stream = system.fifo_input_stream(fifo)  // FIXME potentially blocking forever
wenzelm@34100
   257
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   258
      var c = -1
wenzelm@27949
   259
wenzelm@38573
   260
      def read_chunk(): XML.Body =
wenzelm@34100
   261
      {
wenzelm@34100
   262
        //{{{
wenzelm@34100
   263
        // chunk size
wenzelm@34100
   264
        var n = 0
wenzelm@34100
   265
        c = stream.read
wenzelm@34100
   266
        while (48 <= c && c <= 57) {
wenzelm@34100
   267
          n = 10 * n + (c - 48)
wenzelm@34100
   268
          c = stream.read
wenzelm@34100
   269
        }
wenzelm@34100
   270
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   271
wenzelm@34100
   272
        // chunk content
wenzelm@34100
   273
        val buf =
wenzelm@34100
   274
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   275
          else new Array[Byte](n)
wenzelm@34100
   276
wenzelm@34100
   277
        var i = 0
wenzelm@34100
   278
        var m = 0
wenzelm@34100
   279
        do {
wenzelm@34100
   280
          m = stream.read(buf, i, n - i)
wenzelm@34100
   281
          i += m
wenzelm@34100
   282
        } while (m > 0 && n > i)
wenzelm@34100
   283
wenzelm@34100
   284
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   285
wenzelm@34100
   286
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   287
        //}}}
wenzelm@34100
   288
      }
wenzelm@34100
   289
wenzelm@34100
   290
      do {
wenzelm@27949
   291
        try {
wenzelm@38445
   292
          val header = read_chunk()
wenzelm@38445
   293
          val body = read_chunk()
wenzelm@38445
   294
          header match {
wenzelm@38445
   295
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@38445
   296
                if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@38445
   297
              put_result(Kind.markup(name(0)), props, body)
wenzelm@38445
   298
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   299
          }
wenzelm@27963
   300
        }
wenzelm@28063
   301
        catch {
wenzelm@34100
   302
          case e: IOException =>
wenzelm@37689
   303
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   304
          case e: Protocol_Error =>
wenzelm@37689
   305
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   306
        }
wenzelm@34100
   307
      } while (c != -1)
wenzelm@34100
   308
      stream.close
wenzelm@38270
   309
      close()
wenzelm@34100
   310
wenzelm@38259
   311
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   312
    }
wenzelm@27949
   313
wenzelm@27949
   314
wenzelm@29192
   315
wenzelm@38259
   316
  /** init **/
wenzelm@38259
   317
wenzelm@38259
   318
  /* exec process */
wenzelm@27949
   319
wenzelm@39523
   320
  private val in_fifo = system.mk_fifo()
wenzelm@39523
   321
  private val out_fifo = system.mk_fifo()
wenzelm@39523
   322
  private def rm_fifos() { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@39523
   323
wenzelm@38259
   324
  try {
wenzelm@38259
   325
    val cmdline =
wenzelm@38259
   326
      List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@38270
   327
    proc = Some(system.execute(true, cmdline: _*))
wenzelm@38259
   328
  }
wenzelm@39523
   329
  catch { case e: IOException => rm_fifos(); throw(e) }
wenzelm@28045
   330
wenzelm@38259
   331
wenzelm@38270
   332
  /* I/O actors */
wenzelm@38270
   333
wenzelm@39523
   334
  private val command_input = input_actor("command_input", in_fifo)
wenzelm@39523
   335
  message_actor("message_output", out_fifo)
wenzelm@39519
   336
wenzelm@38270
   337
  private val standard_input = stdin_actor("standard_input", proc.get.getOutputStream)
wenzelm@38270
   338
  stdout_actor("standard_output", proc.get.getInputStream)
wenzelm@38270
   339
wenzelm@38270
   340
wenzelm@38259
   341
  /* exit process */
wenzelm@38253
   342
wenzelm@38636
   343
  Simple_Thread.actor("process_exit") {
wenzelm@38270
   344
    proc match {
wenzelm@38270
   345
      case None =>
wenzelm@38270
   346
      case Some(p) =>
wenzelm@38270
   347
        val rc = p.waitFor()
wenzelm@38270
   348
        Thread.sleep(300)  // FIXME property!?
wenzelm@39523
   349
        put_result(Markup.SYSTEM, "Isabelle process terminated")
wenzelm@38270
   350
        put_result(Markup.EXIT, rc.toString)
wenzelm@38270
   351
    }
wenzelm@38259
   352
    rm_fifos()
wenzelm@38259
   353
  }
wenzelm@28045
   354
wenzelm@28045
   355
wenzelm@28045
   356
wenzelm@38259
   357
  /** main methods **/
wenzelm@38259
   358
wenzelm@38270
   359
  def input_raw(text: String): Unit = standard_input ! Input_Text(text)
wenzelm@38259
   360
wenzelm@38372
   361
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@38372
   362
    command_input ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   363
wenzelm@38270
   364
  def input(name: String, args: String*): Unit =
wenzelm@38372
   365
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   366
wenzelm@39524
   367
  def close(): Unit = { standard_input ! Close; command_input ! Close }
wenzelm@27949
   368
}