src/Pure/Admin/build_log.scala
author wenzelm
Tue Oct 18 11:50:38 2016 +0200 (2016-10-18)
changeset 64297 12a47f263122
parent 64296 544481988e65
child 64298 0f000101652a
permissions -rw-r--r--
support for free-form build tags;
tuned;
     1 /*  Title:      Pure/Admin/build_log.scala
     2     Author:     Makarius
     3 
     4 Build log parsing for current and historic formats.
     5 */
     6 
     7 package isabelle
     8 
     9 
    10 import java.io.{File => JFile}
    11 import java.time.ZoneId
    12 import java.time.format.{DateTimeFormatter, DateTimeParseException}
    13 import java.util.Locale
    14 
    15 import scala.collection.mutable
    16 import scala.util.matching.Regex
    17 
    18 
    19 object Build_Log
    20 {
    21   /** directory content **/
    22 
    23   /* file names */
    24 
    25   def log_date(date: Date): String =
    26     String.format(Locale.ROOT, "%s.%05d",
    27       DateTimeFormatter.ofPattern("yyyy-MM-dd").format(date.rep),
    28       new java.lang.Long((date.time - date.midnight.time).ms / 1000))
    29 
    30   def log_subdir(date: Date): Path =
    31     Path.explode("log") + Path.explode(date.rep.getYear.toString)
    32 
    33   def log_filename(engine: String, date: Date, more: List[String] = Nil): Path =
    34     Path.explode((engine :: log_date(date) :: more).mkString("", "_", ".log"))
    35 
    36 
    37   /* log file collections */
    38 
    39   def is_log(file: JFile): Boolean =
    40     List(".log", ".log.gz", ".log.xz").exists(ext => file.getName.endsWith(ext))
    41 
    42   def isatest_files(dir: Path): List[JFile] =
    43     File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("isatest-makeall-"))
    44 
    45   def afp_test_files(dir: Path): List[JFile] =
    46     File.find_files(dir.file, file => is_log(file) && file.getName.startsWith("afp-test-devel-"))
    47 
    48 
    49 
    50   /** settings **/
    51 
    52   object Settings
    53   {
    54     val build_settings = List("ISABELLE_BUILD_OPTIONS")
    55     val ml_settings = List("ML_PLATFORM", "ML_HOME", "ML_SYSTEM", "ML_OPTIONS")
    56     val all_settings = build_settings ::: ml_settings
    57 
    58     type Entry = (String, String)
    59     type T = List[Entry]
    60 
    61     object Entry
    62     {
    63       def unapply(s: String): Option[Entry] =
    64         s.indexOf('=') match {
    65           case -1 => None
    66           case i =>
    67             val a = s.substring(0, i)
    68             val b = Library.perhaps_unquote(s.substring(i + 1))
    69             Some((a, b))
    70         }
    71       def apply(a: String, b: String): String = a + "=" + quote(b)
    72       def getenv(a: String): String = apply(a, Isabelle_System.getenv(a))
    73     }
    74 
    75     def show(): String =
    76       cat_lines(
    77         build_settings.map(Entry.getenv(_)) ::: List("") ::: ml_settings.map(Entry.getenv(_)))
    78   }
    79 
    80 
    81 
    82   /** log file **/
    83 
    84   def print_date(date: Date): String = Log_File.Date_Format(date)
    85 
    86   object Log_File
    87   {
    88     def apply(name: String, lines: List[String]): Log_File =
    89       new Log_File(name, lines)
    90 
    91     def apply(name: String, text: String): Log_File =
    92       Log_File(name, Library.trim_split_lines(text))
    93 
    94     def apply(file: JFile): Log_File =
    95     {
    96       val name = file.getName
    97       val (base_name, text) =
    98         Library.try_unsuffix(".gz", name) match {
    99           case Some(base_name) => (base_name, File.read_gzip(file))
   100           case None =>
   101             Library.try_unsuffix(".xz", name) match {
   102               case Some(base_name) => (base_name, File.read_xz(file))
   103               case None => (name, File.read(file))
   104             }
   105           }
   106       apply(base_name, text)
   107     }
   108 
   109     def apply(path: Path): Log_File = apply(path.file)
   110 
   111 
   112     /* date format */
   113 
   114     val Date_Format =
   115     {
   116       val fmts =
   117         Date.Formatter.variants(
   118           List("EEE MMM d HH:mm:ss O yyyy", "EEE MMM d HH:mm:ss VV yyyy"),
   119           List(Locale.ENGLISH, Locale.GERMAN)) :::
   120         List(
   121           DateTimeFormatter.RFC_1123_DATE_TIME,
   122           Date.Formatter.pattern("EEE MMM d HH:mm:ss yyyy").withZone(ZoneId.of("Europe/Berlin")))
   123 
   124       def tune_timezone(s: String): String =
   125         s match {
   126           case "CET" | "MET" => "GMT+1"
   127           case "CEST" | "MEST" => "GMT+2"
   128           case "EST" => "Europe/Berlin"
   129           case _ => s
   130         }
   131       def tune_weekday(s: String): String =
   132         s match {
   133           case "Die" => "Di"
   134           case "Mit" => "Mi"
   135           case "Don" => "Do"
   136           case "Fre" => "Fr"
   137           case "Sam" => "Sa"
   138           case "Son" => "So"
   139           case _ => s
   140         }
   141 
   142       def tune(s: String): String =
   143         Word.implode(
   144           Word.explode(s) match {
   145             case a :: "M\uFFFDr" :: bs => tune_weekday(a) :: "Mär" :: bs.map(tune_timezone(_))
   146             case a :: bs => tune_weekday(a) :: bs.map(tune_timezone(_))
   147             case Nil => Nil
   148           }
   149         )
   150 
   151       Date.Format.make(fmts, tune)
   152     }
   153 
   154 
   155     /* inlined content */
   156 
   157     def print_props(marker: String, props: Properties.T): String =
   158       marker + YXML.string_of_body(XML.Encode.properties(props))
   159   }
   160 
   161   class Log_File private(val name: String, val lines: List[String])
   162   {
   163     log_file =>
   164 
   165     override def toString: String = name
   166 
   167     def text: String = cat_lines(lines)
   168 
   169     def err(msg: String): Nothing =
   170       error("Error in log file " + quote(name) + ": " + msg)
   171 
   172 
   173     /* date format */
   174 
   175     object Strict_Date
   176     {
   177       def unapply(s: String): Some[Date] =
   178         try { Some(Log_File.Date_Format.parse(s)) }
   179         catch { case exn: DateTimeParseException => log_file.err(exn.getMessage) }
   180     }
   181 
   182 
   183     /* inlined content */
   184 
   185     def find[A](f: String => Option[A]): Option[A] =
   186       lines.iterator.map(f).find(_.isDefined).map(_.get)
   187 
   188     def find_line(marker: String): Option[String] =
   189       find(Library.try_unprefix(marker, _))
   190 
   191     def find_match(regex: Regex): Option[String] =
   192       lines.iterator.map(regex.unapplySeq(_)).find(res => res.isDefined && res.get.length == 1).
   193         map(res => res.get.head)
   194 
   195 
   196     /* settings */
   197 
   198     def get_setting(a: String): Option[Settings.Entry] =
   199       lines.find(_.startsWith(a + "=")) match {
   200         case Some(line) => Settings.Entry.unapply(line)
   201         case None => None
   202       }
   203 
   204     def get_settings(as: List[String]): Settings.T =
   205       for { a <- as; entry <- get_setting(a) } yield entry
   206 
   207 
   208     /* properties (YXML) */
   209 
   210     val xml_cache = new XML.Cache()
   211 
   212     def parse_props(text: String): Properties.T =
   213       xml_cache.props(XML.Decode.properties(YXML.parse_body(text)))
   214 
   215     def filter_props(marker: String): List[Properties.T] =
   216       for {
   217         line <- lines
   218         s <- Library.try_unprefix(marker, line)
   219         if YXML.detect(s)
   220       } yield parse_props(s)
   221 
   222     def find_props(marker: String): Option[Properties.T] =
   223       find_line(marker) match {
   224         case Some(text) if YXML.detect(text) => Some(parse_props(text))
   225         case _ => None
   226       }
   227 
   228 
   229     /* parse various formats */
   230 
   231     def parse_meta_info(): Meta_Info = Build_Log.parse_meta_info(log_file)
   232 
   233     def parse_build_info(): Build_Info = Build_Log.parse_build_info(log_file)
   234 
   235     def parse_session_info(
   236         default_name: String = "",
   237         command_timings: Boolean = false,
   238         ml_statistics: Boolean = false,
   239         task_statistics: Boolean = false): Session_Info =
   240       Build_Log.parse_session_info(
   241         log_file, default_name, command_timings, ml_statistics, task_statistics)
   242   }
   243 
   244 
   245 
   246   /** meta info **/
   247 
   248   object Field
   249   {
   250     val build_tags = "build_tags"
   251     val build_group_id = "build_group_id"
   252     val build_id = "build_id"
   253     val build_engine = "build_engine"
   254     val build_host = "build_host"
   255     val build_start = "build_start"
   256     val build_end = "build_end"
   257     val isabelle_version = "isabelle_version"
   258     val afp_version = "afp_version"
   259   }
   260 
   261   object Meta_Info
   262   {
   263     val empty: Meta_Info = Meta_Info(Nil, Nil)
   264   }
   265 
   266   sealed case class Meta_Info(props: Properties.T, settings: List[(String, String)])
   267   {
   268     def is_empty: Boolean = props.isEmpty && settings.isEmpty
   269   }
   270 
   271   object Isatest
   272   {
   273     val engine = "isatest"
   274     val Start = new Regex("""^------------------- starting test --- (.+) --- (.+)$""")
   275     val End = new Regex("""^------------------- test (?:successful|FAILED) --- (.+) --- .*$""")
   276     val Isabelle_Version = new Regex("""^Isabelle version: (\S+)$""")
   277     val No_AFP_Version = new Regex("""$.""")
   278   }
   279 
   280   object AFP_Test
   281   {
   282     val engine = "afp-test"
   283     val Start = new Regex("""^Start test(?: for .+)? at ([^,]+), (.*)$""")
   284     val Start_Old = new Regex("""^Start test(?: for .+)? at ([^,]+)$""")
   285     val End = new Regex("""^End test on (.+), .+, elapsed time:.*$""")
   286     val Isabelle_Version = new Regex("""^Isabelle version: .* -- hg id (\S+)$""")
   287     val AFP_Version = new Regex("""^AFP version: .* -- hg id (\S+)$""")
   288     val Bad_Init = new Regex("""^cp:.*: Disc quota exceeded$""")
   289   }
   290 
   291   object Jenkins
   292   {
   293     val engine = "jenkins"
   294     val Start = new Regex("""^Started .*$""")
   295     val Start_Date = new Regex("""^Build started at (.+)$""")
   296     val No_End = new Regex("""$.""")
   297     val Isabelle_Version = new Regex("""^Isabelle id (\S+)$""")
   298     val AFP_Version = new Regex("""^AFP id (\S+)$""")
   299     val CONFIGURATION = "=== CONFIGURATION ==="
   300     val BUILD = "=== BUILD ==="
   301     val FINISHED = "Finished: "
   302   }
   303 
   304   private def parse_meta_info(log_file: Log_File): Meta_Info =
   305   {
   306     def parse(engine: String, host: String, start: Date,
   307       End: Regex, Isabelle_Version: Regex, AFP_Version: Regex): Meta_Info =
   308     {
   309       val build_id =
   310       {
   311         val prefix = if (host != "") host else if (engine != "") engine else ""
   312         (if (prefix == "") "build" else prefix) + ":" + start.time.ms
   313       }
   314       val build_engine = if (engine == "") Nil else List(Field.build_engine -> engine)
   315       val build_host = if (host == "") Nil else List(Field.build_host -> host)
   316 
   317       val start_date = List(Field.build_start -> start.toString)
   318       val end_date =
   319         log_file.lines.last match {
   320           case End(log_file.Strict_Date(end_date)) =>
   321             List(Field.build_end -> end_date.toString)
   322           case _ => Nil
   323         }
   324 
   325       val isabelle_version =
   326         log_file.find_match(Isabelle_Version).map(Field.isabelle_version -> _)
   327       val afp_version =
   328         log_file.find_match(AFP_Version).map(Field.afp_version -> _)
   329 
   330       Meta_Info((Field.build_id -> build_id) :: build_engine ::: build_host :::
   331           start_date ::: end_date ::: isabelle_version.toList ::: afp_version.toList,
   332         log_file.get_settings(Settings.all_settings))
   333     }
   334 
   335     log_file.lines match {
   336       case line :: _ if line.startsWith(Build_History.META_INFO_MARKER) =>
   337         Meta_Info(log_file.find_props(Build_History.META_INFO_MARKER).get,
   338           log_file.get_settings(Settings.all_settings))
   339 
   340       case Isatest.Start(log_file.Strict_Date(start), host) :: _ =>
   341         parse(Isatest.engine, host, start, Isatest.End,
   342           Isatest.Isabelle_Version, Isatest.No_AFP_Version)
   343 
   344       case AFP_Test.Start(log_file.Strict_Date(start), host) :: _ =>
   345         parse(AFP_Test.engine, host, start, AFP_Test.End,
   346           AFP_Test.Isabelle_Version, AFP_Test.AFP_Version)
   347 
   348       case AFP_Test.Start_Old(log_file.Strict_Date(start)) :: _ =>
   349         parse(AFP_Test.engine, "", start, AFP_Test.End,
   350           AFP_Test.Isabelle_Version, AFP_Test.AFP_Version)
   351 
   352       case Jenkins.Start() :: _
   353       if log_file.lines.contains(Jenkins.CONFIGURATION) ||
   354          log_file.lines.last.startsWith(Jenkins.FINISHED) =>
   355         log_file.lines.dropWhile(_ != Jenkins.BUILD) match {
   356           case Jenkins.BUILD :: _ :: Jenkins.Start_Date(log_file.Strict_Date(start)) :: _ =>
   357             parse(Jenkins.engine, "", start.to(ZoneId.of("Europe/Berlin")), Jenkins.No_End,
   358               Jenkins.Isabelle_Version, Jenkins.AFP_Version)
   359           case _ => Meta_Info.empty
   360         }
   361 
   362       case line :: _ if line.startsWith("\0") => Meta_Info.empty
   363       case List(Isatest.End(_)) => Meta_Info.empty
   364       case _ :: AFP_Test.Bad_Init() :: _ => Meta_Info.empty
   365       case Nil => Meta_Info.empty
   366 
   367       case _ => log_file.err("cannot detect log file format")
   368     }
   369   }
   370 
   371 
   372 
   373   /** build info: produced by isabelle build or build_history **/
   374 
   375   val ML_STATISTICS_MARKER = "\fML_statistics = "
   376   val SESSION_NAME = "session_name"
   377 
   378   object Session_Status extends Enumeration
   379   {
   380     val EXISTING = Value("existing")
   381     val FINISHED = Value("finished")
   382     val FAILED = Value("failed")
   383     val CANCELLED = Value("cancelled")
   384   }
   385 
   386   sealed case class Session_Entry(
   387     chapter: String,
   388     groups: List[String],
   389     threads: Option[Int],
   390     timing: Timing,
   391     ml_timing: Timing,
   392     ml_statistics: List[Properties.T],
   393     heap_size: Option[Long],
   394     status: Session_Status.Value)
   395   {
   396     def finished: Boolean = status == Session_Status.FINISHED
   397   }
   398 
   399   sealed case class Build_Info(sessions: Map[String, Session_Entry])
   400   {
   401     def session(name: String): Session_Entry = sessions(name)
   402     def get_session(name: String): Option[Session_Entry] = sessions.get(name)
   403 
   404     def get_default[A](name: String, f: Session_Entry => A, x: A): A =
   405       get_session(name) match {
   406         case Some(entry) => f(entry)
   407         case None => x
   408       }
   409 
   410     def finished_sessions: List[String] = sessions.keySet.iterator.filter(finished(_)).toList
   411     def finished(name: String): Boolean = get_default(name, _.finished, false)
   412     def timing(name: String): Timing = get_default(name, _.timing, Timing.zero)
   413     def ml_timing(name: String): Timing = get_default(name, _.ml_timing, Timing.zero)
   414   }
   415 
   416   private def parse_build_info(log_file: Log_File): Build_Info =
   417   {
   418     object Chapter_Name
   419     {
   420       def unapply(s: String): Some[(String, String)] =
   421         space_explode('/', s) match {
   422           case List(chapter, name) => Some((chapter, name))
   423           case _ => Some(("", s))
   424         }
   425     }
   426 
   427     val Session_No_Groups = new Regex("""^Session (\S+)$""")
   428     val Session_Groups = new Regex("""^Session (\S+) \((.*)\)$""")
   429     val Session_Finished1 =
   430       new Regex("""^Finished (\S+) \((\d+):(\d+):(\d+) elapsed time, (\d+):(\d+):(\d+) cpu time.*$""")
   431     val Session_Finished2 =
   432       new Regex("""^Finished (\S+) \((\d+):(\d+):(\d+) elapsed time.*$""")
   433     val Session_Timing =
   434       new Regex("""^Timing (\S+) \((\d) threads, (\d+\.\d+)s elapsed time, (\d+\.\d+)s cpu time, (\d+\.\d+)s GC time.*$""")
   435     val Session_Started = new Regex("""^(?:Running|Building) (\S+) \.\.\.$""")
   436     val Session_Failed = new Regex("""^(\S+) FAILED""")
   437     val Session_Cancelled = new Regex("""^(\S+) CANCELLED""")
   438     val Heap = new Regex("""^Heap (\S+) \((\d+) bytes\)$""")
   439 
   440     var chapter = Map.empty[String, String]
   441     var groups = Map.empty[String, List[String]]
   442     var threads = Map.empty[String, Int]
   443     var timing = Map.empty[String, Timing]
   444     var ml_timing = Map.empty[String, Timing]
   445     var started = Set.empty[String]
   446     var failed = Set.empty[String]
   447     var cancelled = Set.empty[String]
   448     var ml_statistics = Map.empty[String, List[Properties.T]]
   449     var heap_sizes = Map.empty[String, Long]
   450 
   451     def all_sessions: Set[String] =
   452       chapter.keySet ++ groups.keySet ++ threads.keySet ++ timing.keySet ++ ml_timing.keySet ++
   453       failed ++ cancelled ++ started ++ ml_statistics.keySet ++ heap_sizes.keySet
   454 
   455 
   456     for (line <- log_file.lines) {
   457       line match {
   458         case Session_No_Groups(Chapter_Name(chapt, name)) =>
   459           chapter += (name -> chapt)
   460           groups += (name -> Nil)
   461 
   462         case Session_Groups(Chapter_Name(chapt, name), grps) =>
   463           chapter += (name -> chapt)
   464           groups += (name -> Word.explode(grps))
   465 
   466         case Session_Started(name) =>
   467           started += name
   468 
   469         case Session_Finished1(name,
   470             Value.Int(e1), Value.Int(e2), Value.Int(e3),
   471             Value.Int(c1), Value.Int(c2), Value.Int(c3)) =>
   472           val elapsed = Time.hms(e1, e2, e3)
   473           val cpu = Time.hms(c1, c2, c3)
   474           timing += (name -> Timing(elapsed, cpu, Time.zero))
   475 
   476         case Session_Finished2(name,
   477             Value.Int(e1), Value.Int(e2), Value.Int(e3)) =>
   478           val elapsed = Time.hms(e1, e2, e3)
   479           timing += (name -> Timing(elapsed, Time.zero, Time.zero))
   480 
   481         case Session_Timing(name,
   482             Value.Int(t), Value.Double(e), Value.Double(c), Value.Double(g)) =>
   483           val elapsed = Time.seconds(e)
   484           val cpu = Time.seconds(c)
   485           val gc = Time.seconds(g)
   486           ml_timing += (name -> Timing(elapsed, cpu, gc))
   487           threads += (name -> t)
   488 
   489         case Heap(name, Value.Long(size)) =>
   490           heap_sizes += (name -> size)
   491 
   492         case _ if line.startsWith(ML_STATISTICS_MARKER) =>
   493           val (name, props) =
   494             Library.try_unprefix(ML_STATISTICS_MARKER, line).map(log_file.parse_props(_)) match {
   495               case Some((SESSION_NAME, session_name) :: props) => (session_name, props)
   496               case _ => log_file.err("malformed ML_statistics " + quote(line))
   497             }
   498           ml_statistics += (name -> (props :: ml_statistics.getOrElse(name, Nil)))
   499 
   500         case _ =>
   501       }
   502     }
   503 
   504     val sessions =
   505       Map(
   506         (for (name <- all_sessions.toList) yield {
   507           val status =
   508             if (failed(name)) Session_Status.FAILED
   509             else if (cancelled(name)) Session_Status.CANCELLED
   510             else if (timing.isDefinedAt(name) || ml_timing.isDefinedAt(name))
   511               Session_Status.FINISHED
   512             else if (started(name)) Session_Status.FAILED
   513             else Session_Status.EXISTING
   514           val entry =
   515             Session_Entry(
   516               chapter.getOrElse(name, ""),
   517               groups.getOrElse(name, Nil),
   518               threads.get(name),
   519               timing.getOrElse(name, Timing.zero),
   520               ml_timing.getOrElse(name, Timing.zero),
   521               ml_statistics.getOrElse(name, Nil).reverse,
   522               heap_sizes.get(name),
   523               status)
   524           (name -> entry)
   525         }):_*)
   526     Build_Info(sessions)
   527   }
   528 
   529 
   530 
   531   /** session info: produced by "isabelle build" **/
   532 
   533   sealed case class Session_Info(
   534     session_name: String,
   535     session_timing: Properties.T,
   536     command_timings: List[Properties.T],
   537     ml_statistics: List[Properties.T],
   538     task_statistics: List[Properties.T])
   539 
   540   private def parse_session_info(
   541     log_file: Log_File,
   542     default_name: String,
   543     command_timings: Boolean,
   544     ml_statistics: Boolean,
   545     task_statistics: Boolean): Session_Info =
   546   {
   547     val xml_cache = new XML.Cache()
   548 
   549     val session_name =
   550       log_file.find_line("\fSession.name = ") match {
   551         case None => default_name
   552         case Some(name) if default_name == "" || default_name == name => name
   553         case Some(name) => log_file.err("log from different session " + quote(name))
   554       }
   555     val session_timing = log_file.find_props("\fTiming = ") getOrElse Nil
   556     val command_timings_ =
   557       if (command_timings) log_file.filter_props("\fcommand_timing = ") else Nil
   558     val ml_statistics_ =
   559       if (ml_statistics) log_file.filter_props(ML_STATISTICS_MARKER) else Nil
   560     val task_statistics_ =
   561       if (task_statistics) log_file.filter_props("\ftask_statistics = ") else Nil
   562 
   563     Session_Info(session_name, session_timing, command_timings_, ml_statistics_, task_statistics_)
   564   }
   565 }