src/Pure/System/isabelle_process.scala
author wenzelm
Sat Sep 18 17:14:47 2010 +0200 (2010-09-18 ago)
changeset 39519 b376f53bcc18
parent 39513 fce2202892c4
child 39523 d8971680b0fc
permissions -rw-r--r--
slightly more robust Isabelle_Process startup -- NB: openening fifo streams synchronizes with other end, which may fail to reach that point;
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 val in_fifo = system.mk_fifo()
wenzelm@39519
   151
  private val out_fifo = system.mk_fifo()
wenzelm@39519
   152
  private def rm_fifos() = { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@39519
   153
wenzelm@39519
   154
  private case class Input_Text(text: String)
wenzelm@39519
   155
  private case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@39519
   156
  private case object Close
wenzelm@27949
   157
wenzelm@38270
   158
wenzelm@38270
   159
  /* raw stdin */
wenzelm@38270
   160
wenzelm@38270
   161
  private def stdin_actor(name: String, stream: OutputStream): Actor =
wenzelm@38636
   162
    Simple_Thread.actor(name) {
wenzelm@38253
   163
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   164
      var finished = false
wenzelm@27949
   165
      while (!finished) {
wenzelm@27949
   166
        try {
wenzelm@27949
   167
          //{{{
wenzelm@38259
   168
          receive {
wenzelm@38270
   169
            case Input_Text(text) =>
wenzelm@38270
   170
              // FIXME echo input?!
wenzelm@38259
   171
              writer.write(text)
wenzelm@38259
   172
              writer.flush
wenzelm@38259
   173
            case Close =>
wenzelm@38259
   174
              writer.close
wenzelm@38259
   175
              finished = true
wenzelm@38259
   176
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   177
          }
wenzelm@27949
   178
          //}}}
wenzelm@27949
   179
        }
wenzelm@27949
   180
        catch {
wenzelm@38259
   181
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   182
        }
wenzelm@27949
   183
      }
wenzelm@38259
   184
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   185
    }
wenzelm@27949
   186
wenzelm@27949
   187
wenzelm@38270
   188
  /* raw stdout */
wenzelm@27949
   189
wenzelm@38270
   190
  private def stdout_actor(name: String, stream: InputStream): Actor =
wenzelm@38636
   191
    Simple_Thread.actor(name) {
wenzelm@38253
   192
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   193
      var result = new StringBuilder(100)
wenzelm@27949
   194
wenzelm@27949
   195
      var finished = false
wenzelm@27949
   196
      while (!finished) {
wenzelm@27949
   197
        try {
wenzelm@28045
   198
          //{{{
wenzelm@28045
   199
          var c = -1
wenzelm@28045
   200
          var done = false
wenzelm@28045
   201
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   202
            c = reader.read
wenzelm@28045
   203
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   204
            else done = true
wenzelm@28045
   205
          }
wenzelm@28045
   206
          if (result.length > 0) {
wenzelm@38270
   207
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   208
            result.length = 0
wenzelm@27949
   209
          }
wenzelm@27949
   210
          else {
wenzelm@28045
   211
            reader.close
wenzelm@28045
   212
            finished = true
wenzelm@38270
   213
            close()
wenzelm@38270
   214
          }
wenzelm@38270
   215
          //}}}
wenzelm@38270
   216
        }
wenzelm@38270
   217
        catch {
wenzelm@38270
   218
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@38270
   219
        }
wenzelm@38270
   220
      }
wenzelm@38270
   221
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@38270
   222
    }
wenzelm@38270
   223
wenzelm@38270
   224
wenzelm@38270
   225
  /* command input */
wenzelm@38270
   226
wenzelm@39519
   227
  private def input_actor(name: String): Actor =
wenzelm@38636
   228
    Simple_Thread.actor(name) {
wenzelm@39519
   229
      val stream = new BufferedOutputStream(system.fifo_output_stream(in_fifo))  // FIXME potentially blocking forever
wenzelm@38270
   230
      var finished = false
wenzelm@38270
   231
      while (!finished) {
wenzelm@38270
   232
        try {
wenzelm@38270
   233
          //{{{
wenzelm@38270
   234
          receive {
wenzelm@38270
   235
            case Input_Chunks(chunks) =>
wenzelm@38270
   236
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   237
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   238
              chunks.foreach(stream.write(_));
wenzelm@38270
   239
              stream.flush
wenzelm@38270
   240
            case Close =>
wenzelm@38270
   241
              stream.close
wenzelm@38270
   242
              finished = true
wenzelm@38270
   243
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   244
          }
wenzelm@28045
   245
          //}}}
wenzelm@27963
   246
        }
wenzelm@27963
   247
        catch {
wenzelm@38259
   248
          case e: IOException => put_result(Markup.SYSTEM, name + ": " + e.getMessage)
wenzelm@27949
   249
        }
wenzelm@27949
   250
      }
wenzelm@38259
   251
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   252
    }
wenzelm@27949
   253
wenzelm@27949
   254
wenzelm@38259
   255
  /* message output */
wenzelm@27949
   256
wenzelm@38259
   257
  private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   258
wenzelm@39519
   259
  private def message_actor(name: String): Actor =
wenzelm@38636
   260
    Simple_Thread.actor(name) {
wenzelm@39519
   261
      val stream = system.fifo_input_stream(out_fifo)  // FIXME potentially blocking forever
wenzelm@34100
   262
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   263
      var c = -1
wenzelm@27949
   264
wenzelm@38573
   265
      def read_chunk(): XML.Body =
wenzelm@34100
   266
      {
wenzelm@34100
   267
        //{{{
wenzelm@34100
   268
        // chunk size
wenzelm@34100
   269
        var n = 0
wenzelm@34100
   270
        c = stream.read
wenzelm@34100
   271
        while (48 <= c && c <= 57) {
wenzelm@34100
   272
          n = 10 * n + (c - 48)
wenzelm@34100
   273
          c = stream.read
wenzelm@34100
   274
        }
wenzelm@34100
   275
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   276
wenzelm@34100
   277
        // chunk content
wenzelm@34100
   278
        val buf =
wenzelm@34100
   279
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   280
          else new Array[Byte](n)
wenzelm@34100
   281
wenzelm@34100
   282
        var i = 0
wenzelm@34100
   283
        var m = 0
wenzelm@34100
   284
        do {
wenzelm@34100
   285
          m = stream.read(buf, i, n - i)
wenzelm@34100
   286
          i += m
wenzelm@34100
   287
        } while (m > 0 && n > i)
wenzelm@34100
   288
wenzelm@34100
   289
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   290
wenzelm@34100
   291
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   292
        //}}}
wenzelm@34100
   293
      }
wenzelm@34100
   294
wenzelm@34100
   295
      do {
wenzelm@27949
   296
        try {
wenzelm@38445
   297
          val header = read_chunk()
wenzelm@38445
   298
          val body = read_chunk()
wenzelm@38445
   299
          header match {
wenzelm@38445
   300
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@38445
   301
                if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@38445
   302
              put_result(Kind.markup(name(0)), props, body)
wenzelm@38445
   303
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   304
          }
wenzelm@27963
   305
        }
wenzelm@28063
   306
        catch {
wenzelm@34100
   307
          case e: IOException =>
wenzelm@37689
   308
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   309
          case e: Protocol_Error =>
wenzelm@37689
   310
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   311
        }
wenzelm@34100
   312
      } while (c != -1)
wenzelm@34100
   313
      stream.close
wenzelm@38270
   314
      close()
wenzelm@34100
   315
wenzelm@38259
   316
      put_result(Markup.SYSTEM, name + " terminated")
wenzelm@27949
   317
    }
wenzelm@27949
   318
wenzelm@27949
   319
wenzelm@29192
   320
wenzelm@38259
   321
  /** init **/
wenzelm@38259
   322
wenzelm@38259
   323
  /* exec process */
wenzelm@27949
   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@39519
   339
  private val command_input = input_actor("command_input")
wenzelm@39519
   340
  message_actor("message_output")
wenzelm@39519
   341
wenzelm@38270
   342
  private val standard_input = stdin_actor("standard_input", proc.get.getOutputStream)
wenzelm@38270
   343
  stdout_actor("standard_output", proc.get.getInputStream)
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
}