src/Pure/System/isabelle_process.scala
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 32474 0818e6b1c8a6
child 34100 ea24958c2af5
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
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@27949
    22
  object Kind extends Enumeration {
wenzelm@28344
    23
    //{{{ values and codes
wenzelm@28344
    24
    // internal system notification
wenzelm@28344
    25
    val SYSTEM = Value("SYSTEM")
wenzelm@27949
    26
    // Posix channels/events
wenzelm@27949
    27
    val STDIN = Value("STDIN")
wenzelm@27949
    28
    val STDOUT = Value("STDOUT")
wenzelm@27949
    29
    val SIGNAL = Value("SIGNAL")
wenzelm@27949
    30
    val EXIT = Value("EXIT")
wenzelm@27949
    31
    // Isabelle messages
wenzelm@28344
    32
    val INIT = Value("INIT")
wenzelm@28344
    33
    val STATUS = Value("STATUS")
wenzelm@27949
    34
    val WRITELN = Value("WRITELN")
wenzelm@27949
    35
    val PRIORITY = Value("PRIORITY")
wenzelm@27949
    36
    val TRACING = Value("TRACING")
wenzelm@27949
    37
    val WARNING = Value("WARNING")
wenzelm@27949
    38
    val ERROR = Value("ERROR")
wenzelm@27949
    39
    val DEBUG = Value("DEBUG")
wenzelm@28344
    40
    // messages codes
wenzelm@28344
    41
    val code = Map(
wenzelm@28344
    42
      ('A' : Int) -> Kind.INIT,
wenzelm@28344
    43
      ('B' : Int) -> Kind.STATUS,
wenzelm@28344
    44
      ('C' : Int) -> Kind.WRITELN,
wenzelm@28344
    45
      ('D' : Int) -> Kind.PRIORITY,
wenzelm@28344
    46
      ('E' : Int) -> Kind.TRACING,
wenzelm@28344
    47
      ('F' : Int) -> Kind.WARNING,
wenzelm@28344
    48
      ('G' : Int) -> Kind.ERROR,
wenzelm@28344
    49
      ('H' : Int) -> Kind.DEBUG,
wenzelm@28344
    50
      ('0' : Int) -> Kind.SYSTEM,
wenzelm@28344
    51
      ('1' : Int) -> Kind.STDIN,
wenzelm@28344
    52
      ('2' : Int) -> Kind.STDOUT,
wenzelm@28344
    53
      ('3' : Int) -> Kind.SIGNAL,
wenzelm@28344
    54
      ('4' : Int) -> Kind.EXIT)
wenzelm@29522
    55
    // message markup
wenzelm@29522
    56
    val markup = Map(
wenzelm@29522
    57
      Kind.INIT -> Markup.INIT,
wenzelm@29522
    58
      Kind.STATUS -> Markup.STATUS,
wenzelm@29522
    59
      Kind.WRITELN -> Markup.WRITELN,
wenzelm@29522
    60
      Kind.PRIORITY -> Markup.PRIORITY,
wenzelm@29522
    61
      Kind.TRACING -> Markup.TRACING,
wenzelm@29522
    62
      Kind.WARNING -> Markup.WARNING,
wenzelm@29522
    63
      Kind.ERROR -> Markup.ERROR,
wenzelm@29522
    64
      Kind.DEBUG -> Markup.DEBUG,
wenzelm@29522
    65
      Kind.SYSTEM -> Markup.SYSTEM,
wenzelm@29522
    66
      Kind.STDIN -> Markup.STDIN,
wenzelm@29522
    67
      Kind.STDOUT -> Markup.STDOUT,
wenzelm@29522
    68
      Kind.SIGNAL -> Markup.SIGNAL,
wenzelm@29522
    69
      Kind.EXIT -> Markup.EXIT)
wenzelm@27949
    70
    //}}}
wenzelm@27949
    71
    def is_raw(kind: Value) =
wenzelm@28045
    72
      kind == STDOUT
wenzelm@27990
    73
    def is_control(kind: Value) =
wenzelm@28344
    74
      kind == SYSTEM ||
wenzelm@27990
    75
      kind == SIGNAL ||
wenzelm@28344
    76
      kind == EXIT
wenzelm@27949
    77
    def is_system(kind: Value) =
wenzelm@28344
    78
      kind == SYSTEM ||
wenzelm@27949
    79
      kind == STDIN ||
wenzelm@27949
    80
      kind == SIGNAL ||
wenzelm@27949
    81
      kind == EXIT ||
wenzelm@28498
    82
      kind == STATUS
wenzelm@27949
    83
  }
wenzelm@27949
    84
wenzelm@29572
    85
  class Result(val kind: Kind.Value, val props: List[(String, String)], val result: String) {
wenzelm@27949
    86
    override def toString = {
wenzelm@29522
    87
      val trees = YXML.parse_body_failsafe(result)
wenzelm@29522
    88
      val res =
wenzelm@29522
    89
        if (kind == Kind.STATUS) trees.map(_.toString).mkString
wenzelm@29522
    90
        else trees.flatMap(XML.content(_).mkString).mkString
wenzelm@29572
    91
      if (props.isEmpty)
wenzelm@29572
    92
        kind.toString + " [[" + res + "]]"
wenzelm@29572
    93
      else
wenzelm@29572
    94
        kind.toString + " " +
wenzelm@29572
    95
          (for ((x, y) <- props) yield x + "=" + y).mkString("{", ",", "}") + " [[" + res + "]]"
wenzelm@27949
    96
    }
wenzelm@29192
    97
    def is_raw = Kind.is_raw(kind)
wenzelm@29192
    98
    def is_control = Kind.is_control(kind)
wenzelm@29192
    99
    def is_system = Kind.is_system(kind)
wenzelm@27973
   100
  }
wenzelm@27949
   101
wenzelm@31797
   102
  def parse_message(isabelle_system: Isabelle_System, result: Result) =
wenzelm@29572
   103
  {
wenzelm@29572
   104
    XML.Elem(Markup.MESSAGE, (Markup.CLASS, Kind.markup(result.kind)) :: result.props,
wenzelm@29572
   105
      YXML.parse_body_failsafe(isabelle_system.symbols.decode(result.result)))
wenzelm@29522
   106
  }
wenzelm@27973
   107
}
wenzelm@27973
   108
wenzelm@27973
   109
wenzelm@32474
   110
class Isabelle_Process(isabelle_system: Isabelle_System, receiver: Actor, args: String*)
wenzelm@29192
   111
{
wenzelm@31797
   112
  import Isabelle_Process._
wenzelm@29194
   113
wenzelm@27973
   114
wenzelm@29192
   115
  /* demo constructor */
wenzelm@27973
   116
wenzelm@29192
   117
  def this(args: String*) =
wenzelm@32474
   118
    this(new Isabelle_System,
wenzelm@32474
   119
      new Actor { def act = loop { react { case res => Console.println(res) } } }.start, args: _*)
wenzelm@29174
   120
wenzelm@29174
   121
wenzelm@27973
   122
  /* process information */
wenzelm@27973
   123
wenzelm@29648
   124
  @volatile private var proc: Process = null
wenzelm@29648
   125
  @volatile private var closing = false
wenzelm@29648
   126
  @volatile private var pid: String = null
wenzelm@29648
   127
  @volatile private var the_session: String = null
wenzelm@29572
   128
  def session = the_session
wenzelm@27973
   129
wenzelm@27973
   130
wenzelm@27973
   131
  /* results */
wenzelm@27949
   132
wenzelm@29572
   133
  private def put_result(kind: Kind.Value, props: List[(String, String)], result: String)
wenzelm@29572
   134
  {
wenzelm@29572
   135
    if (kind == Kind.INIT) {
wenzelm@29572
   136
      val map = Map(props: _*)
wenzelm@29572
   137
      if (map.isDefinedAt(Markup.PID)) pid = map(Markup.PID)
wenzelm@29572
   138
      if (map.isDefinedAt(Markup.SESSION)) the_session = map(Markup.SESSION)
wenzelm@27963
   139
    }
wenzelm@32474
   140
    receiver ! new Result(kind, props, result)
wenzelm@27992
   141
  }
wenzelm@27992
   142
wenzelm@27973
   143
wenzelm@27973
   144
  /* signals */
wenzelm@27973
   145
wenzelm@27973
   146
  def interrupt() = synchronized {
wenzelm@27993
   147
    if (proc == null) error("Cannot interrupt Isabelle: no process")
wenzelm@29572
   148
    if (pid == null) put_result(Kind.SYSTEM, Nil, "Cannot interrupt: unknown pid")
wenzelm@27973
   149
    else {
wenzelm@27973
   150
      try {
wenzelm@29178
   151
        if (isabelle_system.execute(true, "kill", "-INT", pid).waitFor == 0)
wenzelm@29572
   152
          put_result(Kind.SIGNAL, Nil, "INT")
wenzelm@27990
   153
        else
wenzelm@29572
   154
          put_result(Kind.SYSTEM, Nil, "Cannot interrupt: kill command failed")
wenzelm@27973
   155
      }
wenzelm@27993
   156
      catch { case e: IOException => error("Cannot interrupt Isabelle: " + e.getMessage) }
wenzelm@27973
   157
    }
wenzelm@27973
   158
  }
wenzelm@27973
   159
wenzelm@27973
   160
  def kill() = synchronized {
wenzelm@27993
   161
    if (proc == 0) error("Cannot kill Isabelle: no process")
wenzelm@27973
   162
    else {
wenzelm@27973
   163
      try_close()
wenzelm@27990
   164
      Thread.sleep(500)
wenzelm@29572
   165
      put_result(Kind.SIGNAL, Nil, "KILL")
wenzelm@27973
   166
      proc.destroy
wenzelm@27973
   167
      proc = null
wenzelm@27990
   168
      pid = null
wenzelm@27973
   169
    }
wenzelm@27973
   170
  }
wenzelm@27973
   171
wenzelm@27949
   172
wenzelm@27949
   173
  /* output being piped into the process */
wenzelm@27949
   174
wenzelm@27990
   175
  private val output = new LinkedBlockingQueue[String]
wenzelm@27949
   176
wenzelm@28045
   177
  private def output_raw(text: String) = synchronized {
wenzelm@27993
   178
    if (proc == null) error("Cannot output to Isabelle: no process")
wenzelm@27993
   179
    if (closing) error("Cannot output to Isabelle: already closing")
wenzelm@27955
   180
    output.put(text)
wenzelm@27949
   181
  }
wenzelm@27949
   182
wenzelm@28303
   183
  def output_sync(text: String) =
wenzelm@28045
   184
    output_raw(" \\<^sync>\n; " + text + " \\<^sync>;\n")
wenzelm@27949
   185
wenzelm@27963
   186
wenzelm@27963
   187
  def command(text: String) =
wenzelm@32448
   188
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   189
wenzelm@29572
   190
  def command(props: List[(String, String)], text: String) =
wenzelm@32448
   191
    output_sync("Isabelle.command " + Isabelle_Syntax.encode_properties(props) + " " +
wenzelm@32448
   192
      Isabelle_Syntax.encode_string(text))
wenzelm@27949
   193
wenzelm@27963
   194
  def ML(text: String) =
wenzelm@32448
   195
    output_sync("ML_val " + Isabelle_Syntax.encode_string(text))
wenzelm@27949
   196
wenzelm@27949
   197
  def close() = synchronized {    // FIXME watchdog/timeout
wenzelm@27949
   198
    output_raw("\u0000")
wenzelm@27949
   199
    closing = true
wenzelm@27949
   200
  }
wenzelm@27949
   201
wenzelm@27949
   202
  def try_close() = synchronized {
wenzelm@27949
   203
    if (proc != null && !closing) {
wenzelm@27949
   204
      try { close() }
wenzelm@27993
   205
      catch { case _: RuntimeException => }
wenzelm@27949
   206
    }
wenzelm@27949
   207
  }
wenzelm@27949
   208
wenzelm@27949
   209
wenzelm@27949
   210
  /* stdin */
wenzelm@27949
   211
wenzelm@28045
   212
  private class StdinThread(out_stream: OutputStream) extends Thread("isabelle: stdin") {
wenzelm@27949
   213
    override def run() = {
wenzelm@31797
   214
      val writer = new BufferedWriter(new OutputStreamWriter(out_stream, Isabelle_System.charset))
wenzelm@27949
   215
      var finished = false
wenzelm@27949
   216
      while (!finished) {
wenzelm@27949
   217
        try {
wenzelm@27949
   218
          //{{{
wenzelm@27955
   219
          val s = output.take
wenzelm@27949
   220
          if (s == "\u0000") {
wenzelm@27949
   221
            writer.close
wenzelm@27949
   222
            finished = true
wenzelm@27949
   223
          }
wenzelm@27949
   224
          else {
wenzelm@29572
   225
            put_result(Kind.STDIN, Nil, s)
wenzelm@27949
   226
            writer.write(s)
wenzelm@27949
   227
            writer.flush
wenzelm@27949
   228
          }
wenzelm@27949
   229
          //}}}
wenzelm@27949
   230
        }
wenzelm@27949
   231
        catch {
wenzelm@29572
   232
          case e: IOException => put_result(Kind.SYSTEM, Nil, "Stdin thread: " + e.getMessage)
wenzelm@27949
   233
        }
wenzelm@27949
   234
      }
wenzelm@29572
   235
      put_result(Kind.SYSTEM, Nil, "Stdin thread terminated")
wenzelm@27949
   236
    }
wenzelm@27949
   237
  }
wenzelm@27949
   238
wenzelm@27949
   239
wenzelm@27949
   240
  /* stdout */
wenzelm@27949
   241
wenzelm@28045
   242
  private class StdoutThread(in_stream: InputStream) extends Thread("isabelle: stdout") {
wenzelm@27949
   243
    override def run() = {
wenzelm@31797
   244
      val reader = new BufferedReader(new InputStreamReader(in_stream, Isabelle_System.charset))
wenzelm@28045
   245
      var result = new StringBuilder(100)
wenzelm@27949
   246
wenzelm@27949
   247
      var finished = false
wenzelm@27949
   248
      while (!finished) {
wenzelm@27949
   249
        try {
wenzelm@28045
   250
          //{{{
wenzelm@28045
   251
          var c = -1
wenzelm@28045
   252
          var done = false
wenzelm@28045
   253
          while (!done && (result.length == 0 || reader.ready)) {
wenzelm@28045
   254
            c = reader.read
wenzelm@28045
   255
            if (c >= 0) result.append(c.asInstanceOf[Char])
wenzelm@28045
   256
            else done = true
wenzelm@28045
   257
          }
wenzelm@28045
   258
          if (result.length > 0) {
wenzelm@29572
   259
            put_result(Kind.STDOUT, Nil, result.toString)
wenzelm@28045
   260
            result.length = 0
wenzelm@27949
   261
          }
wenzelm@27949
   262
          else {
wenzelm@28045
   263
            reader.close
wenzelm@28045
   264
            finished = true
wenzelm@28045
   265
            try_close()
wenzelm@27949
   266
          }
wenzelm@28045
   267
          //}}}
wenzelm@27963
   268
        }
wenzelm@27963
   269
        catch {
wenzelm@29572
   270
          case e: IOException => put_result(Kind.SYSTEM, Nil, "Stdout thread: " + e.getMessage)
wenzelm@27949
   271
        }
wenzelm@27949
   272
      }
wenzelm@29572
   273
      put_result(Kind.SYSTEM, Nil, "Stdout thread terminated")
wenzelm@27949
   274
    }
wenzelm@27949
   275
  }
wenzelm@27949
   276
wenzelm@27949
   277
wenzelm@28045
   278
  /* messages */
wenzelm@27949
   279
wenzelm@28045
   280
  private class MessageThread(fifo: String) extends Thread("isabelle: messages") {
wenzelm@27949
   281
    override def run() = {
wenzelm@29174
   282
      val reader = isabelle_system.fifo_reader(fifo)
wenzelm@28045
   283
      var kind: Kind.Value = null
wenzelm@29572
   284
      var props: List[(String, String)] = Nil
wenzelm@28045
   285
      var result = new StringBuilder
wenzelm@27949
   286
wenzelm@27949
   287
      var finished = false
wenzelm@27949
   288
      while (!finished) {
wenzelm@27949
   289
        try {
wenzelm@28063
   290
          if (kind == null) {
wenzelm@28063
   291
            //{{{ Char mode -- resync
wenzelm@28063
   292
            var c = -1
wenzelm@28063
   293
            do {
wenzelm@28063
   294
              c = reader.read
wenzelm@28063
   295
              if (c >= 0 && c != 2) result.append(c.asInstanceOf[Char])
wenzelm@28063
   296
            } while (c >= 0 && c != 2)
wenzelm@28063
   297
wenzelm@28063
   298
            if (result.length > 0) {
wenzelm@29572
   299
              put_result(Kind.SYSTEM, Nil, "Malformed message:\n" + result.toString)
wenzelm@28063
   300
              result.length = 0
wenzelm@28063
   301
            }
wenzelm@28063
   302
            if (c < 0) {
wenzelm@28063
   303
              reader.close
wenzelm@28063
   304
              finished = true
wenzelm@28063
   305
              try_close()
wenzelm@28045
   306
            }
wenzelm@28045
   307
            else {
wenzelm@28344
   308
              c = reader.read
wenzelm@28344
   309
              if (Kind.code.isDefinedAt(c)) kind = Kind.code(c)
wenzelm@28344
   310
              else kind = null
wenzelm@28063
   311
            }
wenzelm@28063
   312
            //}}}
wenzelm@28063
   313
          }
wenzelm@28063
   314
          else {
wenzelm@28063
   315
            //{{{ Line mode
wenzelm@28063
   316
            val line = reader.readLine
wenzelm@28063
   317
            if (line == null) {
wenzelm@28063
   318
              reader.close
wenzelm@28063
   319
              finished = true
wenzelm@28063
   320
              try_close()
wenzelm@28063
   321
            }
wenzelm@28063
   322
            else {
wenzelm@28063
   323
              val len = line.length
wenzelm@28063
   324
              // property
wenzelm@28063
   325
              if (line.endsWith("\u0002,")) {
wenzelm@28063
   326
                val i = line.indexOf('=')
wenzelm@28063
   327
                if (i > 0) {
wenzelm@28063
   328
                  val name = line.substring(0, i)
wenzelm@28063
   329
                  val value = line.substring(i + 1, len - 2)
wenzelm@29572
   330
                  props = (name, value) :: props
wenzelm@28045
   331
                }
wenzelm@28045
   332
              }
wenzelm@28063
   333
              // last text line
wenzelm@28063
   334
              else if (line.endsWith("\u0002.")) {
wenzelm@28063
   335
                result.append(line.substring(0, len - 2))
wenzelm@29572
   336
                put_result(kind, props.reverse, result.toString)
wenzelm@29573
   337
                kind = null
wenzelm@29573
   338
                props = Nil
wenzelm@28063
   339
                result.length = 0
wenzelm@28063
   340
              }
wenzelm@28063
   341
              // text line
wenzelm@28063
   342
              else {
wenzelm@28063
   343
                result.append(line)
wenzelm@28063
   344
                result.append('\n')
wenzelm@28063
   345
              }
wenzelm@28045
   346
            }
wenzelm@28063
   347
            //}}}
wenzelm@27949
   348
          }
wenzelm@27963
   349
        }
wenzelm@28063
   350
        catch {
wenzelm@29572
   351
          case e: IOException => put_result(Kind.SYSTEM, Nil, "Message thread: " + e.getMessage)
wenzelm@28063
   352
        }
wenzelm@27949
   353
      }
wenzelm@29572
   354
      put_result(Kind.SYSTEM, Nil, "Message thread terminated")
wenzelm@27949
   355
    }
wenzelm@27949
   356
  }
wenzelm@27949
   357
wenzelm@27949
   358
wenzelm@29192
   359
wenzelm@27949
   360
  /** main **/
wenzelm@27949
   361
wenzelm@27949
   362
  {
wenzelm@28497
   363
    /* isabelle version */
wenzelm@28497
   364
wenzelm@28497
   365
    {
wenzelm@29174
   366
      val (msg, rc) = isabelle_system.isabelle_tool("version")
wenzelm@28497
   367
      if (rc != 0) error("Version check failed -- bad Isabelle installation:\n" + msg)
wenzelm@29572
   368
      put_result(Kind.SYSTEM, Nil, msg)
wenzelm@28497
   369
    }
wenzelm@28497
   370
wenzelm@28045
   371
wenzelm@29192
   372
    /* messages */
wenzelm@28045
   373
wenzelm@29174
   374
    val message_fifo = isabelle_system.mk_fifo()
wenzelm@29174
   375
    def rm_fifo() = isabelle_system.rm_fifo(message_fifo)
wenzelm@28045
   376
wenzelm@28063
   377
    val message_thread = new MessageThread(message_fifo)
wenzelm@28063
   378
    message_thread.start
wenzelm@28045
   379
wenzelm@28045
   380
wenzelm@27973
   381
    /* exec process */
wenzelm@27963
   382
wenzelm@27973
   383
    try {
wenzelm@28501
   384
      val cmdline =
wenzelm@29174
   385
        List(isabelle_system.getenv_strict("ISABELLE_PROCESS"), "-W", message_fifo) ++ args
wenzelm@29178
   386
      proc = isabelle_system.execute(true, cmdline: _*)
wenzelm@27949
   387
    }
wenzelm@27993
   388
    catch {
wenzelm@28063
   389
      case e: IOException =>
wenzelm@28063
   390
        rm_fifo()
wenzelm@28063
   391
        error("Failed to execute Isabelle process: " + e.getMessage)
wenzelm@27993
   392
    }
wenzelm@27949
   393
wenzelm@27949
   394
wenzelm@28045
   395
    /* stdin/stdout */
wenzelm@28045
   396
wenzelm@28045
   397
    new StdinThread(proc.getOutputStream).start
wenzelm@28045
   398
    new StdoutThread(proc.getInputStream).start
wenzelm@28045
   399
wenzelm@28045
   400
wenzelm@28045
   401
    /* exit */
wenzelm@27949
   402
wenzelm@28063
   403
    new Thread("isabelle: exit") {
wenzelm@28045
   404
      override def run() = {
wenzelm@28045
   405
        val rc = proc.waitFor()
wenzelm@28045
   406
        Thread.sleep(300)
wenzelm@29572
   407
        put_result(Kind.SYSTEM, Nil, "Exit thread terminated")
wenzelm@29572
   408
        put_result(Kind.EXIT, Nil, Integer.toString(rc))
wenzelm@28063
   409
        rm_fifo()
wenzelm@28045
   410
      }
wenzelm@28063
   411
    }.start
wenzelm@28063
   412
wenzelm@27949
   413
  }
wenzelm@27949
   414
}