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