src/Pure/System/isabelle_process.scala
author wenzelm
Wed Sep 22 13:47:48 2010 +0200 (2010-09-22 ago)
changeset 39585 00be8711082f
parent 39575 c77b9374f45c
child 39587 f84b70e3bb9c
permissions -rw-r--r--
main Isabelle_Process via Isabelle_System.Managed_Process;
simplified init message: no pid;
misc tuning and simplification;
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@39572
    16
import scala.collection.mutable
wenzelm@27949
    17
wenzelm@27973
    18
wenzelm@32474
    19
object Isabelle_Process
wenzelm@32474
    20
{
wenzelm@27949
    21
  /* results */
wenzelm@27949
    22
wenzelm@39525
    23
  object Kind
wenzelm@39525
    24
  {
wenzelm@39525
    25
    val message_markup = Map(
wenzelm@37689
    26
      ('A' : Int) -> Markup.INIT,
wenzelm@37689
    27
      ('B' : Int) -> Markup.STATUS,
wenzelm@38236
    28
      ('C' : Int) -> Markup.REPORT,
wenzelm@38236
    29
      ('D' : Int) -> Markup.WRITELN,
wenzelm@38236
    30
      ('E' : Int) -> Markup.TRACING,
wenzelm@38236
    31
      ('F' : Int) -> Markup.WARNING,
wenzelm@39513
    32
      ('G' : Int) -> Markup.ERROR)
wenzelm@27949
    33
  }
wenzelm@27949
    34
wenzelm@37689
    35
  class Result(val message: XML.Elem)
wenzelm@34100
    36
  {
wenzelm@38230
    37
    def kind = message.markup.name
wenzelm@38230
    38
    def properties = message.markup.properties
wenzelm@37689
    39
    def body = message.body
wenzelm@37689
    40
wenzelm@39525
    41
    def is_init = kind == Markup.INIT
wenzelm@39525
    42
    def is_exit = kind == Markup.EXIT
wenzelm@39525
    43
    def is_stdout = kind == Markup.STDOUT
wenzelm@39525
    44
    def is_system = kind == Markup.SYSTEM
wenzelm@37689
    45
    def is_status = kind == Markup.STATUS
wenzelm@38236
    46
    def is_report = kind == Markup.REPORT
wenzelm@38231
    47
    def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
wenzelm@34100
    48
wenzelm@34100
    49
    override def toString: String =
wenzelm@34100
    50
    {
wenzelm@29522
    51
      val res =
wenzelm@38236
    52
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@37689
    53
        else Pretty.string_of(message.body)
wenzelm@38230
    54
      if (properties.isEmpty)
wenzelm@29572
    55
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    56
      else
wenzelm@29572
    57
        kind.toString + " " +
wenzelm@38230
    58
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    59
    }
wenzelm@27973
    60
  }
wenzelm@27973
    61
}
wenzelm@27973
    62
wenzelm@27973
    63
wenzelm@39528
    64
class Isabelle_Process(system: Isabelle_System, timeout: Int, receiver: Actor, args: String*)
wenzelm@29192
    65
{
wenzelm@31797
    66
  import Isabelle_Process._
wenzelm@29194
    67
wenzelm@27973
    68
wenzelm@29192
    69
  /* demo constructor */
wenzelm@27973
    70
wenzelm@29192
    71
  def this(args: String*) =
wenzelm@39528
    72
    this(new Isabelle_System, 10000,
wenzelm@34213
    73
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    74
wenzelm@29174
    75
wenzelm@39573
    76
  /* system log */
wenzelm@39573
    77
wenzelm@39573
    78
  private val system_results = new mutable.ListBuffer[String]
wenzelm@39573
    79
wenzelm@39573
    80
  private def system_result(text: String)
wenzelm@39573
    81
  {
wenzelm@39573
    82
    synchronized { system_results += text }
wenzelm@39573
    83
    receiver ! new Result(XML.Elem(Markup(Markup.SYSTEM, Nil), List(XML.Text(text))))
wenzelm@39573
    84
  }
wenzelm@39573
    85
wenzelm@39573
    86
  def syslog(): List[String] = synchronized { system_results.toList }
wenzelm@39573
    87
wenzelm@39573
    88
wenzelm@39573
    89
  /* results */
wenzelm@39573
    90
wenzelm@39573
    91
  private val xml_cache = new XML.Cache(131071)
wenzelm@39573
    92
wenzelm@39573
    93
  private def put_result(kind: String, props: List[(String, String)], body: XML.Body)
wenzelm@39573
    94
  {
wenzelm@39585
    95
    if (kind == Markup.INIT) rm_fifos()
wenzelm@39573
    96
    val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@39573
    97
    xml_cache.cache_tree(msg)((message: XML.Tree) =>
wenzelm@39573
    98
      receiver ! new Result(message.asInstanceOf[XML.Elem]))
wenzelm@39573
    99
  }
wenzelm@39573
   100
wenzelm@39573
   101
  private def put_result(kind: String, text: String)
wenzelm@39573
   102
  {
wenzelm@39573
   103
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@39573
   104
  }
wenzelm@39573
   105
wenzelm@39573
   106
wenzelm@39528
   107
  /* input actors */
wenzelm@39528
   108
wenzelm@39528
   109
  private case class Input_Text(text: String)
wenzelm@39528
   110
  private case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@39528
   111
wenzelm@39528
   112
  private case object Close
wenzelm@39585
   113
  private def close(p: (Thread, Actor))
wenzelm@39585
   114
  {
wenzelm@39585
   115
    if (p != null && p._1.isAlive) {
wenzelm@39585
   116
      p._2 ! Close
wenzelm@39585
   117
      p._1.join
wenzelm@39585
   118
    }
wenzelm@39585
   119
  }
wenzelm@39528
   120
wenzelm@39585
   121
  @volatile private var standard_input: (Thread, Actor) = null
wenzelm@39585
   122
  @volatile private var command_input: (Thread, Actor) = null
wenzelm@39528
   123
wenzelm@39528
   124
wenzelm@39585
   125
  /** process manager **/
wenzelm@39528
   126
wenzelm@39528
   127
  private val in_fifo = system.mk_fifo()
wenzelm@39528
   128
  private val out_fifo = system.mk_fifo()
wenzelm@39528
   129
  private def rm_fifos() { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@39528
   130
wenzelm@39585
   131
  private val process =
wenzelm@39528
   132
    try {
wenzelm@39528
   133
      val cmdline =
wenzelm@39528
   134
        List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@39585
   135
      new system.Managed_Process(true, cmdline: _*)
wenzelm@39528
   136
    }
wenzelm@39528
   137
    catch { case e: IOException => rm_fifos(); throw(e) }
wenzelm@39528
   138
wenzelm@39585
   139
  private def terminate_process()
wenzelm@39585
   140
  {
wenzelm@39585
   141
    try { process.terminate }
wenzelm@39585
   142
    catch { case e: IOException => system_result("Failed to terminate Isabelle: " + e.getMessage) }
wenzelm@39585
   143
  }
wenzelm@39528
   144
wenzelm@39585
   145
  private val process_manager = Simple_Thread.fork("process_manager")
wenzelm@39572
   146
  {
wenzelm@39528
   147
    val (startup_failed, startup_output) =
wenzelm@39528
   148
    {
wenzelm@39528
   149
      val expired = System.currentTimeMillis() + timeout
wenzelm@39528
   150
      val result = new StringBuilder(100)
wenzelm@39528
   151
wenzelm@39528
   152
      var finished = false
wenzelm@39528
   153
      while (!finished && System.currentTimeMillis() <= expired) {
wenzelm@39585
   154
        while (!finished && process.stdout.ready) {
wenzelm@39585
   155
          val c = process.stdout.read
wenzelm@39528
   156
          if (c == 2) finished = true
wenzelm@39528
   157
          else result += c.toChar
wenzelm@39528
   158
        }
wenzelm@39528
   159
        Thread.sleep(10)
wenzelm@39528
   160
      }
wenzelm@39528
   161
      (!finished, result.toString)
wenzelm@39528
   162
    }
wenzelm@39572
   163
    system_result(startup_output)
wenzelm@39572
   164
wenzelm@39528
   165
    if (startup_failed) {
wenzelm@39528
   166
      put_result(Markup.EXIT, "127")
wenzelm@39585
   167
      process.stdin.close
wenzelm@39585
   168
      Thread.sleep(300)
wenzelm@39585
   169
      terminate_process()
wenzelm@39528
   170
    }
wenzelm@39528
   171
    else {
wenzelm@39530
   172
      // rendezvous
wenzelm@39530
   173
      val command_stream = system.fifo_output_stream(in_fifo)
wenzelm@39530
   174
      val message_stream = system.fifo_input_stream(out_fifo)
wenzelm@39530
   175
wenzelm@39585
   176
      standard_input = stdin_actor()
wenzelm@39572
   177
      val stdout = stdout_actor()
wenzelm@39585
   178
      command_input = input_actor(command_stream)
wenzelm@39572
   179
      val message = message_actor(message_stream)
wenzelm@39528
   180
wenzelm@39585
   181
      val rc = process.join
wenzelm@39528
   182
      system_result("Isabelle process terminated")
wenzelm@39585
   183
      for ((thread, _) <- List(standard_input, stdout, command_input, message)) thread.join
wenzelm@39572
   184
      system_result("process_manager terminated")
wenzelm@39528
   185
      put_result(Markup.EXIT, rc.toString)
wenzelm@39528
   186
    }
wenzelm@39528
   187
    rm_fifos()
wenzelm@39528
   188
  }
wenzelm@27973
   189
wenzelm@39572
   190
wenzelm@39585
   191
  /* management methods */
wenzelm@27973
   192
wenzelm@39585
   193
  def join() { process_manager.join() }
wenzelm@39528
   194
wenzelm@38270
   195
  def interrupt()
wenzelm@38270
   196
  {
wenzelm@39585
   197
    try { process.interrupt }
wenzelm@39585
   198
    catch { case e: IOException => system_result("Failed to interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   199
  }
wenzelm@27973
   200
wenzelm@39585
   201
  def terminate()
wenzelm@38270
   202
  {
wenzelm@39585
   203
    close()
wenzelm@39585
   204
    system_result("Terminating Isabelle process")
wenzelm@39585
   205
    terminate_process()
wenzelm@27973
   206
  }
wenzelm@27973
   207
wenzelm@27949
   208
wenzelm@27949
   209
wenzelm@38259
   210
  /** stream actors **/
wenzelm@27949
   211
wenzelm@38270
   212
  /* raw stdin */
wenzelm@38270
   213
wenzelm@39572
   214
  private def stdin_actor(): (Thread, Actor) =
wenzelm@39528
   215
  {
wenzelm@39528
   216
    val name = "standard_input"
wenzelm@38636
   217
    Simple_Thread.actor(name) {
wenzelm@27949
   218
      var finished = false
wenzelm@27949
   219
      while (!finished) {
wenzelm@27949
   220
        try {
wenzelm@27949
   221
          //{{{
wenzelm@38259
   222
          receive {
wenzelm@38270
   223
            case Input_Text(text) =>
wenzelm@39585
   224
              process.stdin.write(text)
wenzelm@39585
   225
              process.stdin.flush
wenzelm@38259
   226
            case Close =>
wenzelm@39585
   227
              process.stdin.close
wenzelm@38259
   228
              finished = true
wenzelm@38259
   229
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   230
          }
wenzelm@27949
   231
          //}}}
wenzelm@27949
   232
        }
wenzelm@39525
   233
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   234
      }
wenzelm@39525
   235
      system_result(name + " terminated")
wenzelm@27949
   236
    }
wenzelm@39528
   237
  }
wenzelm@27949
   238
wenzelm@27949
   239
wenzelm@38270
   240
  /* raw stdout */
wenzelm@27949
   241
wenzelm@39572
   242
  private def stdout_actor(): (Thread, Actor) =
wenzelm@39528
   243
  {
wenzelm@39528
   244
    val name = "standard_output"
wenzelm@38636
   245
    Simple_Thread.actor(name) {
wenzelm@28045
   246
      var result = new StringBuilder(100)
wenzelm@27949
   247
wenzelm@27949
   248
      var finished = false
wenzelm@27949
   249
      while (!finished) {
wenzelm@27949
   250
        try {
wenzelm@28045
   251
          //{{{
wenzelm@28045
   252
          var c = -1
wenzelm@28045
   253
          var done = false
wenzelm@39585
   254
          while (!done && (result.length == 0 || process.stdout.ready)) {
wenzelm@39585
   255
            c = process.stdout.read
wenzelm@28045
   256
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   257
            else done = true
wenzelm@28045
   258
          }
wenzelm@28045
   259
          if (result.length > 0) {
wenzelm@38270
   260
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   261
            result.length = 0
wenzelm@27949
   262
          }
wenzelm@27949
   263
          else {
wenzelm@39585
   264
            process.stdout.close
wenzelm@28045
   265
            finished = true
wenzelm@38270
   266
          }
wenzelm@38270
   267
          //}}}
wenzelm@38270
   268
        }
wenzelm@39525
   269
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@38270
   270
      }
wenzelm@39525
   271
      system_result(name + " terminated")
wenzelm@38270
   272
    }
wenzelm@39528
   273
  }
wenzelm@38270
   274
wenzelm@38270
   275
wenzelm@38270
   276
  /* command input */
wenzelm@38270
   277
wenzelm@39572
   278
  private def input_actor(raw_stream: OutputStream): (Thread, Actor) =
wenzelm@39528
   279
  {
wenzelm@39528
   280
    val name = "command_input"
wenzelm@38636
   281
    Simple_Thread.actor(name) {
wenzelm@39530
   282
      val stream = new BufferedOutputStream(raw_stream)
wenzelm@38270
   283
      var finished = false
wenzelm@38270
   284
      while (!finished) {
wenzelm@38270
   285
        try {
wenzelm@38270
   286
          //{{{
wenzelm@38270
   287
          receive {
wenzelm@38270
   288
            case Input_Chunks(chunks) =>
wenzelm@38270
   289
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   290
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   291
              chunks.foreach(stream.write(_));
wenzelm@38270
   292
              stream.flush
wenzelm@38270
   293
            case Close =>
wenzelm@38270
   294
              stream.close
wenzelm@38270
   295
              finished = true
wenzelm@38270
   296
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   297
          }
wenzelm@28045
   298
          //}}}
wenzelm@27963
   299
        }
wenzelm@39525
   300
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   301
      }
wenzelm@39525
   302
      system_result(name + " terminated")
wenzelm@27949
   303
    }
wenzelm@39528
   304
  }
wenzelm@27949
   305
wenzelm@27949
   306
wenzelm@38259
   307
  /* message output */
wenzelm@27949
   308
wenzelm@39572
   309
  private def message_actor(stream: InputStream): (Thread, Actor) =
wenzelm@39526
   310
  {
wenzelm@39526
   311
    class EOF extends Exception
wenzelm@39526
   312
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   313
wenzelm@39528
   314
    val name = "message_output"
wenzelm@38636
   315
    Simple_Thread.actor(name) {
wenzelm@34100
   316
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   317
      var c = -1
wenzelm@27949
   318
wenzelm@38573
   319
      def read_chunk(): XML.Body =
wenzelm@34100
   320
      {
wenzelm@34100
   321
        //{{{
wenzelm@34100
   322
        // chunk size
wenzelm@34100
   323
        var n = 0
wenzelm@34100
   324
        c = stream.read
wenzelm@39526
   325
        if (c == -1) throw new EOF
wenzelm@34100
   326
        while (48 <= c && c <= 57) {
wenzelm@34100
   327
          n = 10 * n + (c - 48)
wenzelm@34100
   328
          c = stream.read
wenzelm@34100
   329
        }
wenzelm@34100
   330
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   331
wenzelm@34100
   332
        // chunk content
wenzelm@34100
   333
        val buf =
wenzelm@34100
   334
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   335
          else new Array[Byte](n)
wenzelm@34100
   336
wenzelm@34100
   337
        var i = 0
wenzelm@34100
   338
        var m = 0
wenzelm@34100
   339
        do {
wenzelm@34100
   340
          m = stream.read(buf, i, n - i)
wenzelm@34100
   341
          i += m
wenzelm@34100
   342
        } while (m > 0 && n > i)
wenzelm@34100
   343
wenzelm@34100
   344
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   345
wenzelm@34100
   346
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   347
        //}}}
wenzelm@34100
   348
      }
wenzelm@34100
   349
wenzelm@34100
   350
      do {
wenzelm@27949
   351
        try {
wenzelm@38445
   352
          val header = read_chunk()
wenzelm@38445
   353
          val body = read_chunk()
wenzelm@38445
   354
          header match {
wenzelm@38445
   355
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@39525
   356
                if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
wenzelm@39525
   357
              put_result(Kind.message_markup(name(0)), props, body)
wenzelm@38445
   358
            case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   359
          }
wenzelm@27963
   360
        }
wenzelm@28063
   361
        catch {
wenzelm@39525
   362
          case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
wenzelm@39525
   363
          case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
wenzelm@39526
   364
          case _: EOF =>
wenzelm@28063
   365
        }
wenzelm@34100
   366
      } while (c != -1)
wenzelm@34100
   367
      stream.close
wenzelm@34100
   368
wenzelm@39525
   369
      system_result(name + " terminated")
wenzelm@27949
   370
    }
wenzelm@39526
   371
  }
wenzelm@27949
   372
wenzelm@27949
   373
wenzelm@38259
   374
  /** main methods **/
wenzelm@38259
   375
wenzelm@39585
   376
  def input_raw(text: String): Unit = standard_input._2 ! Input_Text(text)
wenzelm@38259
   377
wenzelm@38372
   378
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@39585
   379
    command_input._2 ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   380
wenzelm@38270
   381
  def input(name: String, args: String*): Unit =
wenzelm@38372
   382
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@38259
   383
wenzelm@39528
   384
  def close(): Unit = { close(command_input); close(standard_input) }
wenzelm@27949
   385
}