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