-
Notifications
You must be signed in to change notification settings - Fork 479
/
json.go
180 lines (157 loc) · 4.57 KB
/
json.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
package stages
// This package is ported over from grafana/loki/clients/pkg/logentry/stages.
// We aim to port the stages in steps, to avoid introducing huge amounts of
// new code without being able to slowly review, examine and test them.
import (
"errors"
"fmt"
"reflect"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/jmespath/go-jmespath"
json "github.com/json-iterator/go"
)
// Config Errors
const (
ErrExpressionsRequired = "JMES expression is required"
ErrCouldNotCompileJMES = "could not compile JMES expression"
ErrEmptyJSONStageConfig = "empty json stage configuration"
ErrEmptyJSONStageSource = "empty source"
ErrMalformedJSON = "malformed json"
)
// JSONConfig represents a JSON Stage configuration
type JSONConfig struct {
Expressions map[string]string `river:"expressions,attr"`
Source *string `river:"source,attr,optional"`
DropMalformed bool `river:"drop_malformed,attr,optional"`
}
// validateJSONConfig validates a json config and returns a map of necessary jmespath expressions.
func validateJSONConfig(c *JSONConfig) (map[string]*jmespath.JMESPath, error) {
if c == nil {
return nil, errors.New(ErrEmptyJSONStageConfig)
}
if len(c.Expressions) == 0 {
return nil, errors.New(ErrExpressionsRequired)
}
if c.Source != nil && *c.Source == "" {
return nil, errors.New(ErrEmptyJSONStageSource)
}
expressions := map[string]*jmespath.JMESPath{}
for n, e := range c.Expressions {
var err error
jmes := e
// If there is no expression, use the name as the expression.
if e == "" {
jmes = n
}
expressions[n], err = jmespath.Compile(jmes)
if err != nil {
return nil, fmt.Errorf("%s: %w", ErrCouldNotCompileJMES, err)
}
}
return expressions, nil
}
// jsonStage sets extracted data using JMESPath expressions
type jsonStage struct {
cfg *JSONConfig
expressions map[string]*jmespath.JMESPath
logger log.Logger
}
// newJSONStage creates a new json pipeline stage from a config.
func newJSONStage(logger log.Logger, cfg JSONConfig) (Stage, error) {
expressions, err := validateJSONConfig(&cfg)
if err != nil {
return nil, err
}
return &jsonStage{
cfg: &cfg,
expressions: expressions,
logger: log.With(logger, "component", "stage", "type", "json"),
}, nil
}
func (j *jsonStage) Run(in chan Entry) chan Entry {
out := make(chan Entry)
go func() {
defer close(out)
for e := range in {
err := j.processEntry(e.Extracted, &e.Line)
if err != nil && j.cfg.DropMalformed {
continue
}
out <- e
}
}()
return out
}
func (j *jsonStage) processEntry(extracted map[string]interface{}, entry *string) error {
// If a source key is provided, the json stage should process it
// from the extracted map, otherwise should fall back to the entry
input := entry
if j.cfg.Source != nil {
if _, ok := extracted[*j.cfg.Source]; !ok {
if Debug {
level.Debug(j.logger).Log("msg", "source does not exist in the set of extracted values", "source", *j.cfg.Source)
}
return nil
}
value, err := getString(extracted[*j.cfg.Source])
if err != nil {
if Debug {
level.Debug(j.logger).Log("msg", "failed to convert source value to string", "source", *j.cfg.Source, "err", err, "type", reflect.TypeOf(extracted[*j.cfg.Source]))
}
return nil
}
input = &value
}
if input == nil {
if Debug {
level.Debug(j.logger).Log("msg", "cannot parse a nil entry")
}
return nil
}
var data map[string]interface{}
if err := json.Unmarshal([]byte(*input), &data); err != nil {
if Debug {
level.Debug(j.logger).Log("msg", "failed to unmarshal log line", "err", err)
}
return errors.New(ErrMalformedJSON)
}
for n, e := range j.expressions {
r, err := e.Search(data)
if err != nil {
if Debug {
level.Debug(j.logger).Log("msg", "failed to search JMES expression", "err", err)
}
continue
}
switch r.(type) {
case float64:
// All numbers in JSON are unmarshaled to float64.
extracted[n] = r
case string:
extracted[n] = r
case bool:
extracted[n] = r
case nil:
extracted[n] = nil
default:
// If the value wasn't a string or a number, marshal it back to json
jm, err := json.Marshal(r)
if err != nil {
if Debug {
level.Debug(j.logger).Log("msg", "failed to marshal complex type back to string", "err", err)
}
continue
}
extracted[n] = string(jm)
}
}
if Debug {
level.Debug(j.logger).Log("msg", "extracted data debug in json stage", "extracted data", fmt.Sprintf("%v", extracted))
}
return nil
}
// Name implements Stage
func (j *jsonStage) Name() string {
return StageTypeJSON
}