src/Pure/System/build.scala
author wenzelm
Fri Aug 03 14:52:45 2012 +0200 (2012-08-03)
changeset 48661 9149ebdd0241
parent 48660 730ca503e955
child 48671 951bc4c3ee17
permissions -rw-r--r--
timeout for session build job;
tuned error messages;
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@48661
    10
import java.util.{Timer, TimerTask}
wenzelm@48548
    11
import java.io.{BufferedInputStream, FileInputStream,
wenzelm@48494
    12
  BufferedReader, InputStreamReader, IOException}
wenzelm@48494
    13
import java.util.zip.GZIPInputStream
wenzelm@48335
    14
wenzelm@48337
    15
import scala.collection.mutable
wenzelm@48340
    16
import scala.annotation.tailrec
wenzelm@48337
    17
wenzelm@48335
    18
wenzelm@48276
    19
object Build
wenzelm@48276
    20
{
wenzelm@48337
    21
  /** session information **/
wenzelm@48334
    22
wenzelm@48349
    23
  object Session
wenzelm@48349
    24
  {
wenzelm@48421
    25
    /* Info */
wenzelm@48421
    26
wenzelm@48349
    27
    sealed case class Info(
wenzelm@48509
    28
      groups: List[String],
wenzelm@48349
    29
      dir: Path,
wenzelm@48418
    30
      parent: 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@48544
    35
      entry_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@48649
    45
    final class Queue private(graph: Graph[String, Option[Info]] = Graph.string)
wenzelm@48508
    46
      extends PartialFunction[String, Info]
wenzelm@48349
    47
    {
wenzelm@48649
    48
      def apply(name: String): Info = graph.get_node(name).get
wenzelm@48649
    49
      def isDefinedAt(name: String): Boolean =
wenzelm@48649
    50
        graph.defined(name) && graph.get_node(name).isDefined
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@48649
    57
      {
wenzelm@48649
    58
        val parents = info.parent.toList
wenzelm@48649
    59
wenzelm@48649
    60
        val graph1 = (graph /: (name :: parents))(_.default_node(_, None))
wenzelm@48649
    61
        if (graph1.get_node(name).isDefined)
wenzelm@48649
    62
          error("Duplicate session: " + quote(name))
wenzelm@48649
    63
wenzelm@48508
    64
        new Queue(
wenzelm@48649
    65
          try { graph1.map_node(name, _ => Some(info)).add_deps_acyclic(name, parents) }
wenzelm@48349
    66
          catch {
wenzelm@48349
    67
            case exn: Graph.Cycles[_] =>
wenzelm@48349
    68
              error(cat_lines(exn.cycles.map(cycle =>
wenzelm@48349
    69
                "Cyclic session dependency of " +
wenzelm@48508
    70
                  cycle.map(c => quote(c.toString)).mkString(" via "))))
wenzelm@48508
    71
          })
wenzelm@48649
    72
      }
wenzelm@48349
    73
wenzelm@48508
    74
      def - (name: String): Queue = new Queue(graph.del_node(name))
wenzelm@48425
    75
wenzelm@48595
    76
      def required(all_sessions: Boolean, session_groups: List[String], sessions: List[String])
wenzelm@48595
    77
        : (List[String], Queue) =
wenzelm@48509
    78
      {
wenzelm@48649
    79
        (for {
wenzelm@48649
    80
          (name, (Some(info), _)) <- graph.entries
wenzelm@48649
    81
          if info.parent.isDefined; parent = info.parent.get
wenzelm@48649
    82
          if !isDefinedAt(parent)
wenzelm@48649
    83
        } yield parent + " (for " + name + ")").toList match
wenzelm@48649
    84
        {
wenzelm@48649
    85
          case Nil =>
wenzelm@48649
    86
          case bad => error("Bad parent session(s): " + commas(bad))
wenzelm@48649
    87
        }
wenzelm@48649
    88
wenzelm@48595
    89
        sessions.filterNot(isDefinedAt(_)) match {
wenzelm@48595
    90
          case Nil =>
wenzelm@48595
    91
          case bad => error("Undefined session(s): " + commas_quote(bad))
wenzelm@48595
    92
        }
wenzelm@48595
    93
wenzelm@48509
    94
        val selected =
wenzelm@48595
    95
        {
wenzelm@48595
    96
          if (all_sessions) graph.keys.toList
wenzelm@48595
    97
          else {
wenzelm@48595
    98
            val sel_group = session_groups.toSet
wenzelm@48595
    99
            val sel = sessions.toSet
wenzelm@48595
   100
              graph.keys.toList.filter(name =>
wenzelm@48595
   101
                sel(name) || apply(name).groups.exists(sel_group)).toList
wenzelm@48595
   102
          }
wenzelm@48595
   103
        }
wenzelm@48595
   104
        val descendants = graph.all_succs(selected)
wenzelm@48595
   105
        val queue1 = new Queue(graph.restrict(graph.all_preds(selected).toSet))
wenzelm@48595
   106
        (descendants, queue1)
wenzelm@48509
   107
      }
wenzelm@48363
   108
wenzelm@48425
   109
      def dequeue(skip: String => Boolean): Option[(String, Info)] =
wenzelm@48425
   110
      {
wenzelm@48425
   111
        val it = graph.entries.dropWhile(
wenzelm@48649
   112
          { case (name, (info, (deps, _))) => !deps.isEmpty || info.isEmpty || skip(name) })
wenzelm@48649
   113
        if (it.hasNext) { val (name, (info, _)) = it.next; Some((name, info.get)) }
wenzelm@48425
   114
        else None
wenzelm@48425
   115
      }
wenzelm@48425
   116
wenzelm@48422
   117
      def topological_order: List[(String, Info)] =
wenzelm@48595
   118
        graph.topological_order.map(name => (name, apply(name)))
wenzelm@48349
   119
    }
wenzelm@48349
   120
  }
wenzelm@48334
   121
wenzelm@48337
   122
wenzelm@48337
   123
  /* parsing */
wenzelm@48337
   124
wenzelm@48337
   125
  private case class Session_Entry(
wenzelm@48544
   126
    base_name: String,
wenzelm@48462
   127
    this_name: Boolean,
wenzelm@48509
   128
    groups: List[String],
wenzelm@48337
   129
    path: Option[String],
wenzelm@48347
   130
    parent: Option[String],
wenzelm@48337
   131
    description: String,
wenzelm@48421
   132
    options: List[Options.Spec],
wenzelm@48421
   133
    theories: List[(List[Options.Spec], List[String])],
wenzelm@48337
   134
    files: List[String])
wenzelm@48337
   135
wenzelm@48334
   136
  private object Parser extends Parse.Parser
wenzelm@48334
   137
  {
wenzelm@48334
   138
    val SESSION = "session"
wenzelm@48334
   139
    val IN = "in"
wenzelm@48334
   140
    val DESCRIPTION = "description"
wenzelm@48334
   141
    val OPTIONS = "options"
wenzelm@48334
   142
    val THEORIES = "theories"
wenzelm@48334
   143
    val FILES = "files"
wenzelm@48334
   144
wenzelm@48334
   145
    val syntax =
wenzelm@48336
   146
      Outer_Syntax.empty + "!" + "(" + ")" + "+" + "," + "=" + "[" + "]" +
wenzelm@48336
   147
        SESSION + IN + DESCRIPTION + OPTIONS + THEORIES + FILES
wenzelm@48334
   148
wenzelm@48337
   149
    val session_entry: Parser[Session_Entry] =
wenzelm@48334
   150
    {
wenzelm@48334
   151
      val session_name = atom("session name", _.is_name)
wenzelm@48280
   152
wenzelm@48334
   153
      val option =
wenzelm@48334
   154
        name ~ opt(keyword("=") ~! name ^^ { case _ ~ x => x }) ^^ { case x ~ y => (x, y) }
wenzelm@48337
   155
      val options = keyword("[") ~> repsep(option, keyword(",")) <~ keyword("]")
wenzelm@48334
   156
wenzelm@48334
   157
      val theories =
wenzelm@48334
   158
        keyword(THEORIES) ~! ((options | success(Nil)) ~ rep1(theory_name)) ^^
wenzelm@48334
   159
          { case _ ~ (x ~ y) => (x, y) }
wenzelm@48334
   160
wenzelm@48334
   161
      ((keyword(SESSION) ~! session_name) ^^ { case _ ~ x => x }) ~
wenzelm@48336
   162
        (keyword("!") ^^^ true | success(false)) ~
wenzelm@48509
   163
        (keyword("(") ~! (rep1(name) <~ keyword(")")) ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48579
   164
        (opt(keyword(IN) ~! path ^^ { case _ ~ x => x })) ~
wenzelm@48347
   165
        (keyword("=") ~> opt(session_name <~ keyword("+"))) ~
wenzelm@48334
   166
        (keyword(DESCRIPTION) ~! text ^^ { case _ ~ x => x } | success("")) ~
wenzelm@48334
   167
        (keyword(OPTIONS) ~! options ^^ { case _ ~ x => x } | success(Nil)) ~
wenzelm@48347
   168
        rep(theories) ~
wenzelm@48336
   169
        (keyword(FILES) ~! rep1(path) ^^ { case _ ~ x => x } | success(Nil)) ^^
wenzelm@48509
   170
          { case a ~ b ~ c ~ d ~ e ~ f ~ g ~ h ~ i => Session_Entry(a, b, c, d, e, f, g, h, i) }
wenzelm@48334
   171
    }
wenzelm@48334
   172
wenzelm@48548
   173
    def parse_entries(root: Path): List[Session_Entry] =
wenzelm@48334
   174
    {
wenzelm@48411
   175
      val toks = syntax.scan(File.read(root))
wenzelm@48548
   176
      parse_all(rep(session_entry), Token.reader(toks, root.implode)) match {
wenzelm@48334
   177
        case Success(result, _) => result
wenzelm@48334
   178
        case bad => error(bad.toString)
wenzelm@48334
   179
      }
wenzelm@48334
   180
    }
wenzelm@48334
   181
  }
wenzelm@48280
   182
wenzelm@48337
   183
wenzelm@48341
   184
  /* find sessions */
wenzelm@48337
   185
wenzelm@48361
   186
  private val ROOT = Path.explode("ROOT")
wenzelm@48361
   187
  private val SESSIONS = Path.explode("etc/sessions")
wenzelm@48361
   188
wenzelm@48364
   189
  private def is_pure(name: String): Boolean = name == "RAW" || name == "Pure"
wenzelm@48364
   190
wenzelm@48650
   191
  private def sessions_root(options: Options, dir: Path, queue: Session.Queue, root: Path)
wenzelm@48421
   192
    : Session.Queue =
wenzelm@48280
   193
  {
wenzelm@48361
   194
    (queue /: Parser.parse_entries(root))((queue1, entry) =>
wenzelm@48337
   195
      try {
wenzelm@48544
   196
        if (entry.base_name == "") error("Bad session name")
wenzelm@48347
   197
wenzelm@48541
   198
        val full_name =
wenzelm@48544
   199
          if (is_pure(entry.base_name)) {
wenzelm@48347
   200
            if (entry.parent.isDefined) error("Illegal parent session")
wenzelm@48544
   201
            else entry.base_name
wenzelm@48347
   202
          }
wenzelm@48347
   203
          else
wenzelm@48347
   204
            entry.parent match {
wenzelm@48649
   205
              case None => error("Missing parent session")
wenzelm@48649
   206
              case Some(parent_name) =>
wenzelm@48649
   207
                if (entry.this_name) entry.base_name
wenzelm@48649
   208
                else parent_name + "-" + entry.base_name
wenzelm@48347
   209
            }
wenzelm@48339
   210
wenzelm@48337
   211
        val path =
wenzelm@48337
   212
          entry.path match {
wenzelm@48337
   213
            case Some(p) => Path.explode(p)
wenzelm@48544
   214
            case None => Path.basic(entry.base_name)
wenzelm@48337
   215
          }
wenzelm@48339
   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@48544
   223
        val entry_digest =
wenzelm@48544
   224
          SHA1.digest((full_name, entry.parent, entry.options, entry.theories).toString)
wenzelm@48423
   225
wenzelm@48418
   226
        val info =
wenzelm@48544
   227
          Session.Info(entry.groups, dir + path, entry.parent, entry.description,
wenzelm@48544
   228
            session_options, theories, files, entry_digest)
wenzelm@48351
   229
wenzelm@48508
   230
        queue1 + (full_name, info)
wenzelm@48337
   231
      }
wenzelm@48337
   232
      catch {
wenzelm@48337
   233
        case ERROR(msg) =>
wenzelm@48337
   234
          error(msg + "\nThe error(s) above occurred in session entry " +
wenzelm@48548
   235
            quote(entry.base_name) + Position.str_of(root.position))
wenzelm@48352
   236
      })
wenzelm@48352
   237
  }
wenzelm@48352
   238
wenzelm@48650
   239
  private def sessions_dir(options: Options, strict: Boolean, queue: Session.Queue, dir: Path)
wenzelm@48421
   240
    : Session.Queue =
wenzelm@48352
   241
  {
wenzelm@48548
   242
    val root = dir + ROOT
wenzelm@48650
   243
    if (root.is_file) sessions_root(options, dir, queue, root)
wenzelm@48548
   244
    else if (strict) error("Bad session root file: " + root.toString)
wenzelm@48361
   245
    else queue
wenzelm@48352
   246
  }
wenzelm@48352
   247
wenzelm@48595
   248
  def find_sessions(options: Options, more_dirs: List[Path]): Session.Queue =
wenzelm@48352
   249
  {
wenzelm@48650
   250
    val queue1 =
wenzelm@48650
   251
      (Session.Queue.empty /: Isabelle_System.components())(sessions_dir(options, false, _, _))
wenzelm@48650
   252
    val queue2 = (queue1 /: more_dirs)(sessions_dir(options, true, _, _))
wenzelm@48650
   253
    queue2
wenzelm@48280
   254
  }
wenzelm@48341
   255
wenzelm@48341
   256
wenzelm@48424
   257
wenzelm@48424
   258
  /** build **/
wenzelm@48424
   259
wenzelm@48478
   260
  private def echo(msg: String) { java.lang.System.out.println(msg) }
wenzelm@48478
   261
  private def sleep(): Unit = Thread.sleep(500)
wenzelm@48478
   262
wenzelm@48478
   263
wenzelm@48504
   264
  /* source dependencies */
wenzelm@48422
   265
wenzelm@48422
   266
  sealed case class Node(
wenzelm@48422
   267
    loaded_theories: Set[String],
wenzelm@48660
   268
    syntax: Outer_Syntax,
wenzelm@48423
   269
    sources: List[(Path, SHA1.Digest)])
wenzelm@48422
   270
wenzelm@48423
   271
  sealed case class Deps(deps: Map[String, Node])
wenzelm@48423
   272
  {
wenzelm@48583
   273
    def is_empty: Boolean = deps.isEmpty
wenzelm@48660
   274
    def apply(name: String): Node = deps(name)
wenzelm@48504
   275
    def sources(name: String): List[SHA1.Digest] = deps(name).sources.map(_._2)
wenzelm@48423
   276
  }
wenzelm@48423
   277
wenzelm@48478
   278
  def dependencies(verbose: Boolean, queue: Session.Queue): Deps =
wenzelm@48423
   279
    Deps((Map.empty[String, Node] /: queue.topological_order)(
wenzelm@48422
   280
      { case (deps, (name, info)) =>
wenzelm@48660
   281
          val (preloaded, parent_syntax) =
wenzelm@48422
   282
            info.parent match {
wenzelm@48660
   283
              case Some(parent) => (deps(parent).loaded_theories, deps(parent).syntax)
wenzelm@48660
   284
              case None =>
wenzelm@48660
   285
                (Set.empty[String],
wenzelm@48660
   286
                  Outer_Syntax.init() +
wenzelm@48660
   287
                    // FIXME avoid hardwired stuff!?
wenzelm@48660
   288
                    ("hence", Keyword.PRF_ASM_GOAL, "then have") +
wenzelm@48660
   289
                    ("thus", Keyword.PRF_ASM_GOAL, "then show"))
wenzelm@48422
   290
            }
wenzelm@48422
   291
          val thy_info = new Thy_Info(new Thy_Load(preloaded))
wenzelm@48422
   292
wenzelm@48583
   293
          if (verbose) {
wenzelm@48583
   294
            val groups =
wenzelm@48583
   295
              if (info.groups.isEmpty) ""
wenzelm@48583
   296
              else info.groups.mkString(" (", " ", ")")
wenzelm@48583
   297
            echo("Checking " + name + groups + " ...")
wenzelm@48583
   298
          }
wenzelm@48478
   299
wenzelm@48422
   300
          val thy_deps =
wenzelm@48422
   301
            thy_info.dependencies(
wenzelm@48422
   302
              info.theories.map(_._2).flatten.
wenzelm@48422
   303
                map(thy => Document.Node.Name(info.dir + Thy_Load.thy_path(thy))))
wenzelm@48422
   304
wenzelm@48422
   305
          val loaded_theories = preloaded ++ thy_deps.map(_._1.theory)
wenzelm@48423
   306
wenzelm@48660
   307
          val keywords = thy_deps.map({ case (_, Exn.Res(h)) => h.keywords case _ => Nil }).flatten
wenzelm@48660
   308
          val syntax = (parent_syntax /: keywords)(_ + _)
wenzelm@48660
   309
wenzelm@48423
   310
          val all_files =
wenzelm@48422
   311
            thy_deps.map({ case (n, h) =>
wenzelm@48422
   312
              val thy = Path.explode(n.node).expand
wenzelm@48422
   313
              val uses =
wenzelm@48422
   314
                h match {
wenzelm@48422
   315
                  case Exn.Res(d) =>
wenzelm@48422
   316
                    d.uses.map(p => (Path.explode(n.dir) + Path.explode(p._1)).expand)
wenzelm@48422
   317
                  case _ => Nil
wenzelm@48422
   318
                }
wenzelm@48422
   319
              thy :: uses
wenzelm@48422
   320
            }).flatten ::: info.files.map(file => info.dir + file)
wenzelm@48485
   321
          val sources =
wenzelm@48485
   322
            try { all_files.map(p => (p, SHA1.digest(p))) }
wenzelm@48485
   323
            catch {
wenzelm@48485
   324
              case ERROR(msg) =>
wenzelm@48485
   325
                error(msg + "\nThe error(s) above occurred in session " + quote(name))
wenzelm@48485
   326
            }
wenzelm@48422
   327
wenzelm@48660
   328
          deps + (name -> Node(loaded_theories, syntax, sources))
wenzelm@48423
   329
      }))
wenzelm@48422
   330
wenzelm@48422
   331
wenzelm@48424
   332
  /* jobs */
wenzelm@48341
   333
wenzelm@48548
   334
  private class Job(dir: Path, env: Map[String, String], script: String, args: String,
wenzelm@48661
   335
    val parent_heap: String, output: Path, do_output: Boolean, time: Time)
wenzelm@48364
   336
  {
wenzelm@48418
   337
    private val args_file = File.tmp_file("args")
wenzelm@48418
   338
    private val env1 = env + ("ARGS_FILE" -> Isabelle_System.posix_path(args_file.getPath))
wenzelm@48418
   339
    File.write(args_file, args)
wenzelm@48418
   340
wenzelm@48424
   341
    private val (thread, result) =
wenzelm@48548
   342
      Simple_Thread.future("build") { Isabelle_System.bash_env(dir.file, env1, script) }
wenzelm@48418
   343
wenzelm@48418
   344
    def terminate: Unit = thread.interrupt
wenzelm@48418
   345
    def is_finished: Boolean = result.is_finished
wenzelm@48661
   346
wenzelm@48661
   347
    @volatile private var timeout = false
wenzelm@48661
   348
    private val timer: Option[Timer] =
wenzelm@48661
   349
      if (time.seconds > 0.0) {
wenzelm@48661
   350
        val t = new Timer("build", true)
wenzelm@48661
   351
        t.schedule(new TimerTask { def run = { terminate; timeout = true } }, time.ms)
wenzelm@48661
   352
        Some(t)
wenzelm@48661
   353
      }
wenzelm@48661
   354
      else None
wenzelm@48661
   355
wenzelm@48661
   356
    def join: (String, String, Int) = {
wenzelm@48661
   357
      val (out, err, rc) = result.join
wenzelm@48661
   358
      args_file.delete
wenzelm@48661
   359
      timer.map(_.cancel())
wenzelm@48661
   360
wenzelm@48661
   361
      val err1 =
wenzelm@48661
   362
        if (rc == 130)
wenzelm@48661
   363
          (if (err.isEmpty || err.endsWith("\n")) err else err + "\n") +
wenzelm@48661
   364
          (if (timeout) "*** Timeout\n" else "*** Interrupt\n")
wenzelm@48661
   365
        else err
wenzelm@48661
   366
      (out, err1, rc)
wenzelm@48661
   367
    }
wenzelm@48661
   368
wenzelm@48511
   369
    def output_path: Option[Path] = if (do_output) Some(output) else None
wenzelm@48418
   370
  }
wenzelm@48418
   371
wenzelm@48639
   372
  private def start_job(name: String, info: Session.Info, parent_heap: String,
wenzelm@48639
   373
    output: Path, do_output: Boolean, options: Options, verbose: Boolean, browser_info: Path): Job =
wenzelm@48418
   374
  {
wenzelm@48467
   375
    // global browser info dir
wenzelm@48548
   376
    if (options.bool("browser_info") && !(browser_info + Path.explode("index.html")).is_file)
wenzelm@48467
   377
    {
wenzelm@48467
   378
      browser_info.file.mkdirs()
wenzelm@48467
   379
      File.copy(Path.explode("~~/lib/logo/isabelle.gif"),
wenzelm@48467
   380
        browser_info + Path.explode("isabelle.gif"))
wenzelm@48467
   381
      File.write(browser_info + Path.explode("index.html"),
wenzelm@48467
   382
        File.read(Path.explode("~~/lib/html/library_index_header.template")) +
wenzelm@48467
   383
        File.read(Path.explode("~~/lib/html/library_index_content.template")) +
wenzelm@48467
   384
        File.read(Path.explode("~~/lib/html/library_index_footer.template")))
wenzelm@48467
   385
    }
wenzelm@48467
   386
wenzelm@48418
   387
    val parent = info.parent.getOrElse("")
wenzelm@48418
   388
wenzelm@48511
   389
    val env =
wenzelm@48511
   390
      Map("INPUT" -> parent, "TARGET" -> name, "OUTPUT" -> Isabelle_System.standard_path(output))
wenzelm@48364
   391
    val script =
wenzelm@48511
   392
      if (is_pure(name)) {
wenzelm@48511
   393
        if (do_output) "./build " + name + " \"$OUTPUT\""
wenzelm@48511
   394
        else """ rm -f "$OUTPUT"; ./build """ + name
wenzelm@48511
   395
      }
wenzelm@48418
   396
      else {
wenzelm@48418
   397
        """
wenzelm@48418
   398
        . "$ISABELLE_HOME/lib/scripts/timestart.bash"
wenzelm@48418
   399
        """ +
wenzelm@48511
   400
          (if (do_output)
wenzelm@48511
   401
            """
wenzelm@48511
   402
            "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -q -w "$INPUT" "$OUTPUT"
wenzelm@48511
   403
            """
wenzelm@48418
   404
          else
wenzelm@48511
   405
            """
wenzelm@48511
   406
            rm -f "$OUTPUT"; "$ISABELLE_PROCESS" -e "Build.build \"$ARGS_FILE\";" -r -q "$INPUT"
wenzelm@48511
   407
            """) +
wenzelm@48418
   408
        """
wenzelm@48418
   409
        RC="$?"
wenzelm@48418
   410
wenzelm@48418
   411
        . "$ISABELLE_HOME/lib/scripts/timestop.bash"
wenzelm@48418
   412
wenzelm@48418
   413
        if [ "$RC" -eq 0 ]; then
wenzelm@48418
   414
          echo "Finished $TARGET ($TIMES_REPORT)" >&2
wenzelm@48418
   415
        fi
wenzelm@48418
   416
wenzelm@48418
   417
        exit "$RC"
wenzelm@48418
   418
        """
wenzelm@48418
   419
      }
wenzelm@48418
   420
    val args_xml =
wenzelm@48418
   421
    {
wenzelm@48418
   422
      import XML.Encode._
wenzelm@48545
   423
          pair(bool, pair(Options.encode, pair(bool, pair(Path.encode, pair(string,
wenzelm@48545
   424
            pair(string, list(pair(Options.encode, list(Path.encode)))))))))(
wenzelm@48545
   425
          (do_output, (options, (verbose, (browser_info, (parent,
wenzelm@48545
   426
            (name, info.theories)))))))
wenzelm@48418
   427
    }
wenzelm@48661
   428
    new Job(info.dir, env, script, YXML.string_of_body(args_xml), parent_heap,
wenzelm@48661
   429
      output, do_output, Time.seconds(options.real("timeout")))
wenzelm@48364
   430
  }
wenzelm@48364
   431
wenzelm@48424
   432
wenzelm@48504
   433
  /* log files and corresponding heaps */
wenzelm@48504
   434
wenzelm@48505
   435
  private val LOG = Path.explode("log")
wenzelm@48505
   436
  private def log(name: String): Path = LOG + Path.basic(name)
wenzelm@48505
   437
  private def log_gz(name: String): Path = log(name).ext("gz")
wenzelm@48504
   438
wenzelm@48505
   439
  private def sources_stamp(digests: List[SHA1.Digest]): String =
wenzelm@48504
   440
    digests.map(_.toString).sorted.mkString("sources: ", " ", "")
wenzelm@48504
   441
wenzelm@48639
   442
  private val no_heap: String = "heap: -"
wenzelm@48639
   443
wenzelm@48639
   444
  private def heap_stamp(heap: Option[Path]): String =
wenzelm@48504
   445
  {
wenzelm@48504
   446
    "heap: " +
wenzelm@48639
   447
      (heap match {
wenzelm@48504
   448
        case Some(path) =>
wenzelm@48504
   449
          val file = path.file
wenzelm@48504
   450
          if (file.isFile) file.length.toString + " " + file.lastModified.toString
wenzelm@48504
   451
          else "-"
wenzelm@48504
   452
        case None => "-"
wenzelm@48504
   453
      })
wenzelm@48504
   454
  }
wenzelm@48504
   455
wenzelm@48639
   456
  private def read_stamps(path: Path): Option[(String, String, String)] =
wenzelm@48639
   457
    if (path.is_file) {
wenzelm@48639
   458
      val stream = new GZIPInputStream (new BufferedInputStream(new FileInputStream(path.file)))
wenzelm@48504
   459
      val reader = new BufferedReader(new InputStreamReader(stream, Standard_System.charset))
wenzelm@48639
   460
      val (s, h1, h2) =
wenzelm@48639
   461
        try { (reader.readLine, reader.readLine, reader.readLine) }
wenzelm@48639
   462
        finally { reader.close }
wenzelm@48639
   463
      if (s != null && s.startsWith("sources: ") &&
wenzelm@48639
   464
          h1 != null && h1.startsWith("heap: ") &&
wenzelm@48639
   465
          h2 != null && h2.startsWith("heap: ")) Some((s, h1, h2))
wenzelm@48504
   466
      else None
wenzelm@48504
   467
    }
wenzelm@48504
   468
    else None
wenzelm@48504
   469
wenzelm@48504
   470
wenzelm@48425
   471
  /* build */
wenzelm@48424
   472
wenzelm@48509
   473
  def build(
wenzelm@48509
   474
    all_sessions: Boolean = false,
wenzelm@48511
   475
    build_heap: Boolean = false,
wenzelm@48595
   476
    clean_build: Boolean = false,
wenzelm@48509
   477
    more_dirs: List[Path] = Nil,
wenzelm@48509
   478
    session_groups: List[String] = Nil,
wenzelm@48509
   479
    max_jobs: Int = 1,
wenzelm@48509
   480
    no_build: Boolean = false,
wenzelm@48509
   481
    build_options: List[String] = Nil,
wenzelm@48509
   482
    system_mode: Boolean = false,
wenzelm@48509
   483
    verbose: Boolean = false,
wenzelm@48509
   484
    sessions: List[String] = Nil): Int =
wenzelm@48341
   485
  {
wenzelm@48509
   486
    val options = (Options.init() /: build_options)(_.define_simple(_))
wenzelm@48595
   487
    val (descendants, queue) =
wenzelm@48595
   488
      find_sessions(options, more_dirs).required(all_sessions, session_groups, sessions)
wenzelm@48478
   489
    val deps = dependencies(verbose, queue)
wenzelm@48368
   490
wenzelm@48504
   491
    def make_stamp(name: String): String =
wenzelm@48544
   492
      sources_stamp(queue(name).entry_digest :: deps.sources(name))
wenzelm@48504
   493
wenzelm@48504
   494
    val (input_dirs, output_dir, browser_info) =
wenzelm@48504
   495
      if (system_mode) {
wenzelm@48504
   496
        val output_dir = Path.explode("~~/heaps/$ML_IDENTIFIER")
wenzelm@48504
   497
        (List(output_dir), output_dir, Path.explode("~~/browser_info"))
wenzelm@48504
   498
      }
wenzelm@48504
   499
      else {
wenzelm@48504
   500
        val output_dir = Path.explode("$ISABELLE_OUTPUT")
wenzelm@48504
   501
        (output_dir :: Isabelle_System.find_logics_dirs(), output_dir,
wenzelm@48504
   502
         Path.explode("$ISABELLE_BROWSER_INFO"))
wenzelm@48504
   503
      }
wenzelm@48363
   504
wenzelm@48373
   505
    // prepare log dir
wenzelm@48504
   506
    (output_dir + LOG).file.mkdirs()
wenzelm@48373
   507
wenzelm@48595
   508
    // optional cleanup
wenzelm@48595
   509
    if (clean_build) {
wenzelm@48595
   510
      for (name <- descendants) {
wenzelm@48595
   511
        val files =
wenzelm@48595
   512
          List(Path.basic(name), log(name), log_gz(name)).map(output_dir + _).filter(_.is_file)
wenzelm@48595
   513
        if (!files.isEmpty) echo("Cleaning " + name + " ...")
wenzelm@48595
   514
        if (!files.forall(p => p.file.delete)) echo(name + " FAILED to delete")
wenzelm@48595
   515
      }
wenzelm@48595
   516
    }
wenzelm@48595
   517
wenzelm@48425
   518
    // scheduler loop
wenzelm@48639
   519
    case class Result(current: Boolean, heap: String, rc: Int)
wenzelm@48639
   520
wenzelm@48425
   521
    @tailrec def loop(
wenzelm@48425
   522
      pending: Session.Queue,
wenzelm@48425
   523
      running: Map[String, Job],
wenzelm@48639
   524
      results: Map[String, Result]): Map[String, Result] =
wenzelm@48425
   525
    {
wenzelm@48425
   526
      if (pending.is_empty) results
wenzelm@48547
   527
      else
wenzelm@48547
   528
        running.find({ case (_, job) => job.is_finished }) match {
wenzelm@48547
   529
          case Some((name, job)) =>
wenzelm@48547
   530
            // finish job
wenzelm@48424
   531
wenzelm@48547
   532
            val (out, err, rc) = job.join
wenzelm@48547
   533
            echo(Library.trim_line(err))
wenzelm@48373
   534
wenzelm@48639
   535
            val heap =
wenzelm@48639
   536
              if (rc == 0) {
wenzelm@48639
   537
                (output_dir + log(name)).file.delete
wenzelm@48639
   538
wenzelm@48639
   539
                val sources = make_stamp(name)
wenzelm@48639
   540
                val heap = heap_stamp(job.output_path)
wenzelm@48639
   541
                File.write_gzip(output_dir + log_gz(name),
wenzelm@48639
   542
                  sources + "\n" + job.parent_heap + "\n" + heap + "\n" + out)
wenzelm@48639
   543
wenzelm@48639
   544
                heap
wenzelm@48639
   545
              }
wenzelm@48639
   546
              else {
wenzelm@48639
   547
                (output_dir + Path.basic(name)).file.delete
wenzelm@48639
   548
                (output_dir + log_gz(name)).file.delete
wenzelm@48639
   549
wenzelm@48639
   550
                File.write(output_dir + log(name), out)
wenzelm@48639
   551
                echo(name + " FAILED")
wenzelm@48661
   552
                if (rc != 130) {
wenzelm@48661
   553
                  echo("(see also " + (output_dir + log(name)).file.toString + ")")
wenzelm@48661
   554
                  val lines = split_lines(out)
wenzelm@48661
   555
                  val tail = lines.drop(lines.length - 20 max 0)
wenzelm@48661
   556
                  echo("\n" + cat_lines(tail))
wenzelm@48661
   557
                }
wenzelm@48639
   558
wenzelm@48639
   559
                no_heap
wenzelm@48639
   560
              }
wenzelm@48639
   561
            loop(pending - name, running - name, results + (name -> Result(false, heap, rc)))
wenzelm@48528
   562
wenzelm@48547
   563
          case None if (running.size < (max_jobs max 1)) =>
wenzelm@48547
   564
            // check/start next job
wenzelm@48547
   565
            pending.dequeue(running.isDefinedAt(_)) match {
wenzelm@48547
   566
              case Some((name, info)) =>
wenzelm@48639
   567
                val parent_result =
wenzelm@48639
   568
                  info.parent match {
wenzelm@48639
   569
                    case None => Result(true, no_heap, 0)
wenzelm@48639
   570
                    case Some(parent) => results(parent)
wenzelm@48639
   571
                  }
wenzelm@48547
   572
                val output = output_dir + Path.basic(name)
wenzelm@48547
   573
                val do_output = build_heap || queue.is_inner(name)
wenzelm@48547
   574
wenzelm@48639
   575
                val (current, heap) =
wenzelm@48547
   576
                {
wenzelm@48548
   577
                  input_dirs.find(dir => (dir + log_gz(name)).is_file) match {
wenzelm@48547
   578
                    case Some(dir) =>
wenzelm@48639
   579
                      read_stamps(dir + log_gz(name)) match {
wenzelm@48639
   580
                        case Some((s, h1, h2)) =>
wenzelm@48639
   581
                          val heap = heap_stamp(Some(dir + Path.basic(name)))
wenzelm@48639
   582
                          (s == make_stamp(name) && h1 == parent_result.heap && h2 == heap &&
wenzelm@48639
   583
                            !(do_output && heap == no_heap), heap)
wenzelm@48639
   584
                        case None => (false, no_heap)
wenzelm@48547
   585
                      }
wenzelm@48639
   586
                    case None => (false, no_heap)
wenzelm@48504
   587
                  }
wenzelm@48547
   588
                }
wenzelm@48639
   589
                val all_current = current && parent_result.current
wenzelm@48528
   590
wenzelm@48547
   591
                if (all_current)
wenzelm@48639
   592
                  loop(pending - name, running, results + (name -> Result(true, heap, 0)))
wenzelm@48547
   593
                else if (no_build)
wenzelm@48639
   594
                  loop(pending - name, running, results + (name -> Result(false, heap, 1)))
wenzelm@48639
   595
                else if (parent_result.rc == 0) {
wenzelm@48547
   596
                  echo((if (do_output) "Building " else "Running ") + name + " ...")
wenzelm@48547
   597
                  val job =
wenzelm@48639
   598
                    start_job(name, info, parent_result.heap, output, do_output,
wenzelm@48639
   599
                      info.options, verbose, browser_info)
wenzelm@48547
   600
                  loop(pending, running + (name -> job), results)
wenzelm@48547
   601
                }
wenzelm@48547
   602
                else {
wenzelm@48547
   603
                  echo(name + " CANCELLED")
wenzelm@48639
   604
                  loop(pending - name, running, results + (name -> Result(false, heap, 1)))
wenzelm@48547
   605
                }
wenzelm@48547
   606
              case None => sleep(); loop(pending, running, results)
wenzelm@48425
   607
            }
wenzelm@48425
   608
          case None => sleep(); loop(pending, running, results)
wenzelm@48373
   609
        }
wenzelm@48425
   610
    }
wenzelm@48425
   611
wenzelm@48583
   612
    val results =
wenzelm@48583
   613
      if (deps.is_empty) {
wenzelm@48583
   614
        echo("### Nothing to build")
wenzelm@48583
   615
        Map.empty
wenzelm@48583
   616
      }
wenzelm@48583
   617
      else loop(queue, Map.empty, Map.empty)
wenzelm@48583
   618
wenzelm@48639
   619
    val rc = (0 /: results)({ case (rc1, (_, res)) => rc1 max res.rc })
wenzelm@48504
   620
    if (rc != 0 && (verbose || !no_build)) {
wenzelm@48552
   621
      val unfinished =
wenzelm@48639
   622
        (for ((name, res) <- results.iterator if res.rc != 0) yield name).toList.sorted
wenzelm@48473
   623
      echo("Unfinished session(s): " + commas(unfinished))
wenzelm@48473
   624
    }
wenzelm@48473
   625
    rc
wenzelm@48341
   626
  }
wenzelm@48341
   627
wenzelm@48341
   628
wenzelm@48346
   629
  /* command line entry point */
wenzelm@48341
   630
wenzelm@48341
   631
  def main(args: Array[String])
wenzelm@48341
   632
  {
wenzelm@48346
   633
    Command_Line.tool {
wenzelm@48346
   634
      args.toList match {
wenzelm@48346
   635
        case
wenzelm@48346
   636
          Properties.Value.Boolean(all_sessions) ::
wenzelm@48511
   637
          Properties.Value.Boolean(build_heap) ::
wenzelm@48595
   638
          Properties.Value.Boolean(clean_build) ::
wenzelm@48425
   639
          Properties.Value.Int(max_jobs) ::
wenzelm@48469
   640
          Properties.Value.Boolean(no_build) ::
wenzelm@48447
   641
          Properties.Value.Boolean(system_mode) ::
wenzelm@48425
   642
          Properties.Value.Boolean(verbose) ::
wenzelm@48509
   643
          Command_Line.Chunks(more_dirs, session_groups, build_options, sessions) =>
wenzelm@48595
   644
            build(all_sessions, build_heap, clean_build, more_dirs.map(Path.explode),
wenzelm@48595
   645
              session_groups, max_jobs, no_build, build_options, system_mode, verbose, sessions)
wenzelm@48346
   646
        case _ => error("Bad arguments:\n" + cat_lines(args))
wenzelm@48341
   647
      }
wenzelm@48346
   648
    }
wenzelm@48341
   649
  }
wenzelm@48660
   650
wenzelm@48660
   651
wenzelm@48660
   652
  /* static outer syntax */
wenzelm@48660
   653
wenzelm@48660
   654
  // FIXME Symbol.decode!?
wenzelm@48660
   655
  def outer_syntax(session: String): Outer_Syntax =
wenzelm@48660
   656
  {
wenzelm@48660
   657
    val (_, queue) = find_sessions(Options.init(), Nil).required(false, Nil, List(session))
wenzelm@48660
   658
    dependencies(false, queue)(session).syntax
wenzelm@48660
   659
  }
wenzelm@48276
   660
}
wenzelm@48276
   661