src/Pure/System/build.scala
author wenzelm
Thu Jul 26 19:57:33 2012 +0200 (2012-07-26)
changeset 48528 784c6f63d79c
parent 48511 37999ee01156
child 48537 ba0dd46b9214
permissions -rw-r--r--
proper all_current, which regards parent status as well;
wenzelm@48276
     1
/*  Title:      Pure/System/build.scala
wenzelm@48276
     2
    Author:     Makarius
wenzelm@48276
     3
wenzelm@48276
     4
Build and manage Isabelle sessions.
wenzelm@48276
     5
*/
wenzelm@48276
     6
wenzelm@48276
     7
package isabelle
wenzelm@48276
     8
wenzelm@48276
     9
wenzelm@48494
    10
import java.io.{File => JFile, BufferedInputStream, FileInputStream,
wenzelm@48494
    11
  BufferedReader, InputStreamReader, IOException}
wenzelm@48494
    12
import java.util.zip.GZIPInputStream
wenzelm@48335
    13
wenzelm@48337
    14
import scala.collection.mutable
wenzelm@48340
    15
import scala.annotation.tailrec
wenzelm@48337
    16
wenzelm@48335
    17
wenzelm@48276
    18
object Build
wenzelm@48276
    19
{
wenzelm@48337
    20
  /** session information **/
wenzelm@48334
    21
wenzelm@48349
    22
  object Session
wenzelm@48349
    23
  {
wenzelm@48421
    24
    /* Info */
wenzelm@48421
    25
wenzelm@48349
    26
    sealed case class Info(
wenzelm@48457
    27
      base_name: String,
wenzelm@48509
    28
      groups: List[String],
wenzelm@48349
    29
      dir: Path,
wenzelm@48418
    30
      parent: Option[String],
wenzelm@48482
    31
      parent_base_name: Option[String],
wenzelm@48349
    32
      description: String,
wenzelm@48349
    33
      options: Options,
wenzelm@48421
    34
      theories: List[(Options, List[Path])],
wenzelm@48421
    35
      files: List[Path],
wenzelm@48424
    36
      digest: SHA1.Digest)
wenzelm@48421
    37
wenzelm@48421
    38
wenzelm@48421
    39
    /* Queue */
wenzelm@48349
    40
wenzelm@48349
    41
    object Queue
wenzelm@48349
    42
    {
wenzelm@48349
    43
      val empty: Queue = new Queue()
wenzelm@48349
    44
    }
wenzelm@48349
    45
wenzelm@48508
    46
    final class Queue private(graph: Graph[String, Info] = Graph.string)
wenzelm@48508
    47
      extends PartialFunction[String, Info]
wenzelm@48349
    48
    {
wenzelm@48508
    49
      def apply(name: String): Info = graph.get_node(name)
wenzelm@48508
    50
      def isDefinedAt(name: String): Boolean = graph.defined(name)
wenzelm@48508
    51
wenzelm@48508
    52
      def is_inner(name: String): Boolean = !graph.is_maximal(name)
wenzelm@48508
    53
wenzelm@48425
    54
      def is_empty: Boolean = graph.is_empty
wenzelm@48425
    55
wenzelm@48508
    56
      def + (name: String, info: Info): Queue =
wenzelm@48508
    57
        new Queue(
wenzelm@48508
    58
          try { graph.new_node(name, info).add_deps_acyclic(name, info.parent.toList) }
wenzelm@48349
    59
          catch {
wenzelm@48508
    60
            case _: Graph.Duplicate[_] => error("Duplicate session: " + quote(name))
wenzelm@48349
    61
            case exn: Graph.Cycles[_] =>
wenzelm@48349
    62
              error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48349
    63
                "Cyclic session dependency of " +
wenzelm@48508
    64
                  cycle.map(c => quote(c.toString)).mkString(" via "))))
wenzelm@48508
    65
          })
wenzelm@48349
    66
wenzelm@48508
    67
      def - (name: String): Queue = new Queue(graph.del_node(name))
wenzelm@48425
    68
wenzelm@48509
    69
      def required(groups: List[String], names: List[String]): Queue =
wenzelm@48509
    70
      {
wenzelm@48509
    71
        val selected_group = groups.toSet
wenzelm@48509
    72
        val selected_name = names.toSet
wenzelm@48509
    73
        val selected =
wenzelm@48509
    74
          graph.keys.filter(name =>
wenzelm@48509
    75
            selected_name(name) || apply(name).groups.exists(selected_group)).toList
wenzelm@48509
    76
        new Queue(graph.restrict(graph.all_preds(selected).toSet))
wenzelm@48509
    77
      }
wenzelm@48363
    78
wenzelm@48425
    79
      def dequeue(skip: String => Boolean): Option[(String, Info)] =
wenzelm@48425
    80
      {
wenzelm@48425
    81
        val it = graph.entries.dropWhile(
wenzelm@48508
    82
          { case (name, (_, (deps, _))) => !deps.isEmpty || skip(name) })
wenzelm@48508
    83
        if (it.hasNext) { val (name, (info, _)) = it.next; Some((name, info)) }
wenzelm@48425
    84
        else None
wenzelm@48425
    85
      }
wenzelm@48425
    86
wenzelm@48422
    87
      def topological_order: List[(String, Info)] =
wenzelm@48508
    88
        graph.topological_order.map(name => (name, graph.get_node(name)))
wenzelm@48349
    89
    }
wenzelm@48349
    90
  }
wenzelm@48334
    91
wenzelm@48337
    92
wenzelm@48337
    93
  /* parsing */
wenzelm@48337
    94
wenzelm@48337
    95
  private case class Session_Entry(
wenzelm@48337
    96
    name: String,
wenzelm@48462
    97
    this_name: Boolean,
wenzelm@48509
    98
    groups: List[String],
wenzelm@48337
    99
    path: Option[String],
wenzelm@48347
   100
    parent: Option[String],
wenzelm@48337
   101
    description: String,
wenzelm@48421
   102
    options: List[Options.Spec],
wenzelm@48421
   103
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48337
   104
    files: List[String])
wenzelm@48337
   105
wenzelm@48334
   106
  private object Parser extends Parse.Parser
wenzelm@48334
   107
  {
wenzelm@48334
   108
    val SESSION = "session"
wenzelm@48334
   109
    val IN = "in"
wenzelm@48334
   110
    val DESCRIPTION = "description"
wenzelm@48334
   111
    val OPTIONS = "options"
wenzelm@48334
   112
    val THEORIES = "theories"
wenzelm@48334
   113
    val FILES = "files"
wenzelm@48334
   114
wenzelm@48334
   115
    val syntax =
wenzelm@48336
   116
      Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48336
   117
        SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48334
   118
wenzelm@48337
   119
    val session_entry: Parser[Session_Entry] =
wenzelm@48334
   120
    {
wenzelm@48334
   121
      val session_name = atom("session name", _.is_name)
wenzelm@48280
   122
wenzelm@48334
   123
      val option =
wenzelm@48334
   124
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48337
   125
      val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
wenzelm@48334
   126
wenzelm@48334
   127
      val theories =
wenzelm@48334
   128
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
wenzelm@48334
   129
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48334
   130
wenzelm@48334
   131
      ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
wenzelm@48336
   132
        (keyword("!") ^^^ true | success(false)) ~
wenzelm@48509
   133
        (keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48337
   134
        (opt(keyword(IN) ~! string ^^ { case _ ~ x => x })) ~
wenzelm@48347
   135
        (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
wenzelm@48334
   136
        (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
wenzelm@48334
   137
        (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48347
   138
        rep(theories) ~
wenzelm@48336
   139
        (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
wenzelm@48509
   140
          { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
wenzelm@48334
   141
    }
wenzelm@48334
   142
wenzelm@48409
   143
    def parse_entries(root: JFile): List[Session_Entry] =
wenzelm@48334
   144
    {
wenzelm@48411
   145
      val toks = syntax.scan(File.read(root))
wenzelm@48337
   146
      parse_all(rep(session_entry), Token.reader(toks, root.toString)) match {
wenzelm@48334
   147
        case Success(result, _) => result
wenzelm@48334
   148
        case bad => error(bad.toString)
wenzelm@48334
   149
      }
wenzelm@48334
   150
    }
wenzelm@48334
   151
  }
wenzelm@48280
   152
wenzelm@48337
   153
wenzelm@48341
   154
  /* find sessions */
wenzelm@48337
   155
wenzelm@48361
   156
  private val ROOT = Path.explode("ROOT")
wenzelm@48361
   157
  private val SESSIONS = Path.explode("etc/sessions")
wenzelm@48361
   158
wenzelm@48364
   159
  private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48364
   160
wenzelm@48421
   161
  private def sessions_root(options: Options, dir: Path, root: JFile, queue: Session.Queue)
wenzelm@48421
   162
    : Session.Queue =
wenzelm@48280
   163
  {
wenzelm@48361
   164
    (queue /: Parser.parse_entries(root))((queue1, entry) =>
wenzelm@48337
   165
      try {
wenzelm@48347
   166
        if (entry.name == "") error("Bad session name")
wenzelm@48347
   167
wenzelm@48482
   168
        val (full_name, parent_base_name) =
wenzelm@48364
   169
          if (is_pure(entry.name)) {
wenzelm@48347
   170
            if (entry.parent.isDefined) error("Illegal parent session")
wenzelm@48482
   171
            else (entry.name, None: Option[String])
wenzelm@48347
   172
          }
wenzelm@48347
   173
          else
wenzelm@48347
   174
            entry.parent match {
wenzelm@48508
   175
              case Some(parent_name) if queue1.isDefinedAt(parent_name) =>
wenzelm@48482
   176
                val full_name =
wenzelm@48482
   177
                  if (entry.this_name) entry.name
wenzelm@48482
   178
                  else parent_name + "-" + entry.name
wenzelm@48482
   179
                val parent_base_name = Some(queue1(parent_name).base_name)
wenzelm@48482
   180
                (full_name, parent_base_name)
wenzelm@48351
   181
              case _ => error("Bad parent session")
wenzelm@48347
   182
            }
wenzelm@48339
   183
wenzelm@48337
   184
        val path =
wenzelm@48337
   185
          entry.path match {
wenzelm@48337
   186
            case Some(p) => Path.explode(p)
wenzelm@48337
   187
            case None => Path.basic(entry.name)
wenzelm@48337
   188
          }
wenzelm@48339
   189
wenzelm@48467
   190
        val session_options = options ++ entry.options
wenzelm@48467
   191
wenzelm@48421
   192
        val theories =
wenzelm@48467
   193
          entry.theories.map({ case (opts, thys) =>
wenzelm@48467
   194
            (session_options ++ opts, thys.map(Path.explode(_))) })
wenzelm@48421
   195
        val files = entry.files.map(Path.explode(_))
wenzelm@48423
   196
        val digest = SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48423
   197
wenzelm@48418
   198
        val info =
wenzelm@48509
   199
          Session.Info(entry.name, entry.groups, dir + path, entry.parent, parent_base_name,
wenzelm@48467
   200
            entry.description, session_options, theories, files, digest)
wenzelm@48351
   201
wenzelm@48508
   202
        queue1 + (full_name, info)
wenzelm@48337
   203
      }
wenzelm@48337
   204
      catch {
wenzelm@48337
   205
        case ERROR(msg) =>
wenzelm@48337
   206
          error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48370
   207
            quote(entry.name) + Position.str_of(Position.file(root)))
wenzelm@48352
   208
      })
wenzelm@48352
   209
  }
wenzelm@48352
   210
wenzelm@48421
   211
  private def sessions_dir(options: Options, strict: Boolean, dir: Path, queue: Session.Queue)
wenzelm@48421
   212
    : Session.Queue =
wenzelm@48352
   213
  {
wenzelm@48373
   214
    val root = (dir + ROOT).file
wenzelm@48421
   215
    if (root.isFile) sessions_root(options, dir, root, queue)
wenzelm@48352
   216
    else if (strict) error("Bad session root file: " + quote(root.toString))
wenzelm@48361
   217
    else queue
wenzelm@48352
   218
  }
wenzelm@48352
   219
wenzelm@48421
   220
  private def sessions_catalog(options: Options, dir: Path, catalog: JFile, queue: Session.Queue)
wenzelm@48421
   221
    : Session.Queue =
wenzelm@48352
   222
  {
wenzelm@48354
   223
    val dirs =
wenzelm@48411
   224
      split_lines(File.read(catalog)).filterNot(line => line == "" || line.startsWith("#"))
wenzelm@48361
   225
    (queue /: dirs)((queue1, dir1) =>
wenzelm@48352
   226
      try {
wenzelm@48352
   227
        val dir2 = dir + Path.explode(dir1)
wenzelm@48421
   228
        if (dir2.file.isDirectory) sessions_dir(options, true, dir2, queue1)
wenzelm@48352
   229
        else error("Bad session directory: " + dir2.toString)
wenzelm@48337
   230
      }
wenzelm@48352
   231
      catch {
wenzelm@48352
   232
        case ERROR(msg) =>
wenzelm@48352
   233
          error(msg + "\nThe error(s) above occurred in session catalog " + quote(catalog.toString))
wenzelm@48352
   234
      })
wenzelm@48352
   235
  }
wenzelm@48352
   236
wenzelm@48509
   237
  def find_sessions(options: Options, more_dirs: List[Path],
wenzelm@48509
   238
    all_sessions: Boolean, session_groups: List[String], sessions: List[String]): Session.Queue =
wenzelm@48352
   239
  {
wenzelm@48361
   240
    var queue = Session.Queue.empty
wenzelm@48352
   241
wenzelm@48352
   242
    for (dir <- Isabelle_System.components()) {
wenzelm@48421
   243
      queue = sessions_dir(options, false, dir, queue)
wenzelm@48352
   244
wenzelm@48373
   245
      val catalog = (dir + SESSIONS).file
wenzelm@48352
   246
      if (catalog.isFile)
wenzelm@48421
   247
        queue = sessions_catalog(options, dir, catalog, queue)
wenzelm@48337
   248
    }
wenzelm@48352
   249
wenzelm@48421
   250
    for (dir <- more_dirs) queue = sessions_dir(options, true, dir, queue)
wenzelm@48352
   251
wenzelm@48508
   252
    sessions.filter(name => !queue.isDefinedAt(name)) match {
wenzelm@48419
   253
      case Nil =>
wenzelm@48419
   254
      case bad => error("Undefined session(s): " + commas_quote(bad))
wenzelm@48419
   255
    }
wenzelm@48419
   256
wenzelm@48509
   257
    if (all_sessions) queue else queue.required(session_groups, sessions)
wenzelm@48280
   258
  }
wenzelm@48341
   259
wenzelm@48341
   260
wenzelm@48424
   261
wenzelm@48424
   262
  /** build **/
wenzelm@48424
   263
wenzelm@48478
   264
  private def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@48478
   265
  private def sleep(): Unit = Thread.sleep(500)
wenzelm@48478
   266
wenzelm@48478
   267
wenzelm@48504
   268
  /* source dependencies */
wenzelm@48422
   269
wenzelm@48422
   270
  sealed case class Node(
wenzelm@48422
   271
    loaded_theories: Set[String],
wenzelm@48423
   272
    sources: List[(Path, SHA1.Digest)])
wenzelm@48422
   273
wenzelm@48423
   274
  sealed case class Deps(deps: Map[String, Node])
wenzelm@48423
   275
  {
wenzelm@48504
   276
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   277
  }
wenzelm@48423
   278
wenzelm@48478
   279
  def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
wenzelm@48423
   280
    Deps((Map.empty[String, Node] /: queue.topological_order)(
wenzelm@48422
   281
      { case (deps, (name, info)) =>
wenzelm@48422
   282
          val preloaded =
wenzelm@48422
   283
            info.parent match {
wenzelm@48422
   284
              case None => Set.empty[String]
wenzelm@48422
   285
              case Some(parent) => deps(parent).loaded_theories
wenzelm@48422
   286
            }
wenzelm@48422
   287
          val thy_info = new Thy_Info(new Thy_Load(preloaded))
wenzelm@48422
   288
wenzelm@48478
   289
          if (verbose) echo("Checking " + name)
wenzelm@48478
   290
wenzelm@48422
   291
          val thy_deps =
wenzelm@48422
   292
            thy_info.dependencies(
wenzelm@48422
   293
              info.theories.map(_._2).flatten.
wenzelm@48422
   294
                map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   295
wenzelm@48422
   296
          val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
wenzelm@48423
   297
wenzelm@48423
   298
          val all_files =
wenzelm@48422
   299
            thy_deps.map({ case (n, h) =>
wenzelm@48422
   300
              val thy = Path.explode(n.node).expand
wenzelm@48422
   301
              val uses =
wenzelm@48422
   302
                h match {
wenzelm@48422
   303
                  case Exn.Res(d) =>
wenzelm@48422
   304
                    d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
wenzelm@48422
   305
                  case _ => Nil
wenzelm@48422
   306
                }
wenzelm@48422
   307
              thy :: uses
wenzelm@48422
   308
            }).flatten ::: info.files.map(file => info.dir + file)
wenzelm@48485
   309
          val sources =
wenzelm@48485
   310
            try { all_files.map(p => (p, SHA1.digest(p))) }
wenzelm@48485
   311
            catch {
wenzelm@48485
   312
              case ERROR(msg) =>
wenzelm@48485
   313
                error(msg + "\nThe error(s) above occurred in session " + quote(name))
wenzelm@48485
   314
            }
wenzelm@48422
   315
wenzelm@48422
   316
          deps + (name -> Node(loaded_theories, sources))
wenzelm@48423
   317
      }))
wenzelm@48422
   318
wenzelm@48422
   319
wenzelm@48424
   320
  /* jobs */
wenzelm@48341
   321
wenzelm@48494
   322
  private class Job(cwd: JFile, env: Map[String, String], script: String, args: String,
wenzelm@48511
   323
    output: Path, do_output: Boolean)
wenzelm@48364
   324
  {
wenzelm@48418
   325
    private val args_file = File.tmp_file("args")
wenzelm@48418
   326
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   327
    File.write(args_file, args)
wenzelm@48418
   328
wenzelm@48424
   329
    private val (thread, result) =
wenzelm@48424
   330
      Simple_Thread.future("build") { Isabelle_System.bash_env(cwd, env1, script) }
wenzelm@48418
   331
wenzelm@48418
   332
    def terminate: Unit = thread.interrupt
wenzelm@48418
   333
    def is_finished: Boolean = result.is_finished
wenzelm@48425
   334
    def join: (String, String, Int) = { val res = result.join; args_file.delete; res }
wenzelm@48511
   335
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@48418
   336
  }
wenzelm@48418
   337
wenzelm@48511
   338
  private def start_job(name: String, info: Session.Info, output: Path, do_output: Boolean,
wenzelm@48459
   339
    options: Options, timing: Boolean, verbose: Boolean, browser_info: Path): Job =
wenzelm@48418
   340
  {
wenzelm@48467
   341
    // global browser info dir
wenzelm@48467
   342
    if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).file.isFile)
wenzelm@48467
   343
    {
wenzelm@48467
   344
      browser_info.file.mkdirs()
wenzelm@48467
   345
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   346
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   347
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   348
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48467
   349
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   350
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   351
    }
wenzelm@48467
   352
wenzelm@48418
   353
    val parent = info.parent.getOrElse("")
wenzelm@48482
   354
    val parent_base_name = info.parent_base_name.getOrElse("")
wenzelm@48418
   355
wenzelm@48373
   356
    val cwd = info.dir.file
wenzelm@48511
   357
    val env =
wenzelm@48511
   358
      Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output))
wenzelm@48364
   359
    val script =
wenzelm@48511
   360
      if (is_pure(name)) {
wenzelm@48511
   361
        if (do_output) "./build " + name + " \"$OUTPUT\""
wenzelm@48511
   362
        else """ rm -f "$OUTPUT"; ./build """ + name
wenzelm@48511
   363
      }
wenzelm@48418
   364
      else {
wenzelm@48418
   365
        """
wenzelm@48418
   366
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   367
        """ +
wenzelm@48511
   368
          (if (do_output)
wenzelm@48511
   369
            """
wenzelm@48511
   370
            "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
wenzelm@48511
   371
            """
wenzelm@48418
   372
          else
wenzelm@48511
   373
            """
wenzelm@48511
   374
            rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
wenzelm@48511
   375
            """) +
wenzelm@48418
   376
        """
wenzelm@48418
   377
        RC="$?"
wenzelm@48418
   378
wenzelm@48418
   379
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   380
wenzelm@48418
   381
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   382
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   383
        fi
wenzelm@48418
   384
wenzelm@48418
   385
        exit "$RC"
wenzelm@48418
   386
        """
wenzelm@48418
   387
      }
wenzelm@48418
   388
    val args_xml =
wenzelm@48418
   389
    {
wenzelm@48418
   390
      import XML.Encode._
wenzelm@48459
   391
          pair(bool, pair(Options.encode, pair(bool, pair(bool, pair(Path.encode, pair(string,
wenzelm@48459
   392
            pair(string, pair(string, list(pair(Options.encode, list(Path.encode)))))))))))(
wenzelm@48511
   393
          (do_output, (options, (timing, (verbose, (browser_info, (parent_base_name,
wenzelm@48459
   394
            (name, (info.base_name, info.theories)))))))))
wenzelm@48418
   395
    }
wenzelm@48511
   396
    new Job(cwd, env, script, YXML.string_of_body(args_xml), output, do_output)
wenzelm@48364
   397
  }
wenzelm@48364
   398
wenzelm@48424
   399
wenzelm@48504
   400
  /* log files and corresponding heaps */
wenzelm@48504
   401
wenzelm@48505
   402
  private val LOG = Path.explode("log")
wenzelm@48505
   403
  private def log(name: String): Path = LOG + Path.basic(name)
wenzelm@48505
   404
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   405
wenzelm@48505
   406
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@48504
   407
    digests.map(_.toString).sorted.mkString("sources: ", " ", "")
wenzelm@48504
   408
wenzelm@48505
   409
  private def heap_stamp(output: Option[Path]): String =
wenzelm@48504
   410
  {
wenzelm@48504
   411
    "heap: " +
wenzelm@48504
   412
      (output match {
wenzelm@48504
   413
        case Some(path) =>
wenzelm@48504
   414
          val file = path.file
wenzelm@48504
   415
          if (file.isFile) file.length.toString + " " + file.lastModified.toString
wenzelm@48504
   416
          else "-"
wenzelm@48504
   417
        case None => "-"
wenzelm@48504
   418
      })
wenzelm@48504
   419
  }
wenzelm@48504
   420
wenzelm@48505
   421
  private def check_stamps(dir: Path, name: String): Option[(String, Boolean)] =
wenzelm@48504
   422
  {
wenzelm@48504
   423
    val file = (dir + log_gz(name)).file
wenzelm@48504
   424
    if (file.isFile) {
wenzelm@48504
   425
      val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(file)))
wenzelm@48504
   426
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@48504
   427
      val (s, h) = try { (reader.readLine, reader.readLine) } finally { reader.close }
wenzelm@48504
   428
      if (s != null && s.startsWith("sources: ") && h != null && h.startsWith("heap: ") &&
wenzelm@48504
   429
          h == heap_stamp(Some(dir + Path.basic(name)))) Some((s, h != "heap: -"))
wenzelm@48504
   430
      else None
wenzelm@48504
   431
    }
wenzelm@48504
   432
    else None
wenzelm@48504
   433
  }
wenzelm@48504
   434
wenzelm@48504
   435
wenzelm@48425
   436
  /* build */
wenzelm@48424
   437
wenzelm@48509
   438
  def build(
wenzelm@48509
   439
    all_sessions: Boolean = false,
wenzelm@48511
   440
    build_heap: Boolean = false,
wenzelm@48509
   441
    more_dirs: List[Path] = Nil,
wenzelm@48509
   442
    session_groups: List[String] = Nil,
wenzelm@48509
   443
    max_jobs: Int = 1,
wenzelm@48509
   444
    no_build: Boolean = false,
wenzelm@48509
   445
    build_options: List[String] = Nil,
wenzelm@48509
   446
    system_mode: Boolean = false,
wenzelm@48509
   447
    timing: Boolean = false,
wenzelm@48509
   448
    verbose: Boolean = false,
wenzelm@48509
   449
    sessions: List[String] = Nil): Int =
wenzelm@48341
   450
  {
wenzelm@48509
   451
    val options = (Options.init() /: build_options)(_.define_simple(_))
wenzelm@48509
   452
    val queue = find_sessions(options, more_dirs, all_sessions, session_groups, sessions)
wenzelm@48478
   453
    val deps = dependencies(verbose, queue)
wenzelm@48368
   454
wenzelm@48504
   455
    def make_stamp(name: String): String =
wenzelm@48504
   456
      sources_stamp(queue(name).digest :: deps.sources(name))
wenzelm@48504
   457
wenzelm@48504
   458
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   459
      if (system_mode) {
wenzelm@48504
   460
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   461
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   462
      }
wenzelm@48504
   463
      else {
wenzelm@48504
   464
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   465
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   466
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   467
      }
wenzelm@48363
   468
wenzelm@48373
   469
    // prepare log dir
wenzelm@48504
   470
    (output_dir + LOG).file.mkdirs()
wenzelm@48373
   471
wenzelm@48425
   472
    // scheduler loop
wenzelm@48425
   473
    @tailrec def loop(
wenzelm@48425
   474
      pending: Session.Queue,
wenzelm@48425
   475
      running: Map[String, Job],
wenzelm@48425
   476
      results: Map[String, Int]): Map[String, Int] =
wenzelm@48425
   477
    {
wenzelm@48425
   478
      if (pending.is_empty) results
wenzelm@48504
   479
      else if (running.exists({ case (_, job) => job.is_finished }))
wenzelm@48504
   480
      { // finish job
wenzelm@48425
   481
        val (name, job) = running.find({ case (_, job) => job.is_finished }).get
wenzelm@48424
   482
wenzelm@48425
   483
        val (out, err, rc) = job.join
wenzelm@48425
   484
        echo(Library.trim_line(err))
wenzelm@48373
   485
wenzelm@48425
   486
        if (rc == 0) {
wenzelm@48504
   487
          val sources = make_stamp(name)
wenzelm@48504
   488
          val heap = heap_stamp(job.output_path)
wenzelm@48504
   489
          File.write_gzip(output_dir + log_gz(name), sources + "\n" + heap + "\n" + out)
wenzelm@48425
   490
        }
wenzelm@48425
   491
        else {
wenzelm@48504
   492
          File.write(output_dir + log(name), out)
wenzelm@48425
   493
          echo(name + " FAILED")
wenzelm@48504
   494
          echo("(see also " + log(name).file.toString + ")")
wenzelm@48425
   495
          val lines = split_lines(out)
wenzelm@48425
   496
          val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48425
   497
          echo("\n" + cat_lines(tail))
wenzelm@48425
   498
        }
wenzelm@48425
   499
        loop(pending - name, running - name, results + (name -> rc))
wenzelm@48425
   500
      }
wenzelm@48504
   501
      else if (running.size < (max_jobs max 1))
wenzelm@48504
   502
      { // check/start next job
wenzelm@48425
   503
        pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48425
   504
          case Some((name, info)) =>
wenzelm@48528
   505
            val parents_ok = info.parent.map(results(_)).forall(_ == 0)
wenzelm@48528
   506
wenzelm@48511
   507
            val output = output_dir + Path.basic(name)
wenzelm@48511
   508
            val do_output = build_heap || queue.is_inner(name)
wenzelm@48504
   509
wenzelm@48528
   510
            val all_current =
wenzelm@48504
   511
            {
wenzelm@48504
   512
              input_dirs.find(dir => (dir + log_gz(name)).file.isFile) match {
wenzelm@48504
   513
                case Some(dir) =>
wenzelm@48504
   514
                  check_stamps(dir, name) match {
wenzelm@48511
   515
                    case Some((s, h)) => s == make_stamp(name) && (h || !do_output)
wenzelm@48504
   516
                    case None => false
wenzelm@48504
   517
                  }
wenzelm@48504
   518
                case None => false
wenzelm@48504
   519
              }
wenzelm@48528
   520
            } && parents_ok
wenzelm@48528
   521
wenzelm@48528
   522
            if (all_current || no_build)
wenzelm@48528
   523
              loop(pending - name, running, results + (name -> (if (all_current) 0 else 1)))
wenzelm@48528
   524
            else if (parents_ok) {
wenzelm@48511
   525
              echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@48511
   526
              val job =
wenzelm@48511
   527
                start_job(name, info, output, do_output, info.options, timing, verbose, browser_info)
wenzelm@48425
   528
              loop(pending, running + (name -> job), results)
wenzelm@48425
   529
            }
wenzelm@48425
   530
            else {
wenzelm@48425
   531
              echo(name + " CANCELLED")
wenzelm@48425
   532
              loop(pending - name, running, results + (name -> 1))
wenzelm@48425
   533
            }
wenzelm@48425
   534
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   535
        }
wenzelm@48373
   536
      }
wenzelm@48425
   537
      else { sleep(); loop(pending, running, results) }
wenzelm@48425
   538
    }
wenzelm@48425
   539
wenzelm@48473
   540
    val results = loop(queue, Map.empty, Map.empty)
wenzelm@48473
   541
    val rc = (0 /: results)({ case (rc1, (_, rc2)) => rc1 max rc2 })
wenzelm@48504
   542
    if (rc != 0 && (verbose || !no_build)) {
wenzelm@48473
   543
      val unfinished = (for ((name, r) <- results.iterator if r != 0) yield name).toList.sorted
wenzelm@48473
   544
      echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   545
    }
wenzelm@48473
   546
    rc
wenzelm@48341
   547
  }
wenzelm@48341
   548
wenzelm@48341
   549
wenzelm@48346
   550
  /* command line entry point */
wenzelm@48341
   551
wenzelm@48341
   552
  def main(args: Array[String])
wenzelm@48341
   553
  {
wenzelm@48346
   554
    Command_Line.tool {
wenzelm@48346
   555
      args.toList match {
wenzelm@48346
   556
        case
wenzelm@48346
   557
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48511
   558
          Properties.Value.Boolean(build_heap) ::
wenzelm@48425
   559
          Properties.Value.Int(max_jobs) ::
wenzelm@48469
   560
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   561
          Properties.Value.Boolean(system_mode) ::
wenzelm@48459
   562
          Properties.Value.Boolean(timing) ::
wenzelm@48425
   563
          Properties.Value.Boolean(verbose) ::
wenzelm@48509
   564
          Command_Line.Chunks(more_dirs, session_groups, build_options, sessions) =>
wenzelm@48511
   565
            build(all_sessions, build_heap, more_dirs.map(Path.explode), session_groups,
wenzelm@48509
   566
              max_jobs, no_build, build_options, system_mode, timing, verbose, sessions)
wenzelm@48346
   567
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   568
      }
wenzelm@48346
   569
    }
wenzelm@48341
   570
  }
wenzelm@48276
   571
}
wenzelm@48276
   572