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