src/Pure/System/isabelle_system.scala
author wenzelm
Mon Jul 15 10:25:35 2013 +0200 (2013-07-15 ago)
changeset 52655 3b2b1ef13979
parent 52112 3610ae73cfdb
child 52667 d2b12523186d
permissions -rw-r--r--
more careful termination of removed execs, leaving running execs undisturbed;
     1 /*  Title:      Pure/System/isabelle_system.scala
     2     Author:     Makarius
     3 
     4 Fundamental Isabelle system environment: quasi-static module with
     5 optional init operation.
     6 */
     7 
     8 package isabelle
     9 
    10 import java.lang.System
    11 import java.util.regex.Pattern
    12 import java.io.{File => JFile, BufferedReader, InputStreamReader,
    13   BufferedWriter, OutputStreamWriter}
    14 
    15 import scala.util.matching.Regex
    16 
    17 
    18 object Isabelle_System
    19 {
    20   /** bootstrap information **/
    21 
    22   def jdk_home(): String =
    23   {
    24     val java_home = System.getProperty("java.home")
    25     val home = new JFile(java_home)
    26     val parent = home.getParent
    27     if (home.getName == "jre" && parent != null &&
    28         (new JFile(new JFile(parent, "bin"), "javac")).exists) parent
    29     else java_home
    30   }
    31 
    32   private def find_cygwin_root(cygwin_root0: String = ""): String =
    33   {
    34     require(Platform.is_windows)
    35 
    36     val cygwin_root1 = System.getenv("CYGWIN_ROOT")
    37     val cygwin_root2 = System.getProperty("cygwin.root")
    38 
    39     if (cygwin_root0 != null && cygwin_root0 != "") cygwin_root0
    40     else if (cygwin_root1 != null && cygwin_root1 != "") cygwin_root1
    41     else if (cygwin_root2 != null && cygwin_root2 != "") cygwin_root2
    42     else error("Cannot determine Cygwin root directory")
    43   }
    44 
    45 
    46 
    47   /** implicit settings environment **/
    48 
    49   @volatile private var _settings: Option[Map[String, String]] = None
    50 
    51   def settings(): Map[String, String] =
    52   {
    53     if (_settings.isEmpty) init()  // unsynchronized check
    54     _settings.get
    55   }
    56 
    57   /*
    58     Isabelle home precedence:
    59       (1) isabelle_home as explicit argument
    60       (2) ISABELLE_HOME process environment variable (e.g. inherited from running isabelle tool)
    61       (3) isabelle.home system property (e.g. via JVM application boot process)
    62   */
    63   def init(isabelle_home: String = "", cygwin_root: String = ""): Unit = synchronized {
    64     if (_settings.isEmpty) {
    65       import scala.collection.JavaConversions._
    66 
    67       def set_cygwin_root()
    68       {
    69         if (Platform.is_windows)
    70           _settings = Some(_settings.getOrElse(Map.empty) +
    71             ("CYGWIN_ROOT" -> find_cygwin_root(cygwin_root)))
    72       }
    73 
    74       set_cygwin_root()
    75       val env0 = sys.env + ("ISABELLE_JDK_HOME" -> posix_path(jdk_home()))
    76 
    77       val user_home = System.getProperty("user.home")
    78       val env =
    79         if (user_home == null || env0.isDefinedAt("HOME")) env0
    80         else env0 + ("HOME" -> user_home)
    81 
    82       val system_home =
    83         if (isabelle_home != null && isabelle_home != "") isabelle_home
    84         else
    85           env.get("ISABELLE_HOME") match {
    86             case None | Some("") =>
    87               val path = System.getProperty("isabelle.home")
    88               if (path == null || path == "") error("Unknown Isabelle home directory")
    89               else path
    90             case Some(path) => path
    91           }
    92 
    93       val settings =
    94         File.with_tmp_file("settings") { dump =>
    95           val shell_prefix =
    96             if (Platform.is_windows) List(find_cygwin_root(cygwin_root) + "\\bin\\bash", "-l")
    97             else Nil
    98           val cmdline =
    99             shell_prefix ::: List(system_home + "/bin/isabelle", "getenv", "-d", dump.toString)
   100           val (output, rc) = process_output(raw_execute(null, env, true, cmdline: _*))
   101           if (rc != 0) error(output)
   102   
   103           val entries =
   104             (for (entry <- File.read(dump) split "\0" if entry != "") yield {
   105               val i = entry.indexOf('=')
   106               if (i <= 0) (entry -> "")
   107               else (entry.substring(0, i) -> entry.substring(i + 1))
   108             }).toMap
   109           entries + ("PATH" -> entries("PATH_JVM")) - "PATH_JVM"
   110         }
   111       _settings = Some(settings)
   112       set_cygwin_root()
   113     }
   114   }
   115 
   116 
   117   /* getenv */
   118 
   119   def getenv(name: String): String = settings.getOrElse(name, "")
   120 
   121   def getenv_strict(name: String): String =
   122   {
   123     val value = getenv(name)
   124     if (value != "") value else error("Undefined environment variable: " + name)
   125   }
   126 
   127   def get_cygwin_root(): String = getenv_strict("CYGWIN_ROOT")
   128 
   129 
   130   /** file-system operations **/
   131 
   132   /* jvm_path */
   133 
   134   private val Cygdrive = new Regex("/cygdrive/([a-zA-Z])($|/.*)")
   135   private val Named_Root = new Regex("//+([^/]*)(.*)")
   136 
   137   def jvm_path(posix_path: String): String =
   138     if (Platform.is_windows) {
   139       val result_path = new StringBuilder
   140       val rest =
   141         posix_path match {
   142           case Cygdrive(drive, rest) =>
   143             result_path ++= (Library.uppercase(drive) + ":" + JFile.separator)
   144             rest
   145           case Named_Root(root, rest) =>
   146             result_path ++= JFile.separator
   147             result_path ++= JFile.separator
   148             result_path ++= root
   149             rest
   150           case path if path.startsWith("/") =>
   151             result_path ++= get_cygwin_root()
   152             path
   153           case path => path
   154         }
   155       for (p <- space_explode('/', rest) if p != "") {
   156         val len = result_path.length
   157         if (len > 0 && result_path(len - 1) != JFile.separatorChar)
   158           result_path += JFile.separatorChar
   159         result_path ++= p
   160       }
   161       result_path.toString
   162     }
   163     else posix_path
   164 
   165 
   166   /* posix_path */
   167 
   168   def posix_path(jvm_path: String): String =
   169     if (Platform.is_windows) {
   170       val Platform_Root = new Regex("(?i)" +
   171         Pattern.quote(get_cygwin_root()) + """(?:\\+|\z)(.*)""")
   172       val Drive = new Regex("""([a-zA-Z]):\\*(.*)""")
   173 
   174       jvm_path.replace('/', '\\') match {
   175         case Platform_Root(rest) => "/" + rest.replace('\\', '/')
   176         case Drive(letter, rest) =>
   177           "/cygdrive/" + Library.lowercase(letter) +
   178             (if (rest == "") "" else "/" + rest.replace('\\', '/'))
   179         case path => path.replace('\\', '/')
   180       }
   181     }
   182     else jvm_path
   183 
   184   def posix_path(file: JFile): String = posix_path(file.getPath)
   185 
   186 
   187   /* misc path specifications */
   188 
   189   def standard_path(path: Path): String = path.expand.implode
   190 
   191   def platform_path(path: Path): String = jvm_path(standard_path(path))
   192   def platform_file(path: Path): JFile = new JFile(platform_path(path))
   193 
   194   def platform_file_url(raw_path: Path): String =
   195   {
   196     val path = raw_path.expand
   197     require(path.is_absolute)
   198     val s = platform_path(path).replaceAll(" ", "%20")
   199     if (!Platform.is_windows) "file://" + s
   200     else if (s.startsWith("\\\\")) "file:" + s.replace('\\', '/')
   201     else "file:///" + s.replace('\\', '/')
   202   }
   203 
   204 
   205   /* source files of Isabelle/ML bootstrap */
   206 
   207   def source_file(path: Path): Option[Path] =
   208   {
   209     def check(p: Path): Option[Path] = if (p.is_file) Some(p) else None
   210 
   211     if (path.is_absolute || path.is_current) check(path)
   212     else {
   213       check(Path.explode("~~/src/Pure") + path) orElse
   214         (if (getenv("ML_SOURCES") == "") None else check(Path.explode("$ML_SOURCES") + path))
   215     }
   216   }
   217 
   218 
   219   /* mkdirs */
   220 
   221   def mkdirs(path: Path)
   222   {
   223     path.file.mkdirs
   224     if (!path.is_dir) error("Cannot create directory: " + quote(platform_path(path)))
   225   }
   226 
   227 
   228 
   229   /** external processes **/
   230 
   231   /* raw execute for bootstrapping */
   232 
   233   private def raw_execute(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*)
   234     : Process =
   235   {
   236     val cmdline = new java.util.LinkedList[String]
   237     for (s <- args) cmdline.add(s)
   238 
   239     val proc = new ProcessBuilder(cmdline)
   240     if (cwd != null) proc.directory(cwd)
   241     if (env != null) {
   242       proc.environment.clear
   243       for ((x, y) <- env) proc.environment.put(x, y)
   244     }
   245     proc.redirectErrorStream(redirect)
   246     proc.start
   247   }
   248 
   249   private def process_output(proc: Process): (String, Int) =
   250   {
   251     proc.getOutputStream.close
   252     val output = File.read_stream(proc.getInputStream)
   253     val rc =
   254       try { proc.waitFor }
   255       finally {
   256         proc.getInputStream.close
   257         proc.getErrorStream.close
   258         proc.destroy
   259         Thread.interrupted
   260       }
   261     (output, rc)
   262   }
   263 
   264 
   265   /* plain execute */
   266 
   267   def execute_env(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*): Process =
   268   {
   269     val cmdline =
   270       if (Platform.is_windows) List(get_cygwin_root() + "\\bin\\env.exe") ++ args
   271       else args
   272     val env1 = if (env == null) settings else settings ++ env
   273     raw_execute(cwd, env1, redirect, cmdline: _*)
   274   }
   275 
   276   def execute(redirect: Boolean, args: String*): Process =
   277     execute_env(null, null, redirect, args: _*)
   278 
   279 
   280   /* managed process */
   281 
   282   class Managed_Process(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*)
   283   {
   284     private val params =
   285       List(standard_path(Path.explode("~~/lib/scripts/process")), "group", "-", "no_script")
   286     private val proc = execute_env(cwd, env, redirect, (params ++ args):_*)
   287 
   288 
   289     // channels
   290 
   291     val stdin: BufferedWriter =
   292       new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, UTF8.charset))
   293 
   294     val stdout: BufferedReader =
   295       new BufferedReader(new InputStreamReader(proc.getInputStream, UTF8.charset))
   296 
   297     val stderr: BufferedReader =
   298       new BufferedReader(new InputStreamReader(proc.getErrorStream, UTF8.charset))
   299 
   300 
   301     // signals
   302 
   303     private val pid = stdout.readLine
   304 
   305     private def kill(signal: String): Boolean =
   306     {
   307       try {
   308         execute(true, "kill", "-" + signal, "--", "-" + pid).waitFor
   309         execute(true, "kill", "-0", "--", "-" + pid).waitFor == 0
   310       }
   311       catch { case _: InterruptedException => true }
   312     }
   313 
   314     private def multi_kill(signal: String): Boolean =
   315     {
   316       var running = true
   317       var count = 10
   318       while (running && count > 0) {
   319         if (kill(signal)) {
   320           try { Thread.sleep(100) } catch { case _: InterruptedException => }
   321           count -= 1
   322         }
   323         else running = false
   324       }
   325       running
   326     }
   327 
   328     def interrupt() { multi_kill("INT") }
   329     def terminate() { multi_kill("INT") && multi_kill("TERM") && kill("KILL"); proc.destroy }
   330 
   331 
   332     // JVM shutdown hook
   333 
   334     private val shutdown_hook = new Thread { override def run = terminate() }
   335 
   336     try { Runtime.getRuntime.addShutdownHook(shutdown_hook) }
   337     catch { case _: IllegalStateException => }
   338 
   339     private def cleanup() =
   340       try { Runtime.getRuntime.removeShutdownHook(shutdown_hook) }
   341       catch { case _: IllegalStateException => }
   342 
   343 
   344     /* result */
   345 
   346     def join: Int = { val rc = proc.waitFor; cleanup(); rc }
   347   }
   348 
   349 
   350   /* bash */
   351 
   352   final case class Bash_Result(out_lines: List[String], err_lines: List[String], rc: Int)
   353   {
   354     def out: String = cat_lines(out_lines)
   355     def err: String = cat_lines(err_lines)
   356     def add_err(s: String): Bash_Result = copy(err_lines = err_lines ::: List(s))
   357     def set_rc(i: Int): Bash_Result = copy(rc = i)
   358   }
   359 
   360   def bash_env(cwd: JFile, env: Map[String, String], script: String,
   361     progress_stdout: String => Unit = (_: String) => (),
   362     progress_stderr: String => Unit = (_: String) => (),
   363     progress_limit: Option[Long] = None): Bash_Result =
   364   {
   365     File.with_tmp_file("isabelle_script") { script_file =>
   366       File.write(script_file, script)
   367       val proc = new Managed_Process(cwd, env, false, "bash", posix_path(script_file))
   368       proc.stdin.close
   369 
   370       val limited = new Object {
   371         private var count = 0L
   372         def apply(progress: String => Unit)(line: String): Unit = synchronized {
   373           progress(line)
   374           count = count + line.length + 1
   375           progress_limit match {
   376             case Some(limit) if count > limit => proc.terminate
   377             case _ =>
   378           }
   379         }
   380       }
   381       val (_, stdout) =
   382         Simple_Thread.future("bash_stdout") {
   383           File.read_lines(proc.stdout, limited(progress_stdout))
   384         }
   385       val (_, stderr) =
   386         Simple_Thread.future("bash_stderr") {
   387           File.read_lines(proc.stderr, limited(progress_stderr))
   388         }
   389 
   390       val rc =
   391         try { proc.join }
   392         catch { case e: InterruptedException => proc.terminate; 130 }
   393       Bash_Result(stdout.join, stderr.join, rc)
   394     }
   395   }
   396 
   397   def bash(script: String): Bash_Result = bash_env(null, null, script)
   398 
   399 
   400   /* system tools */
   401 
   402   def isabelle_tool(name: String, args: String*): (String, Int) =
   403   {
   404     Path.split(getenv_strict("ISABELLE_TOOLS")).find { dir =>
   405       val file = (dir + Path.basic(name)).file
   406       try {
   407         file.isFile && file.canRead && file.canExecute &&
   408           !name.endsWith("~") && !name.endsWith(".orig")
   409       }
   410       catch { case _: SecurityException => false }
   411     } match {
   412       case Some(dir) =>
   413         val file = standard_path(dir + Path.basic(name))
   414         process_output(execute(true, (List(file) ++ args): _*))
   415       case None => ("Unknown Isabelle tool: " + name, 2)
   416     }
   417   }
   418 
   419 
   420 
   421   /** Isabelle resources **/
   422 
   423   /* components */
   424 
   425   def components(): List[Path] =
   426     Path.split(getenv_strict("ISABELLE_COMPONENTS"))
   427 
   428 
   429   /* logic images */
   430 
   431   def find_logics_dirs(): List[Path] =
   432   {
   433     val ml_ident = Path.explode("$ML_IDENTIFIER").expand
   434     Path.split(getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
   435   }
   436 
   437   def find_logics(): List[String] =
   438     (for {
   439       dir <- find_logics_dirs()
   440       files = dir.file.listFiles() if files != null
   441       file <- files.toList if file.isFile } yield file.getName).sorted
   442 
   443   def default_logic(args: String*): String =
   444   {
   445     args.find(_ != "") match {
   446       case Some(logic) => logic
   447       case None => Isabelle_System.getenv_strict("ISABELLE_LOGIC")
   448     }
   449   }
   450 }