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