src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Tue May 16 15:37:07 2017 +0200 (2017-05-16)
changeset 65843 d547173212d2
parent 65840 8d7b2ac9a245
child 65871 80c1c1f53e72
permissions -rw-r--r--
proper init_settings for init_component (before generated ML_OPTIONS etc.);
fresh start for "Poly/ML 5.7 Linux", suppressing old builds with ML_OPTIONS="-H 500";
     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", options = "-m32 -M8", args = "-a",
   190           detect = Build_Log.Prop.build_tags + " IS NULL"),
   191         Remote_Build("Mac OS X 10.9 Mavericks, quick_and_dirty", "macbroy2",
   192           options = "-m32 -M8 -t quick_and_dirty", args = "-a -o quick_and_dirty",
   193           detect = Build_Log.Prop.build_tags + " = " + SQL.string("quick_and_dirty")),
   194         Remote_Build("Mac OS X 10.9 Mavericks, skip_proofs", "macbroy2",
   195           options = "-m32 -M8 -t skip_proofs", args = "-a -o skip_proofs",
   196           detect = Build_Log.Prop.build_tags + " = " + SQL.string("skip_proofs"))),
   197       List(
   198         Remote_Build("Mac OS X 10.12 Sierra", "macbroy30", options = "-m32 -M2", args = "-a",
   199           detect = Build_Log.Prop.build_start + " > date '2017-03-03'")),
   200       List(Remote_Build("Mac OS X 10.10 Yosemite", "macbroy31", options = "-m32 -M2", args = "-a")),
   201       List(
   202         Remote_Build("Windows", "vmnipkow9", history = 90, shared_home = false,
   203           options = "-m32 -M4", args = "-a",
   204           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86-windows")),
   205         Remote_Build("Windows", "vmnipkow9", history = 90, shared_home = false,
   206           options = "-m64 -M4", args = "-a",
   207           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86_64-windows"))))
   208   }
   209 
   210   private def remote_build_history(rev: String, r: Remote_Build): Logger_Task =
   211   {
   212     val task_name = "build_history-" + r.host
   213     Logger_Task(task_name, logger =>
   214       {
   215         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
   216           ssh =>
   217             {
   218               val self_update = !r.shared_home
   219               val push_isabelle_home = self_update && Mercurial.is_repository(Path.explode("~~"))
   220 
   221               val (results, _) =
   222                 Build_History.remote_build_history(ssh,
   223                   isabelle_repos,
   224                   isabelle_repos.ext(r.host),
   225                   isabelle_repos_source = isabelle_dev_source,
   226                   self_update = self_update,
   227                   push_isabelle_home = push_isabelle_home,
   228                   options =
   229                     "-r " + Bash.string(rev) + " -N " + Bash.string(task_name) + " -f " + r.options,
   230                   args = "-o timeout=10800 " + r.args)
   231 
   232               for ((log_name, bytes) <- results) {
   233                 logger.log(Date.now(), log_name)
   234                 Bytes.write(logger.log_dir + Path.explode(log_name), bytes)
   235               }
   236             })
   237       })
   238   }
   239 
   240   val build_status_profiles: List[Build_Status.Profile] =
   241     (remote_builds_old :: remote_builds).flatten.map(_.profile)
   242 
   243 
   244 
   245   /** task logging **/
   246 
   247   sealed case class Logger_Task(name: String = "", body: Logger => Unit)
   248 
   249   class Log_Service private[Isabelle_Cronjob](progress: Progress, val ssh_context: SSH.Context)
   250   {
   251     current_log.file.delete
   252 
   253     private val thread: Consumer_Thread[String] =
   254       Consumer_Thread.fork("cronjob: logger", daemon = true)(
   255         consume = (text: String) =>
   256           { // critical
   257             File.append(current_log, text + "\n")
   258             File.append(cumulative_log, text + "\n")
   259             progress.echo(text)
   260             true
   261           })
   262 
   263     def shutdown() { thread.shutdown() }
   264 
   265     val hostname = Isabelle_System.hostname()
   266 
   267     def log(date: Date, task_name: String, msg: String): Unit =
   268       if (task_name != "")
   269         thread.send(
   270           "[" + Build_Log.print_date(date) + ", " + hostname + ", " + task_name + "]: " + msg)
   271 
   272     def start_logger(start_date: Date, task_name: String): Logger =
   273       new Logger(this, start_date, task_name)
   274 
   275     def run_task(start_date: Date, task: Logger_Task)
   276     {
   277       val logger = start_logger(start_date, task.name)
   278       val res = Exn.capture { task.body(logger) }
   279       val end_date = Date.now()
   280       val err =
   281         res match {
   282           case Exn.Res(_) => None
   283           case Exn.Exn(exn) =>
   284             System.err.println("Exception trace for " + quote(task.name) + ":")
   285             exn.printStackTrace()
   286             val first_line = Library.split_lines(Exn.message(exn)).headOption getOrElse "exception"
   287             Some(first_line)
   288         }
   289       logger.log_end(end_date, err)
   290     }
   291 
   292     def fork_task(start_date: Date, task: Logger_Task): Task =
   293       new Task(task.name, run_task(start_date, task))
   294   }
   295 
   296   class Logger private[Isabelle_Cronjob](
   297     val log_service: Log_Service, val start_date: Date, val task_name: String)
   298   {
   299     def ssh_context: SSH.Context = log_service.ssh_context
   300     def options: Options = ssh_context.options
   301 
   302     def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
   303 
   304     def log_end(end_date: Date, err: Option[String])
   305     {
   306       val elapsed_time = end_date.time - start_date.time
   307       val msg =
   308         (if (err.isEmpty) "finished" else "ERROR " + err.get) +
   309         (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
   310       log(end_date, msg)
   311     }
   312 
   313     val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
   314 
   315     Isabelle_System.mkdirs(log_dir)
   316     log(start_date, "started")
   317   }
   318 
   319   class Task private[Isabelle_Cronjob](name: String, body: => Unit)
   320   {
   321     private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
   322     def is_finished: Boolean = future.is_finished
   323   }
   324 
   325 
   326 
   327   /** cronjob **/
   328 
   329   def cronjob(progress: Progress, exclude_task: Set[String])
   330   {
   331     /* soft lock */
   332 
   333     val still_running =
   334       try { Some(File.read(main_state_file)) }
   335       catch { case ERROR(_) => None }
   336 
   337     still_running match {
   338       case None | Some("") =>
   339       case Some(running) =>
   340         error("Isabelle cronjob appears to be still running: " + running)
   341     }
   342 
   343 
   344     /* log service */
   345 
   346     val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
   347 
   348     def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
   349 
   350     def run_now(task: Logger_Task) { run(Date.now(), task) }
   351 
   352 
   353     /* structured tasks */
   354 
   355     def SEQ(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   356       for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
   357         run_now(task))
   358 
   359     def PAR(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   360       {
   361         @tailrec def join(running: List[Task])
   362         {
   363           running.partition(_.is_finished) match {
   364             case (Nil, Nil) =>
   365             case (Nil, _ :: _) => Thread.sleep(500); join(running)
   366             case (_ :: _, remaining) => join(remaining)
   367           }
   368         }
   369         val start_date = Date.now()
   370         val running =
   371           for (task <- tasks if !exclude_task(task.name))
   372             yield log_service.fork_task(start_date, task)
   373         join(running)
   374       })
   375 
   376 
   377     /* main */
   378 
   379     val main_start_date = Date.now()
   380     File.write(main_state_file, main_start_date + " " + log_service.hostname)
   381 
   382     val hg = Mercurial.repository(isabelle_repos)
   383     val rev = hg.id()
   384 
   385     run(main_start_date,
   386       Logger_Task("isabelle_cronjob", logger =>
   387         run_now(
   388           SEQ(List(build_release, build_history_base,
   389             PAR(remote_builds.map(seq =>
   390               SEQ(seq.flatMap(r =>
   391                 r.pick(logger.options, rev, r.history_base_filter(hg)).
   392                   map(remote_build_history(_, r)))))),
   393             Logger_Task("jenkins_logs", _ => Jenkins.download_logs(jenkins_jobs, main_dir)),
   394             Logger_Task("build_log_database",
   395               logger => Isabelle_Devel.build_log_database(logger.options)),
   396             Logger_Task("build_status",
   397               logger => Isabelle_Devel.build_status(logger.options)))))))
   398 
   399     log_service.shutdown()
   400 
   401     main_state_file.file.delete
   402   }
   403 
   404 
   405 
   406   /** command line entry point **/
   407 
   408   def main(args: Array[String])
   409   {
   410     Command_Line.tool0 {
   411       var force = false
   412       var verbose = false
   413       var exclude_task = Set.empty[String]
   414 
   415       val getopts = Getopts("""
   416 Usage: Admin/cronjob/main [OPTIONS]
   417 
   418   Options are:
   419     -f           apply force to do anything
   420     -v           verbose
   421     -x NAME      exclude tasks with this name
   422 """,
   423         "f" -> (_ => force = true),
   424         "v" -> (_ => verbose = true),
   425         "x:" -> (arg => exclude_task += arg))
   426 
   427       val more_args = getopts(args)
   428       if (more_args.nonEmpty) getopts.usage()
   429 
   430       val progress = if (verbose) new Console_Progress() else No_Progress
   431 
   432       if (force) cronjob(progress, exclude_task)
   433       else error("Need to apply force to do anything")
   434     }
   435   }
   436 }