src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Tue Nov 14 13:56:38 2017 +0100 (21 months ago)
changeset 67070 85e6c1ff5be3
parent 67049 0bb8369d10d6
child 67075 eada9bd5fff2
permissions -rw-r--r--
removed pointless user_home: no measurable impact;
     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 build_log_dirs =
    28     List(Path.explode("~/log"), Path.explode("~/afp/log"), Path.explode("~/cronjob/log"))
    29 
    30 
    31 
    32   /** particular tasks **/
    33 
    34   /* identify Isabelle + AFP repository snapshots and build release */
    35 
    36   private val build_release =
    37     Logger_Task("build_release", logger =>
    38       {
    39         Isabelle_Devel.make_index()
    40 
    41         val rev = Mercurial.repository(isabelle_repos).id()
    42         val afp_rev = Mercurial.setup_repository(AFP.repos_source, afp_repos).id()
    43 
    44         File.write(logger.log_dir + Build_Log.log_filename("isabelle_identify", logger.start_date),
    45           Build_Log.Identify.content(logger.start_date, Some(rev), Some(afp_rev)))
    46 
    47         Isabelle_Devel.release_snapshot(rev = rev, afp_rev = afp_rev,
    48           parallel_jobs = 4, remote_mac = "macbroy31")
    49       })
    50 
    51 
    52   /* integrity test of build_history vs. build_history_base */
    53 
    54   private val build_history_base =
    55     Logger_Task("build_history_base", logger =>
    56       {
    57         val hg =
    58           Mercurial.setup_repository(
    59             File.standard_path(isabelle_repos), isabelle_repos_test)
    60         for {
    61           (result, log_path) <-
    62             Build_History.build_history(logger.options, isabelle_repos_test,
    63               rev = "build_history_base", fresh = true, build_args = List("HOL"))
    64         } {
    65           result.check
    66           File.move(log_path, logger.log_dir + log_path.base)
    67         }
    68       })
    69 
    70 
    71   /* remote build_history */
    72 
    73   sealed case class Item(
    74     known: Boolean,
    75     isabelle_version: String,
    76     afp_version: Option[String],
    77     pull_date: Date)
    78   {
    79     def unknown: Boolean = !known
    80     def versions: (String, Option[String]) = (isabelle_version, afp_version)
    81 
    82     def known_versions(rev: String, afp_rev: Option[String]): Boolean =
    83       known && rev != "" && isabelle_version == rev &&
    84       (afp_rev.isEmpty || afp_rev.get != "" && afp_version == afp_rev.get)
    85   }
    86 
    87   def recent_items(db: SQL.Database,
    88     days: Int, rev: String, afp_rev: Option[String], sql: SQL.Source): List[Item] =
    89   {
    90     val afp = afp_rev.isDefined
    91     val select =
    92       Build_Log.Data.select_recent_versions(
    93         days = days, rev = rev, afp_rev = afp_rev, sql = "WHERE " + sql)
    94 
    95     db.using_statement(select)(stmt =>
    96       stmt.execute_query().iterator(res =>
    97       {
    98         val known = res.bool(Build_Log.Data.known)
    99         val isabelle_version = res.string(Build_Log.Prop.isabelle_version)
   100         val afp_version = if (afp) proper_string(res.string(Build_Log.Prop.afp_version)) else None
   101         val pull_date = res.date(Build_Log.Data.pull_date(afp))
   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     slow: Boolean = false,
   125     detect: SQL.Source = "")
   126   {
   127     def sql: SQL.Source =
   128       Build_Log.Prop.build_engine + " = " + SQL.string(Build_History.engine) + " AND " +
   129       Build_Log.Prop.build_host + " = " + SQL.string(host) +
   130       (if (detect == "") "" else " AND " + SQL.enclose(detect))
   131 
   132     def profile: Build_Status.Profile =
   133       Build_Status.Profile(description, history = history, afp = afp, slow = slow, sql = sql)
   134 
   135     def pick(
   136       options: Options,
   137       rev: String = "",
   138       filter: Item => Boolean = _ => true): Option[(String, Option[String])] =
   139     {
   140       val afp_rev = if (afp) Some(Mercurial.repository(afp_repos).id()) else None
   141 
   142       val store = Build_Log.store(options)
   143       using(store.open_database())(db =>
   144       {
   145         def pick_days(days: Int, gap: Int): Option[(String, Option[String])] =
   146         {
   147           val items = recent_items(db, days, rev, afp_rev, sql).filter(filter)
   148           def runs = unknown_runs(items).filter(run => run.length >= gap)
   149 
   150           if (historic || items.exists(_.known_versions(rev, afp_rev))) {
   151             val longest_run =
   152               (List.empty[Item] /: runs)({ case (item1, item2) =>
   153                 if (item1.length >= item2.length) item1 else item2
   154               })
   155             if (longest_run.isEmpty) None
   156             else Some(longest_run(longest_run.length / 2).versions)
   157           }
   158           else if (rev != "") Some((rev, afp_rev))
   159           else runs.flatten.headOption.map(_.versions)
   160         }
   161 
   162         pick_days(options.int("build_log_history") max history, 2) orElse
   163         pick_days(200, 5) orElse
   164         pick_days(2000, 1)
   165       })
   166     }
   167   }
   168 
   169   val remote_builds_old: List[Remote_Build] =
   170     List(
   171       Remote_Build("Poly/ML 5.7 Linux", "lxbroy8",
   172         history_base = "37074e22e8be",
   173         options = "-m32 -B -M1x2,2 -t polyml-5.7 -i 'init_component /home/isabelle/contrib/polyml-5.7'",
   174         args = "-N -g timing",
   175         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7") + " AND " +
   176           Build_Log.Settings.ML_OPTIONS + " <> " + SQL.string("-H 500")),
   177       Remote_Build("Poly/ML 5.7.1 Linux", "lxbroy8",
   178         history_base = "a9d5b59c3e12",
   179         options = "-m32 -B -M1x2,2 -t polyml-5.7.1-pre2 -i 'init_component /home/isabelle/contrib/polyml-test-905dae2ebfda'",
   180         args = "-N -g timing",
   181         detect =
   182           Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1") + " OR " +
   183           Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre2")),
   184       Remote_Build("Poly/ML 5.7 Mac OS X", "macbroy2",
   185         history_base = "37074e22e8be",
   186         options = "-m32 -B -M1x4,4 -t polyml-5.7 -i 'init_component /home/isabelle/contrib/polyml-5.7'",
   187         args = "-a",
   188         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7")),
   189       Remote_Build("Poly/ML 5.7.1 Mac OS X", "macbroy2",
   190         history_base = "a9d5b59c3e12",
   191         options = "-m32 -B -M1x4,4 -t polyml-5.7.1-pre2 -i 'init_component /home/isabelle/contrib/polyml-test-905dae2ebfda'",
   192         args = "-a",
   193         detect =
   194         Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1") + " OR " +
   195         Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre2")),
   196       Remote_Build("Poly/ML test", "lxbroy8",
   197         options = "-m32 -B -M1x2,2 -t polyml-test -i 'init_component /home/isabelle/contrib/polyml-5.7-20170217'",
   198         args = "-N -g timing",
   199         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-test")),
   200       Remote_Build("Mac OS X 10.8 Mountain Lion", "macbroy30", options = "-m32 -M2", args = "-a",
   201         detect = Build_Log.Prop.build_start + " < date '2017-03-03'"))
   202 
   203 
   204   val remote_builds1: List[List[Remote_Build]] =
   205   {
   206     List(
   207       List(Remote_Build("Linux A", "lxbroy9",
   208         options = "-m32 -B -M1x2,2", args = "-N -g timing")),
   209       List(Remote_Build("Linux B", "lxbroy10", historic = true, history = 90,
   210         options = "-m32 -B -M1x4,2,4,6", args = "-N -g timing")),
   211       List(
   212         Remote_Build("Mac OS X 10.9 Mavericks", "macbroy2",
   213           options = "-m32 -M8" +
   214             " -e ISABELLE_GHC=ghc -e ISABELLE_MLTON=mlton -e ISABELLE_OCAML=ocaml" +
   215             " -e ISABELLE_OCAMLC=ocamlc -e ISABELLE_SMLNJ=/mnt/nfsbroy/home/smlnj/bin/sml",
   216           args = "-a",
   217           detect = Build_Log.Prop.build_tags.undefined),
   218         Remote_Build("Mac OS X 10.9 Mavericks, quick_and_dirty", "macbroy2",
   219           options = "-m32 -M8 -t quick_and_dirty", args = "-a -o quick_and_dirty",
   220           detect = Build_Log.Prop.build_tags + " = " + SQL.string("quick_and_dirty")),
   221         Remote_Build("Mac OS X 10.9 Mavericks, skip_proofs", "macbroy2",
   222           options = "-m32 -M8 -t skip_proofs", args = "-a -o skip_proofs",
   223           detect = Build_Log.Prop.build_tags + " = " + SQL.string("skip_proofs"))),
   224       List(
   225         Remote_Build("Mac OS X 10.12 Sierra", "macbroy30", options = "-m32 -M2", args = "-a",
   226           detect = Build_Log.Prop.build_start + " > date '2017-03-03'")),
   227       List(Remote_Build("Mac OS X 10.10 Yosemite", "macbroy31", options = "-m32 -M2", args = "-a")),
   228       List(
   229         Remote_Build("Windows", "vmnipkow9", historic = true, history = 90, shared_home = false,
   230           options = "-m32 -M4" +
   231             " -e ISABELLE_OCAML=ocaml -e ISABELLE_OCAMLC=ocamlc" +
   232             " -e ISABELLE_GHC=/usr/local/ghc-8.0.2/bin/ghc" +
   233             " -e ISABELLE_SMLNJ=/usr/local/smlnj-110.81/bin/sml",
   234           args = "-a",
   235           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86-windows")),
   236         Remote_Build("Windows", "vmnipkow9", historic = true, history = 90, shared_home = false,
   237           options = "-m64 -M4" +
   238             " -e ISABELLE_OCAML=ocaml -e ISABELLE_OCAMLC=ocamlc" +
   239             " -e ISABELLE_GHC=/usr/local/ghc-8.0.2/bin/ghc" +
   240             " -e ISABELLE_SMLNJ=/usr/local/smlnj-110.81/bin/sml",
   241           args = "-a",
   242           detect = Build_Log.Settings.ML_PLATFORM + " = " + SQL.string("x86_64-windows"))),
   243     ) :::
   244     {
   245       for { (host, n) <- List("lxbroy6" -> 1, "lxbroy7" -> 2) }
   246       yield {
   247         List(Remote_Build("AFP", host = host,
   248           options = "-m32 -M1x2 -t AFP -P" + n,
   249           args = "-N -X slow",
   250           afp = true,
   251           detect = Build_Log.Prop.build_tags + " = " + SQL.string("AFP")))
   252       }
   253     }
   254   }
   255 
   256   val remote_builds2: List[List[Remote_Build]] =
   257     List(
   258       List(
   259         Remote_Build("AFP slow", "lrzcloud1", shared_home = false,
   260           options = "-m64 -M6 -U30000 -s10 -t AFP",
   261           args = "-g slow",
   262           afp = true,
   263           slow = 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 = 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 
   442     def history_base_filter(r: Remote_Build): Item => Boolean =
   443     {
   444       val base_rev = hg.id(r.history_base)
   445       val nodes = hg_graph.all_succs(List(base_rev)).toSet
   446       (item: Item) => nodes(item.isabelle_version)
   447     }
   448 
   449 
   450     /* main */
   451 
   452     val main_start_date = Date.now()
   453     File.write(main_state_file, main_start_date + " " + log_service.hostname)
   454 
   455     run(main_start_date,
   456       Logger_Task("isabelle_cronjob", logger =>
   457         run_now(
   458           SEQ(List(build_release, build_history_base,
   459             PAR(List(remote_builds1, remote_builds2).map(remote_builds =>
   460               SEQ(List(
   461                 PAR(remote_builds.map(seq =>
   462                   SEQ(
   463                     for {
   464                       (r, i) <- (if (seq.length <= 1) seq.map((_, -1)) else seq.zipWithIndex)
   465                       (rev, afp_rev) <- r.pick(logger.options, hg.id(), history_base_filter(r))
   466                     } yield remote_build_history(rev, afp_rev, i, r)))),
   467                 Logger_Task("jenkins_logs", _ =>
   468                   Jenkins.download_logs(Jenkins.build_log_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 }