in internal/onetime/aianalyze/helpers.go [39:118]
func (a *AiAnalyzer) extractTimeWindowFromText(ctx context.Context, text string, isPacemaker bool) (string, error) {
var timestampFormat, timestampWithoutMicrosecondsFormat string
var logPattern *regexp.Regexp
if isPacemaker {
timestampFormat = "2006-01-02 15:04:05.000"
timestampWithoutMicrosecondsFormat = "2006-01-02 15:04:05"
// Example: "Jan 02 15:04:05.000"
logPattern = regexp.MustCompile(`(\w{3} \d{2} \d{2}:\d{2}:\d{2}\.\d{3})`)
} else {
timestampFormat = "2006-01-02 15:04:05.999999"
timestampWithoutMicrosecondsFormat = "2006-01-02 15:04:05"
// Example: [31641]{-1}[-1/-1] 2024-07-18 20:30:31.545848
logPattern = regexp.MustCompile(`\[\d+\]\{-?\d+}\[-?\d+.*? (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d{6})?)`)
}
var targetTime, logTime time.Time
var err error
targetTime, err = time.Parse(timestampFormat, a.Timestamp)
if err != nil {
targetTime, err = time.Parse(timestampWithoutMicrosecondsFormat, a.Timestamp)
if err != nil {
log.CtxLogger(ctx).Errorw("Error parsing target timestamp", "error", err)
return "", err
}
}
startTime := targetTime.Add(-time.Duration(a.BeforeEventWindow) * time.Second)
endTime := targetTime.Add(time.Duration(a.AfterEventWindow) * time.Second)
windowStart := -1
windowEnd := -1
lines := strings.Split(text, "\n")
for i, line := range lines {
match := logPattern.FindStringSubmatch(line)
if len(match) > 0 {
if isPacemaker {
logTimeStr := match[0]
logTime, err = time.Parse("Jan 2 15:04:05.000", logTimeStr)
if err != nil {
log.CtxLogger(ctx).Errorw("Error parsing log timestamp", "line", line, "error", err)
continue
}
logTime = logTime.AddDate(targetTime.Year(), 0, 0)
} else {
logTimeStr := match[1]
logTime, err = time.Parse(timestampFormat, logTimeStr)
if err != nil {
logTime, err = time.Parse(timestampWithoutMicrosecondsFormat, logTimeStr)
if err != nil {
log.CtxLogger(ctx).Errorw("Error parsing log timestamp", "line", line, "error", err)
continue
}
}
}
if logTime.Before(startTime) {
continue
} else if logTime.After(endTime) {
break
} else {
if windowStart == -1 {
windowStart = i
}
windowEnd = i
}
} else {
if windowStart != -1 {
windowEnd = i
}
}
}
if windowStart != -1 {
return strings.Join(lines[windowStart:windowEnd+1], "\n"), nil
} else {
log.CtxLogger(ctx).Warn("No logs found within the time window")
return "", nil
}
}