src/Pure/Tools/isabelle_process.scala
author wenzelm
Thu Aug 28 22:26:22 2008 +0200 (2008-08-28 ago)
changeset 28056 18dbe34f6c5d
parent 28045 1a6f273108ae
child 28063 3533485fc7b8
permissions -rw-r--r--
moved charset to isabelle_system.scala;
IsabelleSystem.fifo_reader;
wenzelm@27963
     1
/*  Title:      Pure/Tools/isabelle_process.ML
wenzelm@27949
     2
    ID:         $Id$
wenzelm@27949
     3
    Author:     Makarius
wenzelm@27963
     4
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@27949
     5
wenzelm@27949
     6
Isabelle process management -- always reactive due to multi-threaded I/O.
wenzelm@27949
     7
*/
wenzelm@27949
     8
wenzelm@27949
     9
package isabelle
wenzelm@27949
    10
wenzelm@27949
    11
import java.util.Properties
wenzelm@27955
    12
import java.util.concurrent.LinkedBlockingQueue
wenzelm@28045
    13
import java.io.{BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter,
wenzelm@28056
    14
  InputStream, OutputStream, IOException}
wenzelm@27949
    15
wenzelm@27963
    16
import isabelle.{Symbol, XML}
wenzelm@27949
    17
wenzelm@27949
    18
wenzelm@27973
    19
object IsabelleProcess {
wenzelm@27973
    20
wenzelm@27949
    21
  /* results */
wenzelm@27949
    22
wenzelm@27949
    23
  object Kind extends Enumeration {
wenzelm@27949
    24
    //{{{ values
wenzelm@27949
    25
    // Posix channels/events
wenzelm@27949
    26
    val STDIN = Value("STDIN")
wenzelm@27949
    27
    val STDOUT = Value("STDOUT")
wenzelm@27949
    28
    val SIGNAL = Value("SIGNAL")
wenzelm@27949
    29
    val EXIT = Value("EXIT")
wenzelm@27949
    30
    // Isabelle messages
wenzelm@27949
    31
    val WRITELN = Value("WRITELN")
wenzelm@27949
    32
    val PRIORITY = Value("PRIORITY")
wenzelm@27949
    33
    val TRACING = Value("TRACING")
wenzelm@27949
    34
    val WARNING = Value("WARNING")
wenzelm@27949
    35
    val ERROR = Value("ERROR")
wenzelm@27949
    36
    val DEBUG = Value("DEBUG")
wenzelm@27949
    37
    val PROMPT = Value("PROMPT")
wenzelm@27949
    38
    val INIT = Value("INIT")
wenzelm@27949
    39
    val STATUS = Value("STATUS")
wenzelm@27949
    40
    // internal system notification
wenzelm@27949
    41
    val SYSTEM = Value("SYSTEM")
wenzelm@27949
    42
    //}}}
wenzelm@27949
    43
    def is_raw(kind: Value) =
wenzelm@28045
    44
      kind == STDOUT
wenzelm@27990
    45
    def is_control(kind: Value) =
wenzelm@27990
    46
      kind == SIGNAL ||
wenzelm@27990
    47
      kind == EXIT ||
wenzelm@27990
    48
      kind == SYSTEM
wenzelm@27949
    49
    def is_system(kind: Value) =
wenzelm@27949
    50
      kind == STDIN ||
wenzelm@27949
    51
      kind == SIGNAL ||
wenzelm@27949
    52
      kind == EXIT ||
wenzelm@27949
    53
      kind == PROMPT ||
wenzelm@27949
    54
      kind == STATUS ||
wenzelm@27949
    55
      kind == SYSTEM
wenzelm@27949
    56
  }
wenzelm@27949
    57
wenzelm@27973
    58
  class Result(val kind: Kind.Value, val props: Properties, val result: String) {
wenzelm@27949
    59
    override def toString = {
wenzelm@27963
    60
      val res = XML.content(YXML.parse_failsafe(result)).mkString("")
wenzelm@27955
    61
      if (props == null) kind.toString + " [[" + res + "]]"
wenzelm@27955
    62
      else kind.toString + " " + props.toString + " [[" + res + "]]"
wenzelm@27949
    63
    }
wenzelm@27973
    64
    def is_raw() = Kind.is_raw(kind)
wenzelm@27990
    65
    def is_control() = Kind.is_control(kind)
wenzelm@27973
    66
    def is_system() = Kind.is_system(kind)
wenzelm@27973
    67
  }
wenzelm@27949
    68
wenzelm@27973
    69
}
wenzelm@27973
    70
wenzelm@27973
    71
wenzelm@27973
    72
class IsabelleProcess(args: String*) {
wenzelm@27973
    73
wenzelm@27973
    74
  import IsabelleProcess._
wenzelm@27973
    75
wenzelm@27973
    76
wenzelm@27973
    77
  /* process information */
wenzelm@27973
    78
wenzelm@27973
    79
  private var proc: Process = null
wenzelm@27973
    80
  private var closing = false
wenzelm@27973
    81
  private var pid: String = null
wenzelm@27973
    82
  private var the_session: String = null
wenzelm@27973
    83
  def session() = the_session
wenzelm@27973
    84
wenzelm@27973
    85
wenzelm@27973
    86
  /* results */
wenzelm@27949
    87
wenzelm@27990
    88
  private val results = new LinkedBlockingQueue[Result]
wenzelm@27949
    89
wenzelm@27949
    90
  private def put_result(kind: Kind.Value, props: Properties, result: String) {
wenzelm@27963
    91
    if (kind == Kind.INIT && props != null) {
wenzelm@27973
    92
      pid = props.getProperty(Markup.PID)
wenzelm@27973
    93
      the_session = props.getProperty(Markup.SESSION)
wenzelm@27963
    94
    }
wenzelm@27955
    95
    results.put(new Result(kind, props, result))
wenzelm@27949
    96
  }
wenzelm@27949
    97
wenzelm@27990
    98
  def get_result() = results.take
wenzelm@27973
    99
wenzelm@27992
   100
  def try_result() = {
wenzelm@27992
   101
    val res = results.poll
wenzelm@27992
   102
    if (res != null) Some(res) else None
wenzelm@27992
   103
  }
wenzelm@27992
   104
wenzelm@27973
   105
wenzelm@27973
   106
  /* signals */
wenzelm@27973
   107
wenzelm@27973
   108
  def interrupt() = synchronized {
wenzelm@27993
   109
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@27973
   110
    if (pid == null) put_result(Kind.SYSTEM, null, "Cannot interrupt: unknown pid")
wenzelm@27973
   111
    else {
wenzelm@27973
   112
      try {
wenzelm@27990
   113
        if (IsabelleSystem.exec(List("kill", "-INT", pid)).waitFor == 0)
wenzelm@27990
   114
          put_result(Kind.SIGNAL, null, "INT")
wenzelm@27990
   115
        else
wenzelm@27973
   116
          put_result(Kind.SYSTEM, null, "Cannot interrupt: kill command failed")
wenzelm@27973
   117
      }
wenzelm@27993
   118
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   119
    }
wenzelm@27973
   120
  }
wenzelm@27973
   121
wenzelm@27973
   122
  def kill() = synchronized {
wenzelm@27993
   123
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   124
    else {
wenzelm@27973
   125
      try_close()
wenzelm@27990
   126
      Thread.sleep(500)
wenzelm@27973
   127
      put_result(Kind.SIGNAL, null, "KILL")
wenzelm@27973
   128
      proc.destroy
wenzelm@27973
   129
      proc = null
wenzelm@27990
   130
      pid = null
wenzelm@27973
   131
    }
wenzelm@27973
   132
  }
wenzelm@27973
   133
wenzelm@27949
   134
wenzelm@27949
   135
  /* output being piped into the process */
wenzelm@27949
   136
wenzelm@27990
   137
  private val output = new LinkedBlockingQueue[String]
wenzelm@27949
   138
wenzelm@28045
   139
  private def output_raw(text: String) = synchronized {
wenzelm@27993
   140
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@27993
   141
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@27955
   142
    output.put(text)
wenzelm@27949
   143
  }
wenzelm@27949
   144
wenzelm@28045
   145
  private def output_sync(text: String) =
wenzelm@28045
   146
    output_raw(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@27949
   147
wenzelm@27963
   148
wenzelm@27963
   149
  def command(text: String) =
wenzelm@27949
   150
    output_sync("Isabelle.command " + IsabelleSyntax.encode_string(text))
wenzelm@27949
   151
wenzelm@27963
   152
  def command(props: Properties, text: String) =
wenzelm@27949
   153
    output_sync("Isabelle.command " + IsabelleSyntax.encode_properties(props) + " " +
wenzelm@27949
   154
      IsabelleSyntax.encode_string(text))
wenzelm@27949
   155
wenzelm@27963
   156
  def ML(text: String) =
wenzelm@27949
   157
    output_sync("ML_val " + IsabelleSyntax.encode_string(text))
wenzelm@27949
   158
wenzelm@27949
   159
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   160
    output_raw("\u0000")
wenzelm@27949
   161
    closing = true
wenzelm@27949
   162
  }
wenzelm@27949
   163
wenzelm@27949
   164
  def try_close() = synchronized {
wenzelm@27949
   165
    if (proc != null && !closing) {
wenzelm@27949
   166
      try { close() }
wenzelm@27993
   167
      catch { case _: RuntimeException => }
wenzelm@27949
   168
    }
wenzelm@27949
   169
  }
wenzelm@27949
   170
wenzelm@27949
   171
wenzelm@27949
   172
  /* stdin */
wenzelm@27949
   173
wenzelm@28045
   174
  private class StdinThread(out_stream: OutputStream) extends Thread("isabelle: stdin") {
wenzelm@27949
   175
    override def run() = {
wenzelm@28056
   176
      val writer = new BufferedWriter(new OutputStreamWriter(out_stream, IsabelleSystem.charset))
wenzelm@27949
   177
      var finished = false
wenzelm@27949
   178
      while (!finished) {
wenzelm@27949
   179
        try {
wenzelm@27949
   180
          //{{{
wenzelm@27955
   181
          val s = output.take
wenzelm@27949
   182
          if (s == "\u0000") {
wenzelm@27949
   183
            writer.close
wenzelm@27949
   184
            finished = true
wenzelm@27949
   185
          }
wenzelm@27949
   186
          else {
wenzelm@27949
   187
            put_result(Kind.STDIN, null, s)
wenzelm@27949
   188
            writer.write(s)
wenzelm@27949
   189
            writer.flush
wenzelm@27949
   190
          }
wenzelm@27949
   191
          //}}}
wenzelm@27949
   192
        }
wenzelm@27949
   193
        catch {
wenzelm@27949
   194
          case e: IOException => put_result(Kind.SYSTEM, null, "Stdin thread: " + e.getMessage)
wenzelm@27949
   195
        }
wenzelm@27949
   196
      }
wenzelm@27949
   197
      put_result(Kind.SYSTEM, null, "Stdin thread terminated")
wenzelm@27949
   198
    }
wenzelm@27949
   199
  }
wenzelm@27949
   200
wenzelm@27949
   201
wenzelm@27949
   202
  /* stdout */
wenzelm@27949
   203
wenzelm@28045
   204
  private class StdoutThread(in_stream: InputStream) extends Thread("isabelle: stdout") {
wenzelm@27949
   205
    override def run() = {
wenzelm@28056
   206
      val reader = new BufferedReader(new InputStreamReader(in_stream, IsabelleSystem.charset))
wenzelm@28045
   207
      var result = new StringBuilder(100)
wenzelm@27949
   208
wenzelm@27949
   209
      var finished = false
wenzelm@27949
   210
      while (!finished) {
wenzelm@27949
   211
        try {
wenzelm@28045
   212
          //{{{
wenzelm@28045
   213
          var c = -1
wenzelm@28045
   214
          var done = false
wenzelm@28045
   215
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   216
            c = reader.read
wenzelm@28045
   217
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   218
            else done = true
wenzelm@28045
   219
          }
wenzelm@28045
   220
          if (result.length > 0) {
wenzelm@28045
   221
            put_result(Kind.STDOUT, null, result.toString)
wenzelm@28045
   222
            result.length = 0
wenzelm@27949
   223
          }
wenzelm@27949
   224
          else {
wenzelm@28045
   225
            reader.close
wenzelm@28045
   226
            finished = true
wenzelm@28045
   227
            try_close()
wenzelm@27949
   228
          }
wenzelm@28045
   229
          //}}}
wenzelm@27963
   230
        }
wenzelm@27963
   231
        catch {
wenzelm@27949
   232
          case e: IOException => put_result(Kind.SYSTEM, null, "Stdout thread: " + e.getMessage)
wenzelm@27949
   233
        }
wenzelm@27949
   234
      }
wenzelm@27949
   235
      put_result(Kind.SYSTEM, null, "Stdout thread terminated")
wenzelm@27949
   236
    }
wenzelm@27949
   237
  }
wenzelm@27949
   238
wenzelm@27949
   239
wenzelm@28045
   240
  /* messages */
wenzelm@27949
   241
wenzelm@28045
   242
  private class MessageThread(fifo: String) extends Thread("isabelle: messages") {
wenzelm@27949
   243
    override def run() = {
wenzelm@28056
   244
      val reader = IsabelleSystem.fifo_reader(fifo)
wenzelm@28045
   245
      var kind: Kind.Value = null
wenzelm@28045
   246
      var props: Properties = null
wenzelm@28045
   247
      var result = new StringBuilder
wenzelm@27949
   248
wenzelm@27949
   249
      var finished = false
wenzelm@27949
   250
      while (!finished) {
wenzelm@27949
   251
        try {
wenzelm@28045
   252
          try {
wenzelm@28045
   253
            if (kind == null) {
wenzelm@28045
   254
              //{{{ Char mode -- resync
wenzelm@28045
   255
              var c = -1
wenzelm@28045
   256
              do {
wenzelm@28045
   257
                c = reader.read
wenzelm@28045
   258
                if (c >= 0 && c != 2) result.append(c.asInstanceOf[Char])
wenzelm@28045
   259
              } while (c >= 0 && c != 2)
wenzelm@28045
   260
  
wenzelm@28045
   261
              if (result.length > 0) {
wenzelm@28045
   262
                put_result(Kind.SYSTEM, null, "Malformed message:\n" + result.toString)
wenzelm@28045
   263
                result.length = 0
wenzelm@28045
   264
              }
wenzelm@28045
   265
              if (c < 0) {
wenzelm@28045
   266
                reader.close
wenzelm@28045
   267
                finished = true
wenzelm@28045
   268
                try_close()
wenzelm@28045
   269
              }
wenzelm@28045
   270
              else {
wenzelm@28045
   271
                reader.read match {
wenzelm@28045
   272
                  case 'A' => kind = Kind.WRITELN
wenzelm@28045
   273
                  case 'B' => kind = Kind.PRIORITY
wenzelm@28045
   274
                  case 'C' => kind = Kind.TRACING
wenzelm@28045
   275
                  case 'D' => kind = Kind.WARNING
wenzelm@28045
   276
                  case 'E' => kind = Kind.ERROR
wenzelm@28045
   277
                  case 'F' => kind = Kind.DEBUG
wenzelm@28045
   278
                  case 'G' => kind = Kind.PROMPT
wenzelm@28045
   279
                  case 'H' => kind = Kind.INIT
wenzelm@28045
   280
                  case 'I' => kind = Kind.STATUS
wenzelm@28045
   281
                  case _ => kind = null
wenzelm@28045
   282
                }
wenzelm@28045
   283
                props = null
wenzelm@28045
   284
              }
wenzelm@28045
   285
              //}}}
wenzelm@28045
   286
            }
wenzelm@28045
   287
            else {
wenzelm@28045
   288
              //{{{ Line mode
wenzelm@28045
   289
              val line = reader.readLine
wenzelm@28045
   290
              if (line == null) {
wenzelm@28045
   291
                reader.close
wenzelm@28045
   292
                finished = true
wenzelm@28045
   293
                try_close()
wenzelm@28045
   294
              }
wenzelm@28045
   295
              else {
wenzelm@28045
   296
                val len = line.length
wenzelm@28045
   297
                // property
wenzelm@28045
   298
                if (line.endsWith("\u0002,")) {
wenzelm@28045
   299
                  val i = line.indexOf('=')
wenzelm@28045
   300
                  if (i > 0) {
wenzelm@28045
   301
                    val name = line.substring(0, i)
wenzelm@28045
   302
                    val value = line.substring(i + 1, len - 2)
wenzelm@28045
   303
                    if (props == null) props = new Properties
wenzelm@28045
   304
                    if (!props.containsKey(name)) props.setProperty(name, value)
wenzelm@28045
   305
                  }
wenzelm@28045
   306
                }
wenzelm@28045
   307
                // last text line
wenzelm@28045
   308
                else if (line.endsWith("\u0002.")) {
wenzelm@28045
   309
                  result.append(line.substring(0, len - 2))
wenzelm@28045
   310
                  put_result(kind, props, result.toString)
wenzelm@28045
   311
                  result.length = 0
wenzelm@28045
   312
                  kind = null
wenzelm@28045
   313
                }
wenzelm@28045
   314
                // text line
wenzelm@28045
   315
                else {
wenzelm@28045
   316
                  result.append(line)
wenzelm@28045
   317
                  result.append('\n')
wenzelm@28045
   318
                }
wenzelm@28045
   319
              }
wenzelm@28045
   320
              //}}}
wenzelm@28045
   321
            }
wenzelm@27949
   322
          }
wenzelm@28045
   323
          catch {
wenzelm@28045
   324
            case e: IOException => put_result(Kind.SYSTEM, null, "Message thread: " + e.getMessage)
wenzelm@27949
   325
          }
wenzelm@27963
   326
        }
wenzelm@28045
   327
        catch { case _: InterruptedException => finished = true }
wenzelm@27949
   328
      }
wenzelm@28045
   329
      try { put_result(Kind.SYSTEM, null, "Message thread terminated") }
wenzelm@28045
   330
      catch { case _ : InterruptedException => }
wenzelm@27949
   331
    }
wenzelm@27949
   332
  }
wenzelm@27949
   333
wenzelm@27949
   334
wenzelm@27949
   335
  /** main **/
wenzelm@27949
   336
wenzelm@27949
   337
  {
wenzelm@28045
   338
wenzelm@28045
   339
    /* message fifo */
wenzelm@28045
   340
wenzelm@28045
   341
    val fifo =
wenzelm@28045
   342
      try {
wenzelm@28045
   343
        val mkfifo = IsabelleSystem.exec(List(IsabelleSystem.getenv_strict("ISATOOL"), "mkfifo"))
wenzelm@28056
   344
        val fifo = new BufferedReader(new
wenzelm@28056
   345
          InputStreamReader(mkfifo.getInputStream, IsabelleSystem.charset)).readLine
wenzelm@28045
   346
        if (mkfifo.waitFor == 0) fifo
wenzelm@28045
   347
        else error("Failed to create message fifo")
wenzelm@28045
   348
      }
wenzelm@28045
   349
      catch {
wenzelm@28045
   350
        case e: IOException => error("Failed to create message fifo: " + e.getMessage)
wenzelm@28045
   351
      }
wenzelm@28045
   352
wenzelm@28045
   353
    val message_thread = new MessageThread(fifo)
wenzelm@28045
   354
wenzelm@28045
   355
wenzelm@27973
   356
    /* exec process */
wenzelm@27963
   357
wenzelm@27973
   358
    try {
wenzelm@28045
   359
      proc = IsabelleSystem.exec2(List(
wenzelm@28045
   360
        IsabelleSystem.getenv_strict("ISABELLE_HOME") + "/bin/isabelle-process", "-W", fifo) ++ args)
wenzelm@27949
   361
    }
wenzelm@27993
   362
    catch {
wenzelm@27993
   363
      case e: IOException => error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   364
    }
wenzelm@27949
   365
wenzelm@27949
   366
wenzelm@28045
   367
    /* stdin/stdout */
wenzelm@28045
   368
wenzelm@28045
   369
    new StdinThread(proc.getOutputStream).start
wenzelm@28045
   370
    new StdoutThread(proc.getInputStream).start
wenzelm@28045
   371
wenzelm@28045
   372
wenzelm@28045
   373
    /* exit */
wenzelm@27949
   374
wenzelm@28045
   375
    class ExitThread extends Thread("isabelle: exit") {
wenzelm@28045
   376
      override def run() = {
wenzelm@28045
   377
        val rc = proc.waitFor()
wenzelm@28045
   378
        Thread.sleep(300)
wenzelm@28045
   379
        put_result(Kind.SYSTEM, null, "Exit thread terminated")
wenzelm@28045
   380
        put_result(Kind.EXIT, null, Integer.toString(rc))
wenzelm@28045
   381
        message_thread.interrupt
wenzelm@28045
   382
      }
wenzelm@28045
   383
    }
wenzelm@28045
   384
    message_thread.start
wenzelm@27949
   385
    new ExitThread().start
wenzelm@27949
   386
  }
wenzelm@27949
   387
wenzelm@27949
   388
}