src/Pure/System/build.scala
author wenzelm
Sun, 22 Jul 2012 23:31:57 +0200
changeset 49440 0d95980e9aae
parent 49439 e6b0c14f04c8
child 49462 ef600ce4559c
permissions -rw-r--r--
parallel scheduling of jobs;
misc tuning;
     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       dir: Path,
    46       parent: Option[String],
    47       description: String,
    48       options: Options,
    49       theories: List[(Options, List[Path])],
    50       files: List[Path],
    51       digest: SHA1.Digest)
    52 
    53 
    54     /* Queue */
    55 
    56     object Queue
    57     {
    58       val empty: Queue = new Queue()
    59     }
    60 
    61     final class Queue private(
    62       keys: Map[String, Key] = Map.empty,
    63       graph: Graph[Key, Info] = Graph.empty(Key.Ordering))
    64     {
    65       def is_empty: Boolean = graph.is_empty
    66 
    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))
    70 
    71       def + (key: Key, info: Info): Queue =
    72       {
    73         val keys1 =
    74           if (defined(key.name)) error("Duplicate session: " + quote(key.name))
    75           else keys + (key.name -> key)
    76 
    77         val graph1 =
    78           try {
    79             graph.new_node(key, info).add_deps_acyclic(key, info.parent.toList.map(keys(_)))
    80           }
    81           catch {
    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 "))))
    86           }
    87         new Queue(keys1, graph1)
    88       }
    89 
    90       def - (name: String): Queue = new Queue(keys - name, graph.del_node(keys(name)))
    91 
    92       def required(names: List[String]): Queue =
    93       {
    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)
    98       }
    99 
   100       def dequeue(skip: String => Boolean): Option[(String, Info)] =
   101       {
   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)) }
   105         else None
   106       }
   107 
   108       def topological_order: List[(String, Info)] =
   109         graph.topological_order.map(key => (key.name, graph.get_node(key)))
   110     }
   111   }
   112 
   113 
   114   /* parsing */
   115 
   116   private case class Session_Entry(
   117     name: String,
   118     reset: Boolean,
   119     order: Int,
   120     path: Option[String],
   121     parent: Option[String],
   122     description: String,
   123     options: List[Options.Spec],
   124     theories: List[(List[Options.Spec], List[String])],
   125     files: List[String])
   126 
   127   private object Parser extends Parse.Parser
   128   {
   129     val SESSION = "session"
   130     val IN = "in"
   131     val DESCRIPTION = "description"
   132     val OPTIONS = "options"
   133     val THEORIES = "theories"
   134     val FILES = "files"
   135 
   136     val syntax =
   137       Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
   138         SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
   139 
   140     val session_entry: Parser[Session_Entry] =
   141     {
   142       val session_name = atom("session name", _.is_name)
   143       val theory_name = atom("theory name", _.is_name)
   144 
   145       val option =
   146         name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
   147       val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
   148 
   149       val theories =
   150         keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
   151           { case _ ~ (x ~ y) => (x, y) }
   152 
   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)) ~
   160         rep(theories) ~
   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) }
   163     }
   164 
   165     def parse_entries(root: JFile): List[Session_Entry] =
   166     {
   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)
   171       }
   172     }
   173   }
   174 
   175 
   176   /* find sessions */
   177 
   178   private val ROOT = Path.explode("ROOT")
   179   private val SESSIONS = Path.explode("etc/sessions")
   180 
   181   private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
   182 
   183   private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
   184     : Session.Queue =
   185   {
   186     (queue /: Parser.parse_entries(root))((queue1, entry) =>
   187       try {
   188         if (entry.name == "") error("Bad session name")
   189 
   190         val full_name =
   191           if (is_pure(entry.name)) {
   192             if (entry.parent.isDefined) error("Illegal parent session")
   193             else entry.name
   194           }
   195           else
   196             entry.parent match {
   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")
   201             }
   202 
   203         val path =
   204           entry.path match {
   205             case Some(p) => Path.explode(p)
   206             case None => Path.basic(entry.name)
   207           }
   208 
   209         val key = Session.Key(full_name, entry.order)
   210 
   211         val theories =
   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)
   215 
   216         val info =
   217           Session.Info(dir + path, entry.parent,
   218             entry.description, options ++ entry.options, theories, files, digest)
   219 
   220         queue1 + (key, info)
   221       }
   222       catch {
   223         case ERROR(msg) =>
   224           error(msg + "\nThe error(s) above occurred in session entry " +
   225             quote(entry.name) + Position.str_of(Position.file(root)))
   226       })
   227   }
   228 
   229   private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
   230     : Session.Queue =
   231   {
   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))
   235     else queue
   236   }
   237 
   238   private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
   239     : Session.Queue =
   240   {
   241     val dirs =
   242       split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
   243     (queue /: dirs)((queue1, dir1) =>
   244       try {
   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)
   248       }
   249       catch {
   250         case ERROR(msg) =>
   251           error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
   252       })
   253   }
   254 
   255   def find_sessions(options: Options, all_sessions: Boolean, sessions: List[String],
   256     more_dirs: List[Path]): Session.Queue =
   257   {
   258     var queue = Session.Queue.empty
   259 
   260     for (dir <- Isabelle_System.components()) {
   261       queue = sessions_dir(options, false, dir, queue)
   262 
   263       val catalog = (dir + SESSIONS).file
   264       if (catalog.isFile)
   265         queue = sessions_catalog(options, dir, catalog, queue)
   266     }
   267 
   268     for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
   269 
   270     sessions.filter(name => !queue.defined(name)) match {
   271       case Nil =>
   272       case bad => error("Undefined session(s): " + commas_quote(bad))
   273     }
   274 
   275     if (all_sessions) queue else queue.required(sessions)
   276   }
   277 
   278 
   279 
   280   /** build **/
   281 
   282   /* dependencies */
   283 
   284   sealed case class Node(
   285     loaded_theories: Set[String],
   286     sources: List[(Path, SHA1.Digest)])
   287 
   288   sealed case class Deps(deps: Map[String, Node])
   289   {
   290     def sources(name: String): List[(Path, SHA1.Digest)] = deps(name).sources
   291   }
   292 
   293   def dependencies(queue: Session.Queue): Deps =
   294     Deps((Map.empty[String, Node] /: queue.topological_order)(
   295       { case (deps, (name, info)) =>
   296           val preloaded =
   297             info.parent match {
   298               case None => Set.empty[String]
   299               case Some(parent) => deps(parent).loaded_theories
   300             }
   301           val thy_info = new Thy_Info(new Thy_Load(preloaded))
   302 
   303           val thy_deps =
   304             thy_info.dependencies(
   305               info.theories.map(_._2).flatten.
   306                 map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
   307 
   308           val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
   309 
   310           val all_files =
   311             thy_deps.map({ case (n, h) =>
   312               val thy = Path.explode(n.node).expand
   313               val uses =
   314                 h match {
   315                   case Exn.Res(d) =>
   316                     d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
   317                   case _ => Nil
   318                 }
   319               thy :: uses
   320             }).flatten ::: info.files.map(file => info.dir + file)
   321           val sources = all_files.par.map(p => (p, SHA1.digest(p))).toList
   322 
   323           deps + (name -> Node(loaded_theories, sources))
   324       }))
   325 
   326 
   327   /* jobs */
   328 
   329   private class Job(cwd: JFile, env: Map[String, String], script: String, args: String)
   330   {
   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)
   334 
   335     private val (thread, result) =
   336       Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
   337 
   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 }
   341   }
   342 
   343   private def start_job(save: Boolean, name: String, info: Session.Info): Job =
   344   {
   345     val parent = info.parent.getOrElse("")
   346 
   347     val cwd = info.dir.file
   348     val env = Map("INPUT" -> parent, "TARGET" -> name)
   349     val script =
   350       if (is_pure(name)) "./build " + (if (save) "-b " else "") + name
   351       else {
   352         """
   353         . "$ISABELLE_HOME/lib/scripts/timestart.bash"
   354         """ +
   355           (if (save)
   356             """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$TARGET" """
   357           else
   358             """ "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT" """) +
   359         """
   360         RC="$?"
   361 
   362         . "$ISABELLE_HOME/lib/scripts/timestop.bash"
   363 
   364         if [ "$RC" -eq 0 ]; then
   365           echo "Finished $TARGET ($TIMES_REPORT)" >&2
   366         fi
   367 
   368         exit "$RC"
   369         """
   370       }
   371     val args_xml =
   372     {
   373       import XML.Encode._
   374       pair(bool, pair(string, pair(string, list(string))))(
   375         save, (parent, (name, info.theories.map(_._2).flatten.map(_.implode))))
   376     }
   377     new Job(cwd, env, script, YXML.string_of_body(args_xml))
   378   }
   379 
   380 
   381   /* build */
   382 
   383   private def echo(msg: String) { java.lang.System.out.println(msg) }
   384   private def sleep(): Unit = Thread.sleep(500)
   385 
   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 =
   389   {
   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)
   393 
   394 
   395     // prepare browser info dir
   396     if (options.bool("browser_info") &&
   397       !Path.explode("$ISABELLE_BROWSER_INFO/index.html").file.isFile)
   398     {
   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")))
   406     }
   407 
   408     // prepare log dir
   409     val log_dir = Path.explode("$ISABELLE_OUTPUT/log")
   410     log_dir.file.mkdirs()
   411 
   412     // scheduler loop
   413     @tailrec def loop(
   414       pending: Session.Queue,
   415       running: Map[String, Job],
   416       results: Map[String, Int]): Map[String, Int] =
   417     {
   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
   421 
   422         val (out, err, rc) = job.join
   423         echo(Library.trim_line(err))
   424 
   425         val log = log_dir + Path.basic(name)
   426         if (rc == 0) {
   427           val sources =
   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)
   431         }
   432         else {
   433           File.write(log, 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))
   439         }
   440         loop(pending - name, running - name, results + (name -> rc))
   441       }
   442       else if (running.size < (max_jobs max 1)) {
   443         pending.dequeue(running.isDefinedAt(_)) match {
   444           case Some((name, info)) =>
   445             if (list_only) {
   446               echo(name + " in " + info.dir)
   447               loop(pending - name, running, results + (name -> 0))
   448             }
   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)
   454             }
   455             else {
   456               echo(name + " CANCELLED")
   457               loop(pending - name, running, results + (name -> 1))
   458             }
   459           case None => sleep(); loop(pending, running, results)
   460         }
   461       }
   462       else { sleep(); loop(pending, running, results) }
   463     }
   464 
   465     (0 /: loop(queue, Map.empty, Map.empty))({ case (rc1, (_, rc2)) => rc1 max rc2 })
   466   }
   467 
   468 
   469   /* command line entry point */
   470 
   471   def main(args: Array[String])
   472   {
   473     Command_Line.tool {
   474       args.toList match {
   475         case
   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))
   485       }
   486     }
   487   }
   488 }
   489