1 /* Title: Pure/System/build.scala
4 Build and manage Isabelle sessions.
10 import java.io.{File => JFile}
12 import scala.collection.mutable
13 import scala.annotation.tailrec
18 /** session information **/
26 object Ordering extends scala.math.Ordering[Key]
28 def compare(key1: Key, key2: Key): Int =
29 key1.order compare key2.order match {
30 case 0 => key1.name compare key2.name
36 sealed case class Key(name: String, order: Int)
38 override def toString: String = name
44 sealed case class Info(
46 parent: Option[String],
49 theories: List[(Options, List[Path])],
58 val empty: Queue = new Queue()
61 final class Queue private(
62 keys: Map[String, Key] = Map.empty,
63 graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
65 def is_empty: Boolean = graph.is_empty
67 def apply(name: String): Info = graph.get_node(keys(name))
68 def defined(name: String): Boolean = keys.isDefinedAt(name)
69 def is_inner(name: String): Boolean = !graph.is_maximal(keys(name))
71 def + (key: Key, info: Info): Queue =
74 if (defined(key.name)) error("Duplicate session: " + quote(key.name))
75 else keys + (key.name -> key)
79 graph.new_node(key, info).add_deps_acyclic(key, info.parent.toList.map(keys(_)))
82 case exn: Graph.Cycles[_] =>
83 error(cat_lines(exn.cycles.map(cycle =>
84 "Cyclic session dependency of " +
85 cycle.map(key => quote(key.toString)).mkString(" via "))))
87 new Queue(keys1, graph1)
90 def - (name: String): Queue = new Queue(keys - name, graph.del_node(keys(name)))
92 def required(names: List[String]): Queue =
94 val req = graph.all_preds(names.map(keys(_))).map(_.name).toSet
95 val keys1 = keys -- keys.keySet.filter(name => !req(name))
96 val graph1 = graph.restrict(key => keys1.isDefinedAt(key.name))
97 new Queue(keys1, graph1)
100 def dequeue(skip: String => Boolean): Option[(String, Info)] =
102 val it = graph.entries.dropWhile(
103 { case (key, (_, (deps, _))) => !deps.isEmpty || skip(key.name) })
104 if (it.hasNext) { val (key, (info, _)) = it.next; Some((key.name, info)) }
108 def topological_order: List[(String, Info)] =
109 graph.topological_order.map(key => (key.name, graph.get_node(key)))
116 private case class Session_Entry(
120 path: Option[String],
121 parent: Option[String],
123 options: List[Options.Spec],
124 theories: List[(List[Options.Spec], List[String])],
127 private object Parser extends Parse.Parser
129 val SESSION = "session"
131 val DESCRIPTION = "description"
132 val OPTIONS = "options"
133 val THEORIES = "theories"
137 Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
138 SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
140 val session_entry: Parser[Session_Entry] =
142 val session_name = atom("session name", _.is_name)
143 val theory_name = atom("theory name", _.is_name)
146 name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
147 val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
150 keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
151 { case _ ~ (x ~ y) => (x, y) }
153 ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
154 (keyword("!") ^^^ true | success(false)) ~
155 (keyword("(") ~! (nat <~ keyword(")")) ^^ { case _ ~ x => x } | success(Integer.MAX_VALUE)) ~
156 (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
157 (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
158 (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
159 (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
161 (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
162 { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
165 def parse_entries(root: JFile): List[Session_Entry] =
167 val toks = syntax.scan(File.read(root))
168 parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
169 case Success(result, _) => result
170 case bad => error(bad.toString)
178 private val ROOT = Path.explode("ROOT")
179 private val SESSIONS = Path.explode("etc/sessions")
181 private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
183 private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
186 (queue /: Parser.parse_entries(root))((queue1, entry) =>
188 if (entry.name == "") error("Bad session name")
191 if (is_pure(entry.name)) {
192 if (entry.parent.isDefined) error("Illegal parent session")
197 case Some(parent_name) if queue1.defined(parent_name) =>
198 if (entry.reset) entry.name
199 else parent_name + "-" + entry.name
200 case _ => error("Bad parent session")
205 case Some(p) => Path.explode(p)
206 case None => Path.basic(entry.name)
209 val key = Session.Key(full_name, entry.order)
212 entry.theories.map({ case (opts, thys) => (options ++ opts, thys.map(Path.explode(_))) })
213 val files = entry.files.map(Path.explode(_))
214 val digest = SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
217 Session.Info(dir + path, entry.parent,
218 entry.description, options ++ entry.options, theories, files, digest)
224 error(msg + "\nThe error(s) above occurred in session entry " +
225 quote(entry.name) + Position.str_of(Position.file(root)))
229 private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
232 val root = (dir + ROOT).file
233 if (root.isFile) sessions_root(options, dir, root, queue)
234 else if (strict) error("Bad session root file: " + quote(root.toString))
238 private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
242 split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
243 (queue /: dirs)((queue1, dir1) =>
245 val dir2 = dir + Path.explode(dir1)
246 if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
247 else error("Bad session directory: " + dir2.toString)
251 error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
255 def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
256 more_dirs: List[Path]): Session.Queue =
258 var queue = Session.Queue.empty
260 for (dir <- Isabelle_System.components()) {
261 queue = sessions_dir(options, false, dir, queue)
263 val catalog = (dir + SESSIONS).file
265 queue = sessions_catalog(options, dir, catalog, queue)
268 for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
270 sessions.filter(name => !queue.defined(name)) match {
272 case bad => error("Undefined session(s): " + commas_quote(bad))
275 if (all_sessions) queue else queue.required(sessions)
284 sealed case class Node(
285 loaded_theories: Set[String],
286 sources: List[(Path, SHA1.Digest)])
288 sealed case class Deps(deps: Map[String, Node])
290 def sources(name: String): List[(Path, SHA1.Digest)] = deps(name).sources
293 def dependencies(queue: Session.Queue): Deps =
294 Deps((Map.empty[String, Node] /: queue.topological_order)(
295 { case (deps, (name, info)) =>
298 case None => Set.empty[String]
299 case Some(parent) => deps(parent).loaded_theories
301 val thy_info = new Thy_Info(new Thy_Load(preloaded))
304 thy_info.dependencies(
305 info.theories.map(_._2).flatten.
306 map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
308 val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
311 thy_deps.map({ case (n, h) =>
312 val thy = Path.explode(n.node).expand
316 d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
320 }).flatten ::: info.files.map(file => info.dir + file)
321 val sources = all_files.par.map(p => (p, SHA1.digest(p))).toList
323 deps + (name -> Node(loaded_theories, sources))
329 private class Job(cwd: JFile, env: Map[String, String], script: String, args: String)
331 private val args_file = File.tmp_file("args")
332 private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
333 File.write(args_file, args)
335 private val (thread, result) =
336 Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
338 def terminate: Unit = thread.interrupt
339 def is_finished: Boolean = result.is_finished
340 def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
343 private def start_job(save: Boolean, name: String, info: Session.Info): Job =
345 val parent = info.parent.getOrElse("")
347 val cwd = info.dir.file
348 val env = Map("INPUT" -> parent, "TARGET" -> name)
350 if (is_pure(name)) "./build " + (if (save) "-b " else "") + name
353 . "$ISABELLE_HOME/lib/scripts/timestart.bash"
356 """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$TARGET" """
358 """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
362 . "$ISABELLE_HOME/lib/scripts/timestop.bash"
364 if [ "$RC" -eq 0 ]; then
365 echo "Finished $TARGET ($TIMES_REPORT)" >&2
374 pair(bool, pair(string, pair(string, list(string))))(
375 save, (parent, (name, info.theories.map(_._2).flatten.map(_.implode))))
377 new Job(cwd, env, script, YXML.string_of_body(args_xml))
383 private def echo(msg: String) { java.lang.System.out.println(msg) }
384 private def sleep(): Unit = Thread.sleep(500)
386 def build(all_sessions: Boolean, build_images: Boolean, max_jobs: Int,
387 list_only: Boolean, verbose: Boolean,
388 more_dirs: List[Path], more_options: List[String], sessions: List[String]): Int =
390 val options = (Options.init() /: more_options)(_.define_simple(_))
391 val queue = find_sessions(options, all_sessions, sessions, more_dirs)
392 val deps = dependencies(queue)
395 // prepare browser info dir
396 if (options.bool("browser_info") &&
397 !Path.explode("$ISABELLE_BROWSER_INFO/index.html").file.isFile)
399 Path.explode("$ISABELLE_BROWSER_INFO").file.mkdirs()
400 File.copy(Path.explode("$ISABELLE_HOME/lib/logo/isabelle.gif"),
401 Path.explode("$ISABELLE_BROWSER_INFO/isabelle.gif"))
402 File.write(Path.explode("$ISABELLE_BROWSER_INFO/index.html"),
403 File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_header.template")) +
404 File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_content.template")) +
405 File.read(Path.explode("$ISABELLE_HOME/lib/html/library_index_footer.template")))
409 val log_dir = Path.explode("$ISABELLE_OUTPUT/log")
410 log_dir.file.mkdirs()
414 pending: Session.Queue,
415 running: Map[String, Job],
416 results: Map[String, Int]): Map[String, Int] =
418 if (pending.is_empty) results
419 else if (running.exists({ case (_, job) => job.is_finished })) {
420 val (name, job) = running.find({ case (_, job) => job.is_finished }).get
422 val (out, err, rc) = job.join
423 echo(Library.trim_line(err))
425 val log = log_dir + Path.basic(name)
428 (queue(name).digest :: deps.sources(name).map(_._2)).map(_.toString).sorted
429 .mkString("sources: ", " ", "\n")
430 File.write_zip(log.ext("gz"), sources + out)
434 echo(name + " FAILED")
435 echo("(see also " + log.file + ")")
436 val lines = split_lines(out)
437 val tail = lines.drop(lines.length - 20 max 0)
438 echo("\n" + cat_lines(tail))
440 loop(pending - name, running - name, results + (name -> rc))
442 else if (running.size < (max_jobs max 1)) {
443 pending.dequeue(running.isDefinedAt(_)) match {
444 case Some((name, info)) =>
446 echo(name + " in " + info.dir)
447 loop(pending - name, running, results + (name -> 0))
449 else if (info.parent.map(results(_)).forall(_ == 0)) {
450 val save = build_images || queue.is_inner(name)
451 echo((if (save) "Building " else "Running ") + name + " ...")
452 val job = start_job(save, name, info)
453 loop(pending, running + (name -> job), results)
456 echo(name + " CANCELLED")
457 loop(pending - name, running, results + (name -> 1))
459 case None => sleep(); loop(pending, running, results)
462 else { sleep(); loop(pending, running, results) }
465 (0 /: loop(queue, Map.empty, Map.empty))({ case (rc1, (_, rc2)) => rc1 max rc2 })
469 /* command line entry point */
471 def main(args: Array[String])
476 Properties.Value.Boolean(all_sessions) ::
477 Properties.Value.Boolean(build_images) ::
478 Properties.Value.Int(max_jobs) ::
479 Properties.Value.Boolean(list_only) ::
480 Properties.Value.Boolean(verbose) ::
481 Command_Line.Chunks(more_dirs, options, sessions) =>
482 build(all_sessions, build_images, max_jobs, list_only, verbose,
483 more_dirs.map(Path.explode), options, sessions)
484 case _ => error("Bad arguments:\n" + cat_lines(args))