src/Pure/Admin/isabelle_cronjob.scala
author hoelzl
Fri Oct 21 11:02:36 2016 +0200 (2016-10-21)
changeset 64333 692a1b317316
parent 64332 76a3e0f894fd
child 64338 20c543b9fa80
permissions -rw-r--r--
HOL-Probability: Essential Supremum as Limsup over ae_filter
     1 /*  Title:      Pure/Admin/isabelle_cronjob.scala
     2     Author:     Makarius
     3 
     4 Main entry point for administrative cronjob at TUM.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import scala.annotation.tailrec
    11 import scala.collection.mutable
    12 
    13 
    14 object Isabelle_Cronjob
    15 {
    16   /* file-system state: owned by main cronjob */
    17 
    18   val main_dir = Path.explode("~/cronjob")
    19   val main_state_file = main_dir + Path.explode("run/main.state")
    20   val current_log = main_dir + Path.explode("run/main.log")  // owned by log service
    21   val cumulative_log = main_dir + Path.explode("log/main.log")  // owned by log service
    22 
    23   val isabelle_repos = main_dir + Path.explode("isabelle")
    24   val isabelle_repos_test = main_dir + Path.explode("isabelle-test")
    25   val afp_repos = main_dir + Path.explode("AFP")
    26 
    27   val isabelle_dev_source = "http://isabelle.in.tum.de/repos/isabelle"
    28   val isabelle_release_source = "http://bitbucket.org/isabelle_project/isabelle-release"
    29   val afp_source = "https://bitbucket.org/isa-afp/afp-devel"
    30 
    31   val release_snapshot = Path.explode("~/html-data/release_snapshot")
    32 
    33 
    34 
    35   /** particular tasks **/
    36 
    37   /* identify Isabelle + AFP repository snapshots */
    38 
    39   private val isabelle_identify =
    40     Logger_Task("isabelle_identify", logger =>
    41       {
    42         val isabelle_id = Mercurial.repository(isabelle_repos).id()
    43         val afp_id = Mercurial.setup_repository(afp_source, afp_repos).id()
    44 
    45         File.write(logger.log_dir + Build_Log.log_filename("isabelle_identify", logger.start_date),
    46           terminate_lines(
    47             List("isabelle_identify: " + Build_Log.print_date(logger.start_date),
    48               "",
    49               "Isabelle version: " + isabelle_id,
    50               "AFP version: " + afp_id)))
    51       })
    52 
    53 
    54   /* integrity test of build_history vs. build_history_base */
    55 
    56   private val build_history_base =
    57     Logger_Task("build_history_base", logger =>
    58       {
    59         val hg =
    60           Mercurial.setup_repository(
    61             File.standard_path(isabelle_repos), isabelle_repos_test)
    62         for {
    63           (result, log_path) <-
    64             Build_History.build_history(
    65               hg, rev = "build_history_base", fresh = true, build_args = List("HOL"))
    66         } {
    67           result.check
    68           File.copy(log_path, logger.log_dir + log_path.base)
    69         }
    70       })
    71 
    72 
    73   /* build release from repository snapshot */
    74 
    75   private val build_release =
    76     Logger_Task("build_release", logger =>
    77       Isabelle_System.with_tmp_dir("isadist")(base_dir =>
    78         {
    79           val new_snapshot = release_snapshot.ext("new")
    80           val old_snapshot = release_snapshot.ext("old")
    81 
    82           Isabelle_System.rm_tree(new_snapshot)
    83           Isabelle_System.rm_tree(old_snapshot)
    84 
    85           Build_Release.build_release(base_dir, parallel_jobs = 4,
    86             remote_mac = "macbroy30", website = Some(new_snapshot))
    87 
    88           if (release_snapshot.is_dir) File.mv(release_snapshot, old_snapshot)
    89           File.mv(new_snapshot, release_snapshot)
    90           Isabelle_System.rm_tree(old_snapshot)
    91         }))
    92 
    93 
    94   /* remote build_history */
    95 
    96   private sealed case class Remote_Build(
    97     host: String,
    98     user: String = "",
    99     port: Int = SSH.default_port,
   100     shared_home: Boolean = true,
   101     options: String = "",
   102     args: String = "-o timeout=10800 -a")
   103 
   104   private val remote_builds =
   105     List(
   106       Remote_Build("lxbroy10", options = "-m32 -M4 -N"),
   107       Remote_Build("macbroy2", options = "-m32 -M4"),
   108       Remote_Build("macbroy30", options = "-m32 -M2"),
   109       Remote_Build("macbroy31", options = "-m32 -M2"),
   110       Remote_Build("vmnipkow9", options = "-m32 -M4", shared_home = false))
   111 
   112   private def remote_build_history(rev: String, r: Remote_Build): Logger_Task =
   113   {
   114     val task_name = "build_history-" + r.host
   115     Logger_Task(task_name, logger =>
   116       {
   117         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
   118           ssh =>
   119             {
   120               val results =
   121                 Build_History.remote_build_history(ssh,
   122                   isabelle_repos,
   123                   isabelle_repos.ext(r.host),
   124                   isabelle_repos_source = isabelle_dev_source,
   125                   self_update = !r.shared_home,
   126                   options =
   127                     r.options + " -f -r " + Bash.string(rev) + " -N " + Bash.string(task_name),
   128                   args = r.args)
   129               for ((log, bytes) <- results)
   130                 Bytes.write(logger.log_dir + Path.explode(log), bytes)
   131             })
   132       })
   133   }
   134 
   135 
   136 
   137   /** task logging **/
   138 
   139   sealed case class Logger_Task(name: String = "", body: Logger => Unit)
   140 
   141   class Log_Service private[Isabelle_Cronjob](progress: Progress, val ssh_context: SSH.Context)
   142   {
   143     current_log.file.delete
   144 
   145     private val thread: Consumer_Thread[String] =
   146       Consumer_Thread.fork("cronjob: logger", daemon = true)(
   147         consume = (text: String) =>
   148           { // critical
   149             File.append(current_log, text + "\n")
   150             File.append(cumulative_log, text + "\n")
   151             progress.echo(text)
   152             true
   153           })
   154 
   155     def shutdown() { thread.shutdown() }
   156 
   157     val hostname = Isabelle_System.hostname()
   158 
   159     def log(date: Date, task_name: String, msg: String): Unit =
   160       if (task_name != "")
   161         thread.send(
   162           "[" + Build_Log.print_date(date) + ", " + hostname + ", " + task_name + "]: " + msg)
   163 
   164     def start_logger(start_date: Date, task_name: String): Logger =
   165       new Logger(this, start_date, task_name)
   166 
   167     def run_task(start_date: Date, task: Logger_Task)
   168     {
   169       val logger = start_logger(start_date, task.name)
   170       val res = Exn.capture { task.body(logger) }
   171       val end_date = Date.now()
   172       val err =
   173         res match {
   174           case Exn.Res(_) => None
   175           case Exn.Exn(exn) =>
   176             val first_line = Library.split_lines(Exn.message(exn)).headOption getOrElse "exception"
   177             Some(first_line)
   178         }
   179       logger.log_end(end_date, err)
   180     }
   181 
   182     def fork_task(start_date: Date, task: Logger_Task): Task =
   183       new Task(task.name, run_task(start_date, task))
   184   }
   185 
   186   class Logger private[Isabelle_Cronjob](
   187     val log_service: Log_Service, val start_date: Date, val task_name: String)
   188   {
   189     def ssh_context: SSH.Context = log_service.ssh_context
   190 
   191     def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
   192 
   193     def log_end(end_date: Date, err: Option[String])
   194     {
   195       val elapsed_time = end_date.time - start_date.time
   196       val msg =
   197         (if (err.isEmpty) "finished" else "ERROR " + err.get) +
   198         (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
   199       log(end_date, msg)
   200     }
   201 
   202     val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
   203 
   204     Isabelle_System.mkdirs(log_dir)
   205     log(start_date, "started")
   206   }
   207 
   208   class Task private[Isabelle_Cronjob](name: String, body: => Unit)
   209   {
   210     private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
   211     def is_finished: Boolean = future.is_finished
   212   }
   213 
   214 
   215 
   216   /** cronjob **/
   217 
   218   def cronjob(progress: Progress, exclude_task: Set[String])
   219   {
   220     /* soft lock */
   221 
   222     val still_running =
   223       try { Some(File.read(main_state_file)) }
   224       catch { case ERROR(_) => None }
   225 
   226     still_running match {
   227       case None | Some("") =>
   228       case Some(running) =>
   229         error("Isabelle cronjob appears to be still running: " + running)
   230     }
   231 
   232 
   233     /* log service */
   234 
   235     val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
   236 
   237     def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
   238 
   239     def run_now(task: Logger_Task) { run(Date.now(), task) }
   240 
   241 
   242     /* structured tasks */
   243 
   244     def SEQ(tasks: Logger_Task*): Logger_Task = Logger_Task(body = _ =>
   245       for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
   246         run_now(task))
   247 
   248     def PAR(tasks: Logger_Task*): Logger_Task = Logger_Task(body = _ =>
   249       {
   250         @tailrec def join(running: List[Task])
   251         {
   252           running.partition(_.is_finished) match {
   253             case (Nil, Nil) =>
   254             case (Nil, _ :: _) => Thread.sleep(500); join(running)
   255             case (_ :: _, remaining) => join(remaining)
   256           }
   257         }
   258         val start_date = Date.now()
   259         val running =
   260           for (task <- tasks.toList if !exclude_task(task.name))
   261             yield log_service.fork_task(start_date, task)
   262         join(running)
   263       })
   264 
   265 
   266     /* main */
   267 
   268     val main_start_date = Date.now()
   269     File.write(main_state_file, main_start_date + " " + log_service.hostname)
   270 
   271     val rev = Mercurial.repository(isabelle_repos).id()
   272 
   273     run(main_start_date,
   274       Logger_Task("isabelle_cronjob", _ =>
   275         run_now(
   276           SEQ(isabelle_identify, build_history_base, build_release,
   277             PAR(remote_builds.map(remote_build_history(rev, _)):_*)))))
   278 
   279     log_service.shutdown()
   280 
   281     main_state_file.file.delete
   282   }
   283 
   284 
   285 
   286   /** command line entry point **/
   287 
   288   def main(args: Array[String])
   289   {
   290     Command_Line.tool0 {
   291       var force = false
   292       var verbose = false
   293       var exclude_task = Set.empty[String]
   294 
   295       val getopts = Getopts("""
   296 Usage: Admin/cronjob/main [OPTIONS]
   297 
   298   Options are:
   299     -f           apply force to do anything
   300     -v           verbose
   301     -x NAME      exclude tasks with this name
   302 """,
   303         "f" -> (_ => force = true),
   304         "v" -> (_ => verbose = true),
   305         "x:" -> (arg => exclude_task += arg))
   306 
   307       val more_args = getopts(args)
   308       if (more_args.nonEmpty) getopts.usage()
   309 
   310       val progress = if (verbose) new Console_Progress() else Ignore_Progress
   311 
   312       if (force) cronjob(progress, exclude_task)
   313       else error("Need to apply force to do anything")
   314     }
   315   }
   316 }