src/Pure/Tools/build.scala
author wenzelm
Thu Apr 06 22:04:30 2017 +0200 (2017-04-06)
changeset 65415 8cd54b18b68b
parent 65406 cc9e2f1f279d
child 65419 457e4fbed731
permissions -rw-r--r--
clarified signature: tree structure is not essential;
     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: " +
    47               database.expand + (if (msg == "") "" else "\n" + msg))
    48             no_timings
    49           }
    50           try {
    51             using(SQLite.open_database(database))(db =>
    52             {
    53               val build_log = store.read_build_log(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(sessions: Sessions.T, store: Sessions.Store): Queue =
    67     {
    68       val graph = sessions.graph
    69       val names = graph.keys
    70 
    71       val timings = names.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                   sessions(name2).timeout compare sessions(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(names: _*)(Ordering), command_timings)
   105     }
   106   }
   107 
   108   private class Queue(
   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   /* PIDE protocol handler */
   135 
   136   class Handler(progress: Progress, session: Session, session_name: String)
   137     extends Session.Protocol_Handler
   138   {
   139     val result_error: Promise[String] = Future.promise
   140 
   141     override def exit() { result_error.cancel }
   142 
   143     private def build_session_finished(msg: Prover.Protocol_Output): Boolean =
   144     {
   145       val error_message =
   146         try { Pretty.string_of(Symbol.decode_yxml(msg.text)) }
   147         catch { case ERROR(msg) => msg }
   148       result_error.fulfill(error_message)
   149       session.send_stop()
   150       true
   151     }
   152 
   153     private def loading_theory(msg: Prover.Protocol_Output): Boolean =
   154       msg.properties match {
   155         case Markup.Loading_Theory(name) =>
   156           progress.theory(session_name, name)
   157           true
   158         case _ => false
   159       }
   160 
   161     val functions =
   162       List(
   163         Markup.BUILD_SESSION_FINISHED -> build_session_finished _,
   164         Markup.LOADING_THEORY -> loading_theory _)
   165   }
   166 
   167 
   168   /* job: running prover process */
   169 
   170   private class Job(progress: Progress,
   171     name: String,
   172     val info: Sessions.Info,
   173     sessions: Sessions.T,
   174     deps: Sessions.Deps,
   175     store: Sessions.Store,
   176     do_output: Boolean,
   177     verbose: Boolean,
   178     pide: Boolean,
   179     val numa_node: Option[Int],
   180     command_timings: List[Properties.T])
   181   {
   182     val output = store.output_dir + Path.basic(name)
   183     def output_path: Option[Path] = if (do_output) Some(output) else None
   184     output.file.delete
   185 
   186     val options =
   187       numa_node match {
   188         case None => info.options
   189         case Some(n) => info.options.string("ML_process_policy") = NUMA.policy(n)
   190       }
   191 
   192     private val graph_file = Isabelle_System.tmp_file("session_graph", "pdf")
   193     try { isabelle.graphview.Graph_File.write(options, graph_file, deps(name).session_graph) }
   194     catch { case ERROR(_) => /*error should be exposed in ML*/ }
   195 
   196     private val future_result: Future[Process_Result] =
   197       Future.thread("build") {
   198         val parent = info.parent.getOrElse("")
   199 
   200         val args_yxml =
   201           YXML.string_of_body(
   202             {
   203               import XML.Encode._
   204               pair(list(pair(string, int)), pair(list(properties), pair(bool, pair(bool,
   205                 pair(Path.encode, pair(list(pair(Path.encode, Path.encode)), pair(string,
   206                 pair(string, pair(string, pair(string, pair(Path.encode,
   207                 list(pair(Options.encode, list(string))))))))))))))(
   208               (Symbol.codes, (command_timings, (do_output, (verbose,
   209                 (store.browser_info, (info.document_files, (File.standard_path(graph_file),
   210                 (parent, (info.chapter, (name, (Path.current,
   211                 info.theories))))))))))))
   212             })
   213 
   214         val env =
   215           Isabelle_System.settings() +
   216             ("ISABELLE_ML_DEBUGGER" -> options.bool("ML_debugger").toString)
   217 
   218         def save_heap: String =
   219           "ML_Heap.share_common_data (); ML_Heap.save_child " +
   220             ML_Syntax.print_string0(File.platform_path(output))
   221 
   222         if (pide && !Sessions.is_pure(name)) {
   223           val resources = new Resources(name, deps(parent))
   224           val session = new Session(options, resources)
   225           val handler = new Handler(progress, session, name)
   226           session.init_protocol_handler(handler)
   227 
   228           val session_result = Future.promise[Process_Result]
   229 
   230           Isabelle_Process.start(session, options, logic = parent,
   231             cwd = info.dir.file, env = env, sessions = Some(sessions), store = store,
   232             phase_changed =
   233             {
   234               case Session.Ready => session.protocol_command("build_session", args_yxml)
   235               case Session.Terminated(result) => session_result.fulfill(result)
   236               case _ =>
   237             })
   238 
   239           val result = session_result.join
   240           handler.result_error.join match {
   241             case "" => result
   242             case msg =>
   243               result.copy(
   244                 rc = result.rc max 1,
   245                 out_lines = result.out_lines ::: split_lines(Output.error_text(msg)))
   246           }
   247         }
   248         else {
   249           val args_file = Isabelle_System.tmp_file("build")
   250           File.write(args_file, args_yxml)
   251 
   252           val eval =
   253             "Command_Line.tool0 (fn () => (" +
   254             "Build.build " + ML_Syntax.print_string0(File.standard_path(args_file)) +
   255             (if (do_output) "; " + save_heap else "") + "));"
   256 
   257           val process =
   258             if (Sessions.is_pure(name)) {
   259               ML_Process(options, raw_ml_system = true, cwd = info.dir.file,
   260                 args =
   261                   (for ((root, _) <- Thy_Header.ml_roots) yield List("--use", root)).flatten :::
   262                   List("--eval", eval),
   263                 env = env, sessions = Some(sessions), store = store,
   264                 cleanup = () => args_file.delete)
   265             }
   266             else {
   267               ML_Process(options, parent, List("--eval", eval), cwd = info.dir.file,
   268                 env = env, sessions = Some(sessions), store = store,
   269                 cleanup = () => args_file.delete)
   270             }
   271 
   272           process.result(
   273             progress_stdout = (line: String) =>
   274               Library.try_unprefix("\floading_theory = ", line) match {
   275                 case Some(theory) => progress.theory(name, theory)
   276                 case None =>
   277               },
   278             progress_limit =
   279               options.int("process_output_limit") match {
   280                 case 0 => None
   281                 case m => Some(m * 1000000L)
   282               },
   283             strict = false)
   284         }
   285       }
   286 
   287     def terminate: Unit = future_result.cancel
   288     def is_finished: Boolean = future_result.is_finished
   289 
   290     @volatile private var was_timeout = false
   291     private val timeout_request: Option[Event_Timer.Request] =
   292     {
   293       if (info.timeout > Time.zero)
   294         Some(Event_Timer.request(Time.now() + info.timeout) { terminate; was_timeout = true })
   295       else None
   296     }
   297 
   298     def join: Process_Result =
   299     {
   300       val result = future_result.join
   301 
   302       if (result.ok)
   303         Present.finish(progress, store.browser_info, graph_file, info, name)
   304 
   305       graph_file.delete
   306       timeout_request.foreach(_.cancel)
   307 
   308       if (result.interrupted) {
   309         if (was_timeout) result.error(Output.error_text("Timeout")).was_timeout
   310         else result.error(Output.error_text("Interrupt"))
   311       }
   312       else result
   313     }
   314   }
   315 
   316 
   317 
   318   /** build with results **/
   319 
   320   class Results private[Build](results: Map[String, (Option[Process_Result], Sessions.Info)])
   321   {
   322     def sessions: Set[String] = results.keySet
   323     def cancelled(name: String): Boolean = results(name)._1.isEmpty
   324     def apply(name: String): Process_Result = results(name)._1.getOrElse(Process_Result(1))
   325     def info(name: String): Sessions.Info = results(name)._2
   326     val rc =
   327       (0 /: results.iterator.map(
   328         { case (_, (Some(r), _)) => r.rc case (_, (None, _)) => 1 }))(_ max _)
   329     def ok: Boolean = rc == 0
   330 
   331     override def toString: String = rc.toString
   332   }
   333 
   334   def build(
   335     options: Options,
   336     progress: Progress = No_Progress,
   337     build_heap: Boolean = false,
   338     clean_build: Boolean = false,
   339     dirs: List[Path] = Nil,
   340     select_dirs: List[Path] = Nil,
   341     numa_shuffling: Boolean = false,
   342     max_jobs: Int = 1,
   343     list_files: Boolean = false,
   344     check_keywords: Set[String] = Set.empty,
   345     no_build: Boolean = false,
   346     system_mode: Boolean = false,
   347     verbose: Boolean = false,
   348     pide: Boolean = false,
   349     requirements: Boolean = false,
   350     all_sessions: Boolean = false,
   351     exclude_session_groups: List[String] = Nil,
   352     exclude_sessions: List[String] = Nil,
   353     session_groups: List[String] = Nil,
   354     sessions: List[String] = Nil): Results =
   355   {
   356     build_selection(
   357       options = options,
   358       progress = progress,
   359       build_heap = build_heap,
   360       clean_build = clean_build,
   361       dirs = dirs,
   362       select_dirs = select_dirs,
   363       numa_shuffling = numa_shuffling,
   364       max_jobs = max_jobs,
   365       list_files = list_files,
   366       check_keywords = check_keywords,
   367       no_build = no_build,
   368       system_mode = system_mode,
   369       verbose = verbose,
   370       pide = pide,
   371       selection = { full_sessions =>
   372         full_sessions.selection(requirements, all_sessions,
   373           exclude_session_groups, exclude_sessions, session_groups, sessions) })
   374   }
   375 
   376   def build_selection(
   377       options: Options,
   378       progress: Progress = No_Progress,
   379       build_heap: Boolean = false,
   380       clean_build: Boolean = false,
   381       dirs: List[Path] = Nil,
   382       select_dirs: List[Path] = Nil,
   383       numa_shuffling: Boolean = false,
   384       max_jobs: Int = 1,
   385       list_files: Boolean = false,
   386       check_keywords: Set[String] = Set.empty,
   387       no_build: Boolean = false,
   388       system_mode: Boolean = false,
   389       verbose: Boolean = false,
   390       pide: Boolean = false,
   391       selection: Sessions.T => (List[String], Sessions.T) = (_.selection(all_sessions = true))
   392     ): Results =
   393   {
   394     /* session selection and dependencies */
   395 
   396     val build_options = options.int.update("completion_limit", 0).bool.update("ML_statistics", true)
   397     val full_sessions = Sessions.load(build_options, dirs, select_dirs)
   398     val (selected, selected_sessions) = selection(full_sessions)
   399     val deps =
   400       Sessions.deps(selected_sessions, progress = progress, inlined_files = true,
   401         verbose = verbose, list_files = list_files, check_keywords = check_keywords,
   402         global_theories = full_sessions.global_theories)
   403 
   404     def sources_stamp(name: String): List[String] =
   405       (selected_sessions(name).meta_digest :: deps.sources(name)).map(_.toString).sorted
   406 
   407 
   408     /* main build process */
   409 
   410     val store = Sessions.store(system_mode)
   411     val queue = Queue(selected_sessions, store)
   412 
   413     store.prepare_output()
   414 
   415     // optional cleanup
   416     if (clean_build) {
   417       for (name <- full_sessions.graph.all_succs(selected)) {
   418         val files =
   419           List(Path.basic(name), store.database(name), store.log(name), store.log_gz(name)).
   420             map(store.output_dir + _).filter(_.is_file)
   421         if (files.nonEmpty) progress.echo("Cleaning " + name + " ...")
   422         if (!files.forall(p => p.file.delete)) progress.echo(name + " FAILED to delete")
   423       }
   424     }
   425 
   426     // scheduler loop
   427     case class Result(
   428       current: Boolean, heap_stamp: Option[String],
   429       process: Option[Process_Result], info: Sessions.Info)
   430     {
   431       def ok: Boolean =
   432         process match {
   433           case None => false
   434           case Some(res) => res.rc == 0
   435         }
   436     }
   437 
   438     def sleep()
   439     {
   440       try { Thread.sleep(500) }
   441       catch { case Exn.Interrupt() => Exn.Interrupt.impose() }
   442     }
   443 
   444     val numa_nodes = new NUMA.Nodes(numa_shuffling)
   445 
   446     @tailrec def loop(
   447       pending: Queue,
   448       running: Map[String, (List[String], Job)],
   449       results: Map[String, Result]): Map[String, Result] =
   450     {
   451       def used_node(i: Int): Boolean =
   452         running.iterator.exists(
   453           { case (_, (_, job)) => job.numa_node.isDefined && job.numa_node.get == i })
   454 
   455       if (pending.is_empty) results
   456       else {
   457         if (progress.stopped)
   458           for ((_, (_, job)) <- running) job.terminate
   459 
   460         running.find({ case (_, (_, job)) => job.is_finished }) match {
   461           case Some((name, (input_heaps, job))) =>
   462             //{{{ finish job
   463 
   464             val process_result = job.join
   465             process_result.err_lines.foreach(progress.echo(_))
   466             if (process_result.ok)
   467               progress.echo("Finished " + name + " (" + process_result.timing.message_resources + ")")
   468 
   469             val log_lines = process_result.out_lines.filterNot(_.startsWith("\f"))
   470             val process_result_tail =
   471             {
   472               val tail = job.info.options.int("process_output_tail")
   473               process_result.copy(
   474                 out_lines =
   475                   "(see also " + (store.output_dir + store.log(name)).file.toString + ")" ::
   476                   (if (tail == 0) log_lines else log_lines.drop(log_lines.length - tail max 0)))
   477             }
   478 
   479             val heap_stamp =
   480               if (process_result.ok) {
   481                 (store.output_dir + store.log(name)).file.delete
   482                 val heap_stamp =
   483                   for (path <- job.output_path if path.is_file)
   484                     yield Sessions.write_heap_digest(path)
   485 
   486                 File.write_gzip(store.output_dir + store.log_gz(name), terminate_lines(log_lines))
   487 
   488                 heap_stamp
   489               }
   490               else {
   491                 (store.output_dir + Path.basic(name)).file.delete
   492                 (store.output_dir + store.log_gz(name)).file.delete
   493 
   494                 File.write(store.output_dir + store.log(name), terminate_lines(log_lines))
   495                 progress.echo(name + " FAILED")
   496                 if (!process_result.interrupted) progress.echo(process_result_tail.out)
   497 
   498                 None
   499               }
   500 
   501             // write database
   502             {
   503               val database = store.output_dir + store.database(name)
   504               database.file.delete
   505 
   506               using(SQLite.open_database(database))(db =>
   507                 store.write_session_info(db, name,
   508                   build_log =
   509                     Build_Log.Log_File(name, process_result.out_lines).
   510                       parse_session_info(
   511                         command_timings = true, ml_statistics = true, task_statistics = true),
   512                   build =
   513                     Session_Info(sources_stamp(name), input_heaps, heap_stamp, process_result.rc)))
   514             }
   515 
   516             loop(pending - name, running - name,
   517               results + (name -> Result(false, heap_stamp, Some(process_result_tail), job.info)))
   518             //}}}
   519           case None if running.size < (max_jobs max 1) =>
   520             //{{{ check/start next job
   521             pending.dequeue(running.isDefinedAt(_)) match {
   522               case Some((name, info)) =>
   523                 val ancestor_results = selected_sessions.ancestors(name).map(results(_))
   524                 val ancestor_heaps = ancestor_results.flatMap(_.heap_stamp)
   525 
   526                 val do_output = build_heap || Sessions.is_pure(name) || queue.is_inner(name)
   527 
   528                 val (current, heap_stamp) =
   529                 {
   530                   store.find_database_heap(name) match {
   531                     case Some((database, heap_stamp)) =>
   532                       using(SQLite.open_database(database))(store.read_build(_, name)) match {
   533                         case Some(build) =>
   534                           val current =
   535                             build.sources == sources_stamp(name) &&
   536                             build.input_heaps == ancestor_heaps &&
   537                             build.output_heap == heap_stamp &&
   538                             !(do_output && heap_stamp.isEmpty) &&
   539                             build.return_code == 0
   540                           (current, heap_stamp)
   541                         case None => (false, None)
   542                       }
   543                     case None => (false, None)
   544                   }
   545                 }
   546                 val all_current = current && ancestor_results.forall(_.current)
   547 
   548                 if (all_current)
   549                   loop(pending - name, running,
   550                     results + (name -> Result(true, heap_stamp, Some(Process_Result(0)), info)))
   551                 else if (no_build) {
   552                   if (verbose) progress.echo("Skipping " + name + " ...")
   553                   loop(pending - name, running,
   554                     results + (name -> Result(false, heap_stamp, Some(Process_Result(1)), info)))
   555                 }
   556                 else if (ancestor_results.forall(_.ok) && !progress.stopped) {
   557                   val numa_node = numa_nodes.next(used_node(_))
   558                   progress.echo((if (do_output) "Building " else "Running ") + name + " ...")
   559                   val job =
   560                     new Job(progress, name, info, selected_sessions, deps, store, do_output,
   561                       verbose, pide, numa_node, queue.command_timings(name))
   562                   loop(pending, running + (name -> (ancestor_heaps, job)), results)
   563                 }
   564                 else {
   565                   progress.echo(name + " CANCELLED")
   566                   loop(pending - name, running,
   567                     results + (name -> Result(false, heap_stamp, None, info)))
   568                 }
   569               case None => sleep(); loop(pending, running, results)
   570             }
   571             ///}}}
   572           case None => sleep(); loop(pending, running, results)
   573         }
   574       }
   575     }
   576 
   577 
   578     /* build results */
   579 
   580     val results0 =
   581       if (deps.is_empty) {
   582         progress.echo(Output.warning_text("Nothing to build"))
   583         Map.empty[String, Result]
   584       }
   585       else loop(queue, Map.empty, Map.empty)
   586 
   587     val results =
   588       new Results(
   589         (for ((name, result) <- results0.iterator)
   590           yield (name, (result.process, result.info))).toMap)
   591 
   592     if (results.rc != 0 && (verbose || !no_build)) {
   593       val unfinished =
   594         (for {
   595           name <- results.sessions.iterator
   596           if !results(name).ok
   597          } yield name).toList.sorted
   598       progress.echo("Unfinished session(s): " + commas(unfinished))
   599     }
   600 
   601 
   602     /* global browser info */
   603 
   604     if (!no_build) {
   605       val browser_chapters =
   606         (for {
   607           (name, result) <- results0.iterator
   608           if result.ok
   609           info = full_sessions(name)
   610           if info.options.bool("browser_info")
   611         } yield (info.chapter, (name, info.description))).toList.groupBy(_._1).
   612             map({ case (chapter, es) => (chapter, es.map(_._2)) }).filterNot(_._2.isEmpty)
   613 
   614       for ((chapter, entries) <- browser_chapters)
   615         Present.update_chapter_index(store.browser_info, chapter, entries)
   616 
   617       if (browser_chapters.nonEmpty) Present.make_global_index(store.browser_info)
   618     }
   619 
   620     results
   621   }
   622 
   623 
   624   /* Isabelle tool wrapper */
   625 
   626   val isabelle_tool = Isabelle_Tool("build", "build and manage Isabelle sessions", args =>
   627   {
   628     val build_options = Word.explode(Isabelle_System.getenv("ISABELLE_BUILD_OPTIONS"))
   629 
   630     var select_dirs: List[Path] = Nil
   631     var numa_shuffling = false
   632     var pide = false
   633     var requirements = false
   634     var exclude_session_groups: List[String] = Nil
   635     var all_sessions = false
   636     var build_heap = false
   637     var clean_build = false
   638     var dirs: List[Path] = Nil
   639     var session_groups: List[String] = Nil
   640     var max_jobs = 1
   641     var check_keywords: Set[String] = Set.empty
   642     var list_files = false
   643     var no_build = false
   644     var options = (Options.init() /: build_options)(_ + _)
   645     var system_mode = false
   646     var verbose = false
   647     var exclude_sessions: List[String] = Nil
   648 
   649     val getopts = Getopts("""
   650 Usage: isabelle build [OPTIONS] [SESSIONS ...]
   651 
   652   Options are:
   653     -D DIR       include session directory and select its sessions
   654     -N           cyclic shuffling of NUMA CPU nodes (performance tuning)
   655     -P           build via PIDE protocol
   656     -R           operate on requirements of selected sessions
   657     -X NAME      exclude sessions from group NAME and all descendants
   658     -a           select all sessions
   659     -b           build heap images
   660     -c           clean build
   661     -d DIR       include session directory
   662     -g NAME      select session group NAME
   663     -j INT       maximum number of parallel jobs (default 1)
   664     -k KEYWORD   check theory sources for conflicts with proposed keywords
   665     -l           list session source files
   666     -n           no build -- test dependencies only
   667     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   668     -s           system build mode: produce output in ISABELLE_HOME
   669     -v           verbose
   670     -x NAME      exclude session NAME and all descendants
   671 
   672   Build and manage Isabelle sessions, depending on implicit settings:
   673 
   674 """ + Library.prefix_lines("  ", Build_Log.Settings.show()) + "\n",
   675       "D:" -> (arg => select_dirs = select_dirs ::: List(Path.explode(arg))),
   676       "N" -> (_ => numa_shuffling = true),
   677       "P" -> (_ => pide = true),
   678       "R" -> (_ => requirements = true),
   679       "X:" -> (arg => exclude_session_groups = exclude_session_groups ::: List(arg)),
   680       "a" -> (_ => all_sessions = true),
   681       "b" -> (_ => build_heap = true),
   682       "c" -> (_ => clean_build = true),
   683       "d:" -> (arg => dirs = dirs ::: List(Path.explode(arg))),
   684       "g:" -> (arg => session_groups = session_groups ::: List(arg)),
   685       "j:" -> (arg => max_jobs = Value.Int.parse(arg)),
   686       "k:" -> (arg => check_keywords = check_keywords + arg),
   687       "l" -> (_ => list_files = true),
   688       "n" -> (_ => no_build = true),
   689       "o:" -> (arg => options = options + arg),
   690       "s" -> (_ => system_mode = true),
   691       "v" -> (_ => verbose = true),
   692       "x:" -> (arg => exclude_sessions = exclude_sessions ::: List(arg)))
   693 
   694     val sessions = getopts(args)
   695 
   696     val progress = new Console_Progress(verbose = verbose)
   697 
   698     val start_date = Date.now()
   699 
   700     if (verbose) {
   701       progress.echo(
   702         "Started at " + Build_Log.print_date(start_date) +
   703           " (" + Isabelle_System.getenv("ML_IDENTIFIER") + " on " + Isabelle_System.hostname() +")")
   704       progress.echo(Build_Log.Settings.show() + "\n")
   705     }
   706 
   707     val results =
   708       progress.interrupt_handler {
   709         build(options, progress,
   710           build_heap = build_heap,
   711           clean_build = clean_build,
   712           dirs = dirs,
   713           select_dirs = select_dirs,
   714           numa_shuffling = NUMA.enabled_warning(numa_shuffling),
   715           max_jobs = max_jobs,
   716           list_files = list_files,
   717           check_keywords = check_keywords,
   718           no_build = no_build,
   719           system_mode = system_mode,
   720           verbose = verbose,
   721           pide = pide,
   722           requirements = requirements,
   723           all_sessions = all_sessions,
   724           exclude_session_groups = exclude_session_groups,
   725           exclude_sessions = exclude_sessions,
   726           session_groups = session_groups,
   727           sessions = sessions)
   728       }
   729     val end_date = Date.now()
   730     val elapsed_time = end_date.time - start_date.time
   731 
   732     if (verbose) {
   733       progress.echo("\nFinished at " + Build_Log.print_date(end_date))
   734     }
   735 
   736     val total_timing =
   737       (Timing.zero /: results.sessions.iterator.map(a => results(a).timing))(_ + _).
   738         copy(elapsed = elapsed_time)
   739     progress.echo(total_timing.message_resources)
   740 
   741     sys.exit(results.rc)
   742   })
   743 }