src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Fri Oct 13 21:53:22 2017 +0200 (22 months ago)
changeset 66858 2ca6f0275de7
parent 66856 6b90c688a6dc
child 66859 dd846a805fb1
permissions -rw-r--r--
support for AFP versions;
     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 jenkins_jobs = "identify" :: Jenkins.build_log_jobs
    28 
    29 
    30 
    31   /** particular tasks **/
    32 
    33   /* identify Isabelle + AFP repository snapshots and build release */
    34 
    35   private val build_release =
    36     Logger_Task("build_release", logger =>
    37         {
    38           Isabelle_Devel.make_index()
    39 
    40           val rev = Mercurial.repository(isabelle_repos).id()
    41           val afp_rev = Mercurial.setup_repository(AFP.repos_source, afp_repos).id()
    42 
    43           File.write(logger.log_dir + Build_Log.log_filename("isabelle_identify", logger.start_date),
    44             Build_Log.Identify.content(logger.start_date, Some(rev), Some(afp_rev)))
    45 
    46           Isabelle_Devel.release_snapshot(rev = rev, afp_rev = afp_rev,
    47             parallel_jobs = 4, remote_mac = "macbroy31")
    48         })
    49 
    50 
    51   /* integrity test of build_history vs. build_history_base */
    52 
    53   private val build_history_base =
    54     Logger_Task("build_history_base", logger =>
    55       {
    56         val hg =
    57           Mercurial.setup_repository(
    58             File.standard_path(isabelle_repos), isabelle_repos_test)
    59         for {
    60           (result, log_path) <-
    61             Build_History.build_history(
    62               hg, rev = "build_history_base", fresh = true, build_args = List("HOL"))
    63         } {
    64           result.check
    65           File.move(log_path, logger.log_dir + log_path.base)
    66         }
    67       })
    68 
    69 
    70   /* remote build_history */
    71 
    72   sealed case class Item(known: Boolean, isabelle_version: String, pull_date: Date)
    73   {
    74     def unknown: Boolean = !known
    75   }
    76 
    77   def recent_items(db: SQL.Database, days: Int, rev: String, sql: SQL.Source): List[Item] =
    78   {
    79     val select =
    80       Build_Log.Data.select_recent_versions(days = days, rev = rev, sql = "WHERE " + sql)
    81 
    82     db.using_statement(select)(stmt =>
    83       stmt.execute_query().iterator(res =>
    84       {
    85         val known = res.bool(Build_Log.Data.known)
    86         val isabelle_version = res.string(Build_Log.Prop.isabelle_version)
    87         val pull_date = res.date(Build_Log.Data.pull_date)
    88         Item(known, isabelle_version, pull_date)
    89       }).toList)
    90   }
    91 
    92   def unknown_runs(items: List[Item]): List[List[Item]] =
    93   {
    94     val (run, rest) = Library.take_prefix[Item](_.unknown, items.dropWhile(_.known))
    95     if (run.nonEmpty) run :: unknown_runs(rest) else Nil
    96   }
    97 
    98   sealed case class Remote_Build(
    99     description: String,
   100     host: String,
   101     user: String = "",
   102     port: Int = 0,
   103     shared_home: Boolean = true,
   104     historic: Boolean = false,
   105     history: Int = 0,
   106     history_base: String = "build_history_base",
   107     options: String = "",
   108     args: String = "",
   109     detect: SQL.Source = "")
   110   {
   111     def sql: SQL.Source =
   112       Build_Log.Prop.build_engine + " = " + SQL.string(Build_History.engine) + " AND " +
   113       Build_Log.Prop.build_host + " = " + SQL.string(host) +
   114       (if (detect == "") "" else " AND " + SQL.enclose(detect))
   115 
   116     def profile: Build_Status.Profile =
   117       Build_Status.Profile(description, history, sql)
   118 
   119     def history_base_filter(hg: Mercurial.Repository): Set[String] =
   120     {
   121       val rev0 = hg.id(history_base)
   122       val graph = hg.graph()
   123       (rev0 :: graph.all_succs(List(rev0))).toSet
   124     }
   125 
   126     def pick(options: Options, rev: String = "", filter: String => Boolean = (_: String) => true)
   127       : Option[String] =
   128     {
   129       val store = Build_Log.store(options)
   130       using(store.open_database())(db =>
   131       {
   132         def pick_days(days: Int, gap: Int): Option[String] =
   133         {
   134           val items =
   135             recent_items(db, days = days, rev = rev, sql = sql).
   136               filter(item => filter(item.isabelle_version))
   137           def runs = unknown_runs(items).filter(run => run.length >= gap)
   138 
   139           val known_rev =
   140             rev != "" && items.exists(item => item.known && item.isabelle_version == rev)
   141 
   142           if (historic || known_rev) {
   143             val longest_run =
   144               (List.empty[Item] /: runs)({ case (item1, item2) =>
   145                 if (item1.length >= item2.length) item1 else item2
   146               })
   147             if (longest_run.isEmpty) None
   148             else Some(longest_run(longest_run.length / 2).isabelle_version)
   149           }
   150           else if (rev != "") Some(rev)
   151           else runs.flatten.headOption.map(_.isabelle_version)
   152         }
   153 
   154         pick_days(options.int("build_log_history") max history, 2) orElse
   155         pick_days(200, 5) orElse
   156         pick_days(2000, 1)
   157       })
   158     }
   159   }
   160 
   161   val remote_builds_old: List[Remote_Build] =
   162     List(
   163       Remote_Build("Poly/ML 5.7 Linux", "lxbroy8",
   164         history_base = "37074e22e8be",
   165         options = "-m32 -B -M1x2,2 -t polyml-5.7 -i 'init_component /home/isabelle/contrib/polyml-5.7'",
   166         args = "-N -g timing",
   167         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7") + " AND " +
   168           Build_Log.Settings.ML_OPTIONS + " <> " + SQL.string("-H 500")),
   169       Remote_Build("Poly/ML 5.7 Mac OS X", "macbroy2",
   170         history_base = "37074e22e8be",
   171         options = "-m32 -B -M1x4,4 -t polyml-5.7 -i 'init_component /home/isabelle/contrib/polyml-5.7'",
   172         args = "-a",
   173         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7")),
   174       Remote_Build("Poly/ML test", "lxbroy8",
   175         options = "-m32 -B -M1x2,2 -t polyml-test -i 'init_component /home/isabelle/contrib/polyml-5.7-20170217'",
   176         args = "-N -g timing",
   177         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-test")),
   178       Remote_Build("Mac OS X 10.8 Mountain Lion", "macbroy30", options = "-m32 -M2", args = "-a",
   179         detect = Build_Log.Prop.build_start + " < date '2017-03-03'"))
   180 
   181 
   182   val remote_builds: List[List[Remote_Build]] =
   183   {
   184     List(
   185       List(Remote_Build("Poly/ML 5.7.1 Linux", "lxbroy8",
   186         history_base = "37074e22e8be",
   187         options = "-m32 -B -M1x2,2 -t polyml-5.7.1-pre1 -i 'init_component /home/isabelle/contrib/polyml-test-e7a662f8f9c4'",
   188         args = "-N -g timing",
   189         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1"))),
   190       List(Remote_Build("Linux A", "lxbroy9",
   191         options = "-m32 -B -M1x2,2", args = "-N -g timing")),
   192       List(Remote_Build("Linux B", "lxbroy10", historic = true, history = 90,
   193         options = "-m32 -B -M1x4,2,4,6", args = "-N -g timing")),
   194       List(
   195         Remote_Build("Mac OS X 10.9 Mavericks", "macbroy2",
   196           options = "-m32 -M8" +
   197             " -e ISABELLE_GHC=ghc -e ISABELLE_MLTON=mlton -e ISABELLE_OCAML=ocaml" +
   198             " -e ISABELLE_OCAMLC=ocamlc -e ISABELLE_SMLNJ=/mnt/nfsbroy/home/smlnj/bin/sml",
   199           args = "-a",
   200           detect = Build_Log.Prop.build_tags.undefined),
   201         Remote_Build("Mac OS X 10.9 Mavericks, quick_and_dirty", "macbroy2",
   202           options = "-m32 -M8 -t quick_and_dirty", args = "-a -o quick_and_dirty",
   203           detect = Build_Log.Prop.build_tags + " = " + SQL.string("quick_and_dirty")),
   204         Remote_Build("Mac OS X 10.9 Mavericks, skip_proofs", "macbroy2",
   205           options = "-m32 -M8 -t skip_proofs", args = "-a -o skip_proofs",
   206           detect = Build_Log.Prop.build_tags + " = " + SQL.string("skip_proofs")),
   207         Remote_Build("Poly/ML 5.7.1 Mac OS X", "macbroy2",
   208           history_base = "37074e22e8be",
   209           options = "-m32 -B -M1x4,4 -t polyml-5.7.1-pre1 -i 'init_component /home/isabelle/contrib/polyml-test-e7a662f8f9c4'",
   210           args = "-a",
   211           detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1"))),
   212       List(
   213         Remote_Build("Mac OS X 10.12 Sierra", "macbroy30", options = "-m32 -M2", args = "-a",
   214           detect = Build_Log.Prop.build_start + " > date '2017-03-03'")),
   215       List(Remote_Build("Mac OS X 10.10 Yosemite", "macbroy31", options = "-m32 -M2", args = "-a")),
   216       List(
   217         Remote_Build("Windows", "vmnipkow9", historic = true, history = 90, shared_home = false,
   218           options = "-m32 -M4" +
   219             " -e ISABELLE_OCAML=ocaml -e ISABELLE_OCAMLC=ocamlc" +
   220             " -e ISABELLE_GHC=/usr/local/ghc-8.0.2/bin/ghc" +
   221             " -e ISABELLE_SMLNJ=/usr/local/smlnj-110.81/bin/sml",
   222           args = "-a",
   223           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86-windows")),
   224         Remote_Build("Windows", "vmnipkow9", historic = true, history = 90, shared_home = false,
   225           options = "-m64 -M4" +
   226             " -e ISABELLE_OCAML=ocaml -e ISABELLE_OCAMLC=ocamlc" +
   227             " -e ISABELLE_GHC=/usr/local/ghc-8.0.2/bin/ghc" +
   228             " -e ISABELLE_SMLNJ=/usr/local/smlnj-110.81/bin/sml",
   229           args = "-a",
   230           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86_64-windows"))))
   231   }
   232 
   233   private def remote_build_history(rev: String, i: Int, r: Remote_Build): Logger_Task =
   234   {
   235     val task_name = "build_history-" + r.host
   236     Logger_Task(task_name, logger =>
   237       {
   238         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
   239           ssh =>
   240             {
   241               val self_update = !r.shared_home
   242               val push_isabelle_home = self_update && Mercurial.is_repository(Path.explode("~~"))
   243 
   244               val results =
   245                 Build_History.remote_build_history(ssh,
   246                   isabelle_repos,
   247                   isabelle_repos.ext(r.host),
   248                   isabelle_identifier = "cronjob_build_history",
   249                   self_update = self_update,
   250                   push_isabelle_home = push_isabelle_home,
   251                   rev = rev,
   252                   options =
   253                     " -N " + Bash.string(task_name) + (if (i < 0) "" else "_" + (i + 1).toString) +
   254                     " -f " + r.options,
   255                   args = "-o timeout=10800 " + r.args)
   256 
   257               for ((log_name, bytes) <- results) {
   258                 logger.log(Date.now(), log_name)
   259                 Bytes.write(logger.log_dir + Path.explode(log_name), bytes)
   260               }
   261             })
   262       })
   263   }
   264 
   265   val build_status_profiles: List[Build_Status.Profile] =
   266     (remote_builds_old :: remote_builds).flatten.map(_.profile)
   267 
   268 
   269 
   270   /** task logging **/
   271 
   272   sealed case class Logger_Task(name: String = "", body: Logger => Unit)
   273 
   274   class Log_Service private[Isabelle_Cronjob](progress: Progress, val ssh_context: SSH.Context)
   275   {
   276     current_log.file.delete
   277 
   278     private val thread: Consumer_Thread[String] =
   279       Consumer_Thread.fork("cronjob: logger", daemon = true)(
   280         consume = (text: String) =>
   281           { // critical
   282             File.append(current_log, text + "\n")
   283             File.append(cumulative_log, text + "\n")
   284             progress.echo(text)
   285             true
   286           })
   287 
   288     def shutdown() { thread.shutdown() }
   289 
   290     val hostname = Isabelle_System.hostname()
   291 
   292     def log(date: Date, task_name: String, msg: String): Unit =
   293       if (task_name != "")
   294         thread.send(
   295           "[" + Build_Log.print_date(date) + ", " + hostname + ", " + task_name + "]: " + msg)
   296 
   297     def start_logger(start_date: Date, task_name: String): Logger =
   298       new Logger(this, start_date, task_name)
   299 
   300     def run_task(start_date: Date, task: Logger_Task)
   301     {
   302       val logger = start_logger(start_date, task.name)
   303       val res = Exn.capture { task.body(logger) }
   304       val end_date = Date.now()
   305       val err =
   306         res match {
   307           case Exn.Res(_) => None
   308           case Exn.Exn(exn) =>
   309             System.err.println("Exception trace for " + quote(task.name) + ":")
   310             exn.printStackTrace()
   311             val first_line = Library.split_lines(Exn.message(exn)).headOption getOrElse "exception"
   312             Some(first_line)
   313         }
   314       logger.log_end(end_date, err)
   315     }
   316 
   317     def fork_task(start_date: Date, task: Logger_Task): Task =
   318       new Task(task.name, run_task(start_date, task))
   319   }
   320 
   321   class Logger private[Isabelle_Cronjob](
   322     val log_service: Log_Service, val start_date: Date, val task_name: String)
   323   {
   324     def ssh_context: SSH.Context = log_service.ssh_context
   325     def options: Options = ssh_context.options
   326 
   327     def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
   328 
   329     def log_end(end_date: Date, err: Option[String])
   330     {
   331       val elapsed_time = end_date.time - start_date.time
   332       val msg =
   333         (if (err.isEmpty) "finished" else "ERROR " + err.get) +
   334         (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
   335       log(end_date, msg)
   336     }
   337 
   338     val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
   339 
   340     Isabelle_System.mkdirs(log_dir)
   341     log(start_date, "started")
   342   }
   343 
   344   class Task private[Isabelle_Cronjob](name: String, body: => Unit)
   345   {
   346     private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
   347     def is_finished: Boolean = future.is_finished
   348   }
   349 
   350 
   351 
   352   /** cronjob **/
   353 
   354   def cronjob(progress: Progress, exclude_task: Set[String])
   355   {
   356     /* soft lock */
   357 
   358     val still_running =
   359       try { Some(File.read(main_state_file)) }
   360       catch { case ERROR(_) => None }
   361 
   362     still_running match {
   363       case None | Some("") =>
   364       case Some(running) =>
   365         error("Isabelle cronjob appears to be still running: " + running)
   366     }
   367 
   368 
   369     /* log service */
   370 
   371     val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
   372 
   373     def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
   374 
   375     def run_now(task: Logger_Task) { run(Date.now(), task) }
   376 
   377 
   378     /* structured tasks */
   379 
   380     def SEQ(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   381       for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
   382         run_now(task))
   383 
   384     def PAR(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   385       {
   386         @tailrec def join(running: List[Task])
   387         {
   388           running.partition(_.is_finished) match {
   389             case (Nil, Nil) =>
   390             case (Nil, _ :: _) => Thread.sleep(500); join(running)
   391             case (_ :: _, remaining) => join(remaining)
   392           }
   393         }
   394         val start_date = Date.now()
   395         val running =
   396           for (task <- tasks if !exclude_task(task.name))
   397             yield log_service.fork_task(start_date, task)
   398         join(running)
   399       })
   400 
   401 
   402     /* main */
   403 
   404     val main_start_date = Date.now()
   405     File.write(main_state_file, main_start_date + " " + log_service.hostname)
   406 
   407     val hg = Mercurial.repository(isabelle_repos)
   408     val rev = hg.id()
   409 
   410     run(main_start_date,
   411       Logger_Task("isabelle_cronjob", logger =>
   412         run_now(
   413           SEQ(List(build_release, build_history_base,
   414             PAR(remote_builds.map(seq =>
   415               SEQ(
   416                 for {
   417                   (r, i) <- (if (seq.length <= 1) seq.map((_, -1)) else seq.zipWithIndex)
   418                   rev <- r.pick(logger.options, rev, r.history_base_filter(hg))
   419                 } yield remote_build_history(rev, i, r)))),
   420             Logger_Task("jenkins_logs", _ => Jenkins.download_logs(jenkins_jobs, main_dir)),
   421             Logger_Task("build_log_database",
   422               logger => Isabelle_Devel.build_log_database(logger.options)),
   423             Logger_Task("build_status",
   424               logger => Isabelle_Devel.build_status(logger.options)))))))
   425 
   426     log_service.shutdown()
   427 
   428     main_state_file.file.delete
   429   }
   430 
   431 
   432 
   433   /** command line entry point **/
   434 
   435   def main(args: Array[String])
   436   {
   437     Command_Line.tool0 {
   438       var force = false
   439       var verbose = false
   440       var exclude_task = Set.empty[String]
   441 
   442       val getopts = Getopts("""
   443 Usage: Admin/cronjob/main [OPTIONS]
   444 
   445   Options are:
   446     -f           apply force to do anything
   447     -v           verbose
   448     -x NAME      exclude tasks with this name
   449 """,
   450         "f" -> (_ => force = true),
   451         "v" -> (_ => verbose = true),
   452         "x:" -> (arg => exclude_task += arg))
   453 
   454       val more_args = getopts(args)
   455       if (more_args.nonEmpty) getopts.usage()
   456 
   457       val progress = if (verbose) new Console_Progress() else No_Progress
   458 
   459       if (force) cronjob(progress, exclude_task)
   460       else error("Need to apply force to do anything")
   461     }
   462   }
   463 }