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