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