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