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