src/Pure/Admin/build_log.scala
author wenzelm
Tue Oct 18 11:24:14 2016 +0200 (2016-10-18)
changeset 64296 544481988e65
parent 64196 6688b9cd443b
child 64297 12a47f263122
permissions -rw-r--r--
explicit identification of builds and correlated build groups;
     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: String*): Path =
    34     Path.explode((engine :: log_date(date) :: more.toList).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_group_id = "build_group_id"
   251     val build_id = "build_id"
   252     val build_engine = "build_engine"
   253     val build_host = "build_host"
   254     val build_start = "build_start"
   255     val build_end = "build_end"
   256     val isabelle_version = "isabelle_version"
   257     val afp_version = "afp_version"
   258   }
   259 
   260   object Meta_Info
   261   {
   262     val empty: Meta_Info = Meta_Info(Nil, Nil)
   263   }
   264 
   265   sealed case class Meta_Info(props: Properties.T, settings: List[(String, String)])
   266   {
   267     def is_empty: Boolean = props.isEmpty && settings.isEmpty
   268   }
   269 
   270   object Isatest
   271   {
   272     val engine = "isatest"
   273     val Start = new Regex("""^------------------- starting test --- (.+) --- (.+)$""")
   274     val End = new Regex("""^------------------- test (?:successful|FAILED) --- (.+) --- .*$""")
   275     val Isabelle_Version = new Regex("""^Isabelle version: (\S+)$""")
   276     val No_AFP_Version = new Regex("""$.""")
   277   }
   278 
   279   object AFP_Test
   280   {
   281     val engine = "afp-test"
   282     val Start = new Regex("""^Start test(?: for .+)? at ([^,]+), (.*)$""")
   283     val Start_Old = new Regex("""^Start test(?: for .+)? at ([^,]+)$""")
   284     val End = new Regex("""^End test on (.+), .+, elapsed time:.*$""")
   285     val Isabelle_Version = new Regex("""^Isabelle version: .* -- hg id (\S+)$""")
   286     val AFP_Version = new Regex("""^AFP version: .* -- hg id (\S+)$""")
   287     val Bad_Init = new Regex("""^cp:.*: Disc quota exceeded$""")
   288   }
   289 
   290   object Jenkins
   291   {
   292     val engine = "jenkins"
   293     val Start = new Regex("""^Started .*$""")
   294     val Start_Date = new Regex("""^Build started at (.+)$""")
   295     val No_End = new Regex("""$.""")
   296     val Isabelle_Version = new Regex("""^Isabelle id (\S+)$""")
   297     val AFP_Version = new Regex("""^AFP id (\S+)$""")
   298     val CONFIGURATION = "=== CONFIGURATION ==="
   299     val BUILD = "=== BUILD ==="
   300     val FINISHED = "Finished: "
   301   }
   302 
   303   private def parse_meta_info(log_file: Log_File): Meta_Info =
   304   {
   305     def parse(engine: String, host: String, start: Date,
   306       End: Regex, Isabelle_Version: Regex, AFP_Version: Regex): Meta_Info =
   307     {
   308       val build_id =
   309       {
   310         val prefix = if (host != "") host else if (engine != "") engine else ""
   311         (if (prefix == "") "build" else prefix) + ":" + start.time.ms
   312       }
   313       val build_engine = if (engine == "") Nil else List(Field.build_engine -> engine)
   314       val build_host = if (host == "") Nil else List(Field.build_host -> host)
   315 
   316       val start_date = List(Field.build_start -> start.toString)
   317       val end_date =
   318         log_file.lines.last match {
   319           case End(log_file.Strict_Date(end_date)) =>
   320             List(Field.build_end -> end_date.toString)
   321           case _ => Nil
   322         }
   323 
   324       val isabelle_version =
   325         log_file.find_match(Isabelle_Version).map(Field.isabelle_version -> _)
   326       val afp_version =
   327         log_file.find_match(AFP_Version).map(Field.afp_version -> _)
   328 
   329       Meta_Info((Field.build_id -> build_id) :: build_engine ::: build_host :::
   330           start_date ::: end_date ::: isabelle_version.toList ::: afp_version.toList,
   331         log_file.get_settings(Settings.all_settings))
   332     }
   333 
   334     log_file.lines match {
   335       case line :: _ if line.startsWith(Build_History.META_INFO_MARKER) =>
   336         Meta_Info(log_file.find_props(Build_History.META_INFO_MARKER).get,
   337           log_file.get_settings(Settings.all_settings))
   338 
   339       case Isatest.Start(log_file.Strict_Date(start), host) :: _ =>
   340         parse(Isatest.engine, host, start, Isatest.End,
   341           Isatest.Isabelle_Version, Isatest.No_AFP_Version)
   342 
   343       case AFP_Test.Start(log_file.Strict_Date(start), host) :: _ =>
   344         parse(AFP_Test.engine, host, start, AFP_Test.End,
   345           AFP_Test.Isabelle_Version, AFP_Test.AFP_Version)
   346 
   347       case AFP_Test.Start_Old(log_file.Strict_Date(start)) :: _ =>
   348         parse(AFP_Test.engine, "", start, AFP_Test.End,
   349           AFP_Test.Isabelle_Version, AFP_Test.AFP_Version)
   350 
   351       case Jenkins.Start() :: _
   352       if log_file.lines.contains(Jenkins.CONFIGURATION) ||
   353          log_file.lines.last.startsWith(Jenkins.FINISHED) =>
   354         log_file.lines.dropWhile(_ != Jenkins.BUILD) match {
   355           case Jenkins.BUILD :: _ :: Jenkins.Start_Date(log_file.Strict_Date(start)) :: _ =>
   356             parse(Jenkins.engine, "", start.to(ZoneId.of("Europe/Berlin")), Jenkins.No_End,
   357               Jenkins.Isabelle_Version, Jenkins.AFP_Version)
   358           case _ => Meta_Info.empty
   359         }
   360 
   361       case line :: _ if line.startsWith("\0") => Meta_Info.empty
   362       case List(Isatest.End(_)) => Meta_Info.empty
   363       case _ :: AFP_Test.Bad_Init() :: _ => Meta_Info.empty
   364       case Nil => Meta_Info.empty
   365 
   366       case _ => log_file.err("cannot detect log file format")
   367     }
   368   }
   369 
   370 
   371 
   372   /** build info: produced by isabelle build or build_history **/
   373 
   374   val ML_STATISTICS_MARKER = "\fML_statistics = "
   375   val SESSION_NAME = "session_name"
   376 
   377   object Session_Status extends Enumeration
   378   {
   379     val EXISTING = Value("existing")
   380     val FINISHED = Value("finished")
   381     val FAILED = Value("failed")
   382     val CANCELLED = Value("cancelled")
   383   }
   384 
   385   sealed case class Session_Entry(
   386     chapter: String,
   387     groups: List[String],
   388     threads: Option[Int],
   389     timing: Timing,
   390     ml_timing: Timing,
   391     ml_statistics: List[Properties.T],
   392     heap_size: Option[Long],
   393     status: Session_Status.Value)
   394   {
   395     def finished: Boolean = status == Session_Status.FINISHED
   396   }
   397 
   398   sealed case class Build_Info(sessions: Map[String, Session_Entry])
   399   {
   400     def session(name: String): Session_Entry = sessions(name)
   401     def get_session(name: String): Option[Session_Entry] = sessions.get(name)
   402 
   403     def get_default[A](name: String, f: Session_Entry => A, x: A): A =
   404       get_session(name) match {
   405         case Some(entry) => f(entry)
   406         case None => x
   407       }
   408 
   409     def finished_sessions: List[String] = sessions.keySet.iterator.filter(finished(_)).toList
   410     def finished(name: String): Boolean = get_default(name, _.finished, false)
   411     def timing(name: String): Timing = get_default(name, _.timing, Timing.zero)
   412     def ml_timing(name: String): Timing = get_default(name, _.ml_timing, Timing.zero)
   413   }
   414 
   415   private def parse_build_info(log_file: Log_File): Build_Info =
   416   {
   417     object Chapter_Name
   418     {
   419       def unapply(s: String): Some[(String, String)] =
   420         space_explode('/', s) match {
   421           case List(chapter, name) => Some((chapter, name))
   422           case _ => Some(("", s))
   423         }
   424     }
   425 
   426     val Session_No_Groups = new Regex("""^Session (\S+)$""")
   427     val Session_Groups = new Regex("""^Session (\S+) \((.*)\)$""")
   428     val Session_Finished1 =
   429       new Regex("""^Finished (\S+) \((\d+):(\d+):(\d+) elapsed time, (\d+):(\d+):(\d+) cpu time.*$""")
   430     val Session_Finished2 =
   431       new Regex("""^Finished (\S+) \((\d+):(\d+):(\d+) elapsed time.*$""")
   432     val Session_Timing =
   433       new Regex("""^Timing (\S+) \((\d) threads, (\d+\.\d+)s elapsed time, (\d+\.\d+)s cpu time, (\d+\.\d+)s GC time.*$""")
   434     val Session_Started = new Regex("""^(?:Running|Building) (\S+) \.\.\.$""")
   435     val Session_Failed = new Regex("""^(\S+) FAILED""")
   436     val Session_Cancelled = new Regex("""^(\S+) CANCELLED""")
   437     val Heap = new Regex("""^Heap (\S+) \((\d+) bytes\)$""")
   438 
   439     var chapter = Map.empty[String, String]
   440     var groups = Map.empty[String, List[String]]
   441     var threads = Map.empty[String, Int]
   442     var timing = Map.empty[String, Timing]
   443     var ml_timing = Map.empty[String, Timing]
   444     var started = Set.empty[String]
   445     var failed = Set.empty[String]
   446     var cancelled = Set.empty[String]
   447     var ml_statistics = Map.empty[String, List[Properties.T]]
   448     var heap_sizes = Map.empty[String, Long]
   449 
   450     def all_sessions: Set[String] =
   451       chapter.keySet ++ groups.keySet ++ threads.keySet ++ timing.keySet ++ ml_timing.keySet ++
   452       failed ++ cancelled ++ started ++ ml_statistics.keySet ++ heap_sizes.keySet
   453 
   454 
   455     for (line <- log_file.lines) {
   456       line match {
   457         case Session_No_Groups(Chapter_Name(chapt, name)) =>
   458           chapter += (name -> chapt)
   459           groups += (name -> Nil)
   460 
   461         case Session_Groups(Chapter_Name(chapt, name), grps) =>
   462           chapter += (name -> chapt)
   463           groups += (name -> Word.explode(grps))
   464 
   465         case Session_Started(name) =>
   466           started += name
   467 
   468         case Session_Finished1(name,
   469             Value.Int(e1), Value.Int(e2), Value.Int(e3),
   470             Value.Int(c1), Value.Int(c2), Value.Int(c3)) =>
   471           val elapsed = Time.hms(e1, e2, e3)
   472           val cpu = Time.hms(c1, c2, c3)
   473           timing += (name -> Timing(elapsed, cpu, Time.zero))
   474 
   475         case Session_Finished2(name,
   476             Value.Int(e1), Value.Int(e2), Value.Int(e3)) =>
   477           val elapsed = Time.hms(e1, e2, e3)
   478           timing += (name -> Timing(elapsed, Time.zero, Time.zero))
   479 
   480         case Session_Timing(name,
   481             Value.Int(t), Value.Double(e), Value.Double(c), Value.Double(g)) =>
   482           val elapsed = Time.seconds(e)
   483           val cpu = Time.seconds(c)
   484           val gc = Time.seconds(g)
   485           ml_timing += (name -> Timing(elapsed, cpu, gc))
   486           threads += (name -> t)
   487 
   488         case Heap(name, Value.Long(size)) =>
   489           heap_sizes += (name -> size)
   490 
   491         case _ if line.startsWith(ML_STATISTICS_MARKER) =>
   492           val (name, props) =
   493             Library.try_unprefix(ML_STATISTICS_MARKER, line).map(log_file.parse_props(_)) match {
   494               case Some((SESSION_NAME, session_name) :: props) => (session_name, props)
   495               case _ => log_file.err("malformed ML_statistics " + quote(line))
   496             }
   497           ml_statistics += (name -> (props :: ml_statistics.getOrElse(name, Nil)))
   498 
   499         case _ =>
   500       }
   501     }
   502 
   503     val sessions =
   504       Map(
   505         (for (name <- all_sessions.toList) yield {
   506           val status =
   507             if (failed(name)) Session_Status.FAILED
   508             else if (cancelled(name)) Session_Status.CANCELLED
   509             else if (timing.isDefinedAt(name) || ml_timing.isDefinedAt(name))
   510               Session_Status.FINISHED
   511             else if (started(name)) Session_Status.FAILED
   512             else Session_Status.EXISTING
   513           val entry =
   514             Session_Entry(
   515               chapter.getOrElse(name, ""),
   516               groups.getOrElse(name, Nil),
   517               threads.get(name),
   518               timing.getOrElse(name, Timing.zero),
   519               ml_timing.getOrElse(name, Timing.zero),
   520               ml_statistics.getOrElse(name, Nil).reverse,
   521               heap_sizes.get(name),
   522               status)
   523           (name -> entry)
   524         }):_*)
   525     Build_Info(sessions)
   526   }
   527 
   528 
   529 
   530   /** session info: produced by "isabelle build" **/
   531 
   532   sealed case class Session_Info(
   533     session_name: String,
   534     session_timing: Properties.T,
   535     command_timings: List[Properties.T],
   536     ml_statistics: List[Properties.T],
   537     task_statistics: List[Properties.T])
   538 
   539   private def parse_session_info(
   540     log_file: Log_File,
   541     default_name: String,
   542     command_timings: Boolean,
   543     ml_statistics: Boolean,
   544     task_statistics: Boolean): Session_Info =
   545   {
   546     val xml_cache = new XML.Cache()
   547 
   548     val session_name =
   549       log_file.find_line("\fSession.name = ") match {
   550         case None => default_name
   551         case Some(name) if default_name == "" || default_name == name => name
   552         case Some(name) => log_file.err("log from different session " + quote(name))
   553       }
   554     val session_timing = log_file.find_props("\fTiming = ") getOrElse Nil
   555     val command_timings_ =
   556       if (command_timings) log_file.filter_props("\fcommand_timing = ") else Nil
   557     val ml_statistics_ =
   558       if (ml_statistics) log_file.filter_props(ML_STATISTICS_MARKER) else Nil
   559     val task_statistics_ =
   560       if (task_statistics) log_file.filter_props("\ftask_statistics = ") else Nil
   561 
   562     Session_Info(session_name, session_timing, command_timings_, ml_statistics_, task_statistics_)
   563   }
   564 }