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