forked from kata-containers/kata-containers
-
Notifications
You must be signed in to change notification settings - Fork 4
/
parse.go
341 lines (272 loc) · 7.64 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//
// Copyright (c) 2017-2018 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"errors"
"fmt"
"io"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/go-logfmt/logfmt"
)
const (
// Tell time.Parse() how to handle the various logfile timestamp
// formats by providing a number of formats for the "magic" data the
// golang time package mandates:
//
// "Mon Jan 2 15:04:05 -0700 MST 2006"
//
dateFormat = "2006-01-02T15:04:05.999999999Z07:00"
// The timezone of an RFC3339 timestamp can either be "Z" to denote
// UTC, or "+/-HH:MM" to denote an actual offset.
timezonePattern = `(` +
`Z` +
`|` +
`[\+|\-]\d{2}:\d{2}` +
`)`
dateFormatPattern =
// YYYY-MM-DD
`\d{4}-\d{2}-\d{2}` +
// time separator
`T` +
// HH:MM:SS
`\d{2}:\d{2}:\d{2}` +
// high-precision separator
`.` +
// nano-seconds. Note that the quantifier range is
// required because the time.RFC3339Nano format
// trunctates trailing zeros.
`\d{1,9}` +
// timezone
timezonePattern
agentContainerIDPattern = `container_id:"([^"]*)"`
)
type kvPair struct {
key string
value string
}
type kvPairs []kvPair
var (
dateFormatRE *regexp.Regexp
agentContainerIDRE *regexp.Regexp
)
func init() {
dateFormatRE = regexp.MustCompile(dateFormatPattern)
agentContainerIDRE = regexp.MustCompile(agentContainerIDPattern)
}
// parseLogFmtData reads logfmt records using the provided reader and returns
// log entries.
//
// Note that the filename specified is not validated - it is added to the
// returned log entries and also used for returned errors.
func parseLogFmtData(reader io.Reader, file string, ignoreMissingFields bool) (LogEntries, error) {
entries := LogEntries{}
d := logfmt.NewDecoder(reader)
line := uint64(0)
// A record is a single line
for d.ScanRecord() {
line++
var keyvals kvPairs
// split the line into key/value pairs
for d.ScanKeyval() {
key := string(d.Key())
value := string(d.Value())
// If agent debug is enabled, every gRPC request ("req")
// is logged. Since most such requests contain the
// container ID as a `container_id` field, extract and
// save it when present.
//
// See: https://github.com/kata-containers/agent/blob/master/protocols/grpc/agent.proto
//
// Note that we save the container ID in addition to
// the original value.
if key == "req" {
matches := agentContainerIDRE.FindSubmatch([]byte(value))
if matches != nil {
containerID := string(matches[1])
pair := kvPair{
key: "container",
value: containerID,
}
// save key/value pair
keyvals = append(keyvals, pair)
}
}
pair := kvPair{
key: key,
value: value,
}
// save key/value pair
keyvals = append(keyvals, pair)
}
if err := d.Err(); err != nil {
return LogEntries{},
fmt.Errorf("failed to parse file %q, line %d: %v (keyvals: %+v)",
file, line, err, keyvals)
}
entry, err := createLogEntry(file, line, keyvals)
if err != nil {
return LogEntries{}, err
}
err = entry.Check(ignoreMissingFields)
if err != nil {
return LogEntries{}, err
}
entries.Entries = append(entries.Entries, entry)
}
if d.Err() != nil {
return LogEntries{},
fmt.Errorf("failed to parse file %q line %d: %v", file, line, d.Err())
}
return entries, nil
}
// parseLogFile reads a logfmt format logfile and converts it into log
// entries.
func parseLogFile(file string, ignoreMissingFields bool) (LogEntries, error) {
// logfmt is unhappy attempting to read hex-encoded bytes in strings,
// so hide those from it by escaping them.
reader := NewHexByteReader(file)
return parseLogFmtData(reader, file, ignoreMissingFields)
}
// parseLogFiles parses all log files, sorts the results by timestamp and
// returns the collated results
func parseLogFiles(files []string, ignoreMissingFields bool) (LogEntries, error) {
entries := LogEntries{
FormatVersion: logEntryFormatVersion,
}
for _, file := range files {
e, err := parseLogFile(file, ignoreMissingFields)
if err != nil {
return LogEntries{}, err
}
entries.Entries = append(entries.Entries, e.Entries...)
}
sort.Sort(entries)
return entries, nil
}
// parseTime attempts to convert the specified timestamp string into a Time
// object by checking it against various known timestamp formats.
func parseTime(timeString string) (time.Time, error) {
if timeString == "" {
return time.Time{}, errors.New("need time string")
}
t, err := time.Parse(dateFormat, timeString)
if err != nil {
return time.Time{}, err
}
// time.Parse() is "clever" but also doesn't check anything more
// granular than a second, so let's be completely paranoid and check
// via regular expression too.
matched := dateFormatRE.FindAllStringSubmatch(timeString, -1)
if matched == nil {
return time.Time{},
fmt.Errorf("expected time in format %q, got %q", dateFormatPattern, timeString)
}
return t, nil
}
func checkKeyValueValid(key, value string) error {
if key == "" {
return fmt.Errorf("key cannot be blank (value: %q)", value)
}
if strings.TrimSpace(key) == "" {
return fmt.Errorf("key cannot be pure whitespace (value: %q)", value)
}
err := checkValid(key)
if err != nil {
return fmt.Errorf("key %q is invalid (value: %q): %v", key, value, err)
}
err = checkValid(value)
if err != nil {
return fmt.Errorf("value %q is invalid (key: %v): %v", value, key, err)
}
return nil
}
// handleLogEntry takes a partial LogEntry and adds values to it based on the
// key and value specified.
func handleLogEntry(l *LogEntry, key, value string) (err error) {
if l == nil {
return errors.New("invalid LogEntry")
}
if err = checkKeyValueValid(key, value); err != nil {
return fmt.Errorf("%v (entry: %+v)", err, l)
}
switch key {
case "container":
l.Container = value
case "level":
l.Level = value
case "msg":
l.Msg = value
case "name":
l.Name = value
case "pid":
pid := 0
if value != "" {
pid, err = strconv.Atoi(value)
if err != nil {
return fmt.Errorf("failed to parse pid from value %v (entry: %+v, key: %v): %v", value, l, key, err)
}
}
l.Pid = pid
case "sandbox":
l.Sandbox = value
case "source":
l.Source = value
case "time":
t, err := parseTime(value)
if err != nil {
return fmt.Errorf("failed to parse time for value %v (entry: %+v, key: %v): %v", value, l, key, err)
}
l.Time = t
default:
if v, exists := l.Data[key]; exists {
return fmt.Errorf("key %q already exists in map with value %q (entry: %+v)", key, v, l)
}
// non-standard fields are stored here
l.Data[key] = value
}
return nil
}
// createLogEntry converts a logfmt record into a LogEntry.
func createLogEntry(filename string, line uint64, pairs kvPairs) (LogEntry, error) {
if filename == "" {
return LogEntry{}, fmt.Errorf("need filename")
}
if line == 0 {
return LogEntry{}, fmt.Errorf("need line number for file %v", filename)
}
if len(pairs) == 0 {
return LogEntry{}, fmt.Errorf("need key/value pairs for line %v:%d", filename, line)
}
l := LogEntry{}
l.Filename = filename
l.Line = line
l.Data = make(map[string]string)
for _, v := range pairs {
if err := handleLogEntry(&l, v.key, v.value); err != nil {
return LogEntry{}, fmt.Errorf("%v (entry: %+v)", err, l)
}
}
if !disableAgentUnpack && agentLogEntry(l) {
agent, err := unpackAgentLogEntry(l)
if err != nil {
// allow the user to see that the unpack failed
l.Data[agentUnpackFailTag] = "true"
if strict {
return LogEntry{}, err
}
logger.Warnf("failed to unpack agent log entry %v: %v", l, err)
} else {
// the agent log entry totally replaces the proxy log entry
// that encapsulated it.
l = agent
}
}
return l, nil
}