src/Pure/System/isabelle_process.scala
author wenzelm
Mon Nov 28 22:05:32 2011 +0100 (2011-11-28 ago)
changeset 45666 d83797ef0d2d
parent 45633 2cb7e34f6096
child 45672 a497c5d4a523
permissions -rw-r--r--
separate module for concrete Isabelle markup;
wenzelm@43283
     1
/*  Title:      Pure/System/isabelle_process.scala
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@43520
    10
import java.lang.System
wenzelm@27955
    11
import java.util.concurrent.LinkedBlockingQueue
wenzelm@28045
    12
import java.io.{BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter,
wenzelm@38270
    13
  InputStream, OutputStream, BufferedOutputStream, IOException}
wenzelm@27949
    14
wenzelm@32474
    15
import scala.actors.Actor
wenzelm@32474
    16
import Actor._
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@45666
    26
      ('A' : Int) -> Isabelle_Markup.INIT,
wenzelm@45666
    27
      ('B' : Int) -> Isabelle_Markup.STATUS,
wenzelm@45666
    28
      ('C' : Int) -> Isabelle_Markup.REPORT,
wenzelm@45666
    29
      ('D' : Int) -> Isabelle_Markup.WRITELN,
wenzelm@45666
    30
      ('E' : Int) -> Isabelle_Markup.TRACING,
wenzelm@45666
    31
      ('F' : Int) -> Isabelle_Markup.WARNING,
wenzelm@45666
    32
      ('G' : Int) -> Isabelle_Markup.ERROR,
wenzelm@45666
    33
      ('H' : Int) -> Isabelle_Markup.RAW)
wenzelm@27949
    34
  }
wenzelm@27949
    35
wenzelm@44733
    36
  sealed abstract class Message
wenzelm@43721
    37
wenzelm@43721
    38
  class Input(name: String, args: List[String]) extends Message
wenzelm@43721
    39
  {
wenzelm@43721
    40
    override def toString: String =
wenzelm@45666
    41
      XML.Elem(Markup(Isabelle_Markup.PROVER_COMMAND, List((Markup.NAME, name))),
wenzelm@43721
    42
        args.map(s =>
wenzelm@45666
    43
          List(XML.Text("\n"),
wenzelm@45666
    44
            XML.elem(Isabelle_Markup.PROVER_ARG, YXML.parse_body(s)))).flatten).toString
wenzelm@43721
    45
  }
wenzelm@43721
    46
wenzelm@43721
    47
  class Result(val message: XML.Elem) extends Message
wenzelm@34100
    48
  {
wenzelm@43747
    49
    def kind: String = message.markup.name
wenzelm@43780
    50
    def properties: Properties.T = message.markup.properties
wenzelm@43747
    51
    def body: XML.Body = message.body
wenzelm@37689
    52
wenzelm@45666
    53
    def is_init = kind == Isabelle_Markup.INIT
wenzelm@45666
    54
    def is_exit = kind == Isabelle_Markup.EXIT
wenzelm@45666
    55
    def is_stdout = kind == Isabelle_Markup.STDOUT
wenzelm@45666
    56
    def is_stderr = kind == Isabelle_Markup.STDERR
wenzelm@45666
    57
    def is_system = kind == Isabelle_Markup.SYSTEM
wenzelm@45666
    58
    def is_status = kind == Isabelle_Markup.STATUS
wenzelm@45666
    59
    def is_report = kind == Isabelle_Markup.REPORT
wenzelm@45666
    60
    def is_raw = kind == Isabelle_Markup.RAW
wenzelm@39625
    61
    def is_ready = Isar_Document.is_ready(message)
wenzelm@45633
    62
    def is_syslog = is_init || is_exit || is_system || is_ready || is_stderr
wenzelm@34100
    63
wenzelm@34100
    64
    override def toString: String =
wenzelm@34100
    65
    {
wenzelm@29522
    66
      val res =
wenzelm@38236
    67
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@43748
    68
        else if (is_raw) "..."
wenzelm@37689
    69
        else Pretty.string_of(message.body)
wenzelm@38230
    70
      if (properties.isEmpty)
wenzelm@29572
    71
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    72
      else
wenzelm@29572
    73
        kind.toString + " " +
wenzelm@38230
    74
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    75
    }
wenzelm@27973
    76
  }
wenzelm@27973
    77
}
wenzelm@27973
    78
wenzelm@27973
    79
wenzelm@45055
    80
class Isabelle_Process(
wenzelm@45075
    81
    timeout: Time = Time.seconds(25),
wenzelm@45055
    82
    receiver: Isabelle_Process.Message => Unit = Console.println(_),
wenzelm@45055
    83
    args: List[String] = Nil)
wenzelm@29192
    84
{
wenzelm@31797
    85
  import Isabelle_Process._
wenzelm@29194
    86
wenzelm@27973
    87
wenzelm@39626
    88
  /* results */
wenzelm@39573
    89
wenzelm@39573
    90
  private def system_result(text: String)
wenzelm@39573
    91
  {
wenzelm@45666
    92
    receiver(new Result(XML.Elem(Markup(Isabelle_Markup.SYSTEM, Nil), List(XML.Text(text)))))
wenzelm@39573
    93
  }
wenzelm@39573
    94
wenzelm@43745
    95
  private val xml_cache = new XML.Cache()
wenzelm@39573
    96
wenzelm@43780
    97
  private def put_result(kind: String, props: Properties.T, body: XML.Body)
wenzelm@39573
    98
  {
wenzelm@45666
    99
    if (kind == Isabelle_Markup.INIT) system_channel.accepted()
wenzelm@45666
   100
    if (kind == Isabelle_Markup.RAW)
wenzelm@44732
   101
      receiver(new Result(XML.Elem(Markup(kind, props), body)))
wenzelm@43746
   102
    else {
wenzelm@43746
   103
      val msg = XML.Elem(Markup(kind, props), Isar_Document.clean_message(body))
wenzelm@44732
   104
      receiver(new Result(xml_cache.cache_tree(msg).asInstanceOf[XML.Elem]))
wenzelm@43746
   105
    }
wenzelm@39573
   106
  }
wenzelm@39573
   107
wenzelm@39573
   108
  private def put_result(kind: String, text: String)
wenzelm@39573
   109
  {
wenzelm@43695
   110
    put_result(kind, Nil, List(XML.Text(Symbol.decode(text))))
wenzelm@39573
   111
  }
wenzelm@39573
   112
wenzelm@39573
   113
wenzelm@39528
   114
  /* input actors */
wenzelm@39528
   115
wenzelm@39528
   116
  private case class Input_Text(text: String)
wenzelm@39528
   117
  private case class Input_Chunks(chunks: List[Array[Byte]])
wenzelm@39528
   118
wenzelm@39528
   119
  private case object Close
wenzelm@39585
   120
  private def close(p: (Thread, Actor))
wenzelm@39585
   121
  {
wenzelm@39585
   122
    if (p != null && p._1.isAlive) {
wenzelm@39585
   123
      p._2 ! Close
wenzelm@39585
   124
      p._1.join
wenzelm@39585
   125
    }
wenzelm@39585
   126
  }
wenzelm@39528
   127
wenzelm@39585
   128
  @volatile private var standard_input: (Thread, Actor) = null
wenzelm@39585
   129
  @volatile private var command_input: (Thread, Actor) = null
wenzelm@39528
   130
wenzelm@39528
   131
wenzelm@39585
   132
  /** process manager **/
wenzelm@39528
   133
wenzelm@45158
   134
  private val system_channel = System_Channel()
wenzelm@39528
   135
wenzelm@39585
   136
  private val process =
wenzelm@39528
   137
    try {
wenzelm@39528
   138
      val cmdline =
wenzelm@45027
   139
        Isabelle_System.getenv_strict("ISABELLE_PROCESS") ::
wenzelm@45055
   140
          (system_channel.isabelle_args ::: args)
wenzelm@45633
   141
      new Isabelle_System.Managed_Process(false, cmdline: _*)
wenzelm@39528
   142
    }
wenzelm@45027
   143
    catch { case e: IOException => system_channel.accepted(); throw(e) }
wenzelm@39528
   144
wenzelm@39587
   145
  val process_result =
wenzelm@39587
   146
    Simple_Thread.future("process_result") { process.join }
wenzelm@39587
   147
wenzelm@39585
   148
  private def terminate_process()
wenzelm@39585
   149
  {
wenzelm@39585
   150
    try { process.terminate }
wenzelm@39585
   151
    catch { case e: IOException => system_result("Failed to terminate Isabelle: " + e.getMessage) }
wenzelm@39585
   152
  }
wenzelm@39528
   153
wenzelm@39585
   154
  private val process_manager = Simple_Thread.fork("process_manager")
wenzelm@39572
   155
  {
wenzelm@39528
   156
    val (startup_failed, startup_output) =
wenzelm@39528
   157
    {
wenzelm@40848
   158
      val expired = System.currentTimeMillis() + timeout.ms
wenzelm@39528
   159
      val result = new StringBuilder(100)
wenzelm@39528
   160
wenzelm@39587
   161
      var finished: Option[Boolean] = None
wenzelm@39587
   162
      while (finished.isEmpty && System.currentTimeMillis() <= expired) {
wenzelm@39587
   163
        while (finished.isEmpty && process.stdout.ready) {
wenzelm@39585
   164
          val c = process.stdout.read
wenzelm@39587
   165
          if (c == 2) finished = Some(true)
wenzelm@39528
   166
          else result += c.toChar
wenzelm@39528
   167
        }
wenzelm@39587
   168
        if (process_result.is_finished) finished = Some(false)
wenzelm@39587
   169
        else Thread.sleep(10)
wenzelm@39528
   170
      }
wenzelm@39623
   171
      (finished.isEmpty || !finished.get, result.toString.trim)
wenzelm@39528
   172
    }
wenzelm@39572
   173
    system_result(startup_output)
wenzelm@39572
   174
wenzelm@39528
   175
    if (startup_failed) {
wenzelm@45666
   176
      put_result(Isabelle_Markup.EXIT, "Return code: 127")
wenzelm@39585
   177
      process.stdin.close
wenzelm@39585
   178
      Thread.sleep(300)
wenzelm@39585
   179
      terminate_process()
wenzelm@39587
   180
      process_result.join
wenzelm@39528
   181
    }
wenzelm@39528
   182
    else {
wenzelm@45027
   183
      val (command_stream, message_stream) = system_channel.rendezvous()
wenzelm@39530
   184
wenzelm@39585
   185
      standard_input = stdin_actor()
wenzelm@45633
   186
      val stdout = raw_output_actor(false)
wenzelm@45633
   187
      val stderr = raw_output_actor(true)
wenzelm@39585
   188
      command_input = input_actor(command_stream)
wenzelm@39572
   189
      val message = message_actor(message_stream)
wenzelm@39528
   190
wenzelm@39587
   191
      val rc = process_result.join
wenzelm@39618
   192
      system_result("process terminated")
wenzelm@45633
   193
      for ((thread, _) <- List(standard_input, stdout, stderr, command_input, message))
wenzelm@45633
   194
        thread.join
wenzelm@39572
   195
      system_result("process_manager terminated")
wenzelm@45666
   196
      put_result(Isabelle_Markup.EXIT, "Return code: " + rc.toString)
wenzelm@39528
   197
    }
wenzelm@45027
   198
    system_channel.accepted()
wenzelm@39528
   199
  }
wenzelm@27973
   200
wenzelm@39572
   201
wenzelm@39585
   202
  /* management methods */
wenzelm@27973
   203
wenzelm@39585
   204
  def join() { process_manager.join() }
wenzelm@39528
   205
wenzelm@39585
   206
  def terminate()
wenzelm@38270
   207
  {
wenzelm@39585
   208
    close()
wenzelm@39585
   209
    system_result("Terminating Isabelle process")
wenzelm@39585
   210
    terminate_process()
wenzelm@27973
   211
  }
wenzelm@27973
   212
wenzelm@27949
   213
wenzelm@27949
   214
wenzelm@38259
   215
  /** stream actors **/
wenzelm@27949
   216
wenzelm@38270
   217
  /* raw stdin */
wenzelm@38270
   218
wenzelm@39572
   219
  private def stdin_actor(): (Thread, Actor) =
wenzelm@39528
   220
  {
wenzelm@39528
   221
    val name = "standard_input"
wenzelm@38636
   222
    Simple_Thread.actor(name) {
wenzelm@27949
   223
      var finished = false
wenzelm@27949
   224
      while (!finished) {
wenzelm@27949
   225
        try {
wenzelm@27949
   226
          //{{{
wenzelm@38259
   227
          receive {
wenzelm@38270
   228
            case Input_Text(text) =>
wenzelm@39585
   229
              process.stdin.write(text)
wenzelm@39585
   230
              process.stdin.flush
wenzelm@38259
   231
            case Close =>
wenzelm@39585
   232
              process.stdin.close
wenzelm@38259
   233
              finished = true
wenzelm@38259
   234
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   235
          }
wenzelm@27949
   236
          //}}}
wenzelm@27949
   237
        }
wenzelm@39525
   238
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   239
      }
wenzelm@39525
   240
      system_result(name + " terminated")
wenzelm@27949
   241
    }
wenzelm@39528
   242
  }
wenzelm@27949
   243
wenzelm@27949
   244
wenzelm@45633
   245
  /* raw output */
wenzelm@27949
   246
wenzelm@45633
   247
  private def raw_output_actor(err: Boolean): (Thread, Actor) =
wenzelm@39528
   248
  {
wenzelm@45633
   249
    val (name, reader, markup) =
wenzelm@45666
   250
      if (err) ("standard_error", process.stderr, Isabelle_Markup.STDERR)
wenzelm@45666
   251
      else ("standard_output", process.stdout, Isabelle_Markup.STDOUT)
wenzelm@45633
   252
wenzelm@38636
   253
    Simple_Thread.actor(name) {
wenzelm@28045
   254
      var result = new StringBuilder(100)
wenzelm@27949
   255
wenzelm@27949
   256
      var finished = false
wenzelm@27949
   257
      while (!finished) {
wenzelm@27949
   258
        try {
wenzelm@28045
   259
          //{{{
wenzelm@28045
   260
          var c = -1
wenzelm@28045
   261
          var done = false
wenzelm@45633
   262
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@45633
   263
            c = reader.read
wenzelm@28045
   264
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   265
            else done = true
wenzelm@28045
   266
          }
wenzelm@28045
   267
          if (result.length > 0) {
wenzelm@45633
   268
            put_result(markup, result.toString)
wenzelm@28045
   269
            result.length = 0
wenzelm@27949
   270
          }
wenzelm@27949
   271
          else {
wenzelm@45633
   272
            reader.close
wenzelm@28045
   273
            finished = true
wenzelm@38270
   274
          }
wenzelm@38270
   275
          //}}}
wenzelm@38270
   276
        }
wenzelm@39525
   277
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@38270
   278
      }
wenzelm@39525
   279
      system_result(name + " terminated")
wenzelm@38270
   280
    }
wenzelm@39528
   281
  }
wenzelm@38270
   282
wenzelm@38270
   283
wenzelm@38270
   284
  /* command input */
wenzelm@38270
   285
wenzelm@39572
   286
  private def input_actor(raw_stream: OutputStream): (Thread, Actor) =
wenzelm@39528
   287
  {
wenzelm@39528
   288
    val name = "command_input"
wenzelm@38636
   289
    Simple_Thread.actor(name) {
wenzelm@39530
   290
      val stream = new BufferedOutputStream(raw_stream)
wenzelm@38270
   291
      var finished = false
wenzelm@38270
   292
      while (!finished) {
wenzelm@38270
   293
        try {
wenzelm@38270
   294
          //{{{
wenzelm@38270
   295
          receive {
wenzelm@38270
   296
            case Input_Chunks(chunks) =>
wenzelm@38270
   297
              stream.write(Standard_System.string_bytes(
wenzelm@38270
   298
                  chunks.map(_.length).mkString("", ",", "\n")));
wenzelm@38270
   299
              chunks.foreach(stream.write(_));
wenzelm@38270
   300
              stream.flush
wenzelm@38270
   301
            case Close =>
wenzelm@38270
   302
              stream.close
wenzelm@38270
   303
              finished = true
wenzelm@38270
   304
            case bad => System.err.println(name + ": ignoring bad message " + bad)
wenzelm@27949
   305
          }
wenzelm@28045
   306
          //}}}
wenzelm@27963
   307
        }
wenzelm@39525
   308
        catch { case e: IOException => system_result(name + ": " + e.getMessage) }
wenzelm@27949
   309
      }
wenzelm@39525
   310
      system_result(name + " terminated")
wenzelm@27949
   311
    }
wenzelm@39528
   312
  }
wenzelm@27949
   313
wenzelm@27949
   314
wenzelm@38259
   315
  /* message output */
wenzelm@27949
   316
wenzelm@39572
   317
  private def message_actor(stream: InputStream): (Thread, Actor) =
wenzelm@39526
   318
  {
wenzelm@39526
   319
    class EOF extends Exception
wenzelm@39526
   320
    class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@38259
   321
wenzelm@39528
   322
    val name = "message_output"
wenzelm@38636
   323
    Simple_Thread.actor(name) {
wenzelm@34100
   324
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   325
      var c = -1
wenzelm@27949
   326
wenzelm@43746
   327
      def read_chunk(decode: Boolean): XML.Body =
wenzelm@34100
   328
      {
wenzelm@34100
   329
        //{{{
wenzelm@34100
   330
        // chunk size
wenzelm@34100
   331
        var n = 0
wenzelm@34100
   332
        c = stream.read
wenzelm@39526
   333
        if (c == -1) throw new EOF
wenzelm@34100
   334
        while (48 <= c && c <= 57) {
wenzelm@34100
   335
          n = 10 * n + (c - 48)
wenzelm@34100
   336
          c = stream.read
wenzelm@34100
   337
        }
wenzelm@34100
   338
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   339
wenzelm@34100
   340
        // chunk content
wenzelm@34100
   341
        val buf =
wenzelm@34100
   342
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   343
          else new Array[Byte](n)
wenzelm@34100
   344
wenzelm@34100
   345
        var i = 0
wenzelm@34100
   346
        var m = 0
wenzelm@34100
   347
        do {
wenzelm@34100
   348
          m = stream.read(buf, i, n - i)
wenzelm@39731
   349
          if (m != -1) i += m
wenzelm@39731
   350
        } while (m != -1 && n > i)
wenzelm@34100
   351
wenzelm@34100
   352
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   353
wenzelm@43746
   354
        if (decode)
wenzelm@43746
   355
          YXML.parse_body_failsafe(Standard_System.decode_chars(Symbol.decode, buf, 0, n))
wenzelm@43746
   356
        else List(XML.Text(Standard_System.decode_chars(s => s, buf, 0, n).toString))
wenzelm@34100
   357
        //}}}
wenzelm@34100
   358
      }
wenzelm@34100
   359
wenzelm@34100
   360
      do {
wenzelm@27949
   361
        try {
wenzelm@43746
   362
          val header = read_chunk(true)
wenzelm@38445
   363
          header match {
wenzelm@38445
   364
            case List(XML.Elem(Markup(name, props), Nil))
wenzelm@39525
   365
                if name.size == 1 && Kind.message_markup.isDefinedAt(name(0)) =>
wenzelm@43746
   366
              val kind = Kind.message_markup(name(0))
wenzelm@45666
   367
              val body = read_chunk(kind != Isabelle_Markup.RAW)
wenzelm@43746
   368
              put_result(kind, props, body)
wenzelm@43746
   369
            case _ =>
wenzelm@43746
   370
              read_chunk(false)
wenzelm@43746
   371
              throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   372
          }
wenzelm@27963
   373
        }
wenzelm@28063
   374
        catch {
wenzelm@39525
   375
          case e: IOException => system_result("Cannot read message:\n" + e.getMessage)
wenzelm@39525
   376
          case e: Protocol_Error => system_result("Malformed message:\n" + e.getMessage)
wenzelm@39526
   377
          case _: EOF =>
wenzelm@28063
   378
        }
wenzelm@34100
   379
      } while (c != -1)
wenzelm@34100
   380
      stream.close
wenzelm@34100
   381
wenzelm@39525
   382
      system_result(name + " terminated")
wenzelm@27949
   383
    }
wenzelm@39526
   384
  }
wenzelm@27949
   385
wenzelm@27949
   386
wenzelm@38259
   387
  /** main methods **/
wenzelm@38259
   388
wenzelm@39585
   389
  def input_raw(text: String): Unit = standard_input._2 ! Input_Text(text)
wenzelm@38259
   390
wenzelm@38372
   391
  def input_bytes(name: String, args: Array[Byte]*): Unit =
wenzelm@39585
   392
    command_input._2 ! Input_Chunks(Standard_System.string_bytes(name) :: args.toList)
wenzelm@38372
   393
wenzelm@38270
   394
  def input(name: String, args: String*): Unit =
wenzelm@43721
   395
  {
wenzelm@44732
   396
    receiver(new Input(name, args.toList))
wenzelm@38372
   397
    input_bytes(name, args.map(Standard_System.string_bytes): _*)
wenzelm@43721
   398
  }
wenzelm@38259
   399
wenzelm@39528
   400
  def close(): Unit = { close(command_input); close(standard_input) }
wenzelm@27949
   401
}