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