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