1/*  Title:      Pure/Admin/build_status.scala
2    Author:     Makarius
3
4Present recent build status information from database.
5*/
6
7package isabelle
8
9
10object 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(
25    description: String, history: Int = 0, afp: Boolean = false, bulky: Boolean = false, sql: String)
26  {
27    def days(options: Options): Int = options.int("build_log_history") max history
28
29    def stretch(options: Options): Double =
30      (days(options) max default_history min (default_history * 5)).toDouble / default_history
31
32    def select(options: Options, columns: List[SQL.Column], only_sessions: Set[String]): SQL.Source =
33    {
34      Build_Log.Data.universal_table.select(columns, distinct = true,
35        sql = "WHERE " +
36          Build_Log.Data.pull_date(afp) + " > " + Build_Log.Data.recent_time(days(options)) +
37          " AND " +
38          SQL.member(Build_Log.Data.status.ident,
39            List(
40              Build_Log.Session_Status.finished.toString,
41              Build_Log.Session_Status.failed.toString)) +
42          (if (only_sessions.isEmpty) ""
43           else " AND " + SQL.member(Build_Log.Data.session_name.ident, only_sessions)) +
44          " AND " + SQL.enclose(sql))
45    }
46  }
47
48
49  /* build status */
50
51  def build_status(options: Options,
52    progress: Progress = No_Progress,
53    profiles: List[Profile] = default_profiles,
54    only_sessions: Set[String] = Set.empty,
55    verbose: Boolean = false,
56    target_dir: Path = default_target_dir,
57    ml_statistics: Boolean = false,
58    image_size: (Int, Int) = default_image_size)
59  {
60    val ml_statistics_domain =
61      Iterator(ML_Statistics.heap_fields, ML_Statistics.program_fields, ML_Statistics.tasks_fields,
62        ML_Statistics.workers_fields).flatMap(_._2).toSet
63
64    val data =
65      read_data(options, progress = progress, profiles = profiles,
66        only_sessions = only_sessions, verbose = verbose,
67        ml_statistics = ml_statistics, ml_statistics_domain = ml_statistics_domain)
68
69    present_data(data, progress = progress, target_dir = target_dir, image_size = image_size)
70  }
71
72
73  /* read data */
74
75  sealed case class Data(date: Date, entries: List[Data_Entry])
76  sealed case class Data_Entry(
77    name: String, hosts: List[String], stretch: Double, sessions: List[Session])
78  {
79    def failed_sessions: List[Session] =
80      sessions.filter(_.head.failed).sortBy(_.name)
81  }
82  sealed case class Session(
83    name: String, threads: Int, entries: List[Entry],
84    ml_statistics: ML_Statistics, ml_statistics_date: Long)
85  {
86    require(entries.nonEmpty)
87
88    lazy val sorted_entries: List[Entry] = entries.sortBy(entry => - entry.date)
89
90    def head: Entry = sorted_entries.head
91    def order: Long = - head.timing.elapsed.ms
92
93    def finished_entries: List[Entry] = sorted_entries.filter(_.finished)
94    def finished_entries_size: Int = finished_entries.map(_.date).toSet.size
95
96    def check_timing: Boolean = finished_entries_size >= 3
97    def check_heap: Boolean =
98      finished_entries_size >= 3 &&
99      finished_entries.forall(entry =>
100        entry.maximum_heap > 0 ||
101        entry.average_heap > 0 ||
102        entry.stored_heap > 0)
103
104    def make_csv: CSV.File =
105    {
106      val header =
107        List("session_name",
108          "chapter",
109          "pull_date",
110          "afp_pull_date",
111          "isabelle_version",
112          "afp_version",
113          "timing_elapsed",
114          "timing_cpu",
115          "timing_gc",
116          "ml_timing_elapsed",
117          "ml_timing_cpu",
118          "ml_timing_gc",
119          "maximum_code",
120          "average_code",
121          "maximum_stack",
122          "average_stack",
123          "maximum_heap",
124          "average_heap",
125          "stored_heap",
126          "status")
127      val date_format = Date.Format("uuuu-MM-dd HH:mm:ss")
128      val records =
129        for (entry <- sorted_entries) yield {
130          CSV.Record(name,
131            entry.chapter,
132            date_format(entry.pull_date),
133            entry.afp_pull_date match { case Some(date) => date_format(date) case None => "" },
134            entry.isabelle_version,
135            entry.afp_version,
136            entry.timing.elapsed.ms,
137            entry.timing.cpu.ms,
138            entry.timing.gc.ms,
139            entry.ml_timing.elapsed.ms,
140            entry.ml_timing.cpu.ms,
141            entry.ml_timing.gc.ms,
142            entry.maximum_code,
143            entry.average_code,
144            entry.maximum_stack,
145            entry.average_stack,
146            entry.maximum_heap,
147            entry.average_heap,
148            entry.stored_heap,
149            entry.status)
150        }
151      CSV.File(name, header, records)
152    }
153  }
154  sealed case class Entry(
155    chapter: String,
156    pull_date: Date,
157    afp_pull_date: Option[Date],
158    isabelle_version: String,
159    afp_version: String,
160    timing: Timing,
161    ml_timing: Timing,
162    maximum_code: Long,
163    average_code: Long,
164    maximum_stack: Long,
165    average_stack: Long,
166    maximum_heap: Long,
167    average_heap: Long,
168    stored_heap: Long,
169    status: Build_Log.Session_Status.Value,
170    errors: List[String])
171  {
172    val date: Long = (afp_pull_date getOrElse pull_date).unix_epoch
173
174    def finished: Boolean = status == Build_Log.Session_Status.finished
175    def failed: Boolean = status == Build_Log.Session_Status.failed
176
177    def present_errors(name: String): XML.Body =
178    {
179      if (errors.isEmpty)
180        HTML.text(name + print_version(isabelle_version, afp_version, chapter))
181      else {
182        HTML.tooltip_errors(HTML.text(name), errors.map(s => HTML.text(Symbol.decode(s)))) ::
183          HTML.text(print_version(isabelle_version, afp_version, chapter))
184      }
185    }
186  }
187
188  sealed case class Image(name: String, width: Int, height: Int)
189  {
190    def path: Path = Path.basic(name)
191  }
192
193  def print_version(
194    isabelle_version: String, afp_version: String = "", chapter: String = AFP.chapter): String =
195  {
196    val body =
197      proper_string(isabelle_version).map("Isabelle/" + _).toList :::
198      (if (chapter == AFP.chapter) proper_string(afp_version).map("AFP/" + _) else None).toList
199    if (body.isEmpty) "" else body.mkString(" (", ", ", ")")
200  }
201
202  def read_data(options: Options,
203    progress: Progress = No_Progress,
204    profiles: List[Profile] = default_profiles,
205    only_sessions: Set[String] = Set.empty,
206    ml_statistics: Boolean = false,
207    ml_statistics_domain: String => Boolean = (key: String) => true,
208    verbose: Boolean = false): Data =
209  {
210    val date = Date.now()
211    var data_hosts = Map.empty[String, Set[String]]
212    var data_stretch = Map.empty[String, Double]
213    var data_entries = Map.empty[String, Map[String, Session]]
214
215    def get_hosts(data_name: String): Set[String] =
216      data_hosts.getOrElse(data_name, Set.empty)
217
218    val store = Build_Log.store(options)
219
220    using(store.open_database())(db =>
221    {
222      for (profile <- profiles.sortBy(_.description)) {
223        progress.echo("input " + quote(profile.description))
224
225        val afp = profile.afp
226        val columns =
227          List(
228            Build_Log.Data.pull_date(afp = false),
229            Build_Log.Data.pull_date(afp = true),
230            Build_Log.Prop.build_host,
231            Build_Log.Prop.isabelle_version,
232            Build_Log.Prop.afp_version,
233            Build_Log.Settings.ISABELLE_BUILD_OPTIONS,
234            Build_Log.Settings.ML_PLATFORM,
235            Build_Log.Data.session_name,
236            Build_Log.Data.chapter,
237            Build_Log.Data.groups,
238            Build_Log.Data.threads,
239            Build_Log.Data.timing_elapsed,
240            Build_Log.Data.timing_cpu,
241            Build_Log.Data.timing_gc,
242            Build_Log.Data.ml_timing_elapsed,
243            Build_Log.Data.ml_timing_cpu,
244            Build_Log.Data.ml_timing_gc,
245            Build_Log.Data.heap_size,
246            Build_Log.Data.status,
247            Build_Log.Data.errors) :::
248          (if (ml_statistics) List(Build_Log.Data.ml_statistics) else Nil)
249
250        val Threads_Option = """threads\s*=\s*(\d+)""".r
251
252        val sql = profile.select(options, columns, only_sessions)
253        if (verbose) progress.echo(sql)
254
255        db.using_statement(sql)(stmt =>
256        {
257          val res = stmt.execute_query()
258          while (res.next()) {
259            val session_name = res.string(Build_Log.Data.session_name)
260            val chapter = res.string(Build_Log.Data.chapter)
261            val groups = split_lines(res.string(Build_Log.Data.groups))
262            val threads =
263            {
264              val threads1 =
265                res.string(Build_Log.Settings.ISABELLE_BUILD_OPTIONS) match {
266                  case Threads_Option(Value.Int(i)) => i
267                  case _ => 1
268                }
269              val threads2 = res.get_int(Build_Log.Data.threads).getOrElse(1)
270              threads1 max threads2
271            }
272            val ml_platform = res.string(Build_Log.Settings.ML_PLATFORM)
273            val data_name =
274              profile.description +
275                (if (ml_platform.startsWith("x86_64-")) ", 64bit" else "") +
276                (if (threads == 1) "" else ", " + threads + " threads")
277
278            res.get_string(Build_Log.Prop.build_host).foreach(host =>
279              data_hosts += (data_name -> (get_hosts(data_name) + host)))
280
281            data_stretch += (data_name -> profile.stretch(options))
282
283            val isabelle_version = res.string(Build_Log.Prop.isabelle_version)
284            val afp_version = res.string(Build_Log.Prop.afp_version)
285
286            val ml_stats =
287              ML_Statistics(
288                if (ml_statistics) {
289                  Properties.uncompress(
290                    res.bytes(Build_Log.Data.ml_statistics), cache = store.xz_cache)
291                }
292                else Nil,
293                domain = ml_statistics_domain,
294                heading = session_name + print_version(isabelle_version, afp_version, chapter))
295
296            val entry =
297              Entry(
298                chapter = chapter,
299                pull_date = res.date(Build_Log.Data.pull_date(afp = false)),
300                afp_pull_date =
301                  if (afp) res.get_date(Build_Log.Data.pull_date(afp = true)) else None,
302                isabelle_version = isabelle_version,
303                afp_version = afp_version,
304                timing =
305                  res.timing(
306                    Build_Log.Data.timing_elapsed,
307                    Build_Log.Data.timing_cpu,
308                    Build_Log.Data.timing_gc),
309                ml_timing =
310                  res.timing(
311                    Build_Log.Data.ml_timing_elapsed,
312                    Build_Log.Data.ml_timing_cpu,
313                    Build_Log.Data.ml_timing_gc),
314                maximum_code = ml_stats.maximum(ML_Statistics.CODE_SIZE).toLong,
315                average_code = ml_stats.average(ML_Statistics.CODE_SIZE).toLong,
316                maximum_stack = ml_stats.maximum(ML_Statistics.STACK_SIZE).toLong,
317                average_stack = ml_stats.average(ML_Statistics.STACK_SIZE).toLong,
318                maximum_heap = ml_stats.maximum(ML_Statistics.HEAP_SIZE).toLong,
319                average_heap = ml_stats.average(ML_Statistics.HEAP_SIZE).toLong,
320                stored_heap = ML_Statistics.mem_scale(res.long(Build_Log.Data.heap_size)),
321                status = Build_Log.Session_Status.withName(res.string(Build_Log.Data.status)),
322                errors =
323                  Build_Log.uncompress_errors(res.bytes(Build_Log.Data.errors),
324                    cache = store.xz_cache))
325
326            val sessions = data_entries.getOrElse(data_name, Map.empty)
327            val session =
328              sessions.get(session_name) match {
329                case None =>
330                  Session(session_name, threads, List(entry), ml_stats, entry.date)
331                case Some(old) =>
332                  val (ml_stats1, ml_stats1_date) =
333                    if (entry.date > old.ml_statistics_date) (ml_stats, entry.date)
334                    else (old.ml_statistics, old.ml_statistics_date)
335                  Session(session_name, threads, entry :: old.entries, ml_stats1, ml_stats1_date)
336              }
337
338            if ((!afp || chapter == AFP.chapter) &&
339                (!profile.bulky || groups.exists(AFP.groups_bulky.toSet))) {
340              data_entries += (data_name -> (sessions + (session_name -> session)))
341            }
342          }
343        })
344      }
345    })
346
347    val sorted_entries =
348      (for {
349        (name, sessions) <- data_entries.toList
350        sorted_sessions <- proper_list(sessions.toList.map(_._2).sortBy(_.order))
351      }
352      yield {
353        val hosts = get_hosts(name).toList.sorted
354        val stretch = data_stretch(name)
355        Data_Entry(name, hosts, stretch, sorted_sessions)
356      }).sortBy(_.name)
357
358    Data(date, sorted_entries)
359  }
360
361
362  /* present data */
363
364  def present_data(data: Data,
365    progress: Progress = No_Progress,
366    target_dir: Path = default_target_dir,
367    image_size: (Int, Int) = default_image_size)
368  {
369    def clean_name(name: String): String =
370      name.flatMap(c => if (c == ' ' || c == '/') "_" else if (c == ',') "" else c.toString)
371
372    HTML.write_document(target_dir, "index.html",
373      List(HTML.title("Isabelle build status")),
374      List(HTML.chapter("Isabelle build status"),
375        HTML.par(
376          List(HTML.description(
377            List(HTML.text("status date:") -> HTML.text(data.date.toString))))),
378        HTML.par(
379          List(HTML.itemize(data.entries.map({ case data_entry =>
380            List(
381              HTML.link(clean_name(data_entry.name) + "/index.html",
382                HTML.text(data_entry.name))) :::
383            (data_entry.failed_sessions match {
384              case Nil => Nil
385              case sessions =>
386                HTML.break :::
387                List(HTML.span(HTML.error_message, HTML.text("Failed sessions:"))) :::
388                List(HTML.itemize(sessions.map(s => s.head.present_errors(s.name))))
389            })
390          }))))))
391
392    for (data_entry <- data.entries) {
393      val data_name = data_entry.name
394
395      val (image_width, image_height) = image_size
396      val image_width_stretch = (image_width * data_entry.stretch).toInt
397
398      progress.echo("output " + quote(data_name))
399
400      val dir = target_dir + Path.basic(clean_name(data_name))
401      Isabelle_System.mkdirs(dir)
402
403      val data_files =
404        (for (session <- data_entry.sessions) yield {
405          val csv_file = session.make_csv
406          csv_file.write(dir)
407          session.name -> csv_file
408        }).toMap
409
410      val session_plots =
411        Par_List.map((session: Session) =>
412          Isabelle_System.with_tmp_file(session.name, "data") { data_file =>
413            Isabelle_System.with_tmp_file(session.name, "gnuplot") { gnuplot_file =>
414
415              def plot_name(kind: String): String = session.name + "_" + kind + ".png"
416
417              File.write(data_file,
418                cat_lines(
419                  session.finished_entries.map(entry =>
420                    List(entry.date,
421                      entry.timing.elapsed.minutes,
422                      entry.timing.resources.minutes,
423                      entry.ml_timing.elapsed.minutes,
424                      entry.ml_timing.resources.minutes,
425                      entry.maximum_code,
426                      entry.maximum_code,
427                      entry.average_stack,
428                      entry.maximum_stack,
429                      entry.average_heap,
430                      entry.average_heap,
431                      entry.stored_heap).mkString(" "))))
432
433              val max_time =
434                ((0.0 /: session.finished_entries){ case (m, entry) =>
435                  m.max(entry.timing.elapsed.minutes).
436                    max(entry.timing.resources.minutes).
437                    max(entry.ml_timing.elapsed.minutes).
438                    max(entry.ml_timing.resources.minutes) } max 0.1) * 1.1
439              val timing_range = "[0:" + max_time + "]"
440
441              def gnuplot(plot_name: String, plots: List[String], range: String): Image =
442              {
443                val image = Image(plot_name, image_width_stretch, image_height)
444
445                File.write(gnuplot_file, """
446set terminal png size """ + image.width + "," + image.height + """
447set output """ + quote(File.standard_path(dir + image.path)) + """
448set xdata time
449set timefmt "%s"
450set format x "%d-%b"
451set xlabel """ + quote(session.name) + """ noenhanced
452set key left bottom
453plot [] """ + range + " " +
454                plots.map(s => quote(data_file.implode) + " " + s).mkString(", ") + "\n")
455
456                val result =
457                  Isabelle_System.bash("\"$ISABELLE_GNUPLOT\" " + File.bash_path(gnuplot_file))
458                if (!result.ok)
459                  result.error("Gnuplot failed for " + data_name + "/" + plot_name).check
460
461                image
462              }
463
464              val timing_plots =
465              {
466                val plots1 =
467                  List(
468                    """ using 1:2 smooth sbezier title "elapsed time (smooth)" """,
469                    """ using 1:2 smooth csplines title "elapsed time" """)
470                val plots2 =
471                  List(
472                    """ using 1:3 smooth sbezier title "cpu time (smooth)" """,
473                    """ using 1:3 smooth csplines title "cpu time" """)
474                if (session.threads == 1) plots1 else plots1 ::: plots2
475              }
476
477              val ml_timing_plots =
478                List(
479                  """ using 1:4 smooth sbezier title "ML elapsed time (smooth)" """,
480                  """ using 1:4 smooth csplines title "ML elapsed time" """,
481                  """ using 1:5 smooth sbezier title "ML cpu time (smooth)" """,
482                  """ using 1:5 smooth csplines title "ML cpu time" """)
483
484              val heap_plots =
485                List(
486                  """ using 1:10 smooth sbezier title "heap maximum (smooth)" """,
487                  """ using 1:10 smooth csplines title "heap maximum" """,
488                  """ using 1:11 smooth sbezier title "heap average (smooth)" """,
489                  """ using 1:11 smooth csplines title "heap average" """,
490                  """ using 1:12 smooth sbezier title "heap stored (smooth)" """,
491                  """ using 1:12 smooth csplines title "heap stored" """)
492
493              def jfreechart(plot_name: String, fields: ML_Statistics.Fields): Image =
494              {
495                val image = Image(plot_name, image_width, image_height)
496                val chart =
497                  session.ml_statistics.chart(
498                    fields._1 + ": " + session.ml_statistics.heading, fields._2)
499                Graphics_File.write_chart_png(
500                  (dir + image.path).file, chart, image.width, image.height)
501                image
502              }
503
504              val images =
505                (if (session.check_timing)
506                  List(
507                    gnuplot(plot_name("timing"), timing_plots, timing_range),
508                    gnuplot(plot_name("ml_timing"), ml_timing_plots, timing_range))
509                 else Nil) :::
510                (if (session.check_heap)
511                  List(gnuplot(plot_name("heap"), heap_plots, "[0:]"))
512                 else Nil) :::
513                (if (session.ml_statistics.content.nonEmpty)
514                  List(jfreechart(plot_name("heap_chart"), ML_Statistics.heap_fields),
515                    jfreechart(plot_name("program_chart"), ML_Statistics.program_fields)) :::
516                  (if (session.threads > 1)
517                    List(
518                      jfreechart(plot_name("tasks_chart"), ML_Statistics.tasks_fields),
519                      jfreechart(plot_name("workers_chart"), ML_Statistics.workers_fields))
520                   else Nil)
521                 else Nil)
522
523              session.name -> images
524            }
525          }, data_entry.sessions).toMap
526
527      HTML.write_document(dir, "index.html",
528        List(HTML.title("Isabelle build status for " + data_name)),
529        HTML.chapter("Isabelle build status for " + data_name) ::
530        HTML.par(
531          List(HTML.description(
532            List(
533              HTML.text("status date:") -> HTML.text(data.date.toString),
534              HTML.text("build host:") -> HTML.text(commas(data_entry.hosts)))))) ::
535        HTML.par(
536          List(HTML.itemize(
537            data_entry.sessions.map(session =>
538              HTML.link("#session_" + session.name, HTML.text(session.name)) ::
539              HTML.text(" (" + session.head.timing.message_resources + ")"))))) ::
540        data_entry.sessions.flatMap(session =>
541          List(
542            HTML.section(HTML.id("session_" + session.name), session.name),
543            HTML.par(
544              HTML.description(
545                List(
546                  HTML.text("data:") ->
547                    List(HTML.link(data_files(session.name).file_name, HTML.text("CSV"))),
548                  HTML.text("timing:") -> HTML.text(session.head.timing.message_resources),
549                  HTML.text("ML timing:") -> HTML.text(session.head.ml_timing.message_resources)) :::
550                ML_Statistics.mem_print(session.head.maximum_code).map(s =>
551                  HTML.text("code maximum:") -> HTML.text(s)).toList :::
552                ML_Statistics.mem_print(session.head.average_code).map(s =>
553                  HTML.text("code average:") -> HTML.text(s)).toList :::
554                ML_Statistics.mem_print(session.head.maximum_stack).map(s =>
555                  HTML.text("stack maximum:") -> HTML.text(s)).toList :::
556                ML_Statistics.mem_print(session.head.average_stack).map(s =>
557                  HTML.text("stack average:") -> HTML.text(s)).toList :::
558                ML_Statistics.mem_print(session.head.maximum_heap).map(s =>
559                  HTML.text("heap maximum:") -> HTML.text(s)).toList :::
560                ML_Statistics.mem_print(session.head.average_heap).map(s =>
561                  HTML.text("heap average:") -> HTML.text(s)).toList :::
562                ML_Statistics.mem_print(session.head.stored_heap).map(s =>
563                  HTML.text("heap stored:") -> HTML.text(s)).toList :::
564                proper_string(session.head.isabelle_version).map(s =>
565                  HTML.text("Isabelle version:") -> HTML.text(s)).toList :::
566                proper_string(session.head.afp_version).map(s =>
567                  HTML.text("AFP version:") -> HTML.text(s)).toList) ::
568              session_plots.getOrElse(session.name, Nil).map(image =>
569                HTML.size(image.width / 2, image.height / 2)(HTML.image(image.name)))))))
570    }
571  }
572
573
574  /* Isabelle tool wrapper */
575
576  val isabelle_tool =
577    Isabelle_Tool("build_status", "present recent build status information from database", args =>
578    {
579      var target_dir = default_target_dir
580      var ml_statistics = false
581      var only_sessions = Set.empty[String]
582      var options = Options.init()
583      var image_size = default_image_size
584      var verbose = false
585
586      val getopts = Getopts("""
587Usage: isabelle build_status [OPTIONS]
588
589  Options are:
590    -D DIR       target directory (default """ + default_target_dir + """)
591    -M           include full ML statistics
592    -S SESSIONS  only given SESSIONS (comma separated)
593    -l DAYS      length of relevant history (default """ + options.int("build_log_history") + """)
594    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
595    -s WxH       size of PNG image (default """ + image_size._1 + "x" + image_size._2 + """)
596    -v           verbose
597
598  Present performance statistics from build log database, which is specified
599  via system options build_log_database_host, build_log_database_user,
600  build_log_history etc.
601""",
602        "D:" -> (arg => target_dir = Path.explode(arg)),
603        "M" -> (_ => ml_statistics = true),
604        "S:" -> (arg => only_sessions = space_explode(',', arg).toSet),
605        "l:" -> (arg => options = options + ("build_log_history=" + arg)),
606        "o:" -> (arg => options = options + arg),
607        "s:" -> (arg =>
608          space_explode('x', arg).map(Value.Int.parse(_)) match {
609            case List(w, h) if w > 0 && h > 0 => image_size = (w, h)
610            case _ => error("Error bad PNG image size: " + quote(arg))
611          }),
612        "v" -> (_ => verbose = true))
613
614      val more_args = getopts(args)
615      if (more_args.nonEmpty) getopts.usage()
616
617      val progress = new Console_Progress
618
619      build_status(options, progress = progress, only_sessions = only_sessions, verbose = verbose,
620        target_dir = target_dir, ml_statistics = ml_statistics, image_size = image_size)
621    })
622}
623