src/Pure/Admin/build_status.scala
author wenzelm
Sat May 27 12:33:14 2017 +0200 (2017-05-27)
changeset 65942 864a4892e43c
parent 65941 316c30b60ebc
child 65943 bf55ad5eaf75
permissions -rw-r--r--
clarified signature;
     1 /*  Title:      Pure/Admin/build_status.scala
     2     Author:     Makarius
     3 
     4 Present recent build status information from database.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 object Build_Status
    11 {
    12   /* defaults */
    13 
    14   val default_target_dir = Path.explode("build_status")
    15   val default_image_size = (800, 600)
    16   val default_history = 30
    17 
    18   def default_profiles: List[Profile] =
    19     Jenkins.build_status_profiles ::: Isabelle_Cronjob.build_status_profiles
    20 
    21 
    22   /* data profiles */
    23 
    24   sealed case class Profile(description: String, history: Int, sql: String)
    25   {
    26     def days(options: Options): Int = options.int("build_log_history") max history
    27 
    28     def stretch(options: Options): Double =
    29       (days(options) max default_history min (default_history * 5)).toDouble / default_history
    30 
    31     def select(options: Options, columns: List[SQL.Column], only_sessions: Set[String]): SQL.Source =
    32     {
    33       Build_Log.Data.universal_table.select(columns, distinct = true,
    34         sql = "WHERE " +
    35           Build_Log.Data.pull_date + " > " + Build_Log.Data.recent_time(days(options)) + " AND " +
    36           SQL.member(Build_Log.Data.status.ident,
    37             List(
    38               Build_Log.Session_Status.finished.toString,
    39               Build_Log.Session_Status.failed.toString)) +
    40           (if (only_sessions.isEmpty) ""
    41            else " AND " + SQL.member(Build_Log.Data.session_name.ident, only_sessions)) +
    42           " AND " + SQL.enclose(sql) +
    43           " ORDER BY " + Build_Log.Data.pull_date)
    44     }
    45   }
    46 
    47 
    48   /* build status */
    49 
    50   def build_status(options: Options,
    51     progress: Progress = No_Progress,
    52     profiles: List[Profile] = default_profiles,
    53     only_sessions: Set[String] = Set.empty,
    54     verbose: Boolean = false,
    55     target_dir: Path = default_target_dir,
    56     ml_statistics: Boolean = false,
    57     image_size: (Int, Int) = default_image_size)
    58   {
    59     val data =
    60       read_data(options, progress = progress, profiles = profiles,
    61         only_sessions = only_sessions, ml_statistics = ml_statistics, verbose = verbose)
    62 
    63     present_data(data, progress = progress, target_dir = target_dir, image_size = image_size)
    64   }
    65 
    66 
    67   /* read data */
    68 
    69   sealed case class Data(date: Date, entries: List[Data_Entry])
    70   sealed case class Data_Entry(
    71     name: String, hosts: List[String], stretch: Double, sessions: List[Session])
    72   {
    73     def failed_sessions: List[Session] =
    74       sessions.filter(_.head.failed).sortBy(_.name)
    75   }
    76   sealed case class Session(
    77     name: String, threads: Int, entries: List[Entry], ml_statistics: ML_Statistics)
    78   {
    79     require(entries.nonEmpty)
    80 
    81     def head: Entry = entries.head
    82     def order: Long = - head.timing.elapsed.ms
    83 
    84     def finished_entries: List[Entry] = entries.filter(_.finished)
    85 
    86     def check_timing: Boolean = finished_entries.length >= 3
    87     def check_heap: Boolean =
    88       finished_entries.length >= 3 &&
    89       finished_entries.forall(entry =>
    90         entry.maximum_heap > 0 ||
    91         entry.average_heap > 0 ||
    92         entry.stored_heap > 0)
    93   }
    94   sealed case class Entry(
    95     pull_date: Date,
    96     isabelle_version: String,
    97     afp_version: String,
    98     timing: Timing,
    99     ml_timing: Timing,
   100     maximum_heap: Long,
   101     average_heap: Long,
   102     stored_heap: Long,
   103     status: Build_Log.Session_Status.Value,
   104     errors: List[String])
   105   {
   106     def finished: Boolean = status == Build_Log.Session_Status.finished
   107     def failed: Boolean = status == Build_Log.Session_Status.failed
   108 
   109     def present_errors(name: String): XML.Body =
   110       if (errors.isEmpty) HTML.text(name + " (" + isabelle_version + ")")
   111       else {
   112         val tooltip_errors =
   113           errors.map(msg => HTML.error_message_class(HTML.pre(HTML.text(Symbol.decode(msg)))))
   114         val tooltip = List(HTML.tooltip_class(HTML.div(tooltip_errors)))
   115         HTML.error_class(HTML.span(HTML.text(name) ::: tooltip)) ::
   116         HTML.text(" (" + isabelle_version + ")")
   117       }
   118   }
   119 
   120   sealed case class Image(name: String, width: Int, height: Int)
   121   {
   122     def path: Path = Path.basic(name)
   123   }
   124 
   125   def read_data(options: Options,
   126     progress: Progress = No_Progress,
   127     profiles: List[Profile] = default_profiles,
   128     only_sessions: Set[String] = Set.empty,
   129     ml_statistics: Boolean = false,
   130     verbose: Boolean = false): Data =
   131   {
   132     val date = Date.now()
   133     var data_hosts = Map.empty[String, Set[String]]
   134     var data_stretch = Map.empty[String, Double]
   135     var data_entries = Map.empty[String, Map[String, Session]]
   136 
   137     def get_hosts(data_name: String): Set[String] =
   138       data_hosts.getOrElse(data_name, Set.empty)
   139 
   140     val store = Build_Log.store(options)
   141     using(store.open_database())(db =>
   142     {
   143       for (profile <- profiles.sortBy(_.description)) {
   144         progress.echo("input " + quote(profile.description))
   145 
   146         val columns =
   147           List(
   148             Build_Log.Data.pull_date,
   149             Build_Log.Prop.build_host,
   150             Build_Log.Prop.isabelle_version,
   151             Build_Log.Prop.afp_version,
   152             Build_Log.Settings.ISABELLE_BUILD_OPTIONS,
   153             Build_Log.Settings.ML_PLATFORM,
   154             Build_Log.Data.session_name,
   155             Build_Log.Data.threads,
   156             Build_Log.Data.timing_elapsed,
   157             Build_Log.Data.timing_cpu,
   158             Build_Log.Data.timing_gc,
   159             Build_Log.Data.ml_timing_elapsed,
   160             Build_Log.Data.ml_timing_cpu,
   161             Build_Log.Data.ml_timing_gc,
   162             Build_Log.Data.heap_size,
   163             Build_Log.Data.status,
   164             Build_Log.Data.errors) :::
   165           (if (ml_statistics) List(Build_Log.Data.ml_statistics) else Nil)
   166 
   167         val Threads_Option = """threads\s*=\s*(\d+)""".r
   168 
   169         val sql = profile.select(options, columns, only_sessions)
   170         if (verbose) progress.echo(sql)
   171 
   172         db.using_statement(sql)(stmt =>
   173         {
   174           val res = stmt.execute_query()
   175           while (res.next()) {
   176             val session_name = res.string(Build_Log.Data.session_name)
   177             val threads =
   178             {
   179               val threads1 =
   180                 res.string(Build_Log.Settings.ISABELLE_BUILD_OPTIONS) match {
   181                   case Threads_Option(Value.Int(i)) => i
   182                   case _ => 1
   183                 }
   184               val threads2 = res.get_int(Build_Log.Data.threads).getOrElse(1)
   185               threads1 max threads2
   186             }
   187             val ml_platform = res.string(Build_Log.Settings.ML_PLATFORM)
   188             val data_name =
   189               profile.description +
   190                 (if (ml_platform.startsWith("x86_64")) ", 64bit" else "") +
   191                 (if (threads == 1) "" else ", " + threads + " threads")
   192 
   193             res.get_string(Build_Log.Prop.build_host).foreach(host =>
   194               data_hosts += (data_name -> (get_hosts(data_name) + host)))
   195 
   196             data_stretch += (data_name -> profile.stretch(options))
   197 
   198             val isabelle_version = res.string(Build_Log.Prop.isabelle_version)
   199 
   200             val ml_stats =
   201               ML_Statistics(
   202                 if (ml_statistics)
   203                   Properties.uncompress(res.bytes(Build_Log.Data.ml_statistics))
   204                 else Nil, heading = session_name + " (Isabelle/" + isabelle_version + ")")
   205 
   206             val entry =
   207               Entry(
   208                 pull_date = res.date(Build_Log.Data.pull_date),
   209                 isabelle_version = isabelle_version,
   210                 afp_version = res.string(Build_Log.Prop.afp_version),
   211                 timing =
   212                   res.timing(
   213                     Build_Log.Data.timing_elapsed,
   214                     Build_Log.Data.timing_cpu,
   215                     Build_Log.Data.timing_gc),
   216                 ml_timing =
   217                   res.timing(
   218                     Build_Log.Data.ml_timing_elapsed,
   219                     Build_Log.Data.ml_timing_cpu,
   220                     Build_Log.Data.ml_timing_gc),
   221                 maximum_heap = ml_stats.maximum_heap_size,
   222                 average_heap = ml_stats.average_heap_size,
   223                 stored_heap = ML_Statistics.heap_scale(res.long(Build_Log.Data.heap_size)),
   224                 status = Build_Log.Session_Status.withName(res.string(Build_Log.Data.status)),
   225                 errors = Build_Log.uncompress_errors(res.bytes(Build_Log.Data.errors)))
   226 
   227             val sessions = data_entries.getOrElse(data_name, Map.empty)
   228             val entries = sessions.get(session_name).map(_.entries) getOrElse Nil
   229             val session = Session(session_name, threads, entry :: entries, ml_stats)
   230             data_entries += (data_name -> (sessions + (session_name -> session)))
   231           }
   232         })
   233       }
   234     })
   235 
   236     val sorted_entries =
   237       (for {
   238         (name, sessions) <- data_entries.toList
   239         sorted_sessions <- proper_list(sessions.toList.map(_._2).sortBy(_.order))
   240       }
   241       yield {
   242         val hosts = get_hosts(name).toList.sorted
   243         val stretch = data_stretch(name)
   244         Data_Entry(name, hosts, stretch, sorted_sessions)
   245       }).sortBy(_.name)
   246 
   247     Data(date, sorted_entries)
   248   }
   249 
   250 
   251   /* present data */
   252 
   253   def present_data(data: Data,
   254     progress: Progress = No_Progress,
   255     target_dir: Path = default_target_dir,
   256     image_size: (Int, Int) = default_image_size)
   257   {
   258     def clean_name(name: String): String =
   259       name.flatMap(c => if (c == ' ' || c == '/') "_" else if (c == ',') "" else c.toString)
   260 
   261     def print_heap(x: Long): Option[String] =
   262       if (x == 0L) None else Some(x.toString + " M")
   263 
   264     HTML.write_document(target_dir, "index.html",
   265       List(HTML.title("Isabelle build status"),
   266         HTML.style("pre { margin: 1px; white-space: pre-wrap; }")),
   267       List(HTML.chapter("Isabelle build status"),
   268         HTML.par(
   269           List(HTML.description(
   270             List(HTML.text("status date:") -> HTML.text(data.date.toString))))),
   271         HTML.par(
   272           List(HTML.itemize(data.entries.map({ case data_entry =>
   273             List(
   274               HTML.link(clean_name(data_entry.name) + "/index.html",
   275                 HTML.text(data_entry.name))) :::
   276             (data_entry.failed_sessions match {
   277               case Nil => Nil
   278               case sessions =>
   279                 HTML.break :::
   280                 List(HTML.error_message_class(HTML.span(HTML.text("Failed sessions:")))) :::
   281                 List(HTML.itemize(sessions.map(s => s.head.present_errors(s.name))))
   282             })
   283           }))))))
   284 
   285     for (data_entry <- data.entries) {
   286       val data_name = data_entry.name
   287 
   288       val (image_width, image_height) = image_size
   289       val image_width_stretch = (image_width * data_entry.stretch).toInt
   290 
   291       progress.echo("output " + quote(data_name))
   292 
   293       val dir = target_dir + Path.basic(clean_name(data_name))
   294       Isabelle_System.mkdirs(dir)
   295 
   296       val session_plots =
   297         Par_List.map((session: Session) =>
   298           Isabelle_System.with_tmp_file(session.name, "data") { data_file =>
   299             Isabelle_System.with_tmp_file(session.name, "gnuplot") { gnuplot_file =>
   300 
   301               def plot_name(kind: String): String = session.name + "_" + kind + ".png"
   302 
   303               File.write(data_file,
   304                 cat_lines(
   305                   session.finished_entries.map(entry =>
   306                     List(entry.pull_date.unix_epoch,
   307                       entry.timing.elapsed.minutes,
   308                       entry.timing.resources.minutes,
   309                       entry.ml_timing.elapsed.minutes,
   310                       entry.ml_timing.resources.minutes,
   311                       entry.maximum_heap,
   312                       entry.average_heap,
   313                       entry.stored_heap).mkString(" "))))
   314 
   315               val max_time =
   316                 ((0.0 /: session.finished_entries){ case (m, entry) =>
   317                   m.max(entry.timing.elapsed.minutes).
   318                     max(entry.timing.resources.minutes).
   319                     max(entry.ml_timing.elapsed.minutes).
   320                     max(entry.ml_timing.resources.minutes) } max 0.1) * 1.1
   321               val timing_range = "[0:" + max_time + "]"
   322 
   323               def gnuplot(plot_name: String, plots: List[String], range: String): Image =
   324               {
   325                 val image = Image(plot_name, image_width_stretch, image_height)
   326 
   327                 File.write(gnuplot_file, """
   328 set terminal png size """ + image.width + "," + image.height + """
   329 set output """ + quote(File.standard_path(dir + image.path)) + """
   330 set xdata time
   331 set timefmt "%s"
   332 set format x "%d-%b"
   333 set xlabel """ + quote(session.name) + """ noenhanced
   334 set key left bottom
   335 plot [] """ + range + " " +
   336                 plots.map(s => quote(data_file.implode) + " " + s).mkString(", ") + "\n")
   337 
   338                 val result =
   339                   Isabelle_System.bash("\"$ISABELLE_GNUPLOT\" " + File.bash_path(gnuplot_file))
   340                 if (!result.ok)
   341                   result.error("Gnuplot failed for " + data_name + "/" + plot_name).check
   342 
   343                 image
   344               }
   345 
   346               val timing_plots =
   347               {
   348                 val plots1 =
   349                   List(
   350                     """ using 1:2 smooth sbezier title "elapsed time (smooth)" """,
   351                     """ using 1:2 smooth csplines title "elapsed time" """)
   352                 val plots2 =
   353                   List(
   354                     """ using 1:3 smooth sbezier title "cpu time (smooth)" """,
   355                     """ using 1:3 smooth csplines title "cpu time" """)
   356                 if (session.threads == 1) plots1 else plots1 ::: plots2
   357               }
   358 
   359               val ml_timing_plots =
   360                 List(
   361                   """ using 1:4 smooth sbezier title "ML elapsed time (smooth)" """,
   362                   """ using 1:4 smooth csplines title "ML elapsed time" """,
   363                   """ using 1:5 smooth sbezier title "ML cpu time (smooth)" """,
   364                   """ using 1:5 smooth csplines title "ML cpu time" """)
   365 
   366               val heap_plots =
   367                 List(
   368                   """ using 1:6 smooth sbezier title "maximum heap (smooth)" """,
   369                   """ using 1:6 smooth csplines title "maximum heap" """,
   370                   """ using 1:7 smooth sbezier title "average heap (smooth)" """,
   371                   """ using 1:7 smooth csplines title "average heap" """,
   372                   """ using 1:8 smooth sbezier title "stored heap (smooth)" """,
   373                   """ using 1:8 smooth csplines title "stored heap" """)
   374 
   375               def jfreechart(plot_name: String, fields: ML_Statistics.Fields): Image =
   376               {
   377                 val image = Image(plot_name, image_width, image_height)
   378                 val chart =
   379                   session.ml_statistics.chart(
   380                     fields._1 + ": " + session.ml_statistics.heading, fields._2)
   381                 Graphics_File.write_chart_png(
   382                   (dir + image.path).file, chart, image.width, image.height)
   383                 image
   384               }
   385 
   386               val images =
   387                 (if (session.check_timing)
   388                   List(
   389                     gnuplot(plot_name("timing"), timing_plots, timing_range),
   390                     gnuplot(plot_name("ml_timing"), ml_timing_plots, timing_range))
   391                  else Nil) :::
   392                 (if (session.check_heap)
   393                   List(gnuplot(plot_name("heap"), heap_plots, "[0:]"))
   394                  else Nil) :::
   395                 (if (session.ml_statistics.content.nonEmpty)
   396                   List(jfreechart(plot_name("heap_chart"), ML_Statistics.heap_fields)) :::
   397                   (if (session.threads > 1)
   398                     List(
   399                       jfreechart(plot_name("tasks_chart"), ML_Statistics.tasks_fields),
   400                       jfreechart(plot_name("workers_chart"), ML_Statistics.workers_fields))
   401                    else Nil)
   402                  else Nil)
   403 
   404               session.name -> images
   405             }
   406           }, data_entry.sessions).toMap
   407 
   408       HTML.write_document(dir, "index.html",
   409         List(HTML.title("Isabelle build status for " + data_name)),
   410         HTML.chapter("Isabelle build status for " + data_name) ::
   411         HTML.par(
   412           List(HTML.description(
   413             List(
   414               HTML.text("status date:") -> HTML.text(data.date.toString),
   415               HTML.text("build host:") -> HTML.text(commas(data_entry.hosts)))))) ::
   416         HTML.par(
   417           List(HTML.itemize(
   418             data_entry.sessions.map(session =>
   419               HTML.link("#session_" + session.name, HTML.text(session.name)) ::
   420               HTML.text(" (" + session.head.timing.message_resources + ")"))))) ::
   421         data_entry.sessions.flatMap(session =>
   422           List(
   423             HTML.id("session_" + session.name)(HTML.section(session.name)),
   424             HTML.par(
   425               HTML.description(
   426                 List(
   427                   HTML.text("timing:") -> HTML.text(session.head.timing.message_resources),
   428                   HTML.text("ML timing:") -> HTML.text(session.head.ml_timing.message_resources)) :::
   429                 print_heap(session.head.maximum_heap).map(s =>
   430                   HTML.text("maximum heap:") -> HTML.text(s)).toList :::
   431                 print_heap(session.head.average_heap).map(s =>
   432                   HTML.text("average heap:") -> HTML.text(s)).toList :::
   433                 print_heap(session.head.stored_heap).map(s =>
   434                   HTML.text("stored heap:") -> HTML.text(s)).toList :::
   435                 proper_string(session.head.isabelle_version).map(s =>
   436                   HTML.text("Isabelle version:") -> HTML.text(s)).toList :::
   437                 proper_string(session.head.afp_version).map(s =>
   438                   HTML.text("AFP version:") -> HTML.text(s)).toList) ::
   439               session_plots.getOrElse(session.name, Nil).map(image =>
   440                 HTML.width(image.width / 2)(HTML.height(image.height / 2)(
   441                   HTML.image(image.name))))))))
   442     }
   443   }
   444 
   445 
   446   /* Isabelle tool wrapper */
   447 
   448   val isabelle_tool =
   449     Isabelle_Tool("build_status", "present recent build status information from database", args =>
   450     {
   451       var target_dir = default_target_dir
   452       var ml_statistics = false
   453       var only_sessions = Set.empty[String]
   454       var options = Options.init()
   455       var image_size = default_image_size
   456       var verbose = false
   457 
   458       val getopts = Getopts("""
   459 Usage: isabelle build_status [OPTIONS]
   460 
   461   Options are:
   462     -D DIR       target directory (default """ + default_target_dir + """)
   463     -M           include full ML statistics
   464     -S SESSIONS  only given SESSIONS (comma separated)
   465     -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
   466     -s WxH       size of PNG image (default """ + image_size._1 + "x" + image_size._2 + """)
   467     -v           verbose
   468 
   469   Present performance statistics from build log database, which is specified
   470   via system options build_log_database_host, build_log_database_user,
   471   build_log_history etc.
   472 """,
   473         "D:" -> (arg => target_dir = Path.explode(arg)),
   474         "M" -> (_ => ml_statistics = true),
   475         "S:" -> (arg => only_sessions = space_explode(',', arg).toSet),
   476         "o:" -> (arg => options = options + arg),
   477         "s:" -> (arg =>
   478           space_explode('x', arg).map(Value.Int.parse(_)) match {
   479             case List(w, h) if w > 0 && h > 0 => image_size = (w, h)
   480             case _ => error("Error bad PNG image size: " + quote(arg))
   481           }),
   482         "v" -> (_ => verbose = true))
   483 
   484       val more_args = getopts(args)
   485       if (more_args.nonEmpty) getopts.usage()
   486 
   487       val progress = new Console_Progress
   488 
   489       build_status(options, progress = progress, only_sessions = only_sessions, verbose = verbose,
   490         target_dir = target_dir, ml_statistics = ml_statistics, image_size = image_size)
   491 
   492   }, admin = true)
   493 }