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