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