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