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