-
Notifications
You must be signed in to change notification settings - Fork 26
/
collapse_nesting.go
246 lines (202 loc) · 7.24 KB
/
collapse_nesting.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
// Copyright 2023 The Kelemetry Authors.
//
// Licensed 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 tfstep
import (
"encoding/json"
"sort"
"strings"
"github.com/jaegertracing/jaeger/model"
tfconfig "github.com/kubewharf/kelemetry/pkg/frontend/tf/config"
tftree "github.com/kubewharf/kelemetry/pkg/frontend/tf/tree"
"github.com/kubewharf/kelemetry/pkg/manager"
utilmarshal "github.com/kubewharf/kelemetry/pkg/util/marshal"
reflectutil "github.com/kubewharf/kelemetry/pkg/util/reflect"
"github.com/kubewharf/kelemetry/pkg/util/zconstants"
)
func init() {
manager.Global.ProvideListImpl(
"tf-step/collapse-nesting-visitor",
manager.Ptr(&tfconfig.VisitorStep[CollapseNestingVisitor]{}),
&manager.List[tfconfig.RegisteredStep]{},
)
}
// Deletes child spans with a non-pseudo trace source and injects them as logs in the nesting span.
//
// Multiple logs of the same span are aggregated into one log, flattening them into a field.
//
// Must be followed by PruneTagsVisitor in the last step.
type CollapseNestingVisitor struct {
ShouldCollapse utilmarshal.StringFilter `json:"shouldCollapse"` // tests traceSource
TagMappings map[string][]TagMapping `json:"tagMappings"` // key = traceSource
AuditDiffClasses AuditDiffClassification `json:"auditDiffClasses"` // key = prefix
LogTypeMapping map[zconstants.LogType]string `json:"logTypeMapping"` // key = log type, value = log field
}
func (CollapseNestingVisitor) Kind() string { return "CollapseNestingVisitor" }
type TagMapping struct {
FromSpanTag string `json:"fromSpanTag"`
ToLogField string `json:"toLogField"`
}
type AuditDiffClassification struct {
SpecificFields AuditDiffFieldClasses `json:"fields"`
DefaultClass AuditDiffClass `json:"default"`
}
type AuditDiffFieldClasses struct {
fieldMap map[string]*AuditDiffClass // key = field in the form `metadata.resourceVersion`
}
func (c *AuditDiffFieldClasses) UnmarshalJSON(buf []byte) error {
type FieldClass struct {
Fields []string `json:"fields"`
Class AuditDiffClass `json:"class"`
}
var raw []FieldClass
if err := json.Unmarshal(buf, &raw); err != nil {
return err
}
specific := make(map[string]*AuditDiffClass)
for _, fc := range raw {
class := fc.Class
for _, field := range fc.Fields {
specific[field] = &class
}
}
c.fieldMap = specific
return nil
}
type AuditDiffClass struct {
ShouldDisplay bool `json:"shouldDisplay"`
Name string `json:"name"`
Priority int `json:"priority"`
}
func iterStringPrefix[T any](str string, yield func(string) (T, bool)) (T, bool) {
result, hasResult := yield(str)
for ; !hasResult; result, hasResult = yield(str) {
if str[len(str)-1] == ']' {
paired := strings.LastIndex(str, "[")
if paired != -1 {
str = str[:paired]
continue
}
}
delim := strings.LastIndex(str, ".")
if delim != -1 {
str = str[:delim]
continue
}
return reflectutil.ZeroOf[T](), false
}
return result, true
}
func (classes *AuditDiffClassification) Get(path string) *AuditDiffClass {
if class, found := iterStringPrefix(path, func(prefix string) (*AuditDiffClass, bool) {
if class, hasSpecific := classes.SpecificFields.fieldMap[prefix]; hasSpecific {
return class, true
}
return nil, false
}); found {
return class
}
return &classes.DefaultClass
}
func (visitor CollapseNestingVisitor) Enter(tree *tftree.SpanTree, span *model.Span) tftree.TreeVisitor {
if _, isPseudo := model.KeyValues(span.Tags).FindByKey(zconstants.PseudoType); !isPseudo {
return visitor
}
for childId := range tree.Children(span.SpanID) {
visitor.processChild(tree, span, childId)
}
return visitor
}
func (visitor CollapseNestingVisitor) Exit(tree *tftree.SpanTree, span *model.Span) {}
func (visitor CollapseNestingVisitor) processChild(tree *tftree.SpanTree, span *model.Span, childId model.SpanID) {
childSpan := tree.Span(childId)
if _, childIsPseudo := model.KeyValues(childSpan.Tags).FindByKey(zconstants.PseudoType); childIsPseudo {
return
}
traceSourceKv, hasTraceSource := model.KeyValues(childSpan.Tags).FindByKey(zconstants.TraceSource)
if !hasTraceSource {
return
}
traceSource := traceSourceKv.VStr
if !visitor.ShouldCollapse.Matches(traceSource) {
return
}
// move information in childSpan into fields
fields := []model.KeyValue{
model.String(zconstants.TraceSource, traceSource),
model.String(traceSource, childSpan.OperationName),
}
for _, mapping := range visitor.TagMappings[traceSource] {
if kv, hasKey := model.KeyValues(childSpan.Tags).FindByKey(mapping.FromSpanTag); hasKey {
// kv is a copy, so this does not mutate childSpan.Tags (which is deleted anyway)
kv.Key = mapping.ToLogField
if kv.AsStringLossy() != "" {
fields = append(fields, kv)
}
}
}
diffCollector := &auditDiffCollector{
visitor: visitor,
classMap: map[string][]string{},
classPriorities: map[string]int{},
}
otherLogs := []model.KeyValue{}
for _, childLog := range childSpan.Logs {
logTypeKv, _ := model.KeyValues(childLog.Fields).FindByKey(zconstants.LogTypeAttr)
logType := zconstants.LogType(logTypeKv.VStr)
// "event" is the default log key emitted by otel sdk
eventKv, _ := model.KeyValues(childLog.Fields).FindByKey("event")
event := eventKv.VStr
if logType == zconstants.LogTypeObjectDiff {
// this is an audit diff, process specially for better UX
// TODO can this fit in a separate step instead?
diffCollector.process(event)
} else if fieldName, hasMapping := visitor.LogTypeMapping[logType]; hasMapping {
otherLogs = append(otherLogs, model.String(fieldName, event))
}
}
diffClassSlice := []model.KeyValue{}
for className, class := range diffCollector.classMap {
diffClassSlice = append(diffClassSlice, model.String(className, strings.Join(class, "\n")))
}
sort.Slice(diffClassSlice, func(i, j int) bool {
iKey := diffClassSlice[i].Key
jKey := diffClassSlice[j].Key
return diffCollector.classPriorities[iKey] < diffCollector.classPriorities[jKey]
})
fields = append(fields, diffClassSlice...)
fields = append(fields, otherLogs...)
span.Logs = append(span.Logs, model.Log{
Timestamp: childSpan.StartTime,
Fields: fields,
})
tree.Delete(childId)
}
type auditDiffCollector struct {
visitor CollapseNestingVisitor
classMap map[string][]string
classPriorities map[string]int
}
func (collector *auditDiffCollector) process(message string) {
diffLines := strings.Split(message, "\n")
for _, diffLine := range diffLines {
prefixLength := strings.IndexRune(diffLine, ' ')
if prefixLength > 0 {
class := collector.visitor.AuditDiffClasses.Get(diffLine[:prefixLength])
if class.ShouldDisplay {
collector.classMap[class.Name] = append(collector.classMap[class.Name], diffLine)
collector.classPriorities[class.Name] = class.Priority
}
}
}
}