/
sqlcomment.go
185 lines (172 loc) · 6.14 KB
/
sqlcomment.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package tracer
import (
"strconv"
"strings"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/internal/globalconfig"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
)
// SQLCommentInjectionMode represents the mode of SQL comment injection.
type SQLCommentInjectionMode string
const (
// SQLInjectionUndefined represents the comment injection mode is not set. This is the same as SQLInjectionDisabled.
SQLInjectionUndefined SQLCommentInjectionMode = ""
// SQLInjectionDisabled represents the comment injection mode where all injection is disabled.
SQLInjectionDisabled SQLCommentInjectionMode = "disabled"
// SQLInjectionModeService represents the comment injection mode where only service tags (name, env, version) are injected.
SQLInjectionModeService SQLCommentInjectionMode = "service"
// SQLInjectionModeFull represents the comment injection mode where both service tags and tracing tags. Tracing tags include span id, trace id and sampling priority.
SQLInjectionModeFull SQLCommentInjectionMode = "full"
)
// Key names for SQL comment tags.
const (
sqlCommentTraceParent = "traceparent"
sqlCommentParentService = "ddps"
sqlCommentDBService = "dddbs"
sqlCommentParentVersion = "ddpv"
sqlCommentEnv = "dde"
)
// Current trace context version (see https://www.w3.org/TR/trace-context/#version)
const w3cContextVersion = "00"
// SQLCommentCarrier is a carrier implementation that injects a span context in a SQL query in the form
// of a sqlcommenter formatted comment prepended to the original query text.
// See https://google.github.io/sqlcommenter/spec/ for more details.
type SQLCommentCarrier struct {
Query string
Mode SQLCommentInjectionMode
DBServiceName string
SpanID uint64
}
// Inject injects a span context in the carrier's Query field as a comment.
func (c *SQLCommentCarrier) Inject(spanCtx ddtrace.SpanContext) error {
c.SpanID = random.Uint64()
tags := make(map[string]string)
switch c.Mode {
case SQLInjectionUndefined:
fallthrough
case SQLInjectionDisabled:
return nil
case SQLInjectionModeFull:
var (
samplingPriority int
traceID uint64
)
if ctx, ok := spanCtx.(*spanContext); ok {
if sp, ok := ctx.samplingPriority(); ok {
samplingPriority = sp
}
traceID = ctx.TraceID()
}
if traceID == 0 {
traceID = c.SpanID
}
sampled := int64(0)
if samplingPriority > 0 {
sampled = 1
}
tags[sqlCommentTraceParent] = encodeTraceParent(traceID, c.SpanID, sampled)
fallthrough
case SQLInjectionModeService:
var env, version string
if ctx, ok := spanCtx.(*spanContext); ok {
if e, ok := ctx.meta(ext.Environment); ok {
env = e
}
if v, ok := ctx.meta(ext.Version); ok {
version = v
}
}
if globalconfig.ServiceName() != "" {
tags[sqlCommentParentService] = globalconfig.ServiceName()
}
if env != "" {
tags[sqlCommentEnv] = env
}
if version != "" {
tags[sqlCommentParentVersion] = version
}
tags[sqlCommentDBService] = c.DBServiceName
}
c.Query = commentQuery(c.Query, tags)
return nil
}
// encodeTraceParent encodes trace parent as per the w3c trace context spec (https://www.w3.org/TR/trace-context/#version).
func encodeTraceParent(traceID uint64, spanID uint64, sampled int64) string {
var b strings.Builder
// traceparent has a fixed length of 55:
// 2 bytes for the version, 32 for the trace id, 16 for the span id, 2 for the sampled flag and 3 for separators
b.Grow(55)
b.WriteString(w3cContextVersion)
b.WriteRune('-')
tid := strconv.FormatUint(traceID, 16)
for i := 0; i < 32-len(tid); i++ {
b.WriteRune('0')
}
b.WriteString(tid)
b.WriteRune('-')
sid := strconv.FormatUint(spanID, 16)
for i := 0; i < 16-len(sid); i++ {
b.WriteRune('0')
}
b.WriteString(sid)
b.WriteRune('-')
b.WriteRune('0')
b.WriteString(strconv.FormatInt(sampled, 16))
return b.String()
}
var (
keyReplacer = strings.NewReplacer(" ", "%20", "!", "%21", "#", "%23", "$", "%24", "%", "%25", "&", "%26", "'", "%27", "(", "%28", ")", "%29", "*", "%2A", "+", "%2B", ",", "%2C", "/", "%2F", ":", "%3A", ";", "%3B", "=", "%3D", "?", "%3F", "@", "%40", "[", "%5B", "]", "%5D")
valueReplacer = strings.NewReplacer(" ", "%20", "!", "%21", "#", "%23", "$", "%24", "%", "%25", "&", "%26", "'", "%27", "(", "%28", ")", "%29", "*", "%2A", "+", "%2B", ",", "%2C", "/", "%2F", ":", "%3A", ";", "%3B", "=", "%3D", "?", "%3F", "@", "%40", "[", "%5B", "]", "%5D", "'", "\\'")
)
// commentQuery returns the given query with the tags from the SQLCommentCarrier applied to it as a
// prepended SQL comment. The format of the comment follows the sqlcommenter spec.
// See https://google.github.io/sqlcommenter/spec/ for more details.
func commentQuery(query string, tags map[string]string) string {
if len(tags) == 0 {
return ""
}
var b strings.Builder
// the sqlcommenter specification dictates that tags should be sorted. Since we know all injected keys,
// we skip a sorting operation by specifying the order of keys statically
orderedKeys := []string{sqlCommentDBService, sqlCommentEnv, sqlCommentParentService, sqlCommentParentVersion, sqlCommentTraceParent}
first := true
for _, k := range orderedKeys {
if v, ok := tags[k]; ok {
// we need to URL-encode both keys and values and escape single quotes in values
// https://google.github.io/sqlcommenter/spec/
key := keyReplacer.Replace(k)
val := valueReplacer.Replace(v)
if first {
b.WriteString("/*")
} else {
b.WriteRune(',')
}
b.WriteString(key)
b.WriteRune('=')
b.WriteRune('\'')
b.WriteString(val)
b.WriteRune('\'')
first = false
}
}
if b.Len() == 0 {
return query
}
b.WriteString("*/")
if query == "" {
return b.String()
}
log.Debug("Injected sql comment: %s", b.String())
b.WriteRune(' ')
b.WriteString(query)
return b.String()
}
// Extract is not implemented on SQLCommentCarrier
func (c *SQLCommentCarrier) Extract() (ddtrace.SpanContext, error) {
return nil, nil
}