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