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