/
event_strings.go
362 lines (334 loc) · 9.53 KB
/
event_strings.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// © 2022 Nokia.
//
// This code is a Contribution to the gNMIc project (“Work”) made under the Google Software Grant and Corporate Contributor License Agreement (“CLA”) and governed by the Apache License 2.0.
// No other rights or licenses in or to any of Nokia’s intellectual property are granted for any other purpose.
// This code is provided on an “as is” basis without any warranties of any kind.
//
// SPDX-License-Identifier: Apache-2.0
package event_strings
import (
"encoding/json"
"io"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/openconfig/gnmic/pkg/api/types"
"github.com/openconfig/gnmic/pkg/api/utils"
"github.com/openconfig/gnmic/pkg/formatters"
)
const (
processorType = "event-strings"
loggingPrefix = "[" + processorType + "] "
nameField = "name"
valueField = "value"
)
// stringsp provides some of Golang's strings functions to transform: tags, tag names, values and value names
type stringsp struct {
Tags []string `mapstructure:"tags,omitempty" json:"tags,omitempty"`
Values []string `mapstructure:"values,omitempty" json:"values,omitempty"`
TagNames []string `mapstructure:"tag-names,omitempty" json:"tag-names,omitempty"`
ValueNames []string `mapstructure:"value-names,omitempty" json:"value-names,omitempty"`
Debug bool `mapstructure:"debug,omitempty" json:"debug,omitempty"`
Transforms []map[string]*transform `mapstructure:"transforms,omitempty" json:"transforms,omitempty"`
tags []*regexp.Regexp
values []*regexp.Regexp
tagKeys []*regexp.Regexp
valueKeys []*regexp.Regexp
logger *log.Logger
}
type transform struct {
op string
// apply the transformation on name or value
ApplyOn string `mapstructure:"apply-on,omitempty" json:"apply-on,omitempty"`
// Keep the old value or not if the name changed
Keep bool `mapstructure:"keep,omitempty" json:"keep,omitempty"`
// string to be replaced
Old string `mapstructure:"old,omitempty" json:"old,omitempty"`
// replacement string of Old
New string `mapstructure:"new,omitempty" json:"new,omitempty"`
// Prefix to be trimmed
Prefix string `mapstructure:"prefix,omitempty" json:"prefix,omitempty"`
// Suffix to be trimmed
Suffix string `mapstructure:"suffix,omitempty" json:"suffix,omitempty"`
// character to split on
SplitOn string `mapstructure:"split-on,omitempty" json:"split-on,omitempty"`
// character to join with
JoinWith string `mapstructure:"join-with,omitempty" json:"join-with,omitempty"`
// number of first items to ignore when joining
IgnoreFirst int `mapstructure:"ignore-first,omitempty" json:"ignore-first,omitempty"`
// number of last items to ignore when joining
IgnoreLast int `mapstructure:"ignore-last,omitempty" json:"ignore-last,omitempty"`
//
replaceRegexp *regexp.Regexp
}
func init() {
formatters.Register(processorType, func() formatters.EventProcessor {
return &stringsp{
logger: log.New(io.Discard, "", 0),
}
})
}
func (s *stringsp) Init(cfg interface{}, opts ...formatters.Option) error {
err := formatters.DecodeConfig(cfg, s)
if err != nil {
return err
}
for _, opt := range opts {
opt(s)
}
for i := range s.Transforms {
for k := range s.Transforms[i] {
s.Transforms[i][k].op = k
switch k {
case "replace":
s.Transforms[i][k].replaceRegexp, err = regexp.Compile(s.Transforms[i][k].Old)
if err != nil {
return err
}
}
}
}
// init tags regex
s.tags = make([]*regexp.Regexp, 0, len(s.Tags))
for _, reg := range s.Tags {
re, err := regexp.Compile(reg)
if err != nil {
return err
}
s.tags = append(s.tags, re)
}
// init tag names regex
s.tagKeys = make([]*regexp.Regexp, 0, len(s.TagNames))
for _, reg := range s.TagNames {
re, err := regexp.Compile(reg)
if err != nil {
return err
}
s.tagKeys = append(s.tagKeys, re)
}
// init values regex
s.values = make([]*regexp.Regexp, 0, len(s.Values))
for _, reg := range s.Values {
re, err := regexp.Compile(reg)
if err != nil {
return err
}
s.values = append(s.values, re)
}
// init value Keys regex
s.valueKeys = make([]*regexp.Regexp, 0, len(s.ValueNames))
for _, reg := range s.ValueNames {
re, err := regexp.Compile(reg)
if err != nil {
return err
}
s.valueKeys = append(s.valueKeys, re)
}
if s.logger.Writer() != io.Discard {
b, err := json.Marshal(s)
if err != nil {
s.logger.Printf("initialized processor '%s': %+v", processorType, s)
return nil
}
s.logger.Printf("initialized processor '%s': %s", processorType, string(b))
}
return nil
}
func (s *stringsp) Apply(es ...*formatters.EventMsg) []*formatters.EventMsg {
for _, e := range es {
if e == nil {
continue
}
for k, v := range e.Values {
for _, re := range s.valueKeys {
if re.MatchString(k) {
s.logger.Printf("value name '%s' matched regex '%s'", k, re.String())
s.applyValueTransformations(e, k, v)
}
}
for _, re := range s.values {
if vs, ok := v.(string); ok {
if re.MatchString(vs) {
s.logger.Printf("value '%s' matched regex '%s'", vs, re.String())
s.applyValueTransformations(e, k, vs)
}
}
}
}
for k, v := range e.Tags {
for _, re := range s.tagKeys {
if re.MatchString(k) {
s.logger.Printf("tag name '%s' matched regex '%s'", k, re.String())
s.applyTagTransformations(e, k, v)
}
}
for _, re := range s.tags {
if re.MatchString(v) {
s.logger.Printf("tag '%s' matched regex '%s'", k, re.String())
s.applyTagTransformations(e, k, v)
}
}
}
}
return es
}
func (s *stringsp) WithLogger(l *log.Logger) {
if s.Debug && l != nil {
s.logger = log.New(l.Writer(), loggingPrefix, l.Flags())
} else if s.Debug {
s.logger = log.New(os.Stderr, loggingPrefix, utils.DefaultLoggingFlags)
}
}
func (s *stringsp) WithTargets(tcs map[string]*types.TargetConfig) {}
func (s *stringsp) WithActions(act map[string]map[string]interface{}) {}
func (s *stringsp) WithProcessors(procs map[string]map[string]any) {}
func (s *stringsp) applyValueTransformations(e *formatters.EventMsg, k string, v interface{}) {
for _, trans := range s.Transforms {
for _, t := range trans {
if !t.Keep {
delete(e.Values, k)
}
k, v = t.apply(k, v)
e.Values[k] = v
}
}
}
func (s *stringsp) applyTagTransformations(e *formatters.EventMsg, k, v string) {
for _, trans := range s.Transforms {
for _, t := range trans {
if !t.Keep {
delete(e.Tags, k)
}
var vi interface{}
k, vi = t.apply(k, v)
if vs, ok := vi.(string); ok {
e.Tags[k] = vs
} else {
s.logger.Printf("failed to assert %v type as string", vi)
}
}
}
}
func (t *transform) apply(k string, v interface{}) (string, interface{}) {
switch t.op {
case "replace":
return t.replace(k, v)
case "trim-prefix":
return t.trimPrefix(k, v)
case "trim-suffix":
return t.trimSuffix(k, v)
case "title":
return t.toTitle(k, v)
case "to-lower":
return t.toLower(k, v)
case "to-upper":
return t.toUpper(k, v)
case "split":
return t.split(k, v)
case "path-base":
return t.pathBase(k, v)
}
return k, v
}
func (t *transform) replace(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = t.replaceRegexp.ReplaceAllString(k, t.New)
case valueField:
if vs, ok := v.(string); ok {
v = t.replaceRegexp.ReplaceAllString(vs, t.New)
}
}
return k, v
}
func (t *transform) trimPrefix(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = strings.TrimPrefix(k, t.Prefix)
case valueField:
if vs, ok := v.(string); ok {
v = strings.TrimPrefix(vs, t.Prefix)
}
}
return k, v
}
func (t *transform) trimSuffix(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = strings.TrimSuffix(k, t.Suffix)
case valueField:
if vs, ok := v.(string); ok {
v = strings.TrimSuffix(vs, t.Suffix)
}
}
return k, v
}
func (t *transform) toTitle(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = cases.Title(language.English).String(k)
case valueField:
if vs, ok := v.(string); ok {
v = cases.Title(language.English).String(vs)
}
}
return k, v
}
func (t *transform) toLower(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = strings.ToLower(k)
case valueField:
if vs, ok := v.(string); ok {
v = strings.ToLower(vs)
}
}
return k, v
}
func (t *transform) toUpper(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = strings.ToUpper(k)
case valueField:
if vs, ok := v.(string); ok {
v = strings.ToUpper(vs)
}
}
return k, v
}
func (t *transform) split(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
items := strings.Split(k, t.SplitOn)
numItems := len(items)
if numItems <= t.IgnoreFirst || numItems <= t.IgnoreLast || t.IgnoreFirst >= numItems-t.IgnoreLast {
return "", v
}
k = strings.Join(items[t.IgnoreFirst:numItems-t.IgnoreLast], t.JoinWith)
case valueField:
if vs, ok := v.(string); ok {
items := strings.Split(vs, t.SplitOn)
numItems := len(items)
if numItems <= t.IgnoreFirst || numItems <= t.IgnoreLast || t.IgnoreFirst >= numItems-t.IgnoreLast {
return k, ""
}
v = strings.Join(items[t.IgnoreFirst:numItems-t.IgnoreLast], t.JoinWith)
}
}
return k, v
}
func (t *transform) pathBase(k string, v interface{}) (string, interface{}) {
switch t.ApplyOn {
case nameField:
k = filepath.Base(k)
case valueField:
if vs, ok := v.(string); ok {
v = filepath.Base(vs)
}
}
return k, v
}