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