src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Mon May 01 22:45:39 2017 +0200 (2017-05-01)
changeset 65674 23897f5d885d
parent 65670 490649872acc
child 65675 f93ae9861d09
permissions -rw-r--r--
approximate repository identify job based on isabelle-nightly-slow;
more Jenkins changeset patterns found in the wild;
wenzelm@64148
     1
/*  Title:      Pure/Admin/isabelle_cronjob.scala
wenzelm@64148
     2
    Author:     Makarius
wenzelm@64148
     3
wenzelm@64148
     4
Main entry point for administrative cronjob at TUM.
wenzelm@64148
     5
*/
wenzelm@64148
     6
wenzelm@64148
     7
package isabelle
wenzelm@64148
     8
wenzelm@64148
     9
wenzelm@64170
    10
import scala.annotation.tailrec
wenzelm@64170
    11
import scala.collection.mutable
wenzelm@64170
    12
wenzelm@64170
    13
wenzelm@64148
    14
object Isabelle_Cronjob
wenzelm@64148
    15
{
wenzelm@64194
    16
  /* file-system state: owned by main cronjob */
wenzelm@64153
    17
wenzelm@64153
    18
  val main_dir = Path.explode("~/cronjob")
wenzelm@64194
    19
  val main_state_file = main_dir + Path.explode("run/main.state")
wenzelm@64219
    20
  val current_log = main_dir + Path.explode("run/main.log")  // owned by log service
wenzelm@64219
    21
  val cumulative_log = main_dir + Path.explode("log/main.log")  // owned by log service
wenzelm@64153
    22
wenzelm@64231
    23
  val isabelle_repos = main_dir + Path.explode("isabelle")
wenzelm@64231
    24
  val isabelle_repos_test = main_dir + Path.explode("isabelle-test")
wenzelm@64231
    25
  val afp_repos = main_dir + Path.explode("AFP")
wenzelm@64153
    26
wenzelm@64236
    27
  val isabelle_dev_source = "http://isabelle.in.tum.de/repos/isabelle"
wenzelm@64236
    28
  val isabelle_release_source = "http://bitbucket.org/isabelle_project/isabelle-release"
wenzelm@64236
    29
  val afp_source = "https://bitbucket.org/isa-afp/afp-devel"
wenzelm@64236
    30
wenzelm@64218
    31
  val release_snapshot = Path.explode("~/html-data/release_snapshot")
wenzelm@64215
    32
wenzelm@65666
    33
  val jenkins_jobs = List("isabelle-nightly-benchmark")
wenzelm@65666
    34
wenzelm@65647
    35
  val build_log_snapshot = Path.explode("~/html-data/build_log.db")
wenzelm@65647
    36
wenzelm@64153
    37
wenzelm@64192
    38
wenzelm@64192
    39
  /** particular tasks **/
wenzelm@64192
    40
wenzelm@64405
    41
  /* identify Isabelle + AFP repository snapshots and build release */
wenzelm@64192
    42
wenzelm@64405
    43
  private val build_release =
wenzelm@64405
    44
    Logger_Task("build_release", logger =>
wenzelm@64405
    45
      Isabelle_System.with_tmp_dir("isadist")(base_dir =>
wenzelm@64405
    46
        {
wenzelm@64405
    47
          val rev = Mercurial.repository(isabelle_repos).id()
wenzelm@64405
    48
          val afp_rev = Mercurial.setup_repository(afp_source, afp_repos).id()
wenzelm@64192
    49
wenzelm@64405
    50
          File.write(logger.log_dir + Build_Log.log_filename("isabelle_identify", logger.start_date),
wenzelm@65674
    51
            Build_Log.Identify.content(logger.start_date, Some(rev), Some(afp_rev)))
wenzelm@64405
    52
wenzelm@64405
    53
          val new_snapshot = release_snapshot.ext("new")
wenzelm@64405
    54
          val old_snapshot = release_snapshot.ext("old")
wenzelm@64405
    55
wenzelm@64405
    56
          Isabelle_System.rm_tree(new_snapshot)
wenzelm@64405
    57
          Isabelle_System.rm_tree(old_snapshot)
wenzelm@64405
    58
wenzelm@64405
    59
          Build_Release.build_release(base_dir, rev = rev, afp_rev = afp_rev,
wenzelm@64405
    60
            parallel_jobs = 4, remote_mac = "macbroy31", website = Some(new_snapshot))
wenzelm@64405
    61
wenzelm@64482
    62
          if (release_snapshot.is_dir) File.move(release_snapshot, old_snapshot)
wenzelm@64482
    63
          File.move(new_snapshot, release_snapshot)
wenzelm@64405
    64
          Isabelle_System.rm_tree(old_snapshot)
wenzelm@64405
    65
        }))
wenzelm@64192
    66
wenzelm@64192
    67
wenzelm@64194
    68
  /* integrity test of build_history vs. build_history_base */
wenzelm@64193
    69
wenzelm@64194
    70
  private val build_history_base =
wenzelm@64193
    71
    Logger_Task("build_history_base", logger =>
wenzelm@64193
    72
      {
wenzelm@64251
    73
        val hg =
wenzelm@64251
    74
          Mercurial.setup_repository(
wenzelm@64251
    75
            File.standard_path(isabelle_repos), isabelle_repos_test)
wenzelm@64194
    76
        for {
wenzelm@64194
    77
          (result, log_path) <-
wenzelm@64251
    78
            Build_History.build_history(
wenzelm@64251
    79
              hg, rev = "build_history_base", fresh = true, build_args = List("HOL"))
wenzelm@64194
    80
        } {
wenzelm@64194
    81
          result.check
wenzelm@64482
    82
          File.move(log_path, logger.log_dir + log_path.base)
wenzelm@64194
    83
        }
wenzelm@64193
    84
      })
wenzelm@64193
    85
wenzelm@64193
    86
wenzelm@64231
    87
  /* remote build_history */
wenzelm@64231
    88
wenzelm@64409
    89
  sealed case class Remote_Build(
wenzelm@64231
    90
    host: String,
wenzelm@64231
    91
    user: String = "",
wenzelm@65594
    92
    port: Int = 0,
wenzelm@64294
    93
    shared_home: Boolean = true,
wenzelm@64231
    94
    options: String = "",
wenzelm@64351
    95
    args: String = "")
wenzelm@64231
    96
wenzelm@64231
    97
  private val remote_builds =
wenzelm@64231
    98
    List(
wenzelm@65063
    99
      List(Remote_Build("lxbroy8",
wenzelm@65063
   100
        options = "-m32 -B -M1x2,2 -t polyml-test -e 'init_component /home/isabelle/contrib/polyml-5.7-20170217'",
wenzelm@65063
   101
        args = "-N -g timing")),
wenzelm@64506
   102
      List(Remote_Build("lxbroy9", options = "-m32 -B -M1x2,2", args = "-N -g timing")),
wenzelm@64476
   103
      List(Remote_Build("lxbroy10", options = "-m32 -B -M1x4,2,4,6", args = "-N -g timing")),
wenzelm@64351
   104
      List(
wenzelm@64351
   105
        Remote_Build("macbroy2", options = "-m32 -M8", args = "-a"),
wenzelm@64351
   106
        Remote_Build("macbroy2", options = "-m32 -M8 -t quick_and_dirty", args = "-a -o quick_and_dirty"),
wenzelm@64351
   107
        Remote_Build("macbroy2", options = "-m32 -M8 -t skip_proofs", args = "-a -o skip_proofs")),
wenzelm@64351
   108
      List(Remote_Build("macbroy30", options = "-m32 -M2", args = "-a")),
wenzelm@64351
   109
      List(Remote_Build("macbroy31", options = "-m32 -M2", args = "-a")),
wenzelm@64351
   110
      List(
wenzelm@64351
   111
        Remote_Build("vmnipkow9", shared_home = false, options = "-m32 -M4", args = "-a"),
wenzelm@64351
   112
        Remote_Build("vmnipkow9", shared_home = false, options = "-m64 -M4", args = "-a")))
wenzelm@64231
   113
wenzelm@64231
   114
  private def remote_build_history(rev: String, r: Remote_Build): Logger_Task =
wenzelm@64294
   115
  {
wenzelm@64294
   116
    val task_name = "build_history-" + r.host
wenzelm@64294
   117
    Logger_Task(task_name, logger =>
wenzelm@64231
   118
      {
wenzelm@64231
   119
        using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
wenzelm@64259
   120
          ssh =>
wenzelm@64231
   121
            {
wenzelm@64348
   122
              val self_update = !r.shared_home
wenzelm@64348
   123
              val push_isabelle_home = self_update && Mercurial.is_repository(Path.explode("~~"))
wenzelm@64348
   124
wenzelm@64468
   125
              val (results, _) =
wenzelm@64468
   126
                Build_History.remote_build_history(ssh,
wenzelm@64468
   127
                  isabelle_repos,
wenzelm@64468
   128
                  isabelle_repos.ext(r.host),
wenzelm@64538
   129
                  isabelle_repos_source = isabelle_dev_source,
wenzelm@64468
   130
                  self_update = self_update,
wenzelm@64468
   131
                  push_isabelle_home = push_isabelle_home,
wenzelm@64468
   132
                  options =
wenzelm@64479
   133
                    "-r " + Bash.string(rev) + " -N " + Bash.string(task_name) + " -f " + r.options,
wenzelm@64468
   134
                  args = "-o timeout=10800 " + r.args)
wenzelm@64346
   135
wenzelm@64481
   136
              for ((log_name, bytes) <- results) {
wenzelm@64481
   137
                logger.log(Date.now(), log_name)
wenzelm@64468
   138
                Bytes.write(logger.log_dir + Path.explode(log_name), bytes)
wenzelm@64481
   139
              }
wenzelm@64231
   140
            })
wenzelm@64231
   141
      })
wenzelm@64294
   142
  }
wenzelm@64231
   143
wenzelm@64231
   144
wenzelm@65640
   145
  /* maintain build_log database */
wenzelm@65640
   146
wenzelm@65640
   147
  val database_dirs =
wenzelm@65640
   148
    List(Path.explode("~/log"), Path.explode("~/afp/log"), Path.explode("~/cronjob/log"))
wenzelm@65640
   149
wenzelm@65640
   150
  def database_update(options: Options)
wenzelm@65640
   151
  {
wenzelm@65640
   152
    val store = Build_Log.store(options)
wenzelm@65647
   153
    val files = Build_Log.Log_File.find_files(database_dirs)
wenzelm@65670
   154
wenzelm@65670
   155
    // PostgreSQL server
wenzelm@65670
   156
    using(store.open_database())(db =>
wenzelm@65670
   157
      {
wenzelm@65670
   158
        store.write_info(db, files, ml_statistics = true)
wenzelm@65670
   159
        Build_Log.create_full_view(db)
wenzelm@65670
   160
      })
wenzelm@65670
   161
wenzelm@65670
   162
    // SQLite file
wenzelm@65667
   163
    using(SQLite.open_database(build_log_snapshot))(db =>
wenzelm@65667
   164
      {
wenzelm@65667
   165
        store.write_info(db, files)
wenzelm@65667
   166
        db.rebuild
wenzelm@65667
   167
      })
wenzelm@65640
   168
  }
wenzelm@65640
   169
wenzelm@65640
   170
wenzelm@64192
   171
wenzelm@64192
   172
  /** task logging **/
wenzelm@64171
   173
wenzelm@64193
   174
  sealed case class Logger_Task(name: String = "", body: Logger => Unit)
wenzelm@64154
   175
wenzelm@64257
   176
  class Log_Service private[Isabelle_Cronjob](progress: Progress, val ssh_context: SSH.Context)
wenzelm@64171
   177
  {
wenzelm@64219
   178
    current_log.file.delete
wenzelm@64219
   179
wenzelm@64171
   180
    private val thread: Consumer_Thread[String] =
wenzelm@64171
   181
      Consumer_Thread.fork("cronjob: logger", daemon = true)(
wenzelm@64171
   182
        consume = (text: String) =>
wenzelm@64219
   183
          { // critical
wenzelm@64219
   184
            File.append(current_log, text + "\n")
wenzelm@64219
   185
            File.append(cumulative_log, text + "\n")
wenzelm@64171
   186
            progress.echo(text)
wenzelm@64171
   187
            true
wenzelm@64171
   188
          })
wenzelm@64171
   189
wenzelm@64171
   190
    def shutdown() { thread.shutdown() }
wenzelm@64171
   191
wenzelm@64171
   192
    val hostname = Isabelle_System.hostname()
wenzelm@64171
   193
wenzelm@64171
   194
    def log(date: Date, task_name: String, msg: String): Unit =
wenzelm@64193
   195
      if (task_name != "")
wenzelm@64193
   196
        thread.send(
wenzelm@64193
   197
          "[" + Build_Log.print_date(date) + ", " + hostname + ", " + task_name + "]: " + msg)
wenzelm@64171
   198
wenzelm@64171
   199
    def start_logger(start_date: Date, task_name: String): Logger =
wenzelm@64171
   200
      new Logger(this, start_date, task_name)
wenzelm@64154
   201
wenzelm@64171
   202
    def run_task(start_date: Date, task: Logger_Task)
wenzelm@64171
   203
    {
wenzelm@64171
   204
      val logger = start_logger(start_date, task.name)
wenzelm@64171
   205
      val res = Exn.capture { task.body(logger) }
wenzelm@64171
   206
      val end_date = Date.now()
wenzelm@64171
   207
      val err =
wenzelm@64171
   208
        res match {
wenzelm@64171
   209
          case Exn.Res(_) => None
wenzelm@64295
   210
          case Exn.Exn(exn) =>
wenzelm@64410
   211
            System.err.println("Exception trace for " + quote(task.name) + ":")
wenzelm@64397
   212
            exn.printStackTrace()
wenzelm@64295
   213
            val first_line = Library.split_lines(Exn.message(exn)).headOption getOrElse "exception"
wenzelm@64295
   214
            Some(first_line)
wenzelm@64171
   215
        }
wenzelm@64171
   216
      logger.log_end(end_date, err)
wenzelm@64171
   217
    }
wenzelm@64171
   218
wenzelm@64171
   219
    def fork_task(start_date: Date, task: Logger_Task): Task =
wenzelm@64171
   220
      new Task(task.name, run_task(start_date, task))
wenzelm@64171
   221
  }
wenzelm@64171
   222
wenzelm@64171
   223
  class Logger private[Isabelle_Cronjob](
wenzelm@64171
   224
    val log_service: Log_Service, val start_date: Date, val task_name: String)
wenzelm@64162
   225
  {
wenzelm@64257
   226
    def ssh_context: SSH.Context = log_service.ssh_context
wenzelm@65640
   227
    def options: Options = ssh_context.options
wenzelm@64231
   228
wenzelm@64171
   229
    def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
wenzelm@64171
   230
wenzelm@64171
   231
    def log_end(end_date: Date, err: Option[String])
wenzelm@64171
   232
    {
wenzelm@64171
   233
      val elapsed_time = end_date.time - start_date.time
wenzelm@64171
   234
      val msg =
wenzelm@64171
   235
        (if (err.isEmpty) "finished" else "ERROR " + err.get) +
wenzelm@64197
   236
        (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
wenzelm@64171
   237
      log(end_date, msg)
wenzelm@64171
   238
    }
wenzelm@64171
   239
wenzelm@64195
   240
    val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
wenzelm@64195
   241
wenzelm@64195
   242
    Isabelle_System.mkdirs(log_dir)
wenzelm@64171
   243
    log(start_date, "started")
wenzelm@64171
   244
  }
wenzelm@64171
   245
wenzelm@64171
   246
  class Task private[Isabelle_Cronjob](name: String, body: => Unit)
wenzelm@64171
   247
  {
wenzelm@64171
   248
    private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
wenzelm@64171
   249
    def is_finished: Boolean = future.is_finished
wenzelm@64162
   250
  }
wenzelm@64153
   251
wenzelm@64170
   252
wenzelm@64170
   253
wenzelm@64153
   254
  /** cronjob **/
wenzelm@64153
   255
wenzelm@64187
   256
  def cronjob(progress: Progress, exclude_task: Set[String])
wenzelm@64153
   257
  {
wenzelm@64171
   258
    /* soft lock */
wenzelm@64153
   259
wenzelm@64153
   260
    val still_running =
wenzelm@64153
   261
      try { Some(File.read(main_state_file)) }
wenzelm@64153
   262
      catch { case ERROR(_) => None }
wenzelm@64153
   263
wenzelm@64153
   264
    still_running match {
wenzelm@64170
   265
      case None | Some("") =>
wenzelm@64153
   266
      case Some(running) =>
wenzelm@64153
   267
        error("Isabelle cronjob appears to be still running: " + running)
wenzelm@64153
   268
    }
wenzelm@64153
   269
wenzelm@64199
   270
wenzelm@64199
   271
    /* log service */
wenzelm@64199
   272
wenzelm@64257
   273
    val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
wenzelm@64154
   274
wenzelm@64199
   275
    def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
wenzelm@64199
   276
wenzelm@64199
   277
    def run_now(task: Logger_Task) { run(Date.now(), task) }
wenzelm@64154
   278
wenzelm@64154
   279
wenzelm@64199
   280
    /* structured tasks */
wenzelm@64184
   281
wenzelm@64350
   282
    def SEQ(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
wenzelm@64193
   283
      for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
wenzelm@64199
   284
        run_now(task))
wenzelm@64153
   285
wenzelm@64350
   286
    def PAR(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
wenzelm@64170
   287
      {
wenzelm@64199
   288
        @tailrec def join(running: List[Task])
wenzelm@64199
   289
        {
wenzelm@64199
   290
          running.partition(_.is_finished) match {
wenzelm@64199
   291
            case (Nil, Nil) =>
wenzelm@64199
   292
            case (Nil, _ :: _) => Thread.sleep(500); join(running)
wenzelm@64199
   293
            case (_ :: _, remaining) => join(remaining)
wenzelm@64199
   294
          }
wenzelm@64170
   295
        }
wenzelm@64199
   296
        val start_date = Date.now()
wenzelm@64199
   297
        val running =
wenzelm@64350
   298
          for (task <- tasks if !exclude_task(task.name))
wenzelm@64199
   299
            yield log_service.fork_task(start_date, task)
wenzelm@64199
   300
        join(running)
wenzelm@64199
   301
      })
wenzelm@64193
   302
wenzelm@64170
   303
wenzelm@64170
   304
    /* main */
wenzelm@64170
   305
wenzelm@64199
   306
    val main_start_date = Date.now()
wenzelm@64199
   307
    File.write(main_state_file, main_start_date + " " + log_service.hostname)
wenzelm@64199
   308
wenzelm@64232
   309
    val rev = Mercurial.repository(isabelle_repos).id()
wenzelm@64231
   310
wenzelm@64193
   311
    run(main_start_date,
wenzelm@64193
   312
      Logger_Task("isabelle_cronjob", _ =>
wenzelm@64231
   313
        run_now(
wenzelm@64405
   314
          SEQ(List(build_release, build_history_base,
wenzelm@65640
   315
            PAR(remote_builds.map(seq => SEQ(seq.map(remote_build_history(rev, _))))),
wenzelm@65666
   316
            Logger_Task("jenkins_logs", _ => Jenkins.download_logs(jenkins_jobs, main_dir)),
wenzelm@65640
   317
            Logger_Task("build_log_database", logger => database_update(logger.options)))))))
wenzelm@64153
   318
wenzelm@64171
   319
    log_service.shutdown()
wenzelm@64170
   320
wenzelm@64153
   321
    main_state_file.file.delete
wenzelm@64153
   322
  }
wenzelm@64153
   323
wenzelm@64153
   324
wenzelm@64153
   325
wenzelm@64153
   326
  /** command line entry point **/
wenzelm@64153
   327
wenzelm@64148
   328
  def main(args: Array[String])
wenzelm@64148
   329
  {
wenzelm@64148
   330
    Command_Line.tool0 {
wenzelm@64148
   331
      var force = false
wenzelm@64148
   332
      var verbose = false
wenzelm@64187
   333
      var exclude_task = Set.empty[String]
wenzelm@64148
   334
wenzelm@64148
   335
      val getopts = Getopts("""
wenzelm@64148
   336
Usage: Admin/cronjob/main [OPTIONS]
wenzelm@64148
   337
wenzelm@64148
   338
  Options are:
wenzelm@64148
   339
    -f           apply force to do anything
wenzelm@64148
   340
    -v           verbose
wenzelm@64187
   341
    -x NAME      exclude tasks with this name
wenzelm@64148
   342
""",
wenzelm@64148
   343
        "f" -> (_ => force = true),
wenzelm@64187
   344
        "v" -> (_ => verbose = true),
wenzelm@64187
   345
        "x:" -> (arg => exclude_task += arg))
wenzelm@64148
   346
wenzelm@64148
   347
      val more_args = getopts(args)
wenzelm@64148
   348
      if (more_args.nonEmpty) getopts.usage()
wenzelm@64148
   349
wenzelm@64909
   350
      val progress = if (verbose) new Console_Progress() else No_Progress
wenzelm@64148
   351
wenzelm@64187
   352
      if (force) cronjob(progress, exclude_task)
wenzelm@64153
   353
      else error("Need to apply force to do anything")
wenzelm@64148
   354
    }
wenzelm@64148
   355
  }
wenzelm@64148
   356
}