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