This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 79
/
trace_proto.go
296 lines (273 loc) · 8.71 KB
/
trace_proto.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
// Copyright 2017, OpenCensus 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 stackdriver
import (
"fmt"
"math"
"strconv"
"time"
"unicode/utf8"
"cloud.google.com/go/trace/apiv2/tracepb"
timestamppb "github.com/golang/protobuf/ptypes/timestamp"
wrapperspb "github.com/golang/protobuf/ptypes/wrappers"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/trace"
monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
statuspb "google.golang.org/genproto/googleapis/rpc/status"
)
const (
maxAnnotationEventsPerSpan = 32
maxMessageEventsPerSpan = 128
maxAttributeStringValue = 256
agentLabel = "g.co/agent"
labelHTTPHost = `/http/host`
labelHTTPMethod = `/http/method`
labelHTTPStatusCode = `/http/status_code`
labelHTTPPath = `/http/path`
labelHTTPUserAgent = `/http/user_agent`
)
// proto returns a protocol buffer representation of a SpanData.
func protoFromSpanData(s *trace.SpanData, projectID string, mr *monitoredrespb.MonitoredResource, userAgent string) *tracepb.Span {
if s == nil {
return nil
}
traceIDString := s.SpanContext.TraceID.String()
spanIDString := s.SpanContext.SpanID.String()
name := s.Name
switch s.SpanKind {
case trace.SpanKindClient:
name = "Sent." + name
case trace.SpanKindServer:
name = "Recv." + name
}
sp := &tracepb.Span{
Name: "projects/" + projectID + "/traces/" + traceIDString + "/spans/" + spanIDString,
SpanId: spanIDString,
DisplayName: trunc(name, 128),
StartTime: timestampProto(s.StartTime),
EndTime: timestampProto(s.EndTime),
SameProcessAsParentSpan: &wrapperspb.BoolValue{Value: !s.HasRemoteParent},
}
if p := s.ParentSpanID; p != (trace.SpanID{}) {
sp.ParentSpanId = p.String()
}
if s.Status.Code != 0 || s.Status.Message != "" {
sp.Status = &statuspb.Status{Code: s.Status.Code, Message: s.Status.Message}
}
var annotations, droppedAnnotationsCount, messageEvents, droppedMessageEventsCount int
copyAttributes(&sp.Attributes, s.Attributes)
// Copy MonitoredResources as span Attributes
sp.Attributes = copyMonitoredResourceAttributes(sp.Attributes, mr)
as := s.Annotations
for i, a := range as {
if annotations >= maxAnnotationEventsPerSpan {
droppedAnnotationsCount = len(as) - i
break
}
annotation := &tracepb.Span_TimeEvent_Annotation{Description: trunc(a.Message, maxAttributeStringValue)}
copyAttributes(&annotation.Attributes, a.Attributes)
event := &tracepb.Span_TimeEvent{
Time: timestampProto(a.Time),
Value: &tracepb.Span_TimeEvent_Annotation_{Annotation: annotation},
}
annotations++
if sp.TimeEvents == nil {
sp.TimeEvents = &tracepb.Span_TimeEvents{}
}
sp.TimeEvents.TimeEvent = append(sp.TimeEvents.TimeEvent, event)
}
if sp.Attributes == nil {
sp.Attributes = &tracepb.Span_Attributes{
AttributeMap: make(map[string]*tracepb.AttributeValue),
}
}
// Only set the agent label if it is not already set. That enables the
// OpenCensus agent/collector to set the agent label based on the library that
// sent the span to the agent.
//
// We now provide a config option to set the userAgent explicitly, which is
// used both here and in request headers when sending metric data, but have
// retained this non-override functionality for backwards compatibility.
if _, hasAgent := sp.Attributes.AttributeMap[agentLabel]; !hasAgent {
sp.Attributes.AttributeMap[agentLabel] = &tracepb.AttributeValue{
Value: &tracepb.AttributeValue_StringValue{
StringValue: trunc(userAgent, maxAttributeStringValue),
},
}
}
es := s.MessageEvents
for i, e := range es {
if messageEvents >= maxMessageEventsPerSpan {
droppedMessageEventsCount = len(es) - i
break
}
messageEvents++
if sp.TimeEvents == nil {
sp.TimeEvents = &tracepb.Span_TimeEvents{}
}
sp.TimeEvents.TimeEvent = append(sp.TimeEvents.TimeEvent, &tracepb.Span_TimeEvent{
Time: timestampProto(e.Time),
Value: &tracepb.Span_TimeEvent_MessageEvent_{
MessageEvent: &tracepb.Span_TimeEvent_MessageEvent{
Type: tracepb.Span_TimeEvent_MessageEvent_Type(e.EventType),
Id: e.MessageID,
UncompressedSizeBytes: e.UncompressedByteSize,
CompressedSizeBytes: e.CompressedByteSize,
},
},
})
}
if droppedAnnotationsCount != 0 || droppedMessageEventsCount != 0 {
if sp.TimeEvents == nil {
sp.TimeEvents = &tracepb.Span_TimeEvents{}
}
sp.TimeEvents.DroppedAnnotationsCount = clip32(droppedAnnotationsCount)
sp.TimeEvents.DroppedMessageEventsCount = clip32(droppedMessageEventsCount)
}
if len(s.Links) > 0 {
sp.Links = &tracepb.Span_Links{}
sp.Links.Link = make([]*tracepb.Span_Link, 0, len(s.Links))
for _, l := range s.Links {
link := &tracepb.Span_Link{
TraceId: l.TraceID.String(),
SpanId: l.SpanID.String(),
Type: tracepb.Span_Link_Type(l.Type),
}
copyAttributes(&link.Attributes, l.Attributes)
sp.Links.Link = append(sp.Links.Link, link)
}
}
return sp
}
// timestampProto creates a timestamp proto for a time.Time.
func timestampProto(t time.Time) *timestamppb.Timestamp {
return ×tamppb.Timestamp{
Seconds: t.Unix(),
Nanos: int32(t.Nanosecond()),
}
}
// copyMonitoredResourceAttributes copies proto monitoredResource to proto map field (Span_Attributes)
// it creates the map if it is nil.
func copyMonitoredResourceAttributes(out *tracepb.Span_Attributes, mr *monitoredrespb.MonitoredResource) *tracepb.Span_Attributes {
if mr == nil {
return out
}
if out == nil {
out = &tracepb.Span_Attributes{}
}
if out.AttributeMap == nil {
out.AttributeMap = make(map[string]*tracepb.AttributeValue)
}
for k, v := range mr.Labels {
av := attributeValue(v)
out.AttributeMap[fmt.Sprintf("g.co/r/%s/%s", mr.Type, k)] = av
}
return out
}
// copyAttributes copies a map of attributes to a proto map field.
// It creates the map if it is nil.
func copyAttributes(out **tracepb.Span_Attributes, in map[string]interface{}) {
if len(in) == 0 {
return
}
if *out == nil {
*out = &tracepb.Span_Attributes{}
}
if (*out).AttributeMap == nil {
(*out).AttributeMap = make(map[string]*tracepb.AttributeValue)
}
var dropped int32
for key, value := range in {
av := attributeValue(value)
if av == nil {
continue
}
switch key {
case ochttp.PathAttribute:
(*out).AttributeMap[labelHTTPPath] = av
case ochttp.HostAttribute:
(*out).AttributeMap[labelHTTPHost] = av
case ochttp.MethodAttribute:
(*out).AttributeMap[labelHTTPMethod] = av
case ochttp.UserAgentAttribute:
(*out).AttributeMap[labelHTTPUserAgent] = av
case ochttp.StatusCodeAttribute:
(*out).AttributeMap[labelHTTPStatusCode] = av
default:
if len(key) > 128 {
dropped++
continue
}
(*out).AttributeMap[key] = av
}
}
(*out).DroppedAttributesCount = dropped
}
func attributeValue(v interface{}) *tracepb.AttributeValue {
switch value := v.(type) {
case bool:
return &tracepb.AttributeValue{
Value: &tracepb.AttributeValue_BoolValue{BoolValue: value},
}
case int64:
return &tracepb.AttributeValue{
Value: &tracepb.AttributeValue_IntValue{IntValue: value},
}
case float64:
// TODO: set double value if Stackdriver Trace support it in the future.
return &tracepb.AttributeValue{
Value: &tracepb.AttributeValue_StringValue{
StringValue: trunc(strconv.FormatFloat(value, 'f', -1, 64),
maxAttributeStringValue),
},
}
case string:
return &tracepb.AttributeValue{
Value: &tracepb.AttributeValue_StringValue{StringValue: trunc(value, maxAttributeStringValue)},
}
}
return nil
}
// trunc returns a TruncatableString truncated to the given limit.
func trunc(s string, limit int) *tracepb.TruncatableString {
if len(s) > limit {
b := []byte(s[:limit])
for {
r, size := utf8.DecodeLastRune(b)
if r == utf8.RuneError && size == 1 {
b = b[:len(b)-1]
} else {
break
}
}
return &tracepb.TruncatableString{
Value: string(b),
TruncatedByteCount: clip32(len(s) - len(b)),
}
}
return &tracepb.TruncatableString{
Value: s,
TruncatedByteCount: 0,
}
}
// clip32 clips an int to the range of an int32.
func clip32(x int) int32 {
if x < math.MinInt32 {
return math.MinInt32
}
if x > math.MaxInt32 {
return math.MaxInt32
}
return int32(x)
}