-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
event.go
331 lines (293 loc) · 9.2 KB
/
event.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package common
import (
"encoding"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/elastic/beats/v7/libbeat/logp"
)
// EventConverter is used to convert MapStr objects for publishing
type EventConverter interface {
Convert(m MapStr) MapStr
}
// GenericEventConverter is used to normalize MapStr objects for publishing
type GenericEventConverter struct {
log *logp.Logger
keepNull bool
}
// NewGenericEventConverter creates an EventConverter with the given configuration options
func NewGenericEventConverter(keepNull bool) *GenericEventConverter {
return &GenericEventConverter{
log: logp.NewLogger("event"),
keepNull: keepNull,
}
}
// Convert normalizes the types contained in the given MapStr.
//
// Nil values in maps are dropped during the conversion. Any unsupported types
// that are found in the MapStr are dropped and warnings are logged.
func (e *GenericEventConverter) Convert(m MapStr) MapStr {
keys := make([]string, 0, 10)
event, errs := e.normalizeMap(m, keys...)
if len(errs) > 0 {
e.log.Warnf("Unsuccessful conversion to generic event: %v errors: %v, "+
"event=%#v", len(errs), errs, m)
}
return event
}
// normalizeMap normalizes each element contained in the given map. If an error
// occurs during normalization, processing of m will continue, and all errors
// are returned at the end.
func (e *GenericEventConverter) normalizeMap(m MapStr, keys ...string) (MapStr, []error) {
var errs []error
out := make(MapStr, len(m))
for key, value := range m {
v, err := e.normalizeValue(value, append(keys, key)...)
if len(err) > 0 {
errs = append(errs, err...)
}
// Drop nil values from maps.
if !e.keepNull && v == nil {
if e.log.IsDebug() {
e.log.Debugf("Dropped nil value from event where key=%v", joinKeys(append(keys, key)...))
}
continue
}
out[key] = v
}
return out, errs
}
// normalizeMapStrSlice normalizes each individual MapStr.
func (e *GenericEventConverter) normalizeMapStrSlice(maps []MapStr, keys ...string) ([]MapStr, []error) {
var errs []error
out := make([]MapStr, 0, len(maps))
for i, m := range maps {
normalizedMap, err := e.normalizeMap(m, append(keys, strconv.Itoa(i))...)
if len(err) > 0 {
errs = append(errs, err...)
}
out = append(out, normalizedMap)
}
return out, errs
}
// normalizeMapStringSlice normalizes each individual map[string]interface{} and
// returns a []MapStr.
func (e *GenericEventConverter) normalizeMapStringSlice(maps []map[string]interface{}, keys ...string) ([]MapStr, []error) {
var errs []error
out := make([]MapStr, 0, len(maps))
for i, m := range maps {
normalizedMap, err := e.normalizeMap(m, append(keys, strconv.Itoa(i))...)
if len(err) > 0 {
errs = append(errs, err...)
}
out = append(out, normalizedMap)
}
return out, errs
}
// normalizeSlice normalizes each element of the slice and returns a []interface{}.
func (e *GenericEventConverter) normalizeSlice(v reflect.Value, keys ...string) (interface{}, []error) {
var errs []error
var sliceValues []interface{}
n := v.Len()
for i := 0; i < n; i++ {
sliceValue, err := e.normalizeValue(v.Index(i).Interface(), append(keys, strconv.Itoa(i))...)
if len(err) > 0 {
errs = append(errs, err...)
}
sliceValues = append(sliceValues, sliceValue)
}
return sliceValues, errs
}
func (e *GenericEventConverter) normalizeValue(value interface{}, keys ...string) (interface{}, []error) {
if value == nil {
return nil, nil
}
// Normalize time values to a common.Time with UTC time zone.
switch v := value.(type) {
case time.Time:
value = Time(v.UTC())
case []time.Time:
times := make([]Time, 0, len(v))
for _, t := range v {
times = append(times, Time(t.UTC()))
}
value = times
case Time:
value = Time(time.Time(v).UTC())
case []Time:
times := make([]Time, 0, len(v))
for _, t := range v {
times = append(times, Time(time.Time(t).UTC()))
}
value = times
}
switch value.(type) {
case encoding.TextMarshaler:
if reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil() {
return nil, nil
}
text, err := value.(encoding.TextMarshaler).MarshalText()
if err != nil {
return nil, []error{errors.Wrapf(err, "key=%v: error converting %T to string", joinKeys(keys...), value)}
}
return string(text), nil
case string, []string:
case bool, []bool:
case int, int8, int16, int32, int64:
case []int, []int8, []int16, []int32, []int64:
case uint, uint8, uint16, uint32:
case uint64:
return value.(uint64) &^ (1 << 63), nil
case []uint, []uint8, []uint16, []uint32:
case []uint64:
arr := value.([]uint64)
mask := false
for _, v := range arr {
if v >= (1 << 63) {
mask = true
break
}
}
if !mask {
return value, nil
}
tmp := make([]uint64, len(arr))
for i, v := range arr {
tmp[i] = v &^ (1 << 63)
}
return tmp, nil
case float32, float64:
case []float32, []float64:
case complex64, complex128:
case []complex64, []complex128:
case Time, []Time:
case MapStr:
return e.normalizeMap(value.(MapStr), keys...)
case []MapStr:
return e.normalizeMapStrSlice(value.([]MapStr), keys...)
case map[string]interface{}:
return e.normalizeMap(value.(map[string]interface{}), keys...)
case []map[string]interface{}:
return e.normalizeMapStringSlice(value.([]map[string]interface{}), keys...)
default:
v := reflect.ValueOf(value)
switch v.Type().Kind() {
case reflect.Ptr:
// Dereference pointers.
return e.normalizeValue(followPointer(value), keys...)
case reflect.Bool:
return v.Bool(), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int(), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() &^ (1 << 63), nil
case reflect.Float32, reflect.Float64:
return v.Float(), nil
case reflect.Complex64, reflect.Complex128:
return v.Complex(), nil
case reflect.String:
return v.String(), nil
case reflect.Array, reflect.Slice:
return e.normalizeSlice(v, keys...)
case reflect.Map, reflect.Struct:
var m MapStr
err := marshalUnmarshal(value, &m)
if err != nil {
return m, []error{errors.Wrapf(err, "key=%v: error converting %T to MapStr", joinKeys(keys...), value)}
}
return m, nil
default:
// Drop Uintptr, UnsafePointer, Chan, Func, Interface, and any other
// types not specifically handled above.
return nil, []error{fmt.Errorf("key=%v: error unsupported type=%T value=%#v", joinKeys(keys...), value, value)}
}
}
return value, nil
}
// marshalUnmarshal converts an interface to a MapStr by marshalling to JSON
// then unmarshalling the JSON object into a MapStr.
func marshalUnmarshal(in interface{}, out interface{}) error {
// Decode and encode as JSON to normalized the types.
marshaled, err := json.Marshal(in)
if err != nil {
return errors.Wrap(err, "error marshalling to JSON")
}
err = json.Unmarshal(marshaled, out)
if err != nil {
return errors.Wrap(err, "error unmarshalling from JSON")
}
return nil
}
// followPointer accepts an interface{} and if the interface is a pointer then
// the value that v points to is returned. If v is not a pointer then v is
// returned.
func followPointer(v interface{}) interface{} {
if v == nil || reflect.TypeOf(v).Kind() != reflect.Ptr {
return v
}
val := reflect.ValueOf(v)
if val.IsNil() {
return nil
}
return val.Elem().Interface()
}
// joinKeys concatenates the keys into a single string with each key separated
// by a dot.
func joinKeys(keys ...string) string {
// Strip leading empty string.
if len(keys) > 0 && keys[0] == "" {
keys = keys[1:]
}
return strings.Join(keys, ".")
}
// DeDot a string by replacing all . with _
// This helps when sending data to Elasticsearch to prevent object and key collisions.
func DeDot(s string) string {
return strings.Replace(s, ".", "_", -1)
}
// DeDotJSON replaces in keys all . with _
// This helps when sending data to Elasticsearch to prevent object and key collisions.
func DeDotJSON(json interface{}) interface{} {
switch json := json.(type) {
case map[string]interface{}:
result := map[string]interface{}{}
for key, value := range json {
result[DeDot(key)] = DeDotJSON(value)
}
return result
case MapStr:
result := MapStr{}
for key, value := range json {
result[DeDot(key)] = DeDotJSON(value)
}
return result
case []interface{}:
result := make([]interface{}, len(json))
for i, value := range json {
result[i] = DeDotJSON(value)
}
return result
default:
return json
}
}