This repository has been archived by the owner on May 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
tracing.go
298 lines (257 loc) · 7.97 KB
/
tracing.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
// Copyright 2018 Istio 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 signalfx
import (
"context"
"net"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gogo/protobuf/types"
"github.com/golang/glog"
"github.com/signalfx/golib/v3/errors"
"github.com/signalfx/golib/v3/pointer"
"github.com/signalfx/golib/v3/sfxclient"
"github.com/signalfx/golib/v3/trace"
"github.com/signalfx/signalfx-istio-adapter/signalfx/config"
mixer_v1beta1 "istio.io/api/mixer/adapter/model/v1beta1"
istio_policy_v1beta1 "istio.io/api/policy/v1beta1"
"istio.io/istio/mixer/pkg/adapter"
"istio.io/istio/mixer/template/tracespan"
)
// How long to wait for a response from ingest when sending spans. New spans will
// buffer during the round trip so we shouldn't wait too long.
const spanSendTimeout = 8 * time.Second
type traceSpanHandler struct {
ctx context.Context
cancel context.CancelFunc
sink *sfxclient.HTTPSink
spanChan chan *tracespan.InstanceMsg
conf *config.Params_TracingConfig
}
func createTracingHandler(conf *config.Params) (*traceSpanHandler, error) {
var traceSpanHandlerInst *traceSpanHandler
if conf.EnableTracing {
traceSpanHandlerInst = &traceSpanHandler{
sink: createSignalFxClient(conf),
conf: conf.Tracing,
}
if err := traceSpanHandlerInst.InitTracing(int(conf.Tracing.BufferSize)); err != nil {
return nil, err
}
}
return traceSpanHandlerInst, nil
}
func (th *traceSpanHandler) InitTracing(bufferLen int) error {
th.ctx, th.cancel = context.WithCancel(context.Background())
th.spanChan = make(chan *tracespan.InstanceMsg, bufferLen)
go th.sendTraces()
return nil
}
func (th *traceSpanHandler) Shutdown() {
if th.cancel != nil {
th.cancel()
}
}
// Pull spans out of spanChan as they come in and send them to SignalFx.
func (th *traceSpanHandler) sendTraces() {
for {
select {
case <-th.ctx.Done():
return
case inst := <-th.spanChan:
allInsts := th.drainChannel(inst)
spans := make([]*trace.Span, 0, len(allInsts))
for i := range allInsts {
span := th.convertInstance(allInsts[i])
if span.ID == "" {
continue
}
spans = append(spans, span)
}
ctx, cancel := context.WithTimeout(th.ctx, spanSendTimeout)
err := th.sink.AddSpans(ctx, spans)
cancel()
if err != nil {
glog.Errorf("Could not send spans: %s", err.Error())
}
}
}
}
// Pull spans out of the spanChan until it is empty. This helps cut down on
// the number of requests to ingest by batching things when traces come in
// fast.
func (th *traceSpanHandler) drainChannel(initial *tracespan.InstanceMsg) (out []*tracespan.InstanceMsg) {
out = []*tracespan.InstanceMsg{initial}
for {
select {
case inst := <-th.spanChan:
out = append(out, inst)
default:
return out
}
}
}
func (th *traceSpanHandler) HandleTraceSpan(ctx context.Context, req *tracespan.HandleTraceSpanRequest) (*mixer_v1beta1.ReportResult, error) {
if th == nil {
return nil, nil
}
for i := range req.Instances {
span := req.Instances[i]
if os.Getenv("SIGNALFX_TRACE_DUMP") == "true" {
spew.Dump(span, "\n")
}
select {
case th.spanChan <- span:
continue
default:
// Just abandon any remaining spans in `values` at this point to
// help relieve pressure on the buffer
return nil, errors.New("dropping span because trace buffer is full -- you should increase the capacity of it")
}
}
return &mixer_v1beta1.ReportResult{}, nil
}
var (
clientKind = "CLIENT"
serverKind = "SERVER"
)
// Converts an istio span to a SignalFx span, which is currently equivalent to
// a Zipkin V2 span.
func (th *traceSpanHandler) convertInstance(istioSpan *tracespan.InstanceMsg) *trace.Span {
outSpanID := istioSpan.SpanId
outParentSpanID := istioSpan.ParentSpanId
// Fix up span ids so that client/server spans don't share the same span
// ID, if the span has this flag marked.
if istioSpan.RewriteClientSpanId {
if istioSpan.ClientSpan {
outSpanID = deriveNewSpanID(istioSpan.SpanId)
} else {
// We need to make the parent of this server span the client span
// that was rewritten.
outParentSpanID = deriveNewSpanID(istioSpan.SpanId)
}
}
startTime, err := types.TimestampFromProto(istioSpan.StartTime.GetValue())
if err != nil {
glog.Error("Couldn't convert span start time: ", err)
return nil
}
endTime, err := types.TimestampFromProto(istioSpan.EndTime.GetValue())
kind := &serverKind
if istioSpan.ClientSpan {
kind = &clientKind
}
tags := map[string]string{}
// Special handling for the span name since the Istio attribute that is the
// most suited for the span name is request.path which can contain query
// params which could cause high cardinality of the span name.
spanName := istioSpan.SpanName
if strings.Contains(spanName, "?") {
idx := strings.LastIndex(spanName, "?")
qs := spanName[idx+1:]
if vals, err := url.ParseQuery(qs); err == nil {
for k, v := range vals {
tags[k] = strings.Join(v, "; ")
}
}
spanName = spanName[:idx]
}
for k, v := range istioSpan.SpanTags {
tags[k] = adapter.Stringify(decodeValue(v))
}
if istioSpan.HttpStatusCode != 0 {
tags["http.status_code"] = strconv.FormatInt(istioSpan.HttpStatusCode, 10)
if istioSpan.HttpStatusCode >= 500 {
tags["error"] = "server error"
}
}
span := &trace.Span{
ID: outSpanID,
Name: &spanName,
TraceID: istioSpan.TraceId,
Kind: kind,
Timestamp: pointer.Int64(startTime.UnixNano() / int64(time.Microsecond)),
Duration: pointer.Int64(endTime.Sub(startTime).Microseconds()),
Tags: tags,
LocalEndpoint: &trace.Endpoint{},
RemoteEndpoint: &trace.Endpoint{},
}
needsEndpointSwap := !istioSpan.ClientSpan && th.conf.SwapLocalRemoteEndpoints
if needsEndpointSwap {
th.populateLocalEndpoint(istioSpan.SpanTags, span.RemoteEndpoint)
th.populateRemoteEndpoint(istioSpan.SpanTags, span.LocalEndpoint)
} else {
th.populateLocalEndpoint(istioSpan.SpanTags, span.LocalEndpoint)
th.populateRemoteEndpoint(istioSpan.SpanTags, span.RemoteEndpoint)
}
if outParentSpanID != "" {
span.ParentID = &outParentSpanID
}
return span
}
func (th *traceSpanHandler) populateLocalEndpoint(spanTags map[string]*istio_policy_v1beta1.Value, localEndpoint *trace.Endpoint) {
if n, ok := decodeValue(spanTags[th.conf.LocalEndpointNameTagKey]).(string); ok && n != "" {
localEndpoint.ServiceName = &n
}
if ip, ok := decodeValue(spanTags[th.conf.LocalEndpointIpTagKey]).(net.IP); ok {
ips := ip.String()
localEndpoint.Ipv4 = &ips
}
}
func (th *traceSpanHandler) populateRemoteEndpoint(spanTags map[string]*istio_policy_v1beta1.Value, remoteEndpoint *trace.Endpoint) {
if n, ok := decodeValue(spanTags[th.conf.RemoteEndpointNameTagKey]).(string); ok && n != "" {
remoteEndpoint.ServiceName = &n
}
if ip, ok := decodeValue(spanTags[th.conf.RemoteEndpointIpTagKey]).(net.IP); ok {
ips := ip.String()
remoteEndpoint.Ipv4 = &ips
}
}
var hexMapper = map[rune]rune{
'0': '1',
'1': '2',
'2': '3',
'3': '4',
'4': '5',
'5': '6',
'6': '7',
'7': '8',
'8': '9',
'9': 'a',
'a': 'b',
'b': 'c',
'c': 'd',
'd': 'e',
'e': 'f',
'f': '0',
'A': 'b',
'B': 'c',
'C': 'd',
'D': 'e',
'E': 'f',
'F': '0',
}
// This applies a simple Caeser cypher that shifts the hex characters by one
// forward. If spanID contains non-hex chars, the output is undefined.
func deriveNewSpanID(spanID string) string {
var newSpanIDBuilder strings.Builder
for _, r := range spanID {
newSpanIDBuilder.WriteRune(hexMapper[r])
}
return newSpanIDBuilder.String()
}