Debian Codegraph @

core/parsing_time.go

raw
1 package core
2
3 import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8 "time"
9
10 "github.com/juju/errors"
11 )
12
13 // TimeFormatDescr contains all data necessary for Nerdlog to parse timestamps
14 // in the particular logstream. It contains info for both the awk script and Go
15 // client.
16 type TimeFormatDescr struct {
17 // TimestampLayout is a Go-style time layout which should parse the entire
18 // timestamp in the log line, e.g. "Jan _2 15:04:05" or
19 // "2006-01-02T15:04:05.000000Z07:00".
20 TimestampLayout string
21
22 // MinuteKeyLayout is a Go-style time layout which should parse the time
23 // captured by the awk expression `TimeFormatAWKExpr.MinuteKey` (read there
24 // what "minute key" means in the first place).
25 //
26 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
27 // "Jan _2 15:04".
28 //
29 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
30 // "2006-01-02T15:04" (if we decided to include the year) or "01-02T15:04"
31 // (if we decided to not include the year).
32 MinuteKeyLayout string
33
34 // AWKExpr contains all the awk expressions which will be used by the
35 // nerdlog_agent.sh script to get the time components from logs.
36 AWKExpr TimeFormatAWKExpr
37 }
38
39 // TimeFormatAWKExpr contains all the awk expressions which will be used by
40 // the nerdlog_agent.sh script to get the time components from logs.
41 type TimeFormatAWKExpr struct {
42 // Month is an AWK expression to get month number as a string, from "01" to
43 // "12". It may use `monthByName`, which is a map from a 3-char string like
44 // "Jan" to the corresponding string like "01".
45 //
46 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
47 // "monthByName[$1]".
48 //
49 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
50 // "substr($0, 6, 2)".
51 Month string
52
53 // Year is an AWK expression to get year string like "2024". If the format
54 // doesn't contain the year, it may use the already-computed `month` and
55 // `yearByMonth`, which is a mapping from the month (from "01" to "12") to
56 // the corresponding inferred year.
57 //
58 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
59 // "yearByMonth[month]".
60 //
61 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
62 // "substr($0, 1, 4)".
63 Year string
64
65 // Day is an AWK expression to get the day string like "05"; note the leading
66 // zero, it's important (TODO: make it possible to support spaces; it'd mean
67 // having spaces in the index and in the --from and --to args, which has issues)
68 //
69 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
70 // `(length($2) == 1) ? "0" $2 : $2`.
71 //
72 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
73 // "substr($0, 9, 2)".
74 Day string
75
76 // HHMM is an AWK expression to get the hours and minutes string like "14:38".
77 //
78 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
79 // "substr($3, 1, 5)".
80 //
81 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
82 // "substr($0, 12, 5)".
83 HHMM string
84
85 // MinuteKey is an AWK expression to get a string covering all timestamp
86 // components from minute and larger. It'll be used as a key to identify a
87 // particular minute (in the mapping from the minute to the amount of logs in
88 // that minute), hence the name; so it should not include seconds, and it
89 // should include minute+hour+day+month, maybe even year but that's optional,
90 // since Nerdlog is not designed to look at logs spanning more than one year.
91 //
92 // So e.g. for the traditional syslog format "Jan _2 15:04:05", it should be
93 // "substr($0, 1, 12)".
94 //
95 // For the format "2006-01-02T15:04:05.000000Z07:00", it should rather be
96 // "substr($0, 1, 16)" (to include the year) or "substr($0, 6, 11)" (to not
97 // include the year).
98 MinuteKey string
99 }
100
101 func GetTimeFormatDescrFromLogLines(logLines []string) (*TimeFormatDescr, error) {
102 if len(logLines) == 0 {
103 return nil, errors.Errorf("no logs, can't detect time format")
104 }
105
106 descrs := make([]*TimeFormatDescr, 0, len(logLines))
107
108 for i, line := range logLines {
109 layout := DetectTimeLayout(line)
110 if layout == "" {
111 return nil, errors.Errorf("unable to detect time format from %q", line)
112 }
113
114 timeDescr, err := GenerateTimeDescr(layout)
115 if err != nil {
116 return nil, errors.Trace(err)
117 }
118
119 if i > 0 {
120 if descrs[0].TimestampLayout != timeDescr.TimestampLayout {
121 return nil, errors.Errorf(
122 "log lines have different formats: %s and %s",
123 descrs[0].TimestampLayout,
124 timeDescr.TimestampLayout,
125 )
126 }
127 }
128
129 descrs = append(descrs, timeDescr)
130 }
131
132 return descrs[0], nil
133 }
134
135 // DetectTimeLayout tries to detect a time format from a log line.
136 //
137 // TODO: it's pretty simplistic and could be improved, even to avoid having
138 // a predefined set of known formats, but good enough for now.
139 func DetectTimeLayout(logLine string) string {
140 var knownFormats = []string{
141 "Jan _2 15:04:05", // Traditional rsyslog format without year
142 "2006-01-02T15:04:05.000000Z07:00", // ISO8601, used in modern rsyslog by default
143 "2006-01-02T15:04:05.000000-0700", // Used by older versions of journalctl with --output=short-iso-precise
144 "2006-01-02 15:04:05",
145 "2006-01-02T15:04:05Z07:00",
146 "2006-01-02T15:04:05.000Z07:00",
147 "02/Jan/2006:15:04:05 -0700",
148 "2006/01/02 15:04:05",
149 "Mon Jan 2 15:04:05 2006",
150 "02-Jan-2006 15:04:05",
151 "Jan 02 15:04:05",
152
153 // Some variations of Apache HTTP Server logs
154 "[Mon Jan 02 15:04:05.999999 2006]",
155 "[Mon Jan 02 15:04:05 2006]",
156 }
157
158 for _, layout := range knownFormats {
159 for curLen := 5; curLen <= len(layout) && curLen <= len(logLine); curLen++ {
160 sub := logLine[:curLen]
161 _, err := time.Parse(layout, sub)
162 if err == nil {
163 return layout
164 }
165 }
166 }
167 return ""
168 }
169
170 // GenerateTimeDescr takes a Go-style time layout, and returns the full time
171 // format descriptor to be used for parsing all logs.
172 func GenerateTimeDescr(layout string) (*TimeFormatDescr, error) {
173 // Find index positions of time components
174 partInfo := map[string]*indexAndLength{
175 "year": indexAndLengthOfTimeComponent(layout, "2006"),
176 "month": indexAndLengthOfTimeComponent(layout, "Jan", "01", "_1"),
177 "day": indexAndLengthOfTimeComponent(layout, "02", "_2"),
178 "hhmm": indexAndLengthOfTimeComponent(layout, "15:04"),
179 "second": indexAndLengthOfTimeComponent(layout, "05"),
180 }
181
182 // Validate that required fields exist
183 if partInfo["hhmm"] == nil || partInfo["day"] == nil || partInfo["month"] == nil {
184 return nil, errors.New("unsupported layout: required components not found")
185 }
186
187 // Helper to generate substr($0, x, y)
188 substr := func(start, length int) string {
189 return "substr($0, " + itoa(start+1) + ", " + itoa(length) + ")"
190 }
191
192 // Like substr for 2-digit numbers like month or day, but replaces the first
193 // space with "0".
194 //
195 // TODO: ideally support spaces in day and month (which would mean supporting
196 // spaces in index as well as --from and --to), and remove this.
197 substrCheckingForSpace := func(start, length int) string {
198 if length == 2 && layout[start] == '_' {
199 return fmt.Sprintf(
200 `(%s == " ") ? "0" %s : %s`,
201 substr(start, 1),
202 substr(start+1, 1),
203 substr(start, 2),
204 )
205 }
206
207 return substr(start, length)
208 }
209
210 minuteKeyStart := minIndex(partInfo["month"], partInfo["day"], partInfo["hhmm"]).index
211 minuteKeyEnd1 := maxIndex(partInfo["month"], partInfo["day"], partInfo["hhmm"])
212 minuteKeyEnd := minuteKeyEnd1.index + minuteKeyEnd1.length
213
214 if partInfo["second"] != nil {
215 if partInfo["second"].index >= minuteKeyStart && partInfo["second"].index < minuteKeyEnd {
216 return nil, errors.Errorf("seconds are in between of month, day, hour and min; can't extract MinuteKey")
217 }
218 }
219
220 // Extract AWK expressions
221 awk := TimeFormatAWKExpr{
222 // Year will be set later
223 Month: substrCheckingForSpace(partInfo["month"].index, partInfo["month"].length),
224 Day: substrCheckingForSpace(partInfo["day"].index, partInfo["day"].length),
225 HHMM: substr(partInfo["hhmm"].index, partInfo["hhmm"].length),
226 MinuteKey: substr(minuteKeyStart, minuteKeyEnd-minuteKeyStart),
227 }
228
229 if partInfo["year"] != nil {
230 awk.Year = substr(partInfo["year"].index, partInfo["year"].length)
231 } else {
232 awk.Year = "yearByMonth[month]"
233 }
234
235 // If the month is not a number but a string like "Jan", use the mapping.
236 if partInfo["month"].length == 3 {
237 awk.Month = fmt.Sprintf("monthByName[%s]", awk.Month)
238 }
239
240 // Build minute layout (truncated to minute precision)
241 minuteLayout := layout[minuteKeyStart:minuteKeyEnd]
242
243 return &TimeFormatDescr{
244 TimestampLayout: layout,
245 MinuteKeyLayout: minuteLayout,
246 AWKExpr: awk,
247 }, nil
248 }
249
250 // indexAndLengthOfTimeComponent takes one or more timestamp components, such as "2006",
251 // "01", "_1", "1" etc, and returns the index of the given component in the
252 // given string s, not preceded or followed by any number or "_".
253 func indexAndLengthOfTimeComponent(s string, components ...string) *indexAndLength {
254 // Loop over each component provided
255 for _, comp := range components {
256 // Create a regular expression that matches the component, ensuring it is not
257 // preceded or followed by digits or underscores
258 re := fmt.Sprintf(`[^0-9_]?%s[^0-9_]?`, regexp.QuoteMeta(comp))
259
260 // Compile the regex
261 rgx := regexp.MustCompile(re)
262
263 // Find the first occurrence of the component
264 loc := rgx.FindStringIndex(s)
265 if loc != nil {
266 // Return the index of the first match, also removing the potentially
267 // preceding non-digit rune.
268 return &indexAndLength{
269 index: loc[0] + strings.Index(s[loc[0]:], comp),
270 length: len(comp),
271 }
272 }
273 }
274 // Return -1 if no component is found
275 return nil
276 }
277
278 type indexAndLength struct {
279 index int
280 length int
281 }
282
283 func itoa(i int) string {
284 return strconv.Itoa(i)
285 }
286
287 func minIndex(vals ...*indexAndLength) *indexAndLength {
288 curMin := 999
289 curMinIdx := -1
290 for i, v := range vals {
291 if v.index < curMin {
292 curMin = v.index
293 curMinIdx = i
294 }
295 }
296 return vals[curMinIdx]
297 }
298
299 func maxIndex(vals ...*indexAndLength) *indexAndLength {
300 curMax := -1
301 curMaxIdx := -1
302 for i, v := range vals {
303 if v.index > curMax {
304 curMax = v.index
305 curMaxIdx = i
306 }
307 }
308 return vals[curMaxIdx]
309 }