src/Pure/Admin/isabelle_cronjob.scala
author wenzelm
Tue Nov 14 21:16:57 2017 +0100 (18 months ago)
changeset 67075 eada9bd5fff2
parent 67070 85e6c1ff5be3
child 67080 2c0f24e927dd
permissions -rw-r--r--
avoid lxbroy7, which is presently inaccessible, but retain its build history in db queries;
     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   {
   128     def sql: SQL.Source =
   129       Build_Log.Prop.build_engine + " = " + SQL.string(Build_History.engine) + " AND " +
   130       SQL.member(Build_Log.Prop.build_host.ident, host :: more_hosts) +
   131       (if (detect == "") "" else " AND " + SQL.enclose(detect))
   132 
   133     def profile: Build_Status.Profile =
   134       Build_Status.Profile(description, history = history, afp = afp, slow = slow, 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.1 Linux", "lxbroy8",
   179         history_base = "a9d5b59c3e12",
   180         options = "-m32 -B -M1x2,2 -t polyml-5.7.1-pre2 -i 'init_component /home/isabelle/contrib/polyml-test-905dae2ebfda'",
   181         args = "-N -g timing",
   182         detect =
   183           Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1") + " OR " +
   184           Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre2")),
   185       Remote_Build("Poly/ML 5.7 Mac OS X", "macbroy2",
   186         history_base = "37074e22e8be",
   187         options = "-m32 -B -M1x4,4 -t polyml-5.7 -i 'init_component /home/isabelle/contrib/polyml-5.7'",
   188         args = "-a",
   189         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7")),
   190       Remote_Build("Poly/ML 5.7.1 Mac OS X", "macbroy2",
   191         history_base = "a9d5b59c3e12",
   192         options = "-m32 -B -M1x4,4 -t polyml-5.7.1-pre2 -i 'init_component /home/isabelle/contrib/polyml-test-905dae2ebfda'",
   193         args = "-a",
   194         detect =
   195         Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre1") + " OR " +
   196         Build_Log.Prop.build_tags + " = " + SQL.string("polyml-5.7.1-pre2")),
   197       Remote_Build("Poly/ML test", "lxbroy8",
   198         options = "-m32 -B -M1x2,2 -t polyml-test -i 'init_component /home/isabelle/contrib/polyml-5.7-20170217'",
   199         args = "-N -g timing",
   200         detect = Build_Log.Prop.build_tags + " = " + SQL.string("polyml-test")),
   201       Remote_Build("Mac OS X 10.8 Mountain Lion", "macbroy30", options = "-m32 -M2", args = "-a",
   202         detect = Build_Log.Prop.build_start + " < date '2017-03-03'"))
   203 
   204 
   205   val remote_builds1: List[List[Remote_Build]] =
   206   {
   207     List(
   208       List(Remote_Build("Linux A", "lxbroy9",
   209         options = "-m32 -B -M1x2,2", args = "-N -g timing")),
   210       List(Remote_Build("Linux B", "lxbroy10", historic = true, history = 90,
   211         options = "-m32 -B -M1x4,2,4,6", args = "-N -g timing")),
   212       List(
   213         Remote_Build("Mac OS X 10.9 Mavericks", "macbroy2",
   214           options = "-m32 -M8" +
   215             " -e ISABELLE_GHC=ghc -e ISABELLE_MLTON=mlton -e ISABELLE_OCAML=ocaml" +
   216             " -e ISABELLE_OCAMLC=ocamlc -e ISABELLE_SMLNJ=/mnt/nfsbroy/home/smlnj/bin/sml",
   217           args = "-a",
   218           detect = Build_Log.Prop.build_tags.undefined),
   219         Remote_Build("Mac OS X 10.9 Mavericks, quick_and_dirty", "macbroy2",
   220           options = "-m32 -M8 -t quick_and_dirty", args = "-a -o quick_and_dirty",
   221           detect = Build_Log.Prop.build_tags + " = " + SQL.string("quick_and_dirty")),
   222         Remote_Build("Mac OS X 10.9 Mavericks, skip_proofs", "macbroy2",
   223           options = "-m32 -M8 -t skip_proofs", args = "-a -o skip_proofs",
   224           detect = Build_Log.Prop.build_tags + " = " + SQL.string("skip_proofs"))),
   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 { (n, hosts) <- List(1 -> List("lxbroy6"), 2 -> List("lxbroy8", "lxbroy7")) }
   247       yield {
   248         List(Remote_Build("AFP", host = hosts.head, more_hosts = hosts.tail,
   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           slow = true,
   265           detect = Build_Log.Prop.build_tags + " = " + SQL.string("AFP"))))
   266 
   267   private def remote_build_history(
   268     rev: String, afp_rev: Option[String], i: Int, r: Remote_Build): Logger_Task =
   269   {
   270     val task_name = "build_history-" + r.host
   271     Logger_Task(task_name, logger =>
   272       {
   273         using(logger.ssh_context.open_session(host = r.host, user = r.user, port = r.port))(
   274           ssh =>
   275             {
   276               val self_update = !r.shared_home
   277               val push_isabelle_home = self_update && Mercurial.is_repository(Path.explode("~~"))
   278 
   279               val results =
   280                 Build_History.remote_build_history(ssh,
   281                   isabelle_repos,
   282                   isabelle_repos.ext(r.host),
   283                   isabelle_identifier = "cronjob_build_history",
   284                   self_update = self_update,
   285                   push_isabelle_home = push_isabelle_home,
   286                   rev = rev,
   287                   afp_rev = afp_rev,
   288                   options =
   289                     " -N " + Bash.string(task_name) + (if (i < 0) "" else "_" + (i + 1).toString) +
   290                     " -f " + r.options,
   291                   args = "-o timeout=10800 " + r.args)
   292 
   293               for ((log_name, bytes) <- results) {
   294                 logger.log(Date.now(), log_name)
   295                 Bytes.write(logger.log_dir + Path.explode(log_name), bytes)
   296               }
   297             })
   298       })
   299   }
   300 
   301   val build_status_profiles: List[Build_Status.Profile] =
   302     (remote_builds_old :: remote_builds1 ::: remote_builds2).flatten.map(_.profile)
   303 
   304 
   305 
   306   /** task logging **/
   307 
   308   sealed case class Logger_Task(name: String = "", body: Logger => Unit)
   309 
   310   class Log_Service private[Isabelle_Cronjob](progress: Progress, val ssh_context: SSH.Context)
   311   {
   312     current_log.file.delete
   313 
   314     private val thread: Consumer_Thread[String] =
   315       Consumer_Thread.fork("cronjob: logger", daemon = true)(
   316         consume = (text: String) =>
   317           { // critical
   318             File.append(current_log, text + "\n")
   319             File.append(cumulative_log, text + "\n")
   320             progress.echo(text)
   321             true
   322           })
   323 
   324     def shutdown() { thread.shutdown() }
   325 
   326     val hostname = Isabelle_System.hostname()
   327 
   328     def log(date: Date, task_name: String, msg: String): Unit =
   329       if (task_name != "")
   330         thread.send(
   331           "[" + Build_Log.print_date(date) + ", " + hostname + ", " + task_name + "]: " + msg)
   332 
   333     def start_logger(start_date: Date, task_name: String): Logger =
   334       new Logger(this, start_date, task_name)
   335 
   336     def run_task(start_date: Date, task: Logger_Task)
   337     {
   338       val logger = start_logger(start_date, task.name)
   339       val res = Exn.capture { task.body(logger) }
   340       val end_date = Date.now()
   341       val err =
   342         res match {
   343           case Exn.Res(_) => None
   344           case Exn.Exn(exn) =>
   345             System.err.println("Exception trace for " + quote(task.name) + ":")
   346             exn.printStackTrace()
   347             val first_line = split_lines(Exn.message(exn)).headOption getOrElse "exception"
   348             Some(first_line)
   349         }
   350       logger.log_end(end_date, err)
   351     }
   352 
   353     def fork_task(start_date: Date, task: Logger_Task): Task =
   354       new Task(task.name, run_task(start_date, task))
   355   }
   356 
   357   class Logger private[Isabelle_Cronjob](
   358     val log_service: Log_Service, val start_date: Date, val task_name: String)
   359   {
   360     def ssh_context: SSH.Context = log_service.ssh_context
   361     def options: Options = ssh_context.options
   362 
   363     def log(date: Date, msg: String): Unit = log_service.log(date, task_name, msg)
   364 
   365     def log_end(end_date: Date, err: Option[String])
   366     {
   367       val elapsed_time = end_date.time - start_date.time
   368       val msg =
   369         (if (err.isEmpty) "finished" else "ERROR " + err.get) +
   370         (if (elapsed_time.seconds < 3.0) "" else " (" + elapsed_time.message_hms + " elapsed time)")
   371       log(end_date, msg)
   372     }
   373 
   374     val log_dir: Path = main_dir + Build_Log.log_subdir(start_date)
   375 
   376     Isabelle_System.mkdirs(log_dir)
   377     log(start_date, "started")
   378   }
   379 
   380   class Task private[Isabelle_Cronjob](name: String, body: => Unit)
   381   {
   382     private val future: Future[Unit] = Future.thread("cronjob: " + name) { body }
   383     def is_finished: Boolean = future.is_finished
   384   }
   385 
   386 
   387 
   388   /** cronjob **/
   389 
   390   def cronjob(progress: Progress, exclude_task: Set[String])
   391   {
   392     /* soft lock */
   393 
   394     val still_running =
   395       try { Some(File.read(main_state_file)) }
   396       catch { case ERROR(_) => None }
   397 
   398     still_running match {
   399       case None | Some("") =>
   400       case Some(running) =>
   401         error("Isabelle cronjob appears to be still running: " + running)
   402     }
   403 
   404 
   405     /* log service */
   406 
   407     val log_service = new Log_Service(progress, SSH.init_context(Options.init()))
   408 
   409     def run(start_date: Date, task: Logger_Task) { log_service.run_task(start_date, task) }
   410 
   411     def run_now(task: Logger_Task) { run(Date.now(), task) }
   412 
   413 
   414     /* structured tasks */
   415 
   416     def SEQ(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   417       for (task <- tasks.iterator if !exclude_task(task.name) || task.name == "")
   418         run_now(task))
   419 
   420     def PAR(tasks: List[Logger_Task]): Logger_Task = Logger_Task(body = _ =>
   421       {
   422         @tailrec def join(running: List[Task])
   423         {
   424           running.partition(_.is_finished) match {
   425             case (Nil, Nil) =>
   426             case (Nil, _ :: _) => Thread.sleep(500); join(running)
   427             case (_ :: _, remaining) => join(remaining)
   428           }
   429         }
   430         val start_date = Date.now()
   431         val running =
   432           for (task <- tasks if !exclude_task(task.name))
   433             yield log_service.fork_task(start_date, task)
   434         join(running)
   435       })
   436 
   437 
   438     /* repository structure */
   439 
   440     val hg = Mercurial.repository(isabelle_repos)
   441     val hg_graph = hg.graph()
   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                       (rev, afp_rev) <- r.pick(logger.options, hg.id(), history_base_filter(r))
   467                     } yield remote_build_history(rev, afp_rev, i, r)))),
   468                 Logger_Task("jenkins_logs", _ =>
   469                   Jenkins.download_logs(Jenkins.build_log_jobs, main_dir)),
   470                 Logger_Task("build_log_database",
   471                   logger => Isabelle_Devel.build_log_database(logger.options, build_log_dirs)),
   472                 Logger_Task("build_status",
   473                   logger => Isabelle_Devel.build_status(logger.options)))))))))))
   474 
   475     log_service.shutdown()
   476 
   477     main_state_file.file.delete
   478   }
   479 
   480 
   481 
   482   /** command line entry point **/
   483 
   484   def main(args: Array[String])
   485   {
   486     Command_Line.tool0 {
   487       var force = false
   488       var verbose = false
   489       var exclude_task = Set.empty[String]
   490 
   491       val getopts = Getopts("""
   492 Usage: Admin/cronjob/main [OPTIONS]
   493 
   494   Options are:
   495     -f           apply force to do anything
   496     -v           verbose
   497     -x NAME      exclude tasks with this name
   498 """,
   499         "f" -> (_ => force = true),
   500         "v" -> (_ => verbose = true),
   501         "x:" -> (arg => exclude_task += arg))
   502 
   503       val more_args = getopts(args)
   504       if (more_args.nonEmpty) getopts.usage()
   505 
   506       val progress = if (verbose) new Console_Progress() else No_Progress
   507 
   508       if (force) cronjob(progress, exclude_task)
   509       else error("Need to apply force to do anything")
   510     }
   511   }
   512 }