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