src/Pure/System/isabelle_process.scala
author wenzelm
Mon Aug 09 18:18:32 2010 +0200 (2010-08-09 ago)
changeset 38253 3d4e521014f7
parent 38236 d8c7be27e01d
child 38259 2b61c5e27399
permissions -rw-r--r--
Isabelle_Process: separate input fifo for commands (still using the old tty protocol);
some partial workarounds for Cygwin;
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@28056
    12
  InputStream, OutputStream, 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@37689
    22
  object Kind {
wenzelm@29522
    23
    // message markup
wenzelm@29522
    24
    val 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@38236
    31
      ('G' : Int) -> Markup.ERROR,
wenzelm@38236
    32
      ('H' : Int) -> Markup.DEBUG)
wenzelm@37689
    33
    def is_raw(kind: String) =
wenzelm@37689
    34
      kind == Markup.STDOUT
wenzelm@37689
    35
    def is_control(kind: String) =
wenzelm@37689
    36
      kind == Markup.SYSTEM ||
wenzelm@37689
    37
      kind == Markup.SIGNAL ||
wenzelm@37689
    38
      kind == Markup.EXIT
wenzelm@37689
    39
    def is_system(kind: String) =
wenzelm@37689
    40
      kind == Markup.SYSTEM ||
wenzelm@37689
    41
      kind == Markup.STDIN ||
wenzelm@37689
    42
      kind == Markup.SIGNAL ||
wenzelm@37689
    43
      kind == Markup.EXIT ||
wenzelm@37689
    44
      kind == Markup.STATUS
wenzelm@27949
    45
  }
wenzelm@27949
    46
wenzelm@37689
    47
  class Result(val message: XML.Elem)
wenzelm@34100
    48
  {
wenzelm@38230
    49
    def kind = message.markup.name
wenzelm@38230
    50
    def properties = message.markup.properties
wenzelm@37689
    51
    def body = message.body
wenzelm@37689
    52
wenzelm@37689
    53
    def is_raw = Kind.is_raw(kind)
wenzelm@37689
    54
    def is_control = Kind.is_control(kind)
wenzelm@37689
    55
    def is_system = Kind.is_system(kind)
wenzelm@37689
    56
    def is_status = kind == Markup.STATUS
wenzelm@38236
    57
    def is_report = kind == Markup.REPORT
wenzelm@38231
    58
    def is_ready = is_status && body == List(XML.Elem(Markup.Ready, Nil))
wenzelm@34100
    59
wenzelm@34100
    60
    override def toString: String =
wenzelm@34100
    61
    {
wenzelm@29522
    62
      val res =
wenzelm@38236
    63
        if (is_status || is_report) message.body.map(_.toString).mkString
wenzelm@37689
    64
        else Pretty.string_of(message.body)
wenzelm@38230
    65
      if (properties.isEmpty)
wenzelm@29572
    66
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    67
      else
wenzelm@29572
    68
        kind.toString + " " +
wenzelm@38230
    69
          (for ((x, y) <- properties) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    70
    }
wenzelm@34109
    71
wenzelm@37689
    72
    def cache(c: XML.Cache): Result = new Result(c.cache_tree(message).asInstanceOf[XML.Elem])
wenzelm@27973
    73
  }
wenzelm@27973
    74
}
wenzelm@27973
    75
wenzelm@27973
    76
wenzelm@34100
    77
class Isabelle_Process(system: Isabelle_System, receiver: Actor, args: String*)
wenzelm@29192
    78
{
wenzelm@31797
    79
  import Isabelle_Process._
wenzelm@29194
    80
wenzelm@27973
    81
wenzelm@29192
    82
  /* demo constructor */
wenzelm@27973
    83
wenzelm@29192
    84
  def this(args: String*) =
wenzelm@32474
    85
    this(new Isabelle_System,
wenzelm@34213
    86
      actor { loop { react { case res => Console.println(res) } } }, args: _*)
wenzelm@29174
    87
wenzelm@29174
    88
wenzelm@27973
    89
  /* process information */
wenzelm@27973
    90
wenzelm@29648
    91
  @volatile private var proc: Process = null
wenzelm@29648
    92
  @volatile private var closing = false
wenzelm@29648
    93
  @volatile private var pid: String = null
wenzelm@27973
    94
wenzelm@27973
    95
wenzelm@27973
    96
  /* results */
wenzelm@27949
    97
wenzelm@37689
    98
  private def put_result(kind: String, props: List[(String, String)], body: List[XML.Tree])
wenzelm@29572
    99
  {
wenzelm@37689
   100
    if (kind == Markup.INIT) {
wenzelm@34214
   101
      for ((Markup.PID, p) <- props) pid = p
wenzelm@27963
   102
    }
wenzelm@38230
   103
    receiver ! new Result(XML.Elem(Markup(kind, props), body))
wenzelm@34100
   104
  }
wenzelm@34100
   105
wenzelm@37689
   106
  private def put_result(kind: String, text: String)
wenzelm@34100
   107
  {
wenzelm@34100
   108
    put_result(kind, Nil, List(XML.Text(system.symbols.decode(text))))
wenzelm@27992
   109
  }
wenzelm@27992
   110
wenzelm@27973
   111
wenzelm@27973
   112
  /* signals */
wenzelm@27973
   113
wenzelm@27973
   114
  def interrupt() = synchronized {
wenzelm@27993
   115
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@37689
   116
    if (pid == null) put_result(Markup.SYSTEM, "Cannot interrupt: unknown pid")
wenzelm@27973
   117
    else {
wenzelm@27973
   118
      try {
wenzelm@34100
   119
        if (system.execute(true, "kill", "-INT", pid).waitFor == 0)
wenzelm@37689
   120
          put_result(Markup.SIGNAL, "INT")
wenzelm@27990
   121
        else
wenzelm@37689
   122
          put_result(Markup.SYSTEM, "Cannot interrupt: kill command failed")
wenzelm@27973
   123
      }
wenzelm@27993
   124
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   125
    }
wenzelm@27973
   126
  }
wenzelm@27973
   127
wenzelm@27973
   128
  def kill() = synchronized {
wenzelm@27993
   129
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   130
    else {
wenzelm@27973
   131
      try_close()
wenzelm@37132
   132
      Thread.sleep(500)  // FIXME property!?
wenzelm@37689
   133
      put_result(Markup.SIGNAL, "KILL")
wenzelm@27973
   134
      proc.destroy
wenzelm@27973
   135
      proc = null
wenzelm@27990
   136
      pid = null
wenzelm@27973
   137
    }
wenzelm@27973
   138
  }
wenzelm@27973
   139
wenzelm@27949
   140
wenzelm@27949
   141
  /* output being piped into the process */
wenzelm@27949
   142
wenzelm@27990
   143
  private val output = new LinkedBlockingQueue[String]
wenzelm@27949
   144
wenzelm@28045
   145
  private def output_raw(text: String) = synchronized {
wenzelm@27993
   146
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@27993
   147
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@27955
   148
    output.put(text)
wenzelm@27949
   149
  }
wenzelm@27949
   150
wenzelm@28303
   151
  def output_sync(text: String) =
wenzelm@28045
   152
    output_raw(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@27949
   153
wenzelm@27963
   154
wenzelm@27963
   155
  def command(text: String) =
wenzelm@32448
   156
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   157
wenzelm@29572
   158
  def command(props: List[(String, String)], text: String) =
wenzelm@32448
   159
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_properties(props) + " " +
wenzelm@32448
   160
      Isabelle_Syntax.encode_string(text))
wenzelm@27949
   161
wenzelm@37712
   162
  def ML_val(text: String) =
wenzelm@32448
   163
    output_sync("ML_val " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   164
wenzelm@37712
   165
  def ML_command(text: String) =
wenzelm@37712
   166
    output_sync("ML_command " + Isabelle_Syntax.encode_string(text))
wenzelm@37712
   167
wenzelm@27949
   168
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   169
    output_raw("\u0000")
wenzelm@27949
   170
    closing = true
wenzelm@27949
   171
  }
wenzelm@27949
   172
wenzelm@27949
   173
  def try_close() = synchronized {
wenzelm@27949
   174
    if (proc != null && !closing) {
wenzelm@27949
   175
      try { close() }
wenzelm@27993
   176
      catch { case _: RuntimeException => }
wenzelm@27949
   177
    }
wenzelm@27949
   178
  }
wenzelm@27949
   179
wenzelm@27949
   180
wenzelm@38253
   181
  /* commands */
wenzelm@27949
   182
wenzelm@38253
   183
  private class Command_Thread(fifo: String) extends Thread("isabelle: commands")
wenzelm@38253
   184
  {
wenzelm@38253
   185
    override def run()
wenzelm@38253
   186
    {
wenzelm@38253
   187
      val stream = system.fifo_output_stream(fifo)
wenzelm@38253
   188
      val writer = new BufferedWriter(new OutputStreamWriter(stream, Standard_System.charset))
wenzelm@27949
   189
      var finished = false
wenzelm@27949
   190
      while (!finished) {
wenzelm@27949
   191
        try {
wenzelm@27949
   192
          //{{{
wenzelm@27955
   193
          val s = output.take
wenzelm@27949
   194
          if (s == "\u0000") {
wenzelm@27949
   195
            writer.close
wenzelm@27949
   196
            finished = true
wenzelm@27949
   197
          }
wenzelm@27949
   198
          else {
wenzelm@37689
   199
            put_result(Markup.STDIN, s)
wenzelm@27949
   200
            writer.write(s)
wenzelm@27949
   201
            writer.flush
wenzelm@27949
   202
          }
wenzelm@27949
   203
          //}}}
wenzelm@27949
   204
        }
wenzelm@27949
   205
        catch {
wenzelm@38253
   206
          case e: IOException => put_result(Markup.SYSTEM, "Command thread: " + e.getMessage)
wenzelm@27949
   207
        }
wenzelm@27949
   208
      }
wenzelm@38253
   209
      put_result(Markup.SYSTEM, "Command thread terminated")
wenzelm@27949
   210
    }
wenzelm@27949
   211
  }
wenzelm@27949
   212
wenzelm@27949
   213
wenzelm@38253
   214
  /* raw stdout */
wenzelm@27949
   215
wenzelm@38253
   216
  private class Stdout_Thread(stream: InputStream) extends Thread("isabelle: stdout")
wenzelm@38253
   217
  {
wenzelm@38253
   218
    override def run() =
wenzelm@38253
   219
    {
wenzelm@38253
   220
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@28045
   221
      var result = new StringBuilder(100)
wenzelm@27949
   222
wenzelm@27949
   223
      var finished = false
wenzelm@27949
   224
      while (!finished) {
wenzelm@27949
   225
        try {
wenzelm@28045
   226
          //{{{
wenzelm@28045
   227
          var c = -1
wenzelm@28045
   228
          var done = false
wenzelm@28045
   229
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   230
            c = reader.read
wenzelm@28045
   231
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   232
            else done = true
wenzelm@28045
   233
          }
wenzelm@28045
   234
          if (result.length > 0) {
wenzelm@37689
   235
            put_result(Markup.STDOUT, result.toString)
wenzelm@28045
   236
            result.length = 0
wenzelm@27949
   237
          }
wenzelm@27949
   238
          else {
wenzelm@28045
   239
            reader.close
wenzelm@28045
   240
            finished = true
wenzelm@28045
   241
            try_close()
wenzelm@27949
   242
          }
wenzelm@28045
   243
          //}}}
wenzelm@27963
   244
        }
wenzelm@27963
   245
        catch {
wenzelm@37689
   246
          case e: IOException => put_result(Markup.SYSTEM, "Stdout thread: " + e.getMessage)
wenzelm@27949
   247
        }
wenzelm@27949
   248
      }
wenzelm@37689
   249
      put_result(Markup.SYSTEM, "Stdout thread terminated")
wenzelm@27949
   250
    }
wenzelm@27949
   251
  }
wenzelm@27949
   252
wenzelm@27949
   253
wenzelm@28045
   254
  /* messages */
wenzelm@27949
   255
wenzelm@34213
   256
  private class Message_Thread(fifo: String) extends Thread("isabelle: messages")
wenzelm@34100
   257
  {
wenzelm@34100
   258
    private class Protocol_Error(msg: String) extends Exception(msg)
wenzelm@34100
   259
    override def run()
wenzelm@34100
   260
    {
wenzelm@38253
   261
      val stream = system.fifo_input_stream(fifo)
wenzelm@34100
   262
      val default_buffer = new Array[Byte](65536)
wenzelm@34100
   263
      var c = -1
wenzelm@27949
   264
wenzelm@34100
   265
      def read_chunk(): List[XML.Tree] =
wenzelm@34100
   266
      {
wenzelm@34100
   267
        //{{{
wenzelm@34100
   268
        // chunk size
wenzelm@34100
   269
        var n = 0
wenzelm@34100
   270
        c = stream.read
wenzelm@34100
   271
        while (48 <= c && c <= 57) {
wenzelm@34100
   272
          n = 10 * n + (c - 48)
wenzelm@34100
   273
          c = stream.read
wenzelm@34100
   274
        }
wenzelm@34100
   275
        if (c != 10) throw new Protocol_Error("bad message chunk header")
wenzelm@34100
   276
wenzelm@34100
   277
        // chunk content
wenzelm@34100
   278
        val buf =
wenzelm@34100
   279
          if (n <= default_buffer.size) default_buffer
wenzelm@34100
   280
          else new Array[Byte](n)
wenzelm@34100
   281
wenzelm@34100
   282
        var i = 0
wenzelm@34100
   283
        var m = 0
wenzelm@34100
   284
        do {
wenzelm@34100
   285
          m = stream.read(buf, i, n - i)
wenzelm@34100
   286
          i += m
wenzelm@34100
   287
        } while (m > 0 && n > i)
wenzelm@34100
   288
wenzelm@34100
   289
        if (i != n) throw new Protocol_Error("bad message chunk content")
wenzelm@34100
   290
wenzelm@34100
   291
        YXML.parse_body_failsafe(YXML.decode_chars(system.symbols.decode, buf, 0, n))
wenzelm@34100
   292
        //}}}
wenzelm@34100
   293
      }
wenzelm@34100
   294
wenzelm@34100
   295
      do {
wenzelm@27949
   296
        try {
wenzelm@34100
   297
          //{{{
wenzelm@34100
   298
          c = stream.read
wenzelm@34100
   299
          var non_sync = 0
wenzelm@34100
   300
          while (c >= 0 && c != 2) {
wenzelm@34100
   301
            non_sync += 1
wenzelm@34100
   302
            c = stream.read
wenzelm@28063
   303
          }
wenzelm@34100
   304
          if (non_sync > 0)
wenzelm@34100
   305
            throw new Protocol_Error("lost synchronization -- skipping " + non_sync + " bytes")
wenzelm@34100
   306
          if (c == 2) {
wenzelm@34100
   307
            val header = read_chunk()
wenzelm@34100
   308
            val body = read_chunk()
wenzelm@34100
   309
            header match {
wenzelm@38230
   310
              case List(XML.Elem(Markup(name, props), Nil))
wenzelm@37689
   311
                  if name.size == 1 && Kind.markup.isDefinedAt(name(0)) =>
wenzelm@37689
   312
                put_result(Kind.markup(name(0)), props, body)
wenzelm@34100
   313
              case _ => throw new Protocol_Error("bad header: " + header.toString)
wenzelm@28063
   314
            }
wenzelm@27949
   315
          }
wenzelm@34100
   316
          //}}}
wenzelm@27963
   317
        }
wenzelm@28063
   318
        catch {
wenzelm@34100
   319
          case e: IOException =>
wenzelm@37689
   320
            put_result(Markup.SYSTEM, "Cannot read message:\n" + e.getMessage)
wenzelm@34100
   321
          case e: Protocol_Error =>
wenzelm@37689
   322
            put_result(Markup.SYSTEM, "Malformed message:\n" + e.getMessage)
wenzelm@28063
   323
        }
wenzelm@34100
   324
      } while (c != -1)
wenzelm@34100
   325
      stream.close
wenzelm@34100
   326
      try_close()
wenzelm@34100
   327
wenzelm@37689
   328
      put_result(Markup.SYSTEM, "Message thread terminated")
wenzelm@27949
   329
    }
wenzelm@27949
   330
  }
wenzelm@27949
   331
wenzelm@27949
   332
wenzelm@29192
   333
wenzelm@27949
   334
  /** main **/
wenzelm@27949
   335
wenzelm@27949
   336
  {
wenzelm@38253
   337
    /* private communication channels */
wenzelm@28045
   338
wenzelm@38253
   339
    val in_fifo = system.mk_fifo()
wenzelm@38253
   340
    val out_fifo = system.mk_fifo()
wenzelm@38253
   341
    def rm_fifos() = { system.rm_fifo(in_fifo); system.rm_fifo(out_fifo) }
wenzelm@28045
   342
wenzelm@38253
   343
    val command_thread = new Command_Thread(in_fifo)
wenzelm@38253
   344
    val message_thread = new Message_Thread(out_fifo)
wenzelm@38253
   345
wenzelm@38253
   346
    command_thread.start
wenzelm@28063
   347
    message_thread.start
wenzelm@28045
   348
wenzelm@28045
   349
wenzelm@27973
   350
    /* exec process */
wenzelm@27963
   351
wenzelm@27973
   352
    try {
wenzelm@38253
   353
      val cmdline =
wenzelm@38253
   354
        List(system.getenv_strict("ISABELLE_PROCESS"), "-W", in_fifo + ":" + out_fifo) ++ args
wenzelm@34100
   355
      proc = system.execute(true, cmdline: _*)
wenzelm@27949
   356
    }
wenzelm@27993
   357
    catch {
wenzelm@28063
   358
      case e: IOException =>
wenzelm@38253
   359
        rm_fifos()
wenzelm@28063
   360
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   361
    }
wenzelm@34213
   362
    new Stdout_Thread(proc.getInputStream).start
wenzelm@28045
   363
wenzelm@28045
   364
wenzelm@28045
   365
    /* exit */
wenzelm@27949
   366
wenzelm@28063
   367
    new Thread("isabelle: exit") {
wenzelm@38253
   368
      override def run()
wenzelm@38253
   369
      {
wenzelm@28045
   370
        val rc = proc.waitFor()
wenzelm@37132
   371
        Thread.sleep(300)  // FIXME property!?
wenzelm@37689
   372
        put_result(Markup.SYSTEM, "Exit thread terminated")
wenzelm@37689
   373
        put_result(Markup.EXIT, rc.toString)
wenzelm@38253
   374
        rm_fifos()
wenzelm@28045
   375
      }
wenzelm@28063
   376
    }.start
wenzelm@27949
   377
  }
wenzelm@27949
   378
}