/
utility.go
109 lines (93 loc) · 2.57 KB
/
utility.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
package telemetry
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"github.com/matishsiao/goInfo"
)
const (
telemetryContextID string = "shuttle.contextID"
telemetryRunID string = "shuttle.runID"
TelemetryCommand string = "shuttle.command"
TelemetryCommandArgs string = "shuttle.command.args"
)
func WithPhase(phase string) TelemetryOption {
return WithEntry("phase", phase)
}
func WithLabel(label string) TelemetryOption {
return WithEntry("label", label)
}
func WithEntry(key, value string) TelemetryOption {
return func(properties map[string]string) {
properties[key] = value
}
}
func WithGoInfo() TelemetryOption {
return func(properties map[string]string) {
gi, err := goInfo.GetInfo()
if err != nil {
properties["system.goinfo.error"] = err.Error()
return
}
if gi.OS != "" {
properties["system.os"] = gi.OS
}
if gi.Kernel != "" {
properties["system.kernel"] = gi.Kernel
}
if gi.Core != "" {
properties["system.core"] = gi.Core
}
if gi.Platform != "" {
properties["system.platform"] = gi.Platform
}
if gi.Hostname != "" {
properties["system.hostname"] = gi.Hostname
}
if gi.CPUs != 0 {
properties["system.cpus"] = fmt.Sprintf("%d", gi.CPUs)
}
if gi.GoOS != "" {
properties["system.goos"] = gi.GoOS
}
}
}
func includeContext(ctx context.Context, properties map[string]string) map[string]string {
getFromContext(ctx, telemetryContextID, properties)
getFromContext(ctx, telemetryRunID, properties)
getFromContext(ctx, TelemetryCommand, properties)
getFromContextHashValue(ctx, TelemetryCommandArgs, properties)
return properties
}
func getFromContext(ctx context.Context, key string, properties map[string]string) {
if val, ok := ctx.Value(key).(string); ok && val != "" {
properties[key] = val
}
}
func getFromContextHashValue(ctx context.Context, key string, properties map[string]string) {
hasher := sha256.New()
if val, ok := ctx.Value(key).(string); ok && val != "" {
for _, arg := range strings.Split(val, " ") {
keyvaluepair := strings.Split(arg, "=")
if len(keyvaluepair) != 2 {
return
}
properties[fmt.Sprintf("%s.%s", key, keyvaluepair[0])] = fmt.Sprintf(
"sha256(16)=%s",
hex.EncodeToString(hasher.Sum([]byte(keyvaluepair[1])))[0:16],
)
}
}
}
func copyHostMap(original map[string]string, flowProperties map[string]string) map[string]string {
properties := make(map[string]string, len(flowProperties)+len(original))
for k, v := range original {
properties[k] = v
}
for k, v := range flowProperties {
properties[k] = v
}
return properties
}