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