src/Pure/Tools/isabelle_process.scala
author wenzelm
Fri Aug 29 20:36:08 2008 +0200 (2008-08-29 ago)
changeset 28063 3533485fc7b8
parent 28056 18dbe34f6c5d
child 28303 8c4a4f256c16
permissions -rw-r--r--
IsabelleSystem.mk_fifo, IsabelleSystem.rm_fifo;
IsabelleSystem.exec: varargs convenience;
more robust message thread management: no interrupt, but proper rendezvous via fifo (rm_fifo removes unused fifo, if isabelle-process fails);
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@28063
   113
        if (IsabelleSystem.exec("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@28063
   252
          if (kind == null) {
wenzelm@28063
   253
            //{{{ Char mode -- resync
wenzelm@28063
   254
            var c = -1
wenzelm@28063
   255
            do {
wenzelm@28063
   256
              c = reader.read
wenzelm@28063
   257
              if (c >= 0 && c != 2) result.append(c.asInstanceOf[Char])
wenzelm@28063
   258
            } while (c >= 0 && c != 2)
wenzelm@28063
   259
wenzelm@28063
   260
            if (result.length > 0) {
wenzelm@28063
   261
              put_result(Kind.SYSTEM, null, "Malformed message:\n" + result.toString)
wenzelm@28063
   262
              result.length = 0
wenzelm@28063
   263
            }
wenzelm@28063
   264
            if (c < 0) {
wenzelm@28063
   265
              reader.close
wenzelm@28063
   266
              finished = true
wenzelm@28063
   267
              try_close()
wenzelm@28045
   268
            }
wenzelm@28045
   269
            else {
wenzelm@28063
   270
              reader.read match {
wenzelm@28063
   271
                case 'A' => kind = Kind.WRITELN
wenzelm@28063
   272
                case 'B' => kind = Kind.PRIORITY
wenzelm@28063
   273
                case 'C' => kind = Kind.TRACING
wenzelm@28063
   274
                case 'D' => kind = Kind.WARNING
wenzelm@28063
   275
                case 'E' => kind = Kind.ERROR
wenzelm@28063
   276
                case 'F' => kind = Kind.DEBUG
wenzelm@28063
   277
                case 'G' => kind = Kind.PROMPT
wenzelm@28063
   278
                case 'H' => kind = Kind.INIT
wenzelm@28063
   279
                case 'I' => kind = Kind.STATUS
wenzelm@28063
   280
                case _ => kind = null
wenzelm@28045
   281
              }
wenzelm@28063
   282
              props = null
wenzelm@28063
   283
            }
wenzelm@28063
   284
            //}}}
wenzelm@28063
   285
          }
wenzelm@28063
   286
          else {
wenzelm@28063
   287
            //{{{ Line mode
wenzelm@28063
   288
            val line = reader.readLine
wenzelm@28063
   289
            if (line == null) {
wenzelm@28063
   290
              reader.close
wenzelm@28063
   291
              finished = true
wenzelm@28063
   292
              try_close()
wenzelm@28063
   293
            }
wenzelm@28063
   294
            else {
wenzelm@28063
   295
              val len = line.length
wenzelm@28063
   296
              // property
wenzelm@28063
   297
              if (line.endsWith("\u0002,")) {
wenzelm@28063
   298
                val i = line.indexOf('=')
wenzelm@28063
   299
                if (i > 0) {
wenzelm@28063
   300
                  val name = line.substring(0, i)
wenzelm@28063
   301
                  val value = line.substring(i + 1, len - 2)
wenzelm@28063
   302
                  if (props == null) props = new Properties
wenzelm@28063
   303
                  if (!props.containsKey(name)) props.setProperty(name, value)
wenzelm@28045
   304
                }
wenzelm@28045
   305
              }
wenzelm@28063
   306
              // last text line
wenzelm@28063
   307
              else if (line.endsWith("\u0002.")) {
wenzelm@28063
   308
                result.append(line.substring(0, len - 2))
wenzelm@28063
   309
                put_result(kind, props, result.toString)
wenzelm@28063
   310
                result.length = 0
wenzelm@28063
   311
                kind = null
wenzelm@28063
   312
              }
wenzelm@28063
   313
              // text line
wenzelm@28063
   314
              else {
wenzelm@28063
   315
                result.append(line)
wenzelm@28063
   316
                result.append('\n')
wenzelm@28063
   317
              }
wenzelm@28045
   318
            }
wenzelm@28063
   319
            //}}}
wenzelm@27949
   320
          }
wenzelm@27963
   321
        }
wenzelm@28063
   322
        catch {
wenzelm@28063
   323
          case e: IOException => put_result(Kind.SYSTEM, null, "Message thread: " + e.getMessage)
wenzelm@28063
   324
        }
wenzelm@27949
   325
      }
wenzelm@28063
   326
      put_result(Kind.SYSTEM, null, "Message thread terminated")
wenzelm@27949
   327
    }
wenzelm@27949
   328
  }
wenzelm@27949
   329
wenzelm@27949
   330
wenzelm@27949
   331
  /** main **/
wenzelm@27949
   332
wenzelm@27949
   333
  {
wenzelm@28045
   334
wenzelm@28045
   335
    /* message fifo */
wenzelm@28045
   336
wenzelm@28063
   337
    val message_fifo = IsabelleSystem.mk_fifo()
wenzelm@28063
   338
    def rm_fifo() = IsabelleSystem.rm_fifo(message_fifo)
wenzelm@28045
   339
wenzelm@28063
   340
    val message_thread = new MessageThread(message_fifo)
wenzelm@28063
   341
    message_thread.start
wenzelm@28045
   342
wenzelm@28045
   343
wenzelm@27973
   344
    /* exec process */
wenzelm@27963
   345
wenzelm@27973
   346
    try {
wenzelm@28063
   347
      val cmdline = List(IsabelleSystem.getenv_strict("ISABELLE_HOME") +
wenzelm@28063
   348
          "/bin/isabelle-process", "-W", message_fifo) ++ args
wenzelm@28063
   349
      proc = IsabelleSystem.exec2(cmdline: _*)
wenzelm@27949
   350
    }
wenzelm@27993
   351
    catch {
wenzelm@28063
   352
      case e: IOException =>
wenzelm@28063
   353
        rm_fifo()
wenzelm@28063
   354
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   355
    }
wenzelm@27949
   356
wenzelm@27949
   357
wenzelm@28045
   358
    /* stdin/stdout */
wenzelm@28045
   359
wenzelm@28045
   360
    new StdinThread(proc.getOutputStream).start
wenzelm@28045
   361
    new StdoutThread(proc.getInputStream).start
wenzelm@28045
   362
wenzelm@28045
   363
wenzelm@28045
   364
    /* exit */
wenzelm@27949
   365
wenzelm@28063
   366
    new Thread("isabelle: exit") {
wenzelm@28045
   367
      override def run() = {
wenzelm@28045
   368
        val rc = proc.waitFor()
wenzelm@28045
   369
        Thread.sleep(300)
wenzelm@28045
   370
        put_result(Kind.SYSTEM, null, "Exit thread terminated")
wenzelm@28045
   371
        put_result(Kind.EXIT, null, Integer.toString(rc))
wenzelm@28063
   372
        rm_fifo()
wenzelm@28045
   373
      }
wenzelm@28063
   374
    }.start
wenzelm@28063
   375
wenzelm@27949
   376
  }
wenzelm@27949
   377
wenzelm@27949
   378
}