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