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