-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
entry_parser.go
104 lines (93 loc) · 2.29 KB
/
entry_parser.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
package api
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"github.com/prometheus/common/model"
)
// EntryParser describes how to parse log lines.
type EntryParser int
// Different supported EntryParsers.
const (
Docker EntryParser = iota
Raw
CRI
)
var (
criPattern = regexp.MustCompile(`^(?s)(?P<time>\S+?) (?P<stream>stdout|stderr) (?P<flags>\S+?) (?P<content>.*)$`)
)
// String returns a string representation of the EntryParser.
func (e EntryParser) String() string {
switch e {
case CRI:
return "cri"
case Docker:
return "docker"
case Raw:
return "raw"
default:
panic(e)
}
}
// Set implements flag.Value.
func (e *EntryParser) Set(s string) error {
switch strings.ToLower(s) {
case "cri":
*e = CRI
return nil
case "docker":
*e = Docker
return nil
case "raw":
*e = Raw
return nil
default:
return fmt.Errorf("unrecognised EntryParser: %v", s)
}
}
// UnmarshalYAML implements yaml.Unmarshaler.
func (e *EntryParser) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
return e.Set(s)
}
// Wrap implements EntryMiddleware.
func (e EntryParser) Wrap(next EntryHandler) EntryHandler {
switch e {
case CRI:
return EntryHandlerFunc(func(labels model.LabelSet, _ time.Time, line string) error {
parts := criPattern.FindStringSubmatch(line)
if parts == nil || len(parts) < 5 {
return fmt.Errorf("Line did not match the CRI log format: '%s'", line)
}
timestamp, err := time.Parse(time.RFC3339Nano, parts[1])
if err != nil {
return fmt.Errorf("CRI timestamp '%s' does not match RFC3339Nano", parts[1])
}
labels = labels.Merge(model.LabelSet{"stream": model.LabelValue(parts[2])})
return next.Handle(labels, timestamp, parts[4])
})
case Docker:
return EntryHandlerFunc(func(labels model.LabelSet, _ time.Time, line string) error {
// Docker-style json object per line.
var entry struct {
Log string
Stream string
Time time.Time
}
if err := json.Unmarshal([]byte(line), &entry); err != nil {
return err
}
labels = labels.Merge(model.LabelSet{"stream": model.LabelValue(entry.Stream)})
return next.Handle(labels, entry.Time, entry.Log)
})
case Raw:
return next
default:
panic(fmt.Sprintf("unrecognised EntryParser: %s", e))
}
}