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