src/Pure/Tools/build.scala
author wenzelm
Fri Mar 17 20:21:01 2017 +0100 (2017-03-17)
changeset 65291 57c85c83c11b
parent 65289 86d93effc3df
child 65294 69100bf4ead4
permissions -rw-r--r--
maintain persistent session info in SQLite database instead of log file;
     1 /*  Title:      Pure/Tools/build.scala
     2     Author:     Makarius
     3     Options:    :folding=explicit:
     4 
     5 Build and manage Isabelle sessions.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import java.io.{BufferedInputStream, FileInputStream,
    12   BufferedReader, InputStreamReader, IOException}
    13 import java.util.zip.GZIPInputStream
    14 
    15 import scala.collection.SortedSet
    16 import scala.collection.mutable
    17 import scala.annotation.tailrec
    18 
    19 
    20 object Build
    21 {
    22   /** auxiliary **/
    23 
    24   /* persistent build info */
    25 
    26   sealed case class Session_Info(
    27     sources: List[String],
    28     input_heaps: List[String],
    29     output_heap: Option[String],
    30     return_code: Int)
    31 
    32 
    33   /* queue with scheduling information */
    34 
    35   private object Queue
    36   {
    37     def load_timings(store: Sessions.Store, name: String): (List[Properties.T], Double) =
    38     {
    39       val no_timings: (List[Properties.T], Double) = (Nil, 0.0)
    40 
    41       store.find_database(name) match {
    42         case None => no_timings
    43         case Some(database) =>
    44           def ignore_error(msg: String) =
    45           {
    46             Output.warning("Ignoring bad database: " + database + (if (msg == "") "" else "\n" + msg))
    47             no_timings
    48           }
    49           try {
    50             using(SQLite.open_database(database))(db =>
    51             {
    52               val build_log =
    53                 Sessions.Session_Info.read_build_log(store, db, name, command_timings = true)
    54               val session_timing = Markup.Elapsed.unapply(build_log.session_timing) getOrElse 0.0
    55               (build_log.command_timings, session_timing)
    56             })
    57           }
    58           catch {
    59             case ERROR(msg) => ignore_error(msg)
    60             case exn: java.lang.Error => ignore_error(Exn.message(exn))
    61             case _: XML.Error => ignore_error("")
    62           }
    63       }
    64     }
    65 
    66     def apply(tree: Sessions.Tree, store: Sessions.Store): Queue =
    67     {
    68       val graph = tree.graph
    69       val sessions = graph.keys
    70 
    71       val timings = sessions.map(name => (name, load_timings(store, name)))
    72       val command_timings =
    73         Map(timings.map({ case (name, (ts, _)) => (name, ts) }): _*).withDefaultValue(Nil)
    74       val session_timing =
    75         Map(timings.map({ case (name, (_, t)) => (name, t) }): _*).withDefaultValue(0.0)
    76 
    77       def outdegree(name: String): Int = graph.imm_succs(name).size
    78 
    79       object Ordering extends scala.math.Ordering[String]
    80       {
    81         def compare_timing(name1: String, name2: String): Int =
    82         {
    83           val t1 = session_timing(name1)
    84           val t2 = session_timing(name2)
    85           if (t1 == 0.0 || t2 == 0.0) 0
    86           else t1 compare t2
    87         }
    88 
    89         def compare(name1: String, name2: String): Int =
    90           outdegree(name2) compare outdegree(name1) match {
    91             case 0 =>
    92               compare_timing(name2, name1) match {
    93                 case 0 =>
    94                   tree(name2).timeout compare tree(name1).timeout match {
    95                     case 0 => name1 compare name2
    96                     case ord => ord
    97                   }
    98                 case ord => ord
    99               }
   100             case ord => ord
   101           }
   102       }
   103 
   104       new Queue(graph, SortedSet(sessions: _*)(Ordering), command_timings)
   105     }
   106   }
   107 
   108   private final class Queue private(
   109     graph: Graph[String, Sessions.Info],
   110     order: SortedSet[String],
   111     val command_timings: String => List[Properties.T])
   112   {
   113     def is_inner(name: String): Boolean = !graph.is_maximal(name)
   114 
   115     def is_empty: Boolean = graph.is_empty
   116 
   117     def - (name: String): Queue =
   118       new Queue(graph.del_node(name),
   119         order - name,  // FIXME scala-2.10.0 TreeSet problem!?
   120         command_timings)
   121 
   122     def dequeue(skip: String => Boolean): Option[(String, Sessions.Info)] =
   123     {
   124       val it = order.iterator.dropWhile(name =>
   125         skip(name)
   126           || !graph.defined(name)  // FIXME scala-2.10.0 TreeSet problem!?
   127           || !graph.is_minimal(name))
   128       if (it.hasNext) { val name = it.next; Some((name, graph.get_node(name))) }
   129       else None
   130     }
   131   }
   132 
   133 
   134   /* jobs */
   135 
   136   private class Job(progress: Progress, name: String, val info: Sessions.Info, tree: Sessions.Tree,
   137     store: Sessions.Store, do_output: Boolean, verbose: Boolean, val numa_node: Option[Int],
   138     session_graph: Graph_Display.Graph, command_timings: List[Properties.T])
   139   {
   140     val output = store.output_dir + Path.basic(name)
   141     def output_path: Option[Path] = if (do_output) Some(output) else None
   142     def output_save_state: String =
   143       if (do_output) "ML_Heap.save_child " + ML_Syntax.print_string0(File.platform_path(output))
   144       else ""
   145     output.file.delete
   146 
   147     private val parent = info.parent.getOrElse("")
   148 
   149     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   150     try { isabelle.graphview.Graph_File.write(info.options, graph_file, session_graph) }
   151     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   152 
   153     private val env =
   154       Isabelle_System.settings() +
   155         ("ISABELLE_ML_DEBUGGER" -> info.options.bool("ML_debugger").toString)
   156 
   157     private val future_result: Future[Process_Result] =
   158       Future.thread("build") {
   159         val args_file = Isabelle_System.tmp_file("build")
   160         File.write(args_file, YXML.string_of_body(
   161             {
   162               val theories = info.theories.map(x => (x._2, x._3))
   163               import XML.Encode._
   164               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   165                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   166                 pair(string, pair(string, pair(string,
   167                 list(pair(Options.encode, list(Path.encode)))))))))))))(
   168               (Symbol.codes, (command_timings, (do_output, (verbose,
   169                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   170                 (parent, (info.chapter, (name,
   171                 theories)))))))))))
   172             }))
   173 
   174         val eval =
   175           "Command_Line.tool0 (fn () => (" +
   176           "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   177           (if (do_output) "; ML_Heap.share_common_data (); " + output_save_state
   178            else "") + "));"
   179 
   180         val process_options =
   181           numa_node match {
   182             case None => info.options
   183             case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   184           }
   185         val process =
   186           if (Sessions.pure_name(name)) {
   187             ML_Process(process_options, raw_ml_system = true, cwd = info.dir.file,
   188               args =
   189                 (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   190                 List("--eval", eval),
   191               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   192           }
   193           else {
   194             ML_Process(process_options, parent, List("--eval", eval), cwd = info.dir.file,
   195               env = env, tree = Some(tree), store = store, cleanup = () => args_file.delete)
   196           }
   197 
   198         process.result(
   199           progress_stdout = (line: String) =>
   200             Library.try_unprefix("\floading_theory = ", line) match {
   201               case Some(theory) => progress.theory(name, theory)
   202               case None =>
   203             },
   204           progress_limit =
   205             info.options.int("process_output_limit") match {
   206               case 0 => None
   207               case m => Some(m * 1000000L)
   208             },
   209           strict = false)
   210       }
   211 
   212     def terminate: Unit = future_result.cancel
   213     def is_finished: Boolean = future_result.is_finished
   214 
   215     @volatile private var was_timeout = false
   216     private val timeout_request: Option[Event_Timer.Request] =
   217     {
   218       if (info.timeout > Time.zero)
   219         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   220       else None
   221     }
   222 
   223     def join: Process_Result =
   224     {
   225       val result = future_result.join
   226 
   227       if (result.ok)
   228         Present.finish(progress, store.browser_info, graph_file, info, name)
   229 
   230       graph_file.delete
   231       timeout_request.foreach(_.cancel)
   232 
   233       if (result.interrupted) {
   234         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   235         else result.error(Output.error_text("Interrupt"))
   236       }
   237       else result
   238     }
   239   }
   240 
   241 
   242 
   243   /** build with results **/
   244 
   245   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   246   {
   247     def sessions: Set[String] = results.keySet
   248     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   249     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   250     def info(name: String): Sessions.Info = results(name)._2
   251     val rc =
   252       (0 /: results.iterator.map(
   253         { case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   254     def ok: Boolean = rc == 0
   255 
   256     override def toString: String = rc.toString
   257   }
   258 
   259   def build(
   260     options: Options,
   261     progress: Progress = No_Progress,
   262     build_heap: Boolean = false,
   263     clean_build: Boolean = false,
   264     dirs: List[Path] = Nil,
   265     select_dirs: List[Path] = Nil,
   266     numa_shuffling: Boolean = false,
   267     max_jobs: Int = 1,
   268     list_files: Boolean = false,
   269     check_keywords: Set[String] = Set.empty,
   270     no_build: Boolean = false,
   271     system_mode: Boolean = false,
   272     verbose: Boolean = false,
   273     requirements: Boolean = false,
   274     all_sessions: Boolean = false,
   275     exclude_session_groups: List[String] = Nil,
   276     exclude_sessions: List[String] = Nil,
   277     session_groups: List[String] = Nil,
   278     sessions: List[String] = Nil): Results =
   279   {
   280     build_selection(
   281       options = options,
   282       progress = progress,
   283       build_heap = build_heap,
   284       clean_build = clean_build,
   285       dirs = dirs,
   286       select_dirs = select_dirs,
   287       numa_shuffling = numa_shuffling,
   288       max_jobs = max_jobs,
   289       list_files = list_files,
   290       check_keywords = check_keywords,
   291       no_build = no_build,
   292       system_mode = system_mode,
   293       verbose = verbose,
   294       selection = { full_tree =>
   295         full_tree.selection(requirements, all_sessions,
   296           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   297   }
   298 
   299   def build_selection(
   300     options: Options,
   301     progress: Progress = No_Progress,
   302     build_heap: Boolean = false,
   303     clean_build: Boolean = false,
   304     dirs: List[Path] = Nil,
   305     select_dirs: List[Path] = Nil,
   306     numa_shuffling: Boolean = false,
   307     max_jobs: Int = 1,
   308     list_files: Boolean = false,
   309     check_keywords: Set[String] = Set.empty,
   310     no_build: Boolean = false,
   311     system_mode: Boolean = false,
   312     verbose: Boolean = false,
   313     selection: Sessions.Tree => (List[String], Sessions.Tree) =
   314       (_.selection(all_sessions = true))): Results =
   315   {
   316     /* session selection and dependencies */
   317 
   318     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   319     val full_tree = Sessions.load(build_options, dirs, select_dirs)
   320     val (selected, selected_tree) = selection(full_tree)
   321     val deps =
   322       Sessions.dependencies(progress, true, verbose, list_files, check_keywords, selected_tree)
   323 
   324     def sources_stamp(name: String): List[String] =
   325       (selected_tree(name).meta_digest :: deps.sources(name)).map(_.toString).sorted
   326 
   327 
   328     /* main build process */
   329 
   330     val store = Sessions.store(system_mode)
   331     val queue = Queue(selected_tree, store)
   332 
   333     store.prepare_output()
   334 
   335     // optional cleanup
   336     if (clean_build) {
   337       for (name <- full_tree.graph.all_succs(selected)) {
   338         val files =
   339           List(Path.basic(name), store.database(name), store.log(name), store.log_gz(name)).
   340             map(store.output_dir + _).filter(_.is_file)
   341         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   342         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   343       }
   344     }
   345 
   346     // scheduler loop
   347     case class Result(
   348       current: Boolean, heap_stamp: Option[String],
   349       process: Option[Process_Result], info: Sessions.Info)
   350     {
   351       def ok: Boolean =
   352         process match {
   353           case None => false
   354           case Some(res) => res.rc == 0
   355         }
   356     }
   357 
   358     def sleep()
   359     {
   360       try { Thread.sleep(500) }
   361       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   362     }
   363 
   364     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   365 
   366     @tailrec def loop(
   367       pending: Queue,
   368       running: Map[String, (List[String], Job)],
   369       results: Map[String, Result]): Map[String, Result] =
   370     {
   371       def used_node(i: Int): Boolean =
   372         running.iterator.exists(
   373           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   374 
   375       if (pending.is_empty) results
   376       else {
   377         if (progress.stopped)
   378           for ((_, (_, job)) <- running) job.terminate
   379 
   380         running.find({ case (_, (_, job)) => job.is_finished }) match {
   381           case Some((name, (input_heaps, job))) =>
   382             //{{{ finish job
   383 
   384             val process_result = job.join
   385             process_result.err_lines.foreach(progress.echo(_))
   386             if (process_result.ok)
   387               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   388 
   389             val process_result_tail =
   390             {
   391               val lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   392               val tail = job.info.options.int("process_output_tail")
   393               val lines1 = if (tail == 0) lines else lines.drop(lines.length - tail max 0)
   394               process_result.copy(
   395                 out_lines =
   396                   "(see also " + (store.output_dir + store.log(name)).file.toString + ")" ::
   397                   lines1)
   398             }
   399 
   400             val heap_stamp =
   401               if (process_result.ok) {
   402                 (store.output_dir + store.log(name)).file.delete
   403                 val heap_stamp =
   404                   for (path <- job.output_path if path.is_file)
   405                     yield Sessions.write_heap_digest(path)
   406 
   407                 File.write_gzip(store.output_dir + store.log_gz(name),
   408                   terminate_lines(process_result.out_lines))
   409 
   410                 heap_stamp
   411               }
   412               else {
   413                 (store.output_dir + Path.basic(name)).file.delete
   414                 (store.output_dir + store.log_gz(name)).file.delete
   415 
   416                 File.write(store.output_dir + store.log(name),
   417                   terminate_lines(process_result.out_lines))
   418                 progress.echo(name + " FAILED")
   419                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   420 
   421                 None
   422               }
   423 
   424             // write database
   425             {
   426               val database = store.output_dir + store.database(name)
   427               database.file.delete
   428 
   429               using(SQLite.open_database(database))(db =>
   430                 Sessions.Session_Info.write(store, db,
   431                   build_log =
   432                     Build_Log.Log_File(name, process_result.out_lines).
   433                       parse_session_info(name,
   434                         command_timings = true, ml_statistics = true, task_statistics = true),
   435                   build =
   436                     Session_Info(sources_stamp(name), input_heaps, heap_stamp, process_result.rc)))
   437             }
   438 
   439             loop(pending - name, running - name,
   440               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   441             //}}}
   442           case None if running.size < (max_jobs max 1) =>
   443             //{{{ check/start next job
   444             pending.dequeue(running.isDefinedAt(_)) match {
   445               case Some((name, info)) =>
   446                 val ancestor_results = selected_tree.ancestors(name).map(results(_))
   447                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   448 
   449                 val do_output = build_heap || Sessions.pure_name(name) || queue.is_inner(name)
   450 
   451                 val (current, heap_stamp) =
   452                 {
   453                   store.find_database_heap(name) match {
   454                     case Some((database, heap_stamp)) =>
   455                       using(SQLite.open_database(database))(
   456                         Sessions.Session_Info.read_build(store, _)) match
   457                       {
   458                         case Some(build) =>
   459                           val current =
   460                             build.sources == sources_stamp(name) &&
   461                             build.input_heaps == ancestor_heaps &&
   462                             build.output_heap == heap_stamp &&
   463                             !(do_output && heap_stamp.isEmpty) &&
   464                             build.return_code == 0
   465                           (current, heap_stamp)
   466                         case None => (false, None)
   467                       }
   468                     case None => (false, None)
   469                   }
   470                 }
   471                 val all_current = current && ancestor_results.forall(_.current)
   472 
   473                 if (all_current)
   474                   loop(pending - name, running,
   475                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   476                 else if (no_build) {
   477                   if (verbose) progress.echo("Skipping " + name + " ...")
   478                   loop(pending - name, running,
   479                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   480                 }
   481                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   482                   val numa_node = numa_nodes.next(used_node(_))
   483                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   484                   val job =
   485                     new Job(progress, name, info, selected_tree, store, do_output, verbose,
   486                       numa_node, deps(name).session_graph, queue.command_timings(name))
   487                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   488                 }
   489                 else {
   490                   progress.echo(name + " CANCELLED")
   491                   loop(pending - name, running,
   492                     results + (name -> Result(false, heap_stamp, None, info)))
   493                 }
   494               case None => sleep(); loop(pending, running, results)
   495             }
   496             ///}}}
   497           case None => sleep(); loop(pending, running, results)
   498         }
   499       }
   500     }
   501 
   502 
   503     /* build results */
   504 
   505     val results0 =
   506       if (deps.is_empty) {
   507         progress.echo(Output.warning_text("Nothing to build"))
   508         Map.empty[String, Result]
   509       }
   510       else loop(queue, Map.empty, Map.empty)
   511 
   512     val results =
   513       new Results(
   514         (for ((name, result) <- results0.iterator)
   515           yield (name, (result.process, result.info))).toMap)
   516 
   517     if (results.rc != 0 && (verbose || !no_build)) {
   518       val unfinished =
   519         (for {
   520           name <- results.sessions.iterator
   521           if !results(name).ok
   522          } yield name).toList.sorted
   523       progress.echo("Unfinished session(s): " + commas(unfinished))
   524     }
   525 
   526 
   527     /* global browser info */
   528 
   529     if (!no_build) {
   530       val browser_chapters =
   531         (for {
   532           (name, result) <- results0.iterator
   533           if result.ok
   534           info = full_tree(name)
   535           if info.options.bool("browser_info")
   536         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   537             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   538 
   539       for ((chapter, entries) <- browser_chapters)
   540         Present.update_chapter_index(store.browser_info, chapter, entries)
   541 
   542       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   543     }
   544 
   545     results
   546   }
   547 
   548 
   549   /* Isabelle tool wrapper */
   550 
   551   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   552   {
   553     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   554 
   555     var select_dirs: List[Path] = Nil
   556     var numa_shuffling = false
   557     var requirements = false
   558     var exclude_session_groups: List[String] = Nil
   559     var all_sessions = false
   560     var build_heap = false
   561     var clean_build = false
   562     var dirs: List[Path] = Nil
   563     var session_groups: List[String] = Nil
   564     var max_jobs = 1
   565     var check_keywords: Set[String] = Set.empty
   566     var list_files = false
   567     var no_build = false
   568     var options = (Options.init() /: build_options)(_ + _)
   569     var system_mode = false
   570     var verbose = false
   571     var exclude_sessions: List[String] = Nil
   572 
   573     val getopts = Getopts("""
   574 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   575 
   576   Options are:
   577     -D DIR       include session directory and select its sessions
   578     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   579     -R           operate on requirements of selected sessions
   580     -X NAME      exclude sessions from group NAME and all descendants
   581     -a           select all sessions
   582     -b           build heap images
   583     -c           clean build
   584     -d DIR       include session directory
   585     -g NAME      select session group NAME
   586     -j INT       maximum number of parallel jobs (default 1)
   587     -k KEYWORD   check theory sources for conflicts with proposed keywords
   588     -l           list session source files
   589     -n           no build -- test dependencies only
   590     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   591     -s           system build mode: produce output in ISABELLE_HOME
   592     -v           verbose
   593     -x NAME      exclude session NAME and all descendants
   594 
   595   Build and manage Isabelle sessions, depending on implicit settings:
   596 
   597 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   598       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   599       "N" -> (_ => numa_shuffling = true),
   600       "R" -> (_ => requirements = true),
   601       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   602       "a" -> (_ => all_sessions = true),
   603       "b" -> (_ => build_heap = true),
   604       "c" -> (_ => clean_build = true),
   605       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   606       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   607       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   608       "k:" -> (arg => check_keywords = check_keywords + arg),
   609       "l" -> (_ => list_files = true),
   610       "n" -> (_ => no_build = true),
   611       "o:" -> (arg => options = options + arg),
   612       "s" -> (_ => system_mode = true),
   613       "v" -> (_ => verbose = true),
   614       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   615 
   616     val sessions = getopts(args)
   617 
   618     val progress = new Console_Progress(verbose = verbose)
   619 
   620     val start_date = Date.now()
   621 
   622     if (verbose) {
   623       progress.echo(
   624         "Started at " + Build_Log.print_date(start_date) +
   625           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   626       progress.echo(Build_Log.Settings.show() + "\n")
   627     }
   628 
   629     val results =
   630       progress.interrupt_handler {
   631         build(options, progress,
   632           build_heap = build_heap,
   633           clean_build = clean_build,
   634           dirs = dirs,
   635           select_dirs = select_dirs,
   636           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   637           max_jobs = max_jobs,
   638           list_files = list_files,
   639           check_keywords = check_keywords,
   640           no_build = no_build,
   641           system_mode = system_mode,
   642           verbose = verbose,
   643           requirements = requirements,
   644           all_sessions = all_sessions,
   645           exclude_session_groups = exclude_session_groups,
   646           exclude_sessions = exclude_sessions,
   647           session_groups = session_groups,
   648           sessions = sessions)
   649       }
   650     val end_date = Date.now()
   651     val elapsed_time = end_date.time - start_date.time
   652 
   653     if (verbose) {
   654       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   655     }
   656 
   657     val total_timing =
   658       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   659         copy(elapsed = elapsed_time)
   660     progress.echo(total_timing.message_resources)
   661 
   662     sys.exit(results.rc)
   663   })
   664 
   665 
   666   /* PIDE protocol */
   667 
   668   def build_theories(
   669     session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   670       session.get_protocol_handler(classOf[Handler].getName) match {
   671         case Some(handler: Handler) => handler.build_theories(session, master_dir, theories)
   672         case _ => error("Cannot invoke build_theories: bad protocol handler")
   673       }
   674 
   675   class Handler(progress: Progress, session_name: String) extends Session.Protocol_Handler
   676   {
   677     private val pending = Synchronized(Map.empty[String, Promise[XML.Body]])
   678 
   679     override def exit(): Unit =
   680       pending.change(promises => { for ((_, promise) <- promises) promise.cancel; Map.empty })
   681 
   682     def build_theories(
   683       session: Session, master_dir: Path, theories: List[(Options, List[Path])]): Promise[XML.Body] =
   684     {
   685       val promise = Future.promise[XML.Body]
   686       val id = Document_ID.make().toString
   687       pending.change(promises => promises + (id -> promise))
   688       session.build_theories(id, master_dir, theories)
   689       promise
   690     }
   691 
   692     private def loading_theory(msg: Prover.Protocol_Output): Boolean =
   693       msg.properties match {
   694         case Markup.Loading_Theory(name) => progress.theory(session_name, name); true
   695         case _ => false
   696       }
   697 
   698     private def build_theories_result(msg: Prover.Protocol_Output): Boolean =
   699       msg.properties match {
   700         case Markup.Build_Theories_Result(id) =>
   701           pending.change_result(promises =>
   702             promises.get(id) match {
   703               case Some(promise) =>
   704                 val error_message =
   705                   try { YXML.parse_body(Symbol.decode(msg.text)) }
   706                   catch { case exn: Throwable => List(XML.Text(Exn.message(exn))) }
   707                 promise.fulfill(error_message)
   708                 (true, promises - id)
   709               case None =>
   710                 (false, promises)
   711             })
   712         case _ => false
   713       }
   714 
   715     val functions =
   716       List(
   717         Markup.BUILD_THEORIES_RESULT -> build_theories_result _,
   718         Markup.LOADING_THEORY -> loading_theory _)
   719   }
   720 }