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