src/Pure/System/build.scala
author wenzelm
Fri Jul 27 13:33:34 2012 +0200 (2012-07-27)
changeset 48547 b3b092d0a9fe
parent 48546 f81cf2fcd3a0
child 48548 49afe0e92163
permissions -rw-r--r--
tuned;
     1 /*  Title:      Pure/System/build.scala
     2     Author:     Makarius
     3 
     4 Build and manage Isabelle sessions.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import java.io.{File => JFile, BufferedInputStream, FileInputStream,
    11   BufferedReader, InputStreamReader, IOException}
    12 import java.util.zip.GZIPInputStream
    13 
    14 import scala.collection.mutable
    15 import scala.annotation.tailrec
    16 
    17 
    18 object Build
    19 {
    20   /** session information **/
    21 
    22   object Session
    23   {
    24     /* Info */
    25 
    26     sealed case class Info(
    27       groups: List[String],
    28       dir: Path,
    29       parent: Option[String],
    30       description: String,
    31       options: Options,
    32       theories: List[(Options, List[Path])],
    33       files: List[Path],
    34       entry_digest: SHA1.Digest)
    35 
    36 
    37     /* Queue */
    38 
    39     object Queue
    40     {
    41       val empty: Queue = new Queue()
    42     }
    43 
    44     final class Queue private(graph: Graph[String, Info] = Graph.string)
    45       extends PartialFunction[String, Info]
    46     {
    47       def apply(name: String): Info = graph.get_node(name)
    48       def isDefinedAt(name: String): Boolean = graph.defined(name)
    49 
    50       def is_inner(name: String): Boolean = !graph.is_maximal(name)
    51 
    52       def is_empty: Boolean = graph.is_empty
    53 
    54       def + (name: String, info: Info): Queue =
    55         new Queue(
    56           try { graph.new_node(name, info).add_deps_acyclic(name, info.parent.toList) }
    57           catch {
    58             case _: Graph.Duplicate[_] => error("Duplicate session: " + quote(name))
    59             case exn: Graph.Cycles[_] =>
    60               error(cat_lines(exn.cycles.map(cycle =>
    61                 "Cyclic session dependency of " +
    62                   cycle.map(c => quote(c.toString)).mkString(" via "))))
    63           })
    64 
    65       def - (name: String): Queue = new Queue(graph.del_node(name))
    66 
    67       def required(groups: List[String], names: List[String]): Queue =
    68       {
    69         val selected_group = groups.toSet
    70         val selected_name = names.toSet
    71         val selected =
    72           graph.keys.filter(name =>
    73             selected_name(name) || apply(name).groups.exists(selected_group)).toList
    74         new Queue(graph.restrict(graph.all_preds(selected).toSet))
    75       }
    76 
    77       def dequeue(skip: String => Boolean): Option[(String, Info)] =
    78       {
    79         val it = graph.entries.dropWhile(
    80           { case (name, (_, (deps, _))) => !deps.isEmpty || skip(name) })
    81         if (it.hasNext) { val (name, (info, _)) = it.next; Some((name, info)) }
    82         else None
    83       }
    84 
    85       def topological_order: List[(String, Info)] =
    86         graph.topological_order.map(name => (name, graph.get_node(name)))
    87     }
    88   }
    89 
    90 
    91   /* parsing */
    92 
    93   private case class Session_Entry(
    94     base_name: String,
    95     this_name: Boolean,
    96     groups: List[String],
    97     path: Option[String],
    98     parent: Option[String],
    99     description: String,
   100     options: List[Options.Spec],
   101     theories: List[(List[Options.Spec], List[String])],
   102     files: List[String])
   103 
   104   private object Parser extends Parse.Parser
   105   {
   106     val SESSION = "session"
   107     val IN = "in"
   108     val DESCRIPTION = "description"
   109     val OPTIONS = "options"
   110     val THEORIES = "theories"
   111     val FILES = "files"
   112 
   113     val syntax =
   114       Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
   115         SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
   116 
   117     val session_entry: Parser[Session_Entry] =
   118     {
   119       val session_name = atom("session name", _.is_name)
   120 
   121       val option =
   122         name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   123       val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
   124 
   125       val theories =
   126         keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
   127           { case _ ~ (x ~ y) => (x, y) }
   128 
   129       ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
   130         (keyword("!") ^^^ true | success(false)) ~
   131         (keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x } | success(Nil)) ~
   132         (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
   133         (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
   134         (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
   135         (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
   136         rep(theories) ~
   137         (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
   138           { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
   139     }
   140 
   141     def parse_entries(root: JFile): List[Session_Entry] =
   142     {
   143       val toks = syntax.scan(File.read(root))
   144       parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
   145         case Success(result, _) => result
   146         case bad => error(bad.toString)
   147       }
   148     }
   149   }
   150 
   151 
   152   /* find sessions */
   153 
   154   private val ROOT = Path.explode("ROOT")
   155   private val SESSIONS = Path.explode("etc/sessions")
   156 
   157   private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
   158 
   159   private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
   160     : Session.Queue =
   161   {
   162     (queue /: Parser.parse_entries(root))((queue1, entry) =>
   163       try {
   164         if (entry.base_name == "") error("Bad session name")
   165 
   166         val full_name =
   167           if (is_pure(entry.base_name)) {
   168             if (entry.parent.isDefined) error("Illegal parent session")
   169             else entry.base_name
   170           }
   171           else
   172             entry.parent match {
   173               case Some(parent_name) if queue1.isDefinedAt(parent_name) =>
   174                 val full_name =
   175                   if (entry.this_name) entry.base_name
   176                   else parent_name + "-" + entry.base_name
   177                 full_name
   178               case _ => error("Bad parent session")
   179             }
   180 
   181         val path =
   182           entry.path match {
   183             case Some(p) => Path.explode(p)
   184             case None => Path.basic(entry.base_name)
   185           }
   186 
   187         val session_options = options ++ entry.options
   188 
   189         val theories =
   190           entry.theories.map({ case (opts, thys) =>
   191             (session_options ++ opts, thys.map(Path.explode(_))) })
   192         val files = entry.files.map(Path.explode(_))
   193         val entry_digest =
   194           SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
   195 
   196         val info =
   197           Session.Info(entry.groups, dir + path, entry.parent, entry.description,
   198             session_options, theories, files, entry_digest)
   199 
   200         queue1 + (full_name, info)
   201       }
   202       catch {
   203         case ERROR(msg) =>
   204           error(msg + "\nThe error(s) above occurred in session entry " +
   205             quote(entry.base_name) + Position.str_of(Position.file(root)))
   206       })
   207   }
   208 
   209   private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
   210     : Session.Queue =
   211   {
   212     val root = (dir + ROOT).file
   213     if (root.isFile) sessions_root(options, dir, root, queue)
   214     else if (strict) error("Bad session root file: " + quote(root.toString))
   215     else queue
   216   }
   217 
   218   private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
   219     : Session.Queue =
   220   {
   221     val dirs =
   222       split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
   223     (queue /: dirs)((queue1, dir1) =>
   224       try {
   225         val dir2 = dir + Path.explode(dir1)
   226         if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
   227         else error("Bad session directory: " + dir2.toString)
   228       }
   229       catch {
   230         case ERROR(msg) =>
   231           error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
   232       })
   233   }
   234 
   235   def find_sessions(options: Options, more_dirs: List[Path],
   236     all_sessions: Boolean, session_groups: List[String], sessions: List[String]): Session.Queue =
   237   {
   238     var queue = Session.Queue.empty
   239 
   240     for (dir <- Isabelle_System.components()) {
   241       queue = sessions_dir(options, false, dir, queue)
   242 
   243       val catalog = (dir + SESSIONS).file
   244       if (catalog.isFile)
   245         queue = sessions_catalog(options, dir, catalog, queue)
   246     }
   247 
   248     for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
   249 
   250     sessions.filter(name => !queue.isDefinedAt(name)) match {
   251       case Nil =>
   252       case bad => error("Undefined session(s): " + commas_quote(bad))
   253     }
   254 
   255     if (all_sessions) queue else queue.required(session_groups, sessions)
   256   }
   257 
   258 
   259 
   260   /** build **/
   261 
   262   private def echo(msg: String) { java.lang.System.out.println(msg) }
   263   private def sleep(): Unit = Thread.sleep(500)
   264 
   265 
   266   /* source dependencies */
   267 
   268   sealed case class Node(
   269     loaded_theories: Set[String],
   270     sources: List[(Path, SHA1.Digest)])
   271 
   272   sealed case class Deps(deps: Map[String, Node])
   273   {
   274     def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
   275   }
   276 
   277   def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
   278     Deps((Map.empty[String, Node] /: queue.topological_order)(
   279       { case (deps, (name, info)) =>
   280           val preloaded =
   281             info.parent match {
   282               case None => Set.empty[String]
   283               case Some(parent) => deps(parent).loaded_theories
   284             }
   285           val thy_info = new Thy_Info(new Thy_Load(preloaded))
   286 
   287           if (verbose) echo("Checking " + name + " ...")
   288 
   289           val thy_deps =
   290             thy_info.dependencies(
   291               info.theories.map(_._2).flatten.
   292                 map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
   293 
   294           val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
   295 
   296           val all_files =
   297             thy_deps.map({ case (n, h) =>
   298               val thy = Path.explode(n.node).expand
   299               val uses =
   300                 h match {
   301                   case Exn.Res(d) =>
   302                     d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
   303                   case _ => Nil
   304                 }
   305               thy :: uses
   306             }).flatten ::: info.files.map(file => info.dir + file)
   307           val sources =
   308             try { all_files.map(p => (p, SHA1.digest(p))) }
   309             catch {
   310               case ERROR(msg) =>
   311                 error(msg + "\nThe error(s) above occurred in session " + quote(name))
   312             }
   313 
   314           deps + (name -> Node(loaded_theories, sources))
   315       }))
   316 
   317 
   318   /* jobs */
   319 
   320   private class Job(cwd: JFile, env: Map[String, String], script: String, args: String,
   321     output: Path, do_output: Boolean)
   322   {
   323     private val args_file = File.tmp_file("args")
   324     private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
   325     File.write(args_file, args)
   326 
   327     private val (thread, result) =
   328       Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
   329 
   330     def terminate: Unit = thread.interrupt
   331     def is_finished: Boolean = result.is_finished
   332     def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
   333     def output_path: Option[Path] = if (do_output) Some(output) else None
   334   }
   335 
   336   private def start_job(name: String, info: Session.Info, output: Path, do_output: Boolean,
   337     options: Options, verbose: Boolean, browser_info: Path): Job =
   338   {
   339     // global browser info dir
   340     if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).file.isFile)
   341     {
   342       browser_info.file.mkdirs()
   343       File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
   344         browser_info + Path.explode("isabelle.gif"))
   345       File.write(browser_info + Path.explode("index.html"),
   346         File.read(Path.explode("~~/lib/html/library_index_header.template")) +
   347         File.read(Path.explode("~~/lib/html/library_index_content.template")) +
   348         File.read(Path.explode("~~/lib/html/library_index_footer.template")))
   349     }
   350 
   351     val parent = info.parent.getOrElse("")
   352 
   353     val cwd = info.dir.file
   354     val env =
   355       Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output))
   356     val script =
   357       if (is_pure(name)) {
   358         if (do_output) "./build " + name + " \"$OUTPUT\""
   359         else """ rm -f "$OUTPUT"; ./build """ + name
   360       }
   361       else {
   362         """
   363         . "$ISABELLE_HOME/lib/scripts/timestart.bash"
   364         """ +
   365           (if (do_output)
   366             """
   367             "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
   368             """
   369           else
   370             """
   371             rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
   372             """) +
   373         """
   374         RC="$?"
   375 
   376         . "$ISABELLE_HOME/lib/scripts/timestop.bash"
   377 
   378         if [ "$RC" -eq 0 ]; then
   379           echo "Finished $TARGET ($TIMES_REPORT)" >&2
   380         fi
   381 
   382         exit "$RC"
   383         """
   384       }
   385     val args_xml =
   386     {
   387       import XML.Encode._
   388           pair(bool, pair(Options.encode, pair(bool, pair(Path.encode, pair(string,
   389             pair(string, list(pair(Options.encode, list(Path.encode)))))))))(
   390           (do_output, (options, (verbose, (browser_info, (parent,
   391             (name, info.theories)))))))
   392     }
   393     new Job(cwd, env, script, YXML.string_of_body(args_xml), output, do_output)
   394   }
   395 
   396 
   397   /* log files and corresponding heaps */
   398 
   399   private val LOG = Path.explode("log")
   400   private def log(name: String): Path = LOG + Path.basic(name)
   401   private def log_gz(name: String): Path = log(name).ext("gz")
   402 
   403   private def sources_stamp(digests: List[SHA1.Digest]): String =
   404     digests.map(_.toString).sorted.mkString("sources: ", " ", "")
   405 
   406   private def heap_stamp(output: Option[Path]): String =
   407   {
   408     "heap: " +
   409       (output match {
   410         case Some(path) =>
   411           val file = path.file
   412           if (file.isFile) file.length.toString + " " + file.lastModified.toString
   413           else "-"
   414         case None => "-"
   415       })
   416   }
   417 
   418   private def check_stamps(dir: Path, name: String): Option[(String, Boolean)] =
   419   {
   420     val file = (dir + log_gz(name)).file
   421     if (file.isFile) {
   422       val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(file)))
   423       val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
   424       val (s, h) = try { (reader.readLine, reader.readLine) } finally { reader.close }
   425       if (s != null && s.startsWith("sources: ") && h != null && h.startsWith("heap: ") &&
   426           h == heap_stamp(Some(dir + Path.basic(name)))) Some((s, h != "heap: -"))
   427       else None
   428     }
   429     else None
   430   }
   431 
   432 
   433   /* build */
   434 
   435   def build(
   436     all_sessions: Boolean = false,
   437     build_heap: Boolean = false,
   438     more_dirs: List[Path] = Nil,
   439     session_groups: List[String] = Nil,
   440     max_jobs: Int = 1,
   441     no_build: Boolean = false,
   442     build_options: List[String] = Nil,
   443     system_mode: Boolean = false,
   444     verbose: Boolean = false,
   445     sessions: List[String] = Nil): Int =
   446   {
   447     val options = (Options.init() /: build_options)(_.define_simple(_))
   448     val queue = find_sessions(options, more_dirs, all_sessions, session_groups, sessions)
   449     val deps = dependencies(verbose, queue)
   450 
   451     def make_stamp(name: String): String =
   452       sources_stamp(queue(name).entry_digest :: deps.sources(name))
   453 
   454     val (input_dirs, output_dir, browser_info) =
   455       if (system_mode) {
   456         val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
   457         (List(output_dir), output_dir, Path.explode("~~/browser_info"))
   458       }
   459       else {
   460         val output_dir = Path.explode("$ISABELLE_OUTPUT")
   461         (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
   462          Path.explode("$ISABELLE_BROWSER_INFO"))
   463       }
   464 
   465     // prepare log dir
   466     (output_dir + LOG).file.mkdirs()
   467 
   468     // scheduler loop
   469     @tailrec def loop(
   470       pending: Session.Queue,
   471       running: Map[String, Job],
   472       results: Map[String, (Boolean, Int)]): Map[String, (Boolean, Int)] =
   473     {
   474       if (pending.is_empty) results
   475       else
   476         running.find({ case (_, job) => job.is_finished }) match {
   477           case Some((name, job)) =>
   478             // finish job
   479 
   480             val (out, err, rc) = job.join
   481             echo(Library.trim_line(err))
   482 
   483             if (rc == 0) {
   484               val sources = make_stamp(name)
   485               val heap = heap_stamp(job.output_path)
   486               File.write_gzip(output_dir + log_gz(name), sources + "\n" + heap + "\n" + out)
   487             }
   488             else {
   489               File.write(output_dir + log(name), out)
   490               echo(name + " FAILED")
   491               echo("(see also " + log(name).file.toString + ")")
   492               val lines = split_lines(out)
   493               val tail = lines.drop(lines.length - 20 max 0)
   494               echo("\n" + cat_lines(tail))
   495             }
   496             loop(pending - name, running - name, results + (name -> (false, rc)))
   497 
   498           case None if (running.size < (max_jobs max 1)) =>
   499             // check/start next job
   500             pending.dequeue(running.isDefinedAt(_)) match {
   501               case Some((name, info)) =>
   502                 val parent_result = info.parent.map(results(_))
   503                 val parent_current = parent_result.forall(_._1)
   504                 val parent_ok = parent_result.forall(_._2 == 0)
   505 
   506                 val output = output_dir + Path.basic(name)
   507                 val do_output = build_heap || queue.is_inner(name)
   508 
   509                 val current =
   510                 {
   511                   input_dirs.find(dir => (dir + log_gz(name)).file.isFile) match {
   512                     case Some(dir) =>
   513                       check_stamps(dir, name) match {
   514                         case Some((s, h)) => s == make_stamp(name) && (h || !do_output)
   515                         case None => false
   516                       }
   517                     case None => false
   518                   }
   519                 }
   520                 val all_current = current && parent_current
   521 
   522                 if (all_current)
   523                   loop(pending - name, running, results + (name -> (true, 0)))
   524                 else if (no_build)
   525                   loop(pending - name, running, results + (name -> (false, 1)))
   526                 else if (parent_ok) {
   527                   echo((if (do_output) "Building " else "Running ") + name + " ...")
   528                   val job =
   529                     start_job(name, info, output, do_output, info.options, verbose, browser_info)
   530                   loop(pending, running + (name -> job), results)
   531                 }
   532                 else {
   533                   echo(name + " CANCELLED")
   534                   loop(pending - name, running, results + (name -> (false, 1)))
   535                 }
   536               case None => sleep(); loop(pending, running, results)
   537             }
   538           case None => sleep(); loop(pending, running, results)
   539         }
   540     }
   541 
   542     val results = loop(queue, Map.empty, Map.empty)
   543     val rc = (0 /: results)({ case (rc1, (_, (_, rc2))) => rc1 max rc2 })
   544     if (rc != 0 && (verbose || !no_build)) {
   545       val unfinished = (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
   546       echo("Unfinished session(s): " + commas(unfinished))
   547     }
   548     rc
   549   }
   550 
   551 
   552   /* command line entry point */
   553 
   554   def main(args: Array[String])
   555   {
   556     Command_Line.tool {
   557       args.toList match {
   558         case
   559           Properties.Value.Boolean(all_sessions) ::
   560           Properties.Value.Boolean(build_heap) ::
   561           Properties.Value.Int(max_jobs) ::
   562           Properties.Value.Boolean(no_build) ::
   563           Properties.Value.Boolean(system_mode) ::
   564           Properties.Value.Boolean(verbose) ::
   565           Command_Line.Chunks(more_dirs, session_groups, build_options, sessions) =>
   566             build(all_sessions, build_heap, more_dirs.map(Path.explode), session_groups,
   567               max_jobs, no_build, build_options, system_mode, verbose, sessions)
   568         case _ => error("Bad arguments:\n" + cat_lines(args))
   569       }
   570     }
   571   }
   572 }
   573