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