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