src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Tue Oct 18 10:05:38 2016 +0200 (2016-10-18)
changeset 64294 303976a45afe
parent 64277 5ca4ac099e94
child 64295 6aefa7e66888
permissions -rw-r--r--
shared_home is default for classic isatest home setup;
distinct ISABELLE_IDENTIFIER for all tasks;
     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 
   111   private def remote_build_history(rev: String, r: Remote_Build): Logger_Task =
   112   {
   113     val task_name = "build_history-" + r.host
   114     Logger_Task(task_name, logger =>
   115       {
   116         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
   117           ssh =>
   118             {
   119               val results =
   120                 Build_History.remote_build_history(ssh,
   121                   isabelle_repos,
   122                   isabelle_repos.ext(r.host),
   123                   isabelle_repos_source = isabelle_dev_source,
   124                   self_update = !r.shared_home,
   125                   options =
   126                     r.options + " -f -r " + File.bash_string(rev) +
   127                       " -N " + File.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) => Some(Exn.message(exn))
   176         }
   177       logger.log_end(end_date, err)
   178     }
   179 
   180     def fork_task(start_date: Date, task: Logger_Task): Task =
   181       new Task(task.name, run_task(start_date, task))
   182   }
   183 
   184   class Logger private[Isabelle_Cronjob](
   185     val log_service: Log_Service, val start_date: Date, val task_name: String)
   186   {
   187     def ssh_context: SSH.Context = log_service.ssh_context
   188 
   189     def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
   190 
   191     def log_end(end_date: Date, err: Option[String])
   192     {
   193       val elapsed_time = end_date.time - start_date.time
   194       val msg =
   195         (if (err.isEmpty) "finished" else "ERROR " + err.get) +
   196         (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
   197       log(end_date, msg)
   198     }
   199 
   200     val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
   201 
   202     Isabelle_System.mkdirs(log_dir)
   203     log(start_date, "started")
   204   }
   205 
   206   class Task private[Isabelle_Cronjob](name: String, body: => Unit)
   207   {
   208     private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
   209     def is_finished: Boolean = future.is_finished
   210   }
   211 
   212 
   213 
   214   /** cronjob **/
   215 
   216   def cronjob(progress: Progress, exclude_task: Set[String])
   217   {
   218     /* soft lock */
   219 
   220     val still_running =
   221       try { Some(File.read(main_state_file)) }
   222       catch { case ERROR(_) => None }
   223 
   224     still_running match {
   225       case None | Some("") =>
   226       case Some(running) =>
   227         error("Isabelle cronjob appears to be still running: " + running)
   228     }
   229 
   230 
   231     /* log service */
   232 
   233     val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
   234 
   235     def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
   236 
   237     def run_now(task: Logger_Task) { run(Date.now(), task) }
   238 
   239 
   240     /* structured tasks */
   241 
   242     def SEQ(tasks: Logger_Task*): Logger_Task = Logger_Task(body = _ =>
   243       for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
   244         run_now(task))
   245 
   246     def PAR(tasks: Logger_Task*): Logger_Task = Logger_Task(body = _ =>
   247       {
   248         @tailrec def join(running: List[Task])
   249         {
   250           running.partition(_.is_finished) match {
   251             case (Nil, Nil) =>
   252             case (Nil, _ :: _) => Thread.sleep(500); join(running)
   253             case (_ :: _, remaining) => join(remaining)
   254           }
   255         }
   256         val start_date = Date.now()
   257         val running =
   258           for (task <- tasks.toList if !exclude_task(task.name))
   259             yield log_service.fork_task(start_date, task)
   260         join(running)
   261       })
   262 
   263 
   264     /* main */
   265 
   266     val main_start_date = Date.now()
   267     File.write(main_state_file, main_start_date + " " + log_service.hostname)
   268 
   269     val rev = Mercurial.repository(isabelle_repos).id()
   270 
   271     run(main_start_date,
   272       Logger_Task("isabelle_cronjob", _ =>
   273         run_now(
   274           SEQ(isabelle_identify, build_history_base, build_release,
   275             PAR(remote_builds.map(remote_build_history(rev, _)):_*)))))
   276 
   277     log_service.shutdown()
   278 
   279     main_state_file.file.delete
   280   }
   281 
   282 
   283 
   284   /** command line entry point **/
   285 
   286   def main(args: Array[String])
   287   {
   288     Command_Line.tool0 {
   289       var force = false
   290       var verbose = false
   291       var exclude_task = Set.empty[String]
   292 
   293       val getopts = Getopts("""
   294 Usage: Admin/cronjob/main [OPTIONS]
   295 
   296   Options are:
   297     -f           apply force to do anything
   298     -v           verbose
   299     -x NAME      exclude tasks with this name
   300 """,
   301         "f" -> (_ => force = true),
   302         "v" -> (_ => verbose = true),
   303         "x:" -> (arg => exclude_task += arg))
   304 
   305       val more_args = getopts(args)
   306       if (more_args.nonEmpty) getopts.usage()
   307 
   308       val progress = if (verbose) new Console_Progress() else Ignore_Progress
   309 
   310       if (force) cronjob(progress, exclude_task)
   311       else error("Need to apply force to do anything")
   312     }
   313   }
   314 }