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