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