/
trace_context.go
291 lines (257 loc) · 7.56 KB
/
trace_context.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
package instrumentation
import (
"encoding/json"
"fmt"
"log"
"github.com/google/uuid"
"k8s.io/apimachinery/pkg/api/meta"
mergelogpb "github.com/eppppi/k8s-cp-dt/mergelog/src/pkg/grpc"
)
const (
KOC_KEY = "eppppi.github.io/koc"
)
var numAncCpids = 10
type TraceContext struct {
Cpid string `json:"cpid"`
AncCpids []string `json:"ancCpids"`
}
// DeepCopyTraceContext deep copies a trace context
func (tctx *TraceContext) DeepCopyTraceContext() *TraceContext {
if tctx == nil {
return nil
}
return newTraceContext(tctx.Cpid, tctx.AncCpids)
}
// ValidateTctx validates if tctx is valid
func (tctx *TraceContext) validateTctx() error {
if tctx == nil {
return fmt.Errorf("validation failed: tctx is nil")
}
if tctx.Cpid == "" {
return fmt.Errorf("validation failed: cpid is empty string")
}
if len(tctx.AncCpids) > numAncCpids {
// return fmt.Errorf("validation failed: ancCpids (limit: %d) is too long %d", numAncCpids, len(tctx.AncCpids))
log.Printf("warning: ancCpids (limit: %d) is too long %d\n", numAncCpids, len(tctx.AncCpids))
}
if containsString(tctx.AncCpids, tctx.Cpid) {
return fmt.Errorf("validation failed: cpid is included in ancCpids")
}
return nil
}
type KeyWithTraceContexts struct {
Key interface{}
TraceCtxs []*TraceContext
}
// NewRootTraceContext creates a new root trace context and send mergelog of it
func NewRootTraceContextAndSendMergelog(message, by string) *TraceContext {
cpid, _ := generateCpid()
newTctx := newTraceContext(cpid, []string{})
sendMergelog(cpid, []string{}, mergelogpb.CauseType_CAUSE_TYPE_NEW_CHANGE, message, by)
return newTctx
}
// newTraceContext creates a new trace context (deep copy)
func newTraceContext(cpid string, ancCpids []string) *TraceContext {
newAncCpids := make([]string, len(ancCpids))
copy(newAncCpids, ancCpids)
return &TraceContext{
Cpid: cpid,
AncCpids: newAncCpids,
}
}
// GetCpid gets cpid
func (tctx *TraceContext) GetCpid() string {
if tctx == nil {
return ""
}
return tctx.Cpid
}
// SetCpid sets cpid
func (tctx *TraceContext) SetCpid(cpid string) {
if tctx == nil {
return
}
tctx.Cpid = cpid
}
// GetAncCpids gets ancestor cpids
func (tctx *TraceContext) GetAncCpids() []string {
if tctx == nil {
return nil
}
return tctx.AncCpids
}
// SetAncCpids sets ancestor cpids
func (tctx *TraceContext) SetAncCpids(ancCpids []string) {
if tctx == nil {
return
}
tctx.AncCpids = ancCpids
}
// GenerateCpid generates a cpid
func generateCpid() (string, error) {
newUuid, err := uuid.NewRandom()
if err != nil {
return "", err
}
return newUuid.String(), nil
}
// REFACTOR: from interface{} to runtime.Object
// GetTraceContext returns trace context (maybe nil)
func GetTraceContext(objInterface interface{}) *TraceContext {
obj, err := meta.Accessor(objInterface)
if err != nil {
return nil
}
annotations := obj.GetAnnotations()
if ctxs, ok := annotations[KOC_KEY]; ok {
var traceCtxs TraceContext
err := json.Unmarshal([]byte(ctxs), &traceCtxs)
if err != nil {
log.Printf("warning: unmarshal error: %v\n, returning nil", err)
return nil
}
return &traceCtxs
} else {
log.Printf("no trace context in this object, returning nil (name: %s)\n", obj.GetName())
return nil
}
}
// REFACTOR: from interface{} to runtime.Object
// SetTraceContext sets trace context
func SetTraceContext(objInterface interface{}, traceCtx *TraceContext) error {
if err := traceCtx.validateTctx(); err != nil {
return err
}
obj, err := meta.Accessor(objInterface)
if err != nil {
return err
}
annotations := obj.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
ctxsString, err := json.Marshal(traceCtx)
if err != nil {
log.Printf("warning: marshal error: %v", err)
}
annotations[KOC_KEY] = string(ctxsString)
obj.SetAnnotations(annotations)
return nil
}
// ====================================
// mergeTctxs merges tctxs and returns the new tctx (maybe nil), dest cpid, and source cpids
// if sourceCpids is nil, no need to send a mergelog.
func mergeTctxs(tctxs []*TraceContext) (retTctx *TraceContext, destCpid string, sourceCpids []string) {
// validate args
if len(tctxs) == 0 {
return nil, "", nil
}
for _, tctx := range tctxs {
if err := tctx.validateTctx(); err != nil {
log.Printf("tctx(%v) is invalid, so cannot add: %v\n", tctx, err)
return nil, "", nil
}
}
cg := createCpidGraph(tctxs)
if len(cg.roots) == 0 { // TODO: This should not happen(?), and this func should not return nil
return nil, "", nil
}
if len(cg.roots) == 1 {
log.Println("only 1 root exists, no need to merge")
for k := range cg.roots {
destCpid = k
}
sourceCpids = nil
} else {
destCpid, _ = generateCpid()
sourceCpids = make([]string, len(cg.roots))
{
i := 0
for k := range cg.roots {
sourceCpids[i] = k
i++
}
}
cg.addTraceContext(&TraceContext{destCpid, sourceCpids})
}
min := numAncCpids
if len(cg.roots[destCpid]) < min {
min = len(cg.roots[destCpid])
}
newAncCpids := cg.roots[destCpid][:min]
log.Println("EPPPPI-DEBUG= newAncCpids in mergeTctxs():", newAncCpids)
retTctx = newTraceContext(destCpid, newAncCpids)
log.Println("EPPPPI-DEBUG= retTctx in mergeTctxs():", retTctx)
return retTctx, destCpid, sourceCpids
}
// use case: finding best ancCpids in each controller, *not for trace server*
type cpidGraph struct {
// 深さ1に固定する。祖先の祖先が出てきた場合はrootに直接繋ぐようにする。
// NOTE: any root key MUST NOT be included in as a value of other keys.
roots map[string][]string
}
func newEmptyCpidGraph() *cpidGraph {
return &cpidGraph{
roots: make(map[string][]string),
}
}
// CreateCpidGraph creates a cpid graph from trace contexts
// all trace contexts must be valid
func createCpidGraph(tctxs []*TraceContext) *cpidGraph {
cg := newEmptyCpidGraph()
for _, tctx := range tctxs {
cg.addTraceContext(tctx)
}
return cg
}
// fronter is newer
func (cg *cpidGraph) addTraceContext(tctx *TraceContext) {
if err := tctx.validateTctx(); err != nil {
log.Printf("tctx(%v) is invalid, so cannot add: %v\n", tctx, err)
return
}
// step 1: check if any of tctx.AncCpids matches in any roots.
// if so, add values of the root to cg.roots[tctx.Cpid] and delete the root from cg.roots. if not, do nothing.
tmpAncCpidsOfTctx := make([]string, len(tctx.AncCpids))
copy(tmpAncCpidsOfTctx, tctx.AncCpids)
for k := range cg.roots {
if containsString(tctx.AncCpids, k) { // 自分の先祖(k)を発見した場合、そのさらに先祖(cg.roots[k])を自分のtmpAncCpidsOfTctxに追加していく
for _, v := range cg.roots[k] {
if !containsString(tmpAncCpidsOfTctx, v) {
tmpAncCpidsOfTctx = append(tmpAncCpidsOfTctx, v)
}
}
delete(cg.roots, k)
}
}
// step 2: check if tctx.Cpid is included in any values or roots.
// if so, add tctx.AncCpids to the values of the root. if not, add tctx to roots.
cpidIsIncluded := false
for k := range cg.roots {
if k == tctx.Cpid || containsString(cg.roots[k], tctx.Cpid) {
for i := len(tmpAncCpidsOfTctx) - 1; i >= 0; i-- {
if !containsString(cg.roots[k], tmpAncCpidsOfTctx[i]) {
cg.roots[k] = append([]string{tmpAncCpidsOfTctx[i]}, cg.roots[k]...)
}
}
cpidIsIncluded = true
}
}
if !cpidIsIncluded {
cg.roots[tctx.Cpid] = tmpAncCpidsOfTctx
}
}
// ======= utils =======
// Contains returns true if str is included in slice
// implemented because slices.Contains is introduced in go 1.21 (which is not supported in k8s 1.27)
func containsString(slice []string, str string) bool {
if slice == nil {
return false
}
for _, s := range slice {
if s == str {
return true
}
}
return false
}