Skip to content
This repository was archived by the owner on Oct 3, 2023. It is now read-only.

Commit db101e3

Browse files
Add option to allow user agent to be explicitly overridden (#274)
1 parent 19b2ae7 commit db101e3

7 files changed

Lines changed: 72 additions & 16 deletions

File tree

stackdriver.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import (
6060
metadataapi "cloud.google.com/go/compute/metadata"
6161
traceapi "cloud.google.com/go/trace/apiv2"
6262
"contrib.go.opencensus.io/exporter/stackdriver/monitoredresource"
63+
opencensus "go.opencensus.io"
6364
"go.opencensus.io/resource"
6465
"go.opencensus.io/resource/resourcekeys"
6566
"go.opencensus.io/stats/view"
@@ -279,12 +280,18 @@ type Options struct {
279280
// time-series then it will result into an error for the entire CreateTimeSeries request
280281
// which may contain more than one time-series.
281282
ResourceByDescriptor func(*metricdata.Descriptor, map[string]string) (map[string]string, monitoredresource.Interface)
283+
284+
// Override the user agent value supplied to Monitoring APIs and included as an
285+
// attribute in trace data.
286+
UserAgent string
282287
}
283288

284289
const defaultTimeout = 5 * time.Second
285290

286291
var defaultDomain = path.Join("custom.googleapis.com", "opencensus")
287292

293+
var defaultUserAgent = fmt.Sprintf("opencensus-go %s; stackdriver-exporter %s", opencensus.Version(), version)
294+
288295
// Exporter is a stats and trace exporter that uploads data to Stackdriver.
289296
//
290297
// You can create a single Exporter and register it as both a trace exporter
@@ -362,6 +369,9 @@ func NewExporter(o Options) (*Exporter, error) {
362369
if o.MetricPrefix != "" && !strings.HasSuffix(o.MetricPrefix, "/") {
363370
o.MetricPrefix = o.MetricPrefix + "/"
364371
}
372+
if o.UserAgent == "" {
373+
o.UserAgent = defaultUserAgent
374+
}
365375

366376
se, err := newStatsExporter(o)
367377
if err != nil {

stackdriver_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,14 @@ func TestGRPC(t *testing.T) {
136136

137137
client.Single(context.Background(), &testpb.FooRequest{SleepNanos: int64(42 * time.Millisecond)})
138138
}
139+
140+
func TestUserAgent(t *testing.T) {
141+
e, err := NewExporter(Options{UserAgent: "OpenCensus Service"})
142+
if err != nil {
143+
t.Fatal(err)
144+
}
145+
146+
if want, got := "OpenCensus Service", e.statsExporter.o.UserAgent; want != got {
147+
t.Fatalf("UserAgent = %q; want %q", got, want)
148+
}
149+
}

stats.go

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import (
2626
"sync"
2727
"time"
2828

29-
opencensus "go.opencensus.io"
3029
"go.opencensus.io/stats"
3130
"go.opencensus.io/stats/view"
3231
"go.opencensus.io/tag"
@@ -52,11 +51,9 @@ const (
5251
opencensusTaskKey = "opencensus_task"
5352
opencensusTaskDescription = "Opencensus task identifier"
5453
defaultDisplayNamePrefix = "OpenCensus"
55-
version = "0.10.0"
54+
version = "0.12.3"
5655
)
5756

58-
var userAgent = fmt.Sprintf("opencensus-go %s; stackdriver-exporter %s", opencensus.Version(), version)
59-
6057
// statsExporter exports stats to the Stackdriver Monitoring.
6158
type statsExporter struct {
6259
o Options
@@ -89,7 +86,7 @@ func newStatsExporter(o Options) (*statsExporter, error) {
8986
return nil, errBlankProjectID
9087
}
9188

92-
opts := append(o.MonitoringClientOptions, option.WithUserAgent(userAgent))
89+
opts := append(o.MonitoringClientOptions, option.WithUserAgent(o.UserAgent))
9390
ctx := o.Context
9491
if ctx == nil {
9592
ctx = context.Background()

trace.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func newTraceExporterWithClient(o Options, c *tracingclient.Client) *traceExport
9898

9999
// ExportSpan exports a SpanData to Stackdriver Trace.
100100
func (e *traceExporter) ExportSpan(s *trace.SpanData) {
101-
protoSpan := protoFromSpanData(s, e.projectID, e.o.Resource)
101+
protoSpan := protoFromSpanData(s, e.projectID, e.o.Resource, e.o.UserAgent)
102102
protoSize := proto.Size(protoSpan)
103103
err := e.bundler.Add(protoSpan, protoSize)
104104
switch err {
@@ -137,7 +137,7 @@ func (e *traceExporter) pushTraceSpans(ctx context.Context, node *commonpb.Node,
137137
}
138138

139139
for _, span := range spans {
140-
protoSpans = append(protoSpans, protoFromSpanData(span, e.projectID, res))
140+
protoSpans = append(protoSpans, protoFromSpanData(span, e.projectID, res, e.o.UserAgent))
141141
}
142142

143143
req := tracepb.BatchWriteSpansRequest{

trace_proto.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ const (
4444
)
4545

4646
// proto returns a protocol buffer representation of a SpanData.
47-
func protoFromSpanData(s *trace.SpanData, projectID string, mr *monitoredrespb.MonitoredResource) *tracepb.Span {
47+
func protoFromSpanData(s *trace.SpanData, projectID string, mr *monitoredrespb.MonitoredResource, userAgent string) *tracepb.Span {
4848
if s == nil {
4949
return nil
5050
}
@@ -109,6 +109,10 @@ func protoFromSpanData(s *trace.SpanData, projectID string, mr *monitoredrespb.M
109109
// Only set the agent label if it is not already set. That enables the
110110
// OpenCensus agent/collector to set the agent label based on the library that
111111
// sent the span to the agent.
112+
//
113+
// We now provide a config option to set the userAgent explicitly, which is
114+
// used both here and in request headers when sending metric data, but have
115+
// retained this non-override functionality for backwards compatibility.
112116
if _, hasAgent := sp.Attributes.AttributeMap[agentLabel]; !hasAgent {
113117
sp.Attributes.AttributeMap[agentLabel] = &tracepb.AttributeValue{
114118
Value: &tracepb.AttributeValue_StringValue{

trace_proto_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ func generateSpan() {
109109
}
110110

111111
func createExpectedSpans() spans {
112-
ua := trunc(userAgent, len(userAgent))
112+
ua := trunc(defaultUserAgent, len(defaultUserAgent))
113113
expectedSpans := spans{
114114
&tracepb.Span{
115115
DisplayName: trunc("span0", 128),
@@ -284,7 +284,7 @@ func TestExportTrace(t *testing.T) {
284284

285285
var spbs spans
286286
for _, s := range te.spans {
287-
spbs = append(spbs, protoFromSpanData(s, "testproject", nil))
287+
spbs = append(spbs, protoFromSpanData(s, "testproject", nil, defaultUserAgent))
288288
}
289289
sort.Sort(spbs)
290290

@@ -396,7 +396,7 @@ func TestExportTraceWithMonitoredResource(t *testing.T) {
396396
mr := createGCEInstanceMonitoredResource()
397397

398398
for _, s := range te.spans {
399-
gceSpbs = append(gceSpbs, protoFromSpanData(s, "testproject", mr))
399+
gceSpbs = append(gceSpbs, protoFromSpanData(s, "testproject", mr, defaultUserAgent))
400400
}
401401

402402
for _, span := range gceSpbs {
@@ -410,7 +410,7 @@ func TestExportTraceWithMonitoredResource(t *testing.T) {
410410
mr = createGKEContainerMonitoredResource()
411411

412412
for _, s := range te.spans {
413-
gkeSpbs = append(gkeSpbs, protoFromSpanData(s, "testproject", mr))
413+
gkeSpbs = append(gkeSpbs, protoFromSpanData(s, "testproject", mr, defaultUserAgent))
414414
}
415415

416416
for _, span := range gkeSpbs {
@@ -427,7 +427,7 @@ func TestExportTraceWithMonitoredResource(t *testing.T) {
427427
var awsEc2Spbs spans
428428
mr = createAWSEC2MonitoredResource()
429429
for _, s := range te.spans {
430-
awsEc2Spbs = append(awsEc2Spbs, protoFromSpanData(s, "testproject", mr))
430+
awsEc2Spbs = append(awsEc2Spbs, protoFromSpanData(s, "testproject", mr, defaultUserAgent))
431431
}
432432

433433
for _, span := range awsEc2Spbs {
@@ -500,7 +500,7 @@ func BenchmarkProto(b *testing.B) {
500500
}
501501
var x int
502502
for i := 0; i < b.N; i++ {
503-
s := protoFromSpanData(sd, `testproject`, nil)
503+
s := protoFromSpanData(sd, `testproject`, nil, defaultUserAgent)
504504
x += len(s.Name)
505505
}
506506
if x == 0 {

trace_test.go

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func TestTraceSpansBufferMaxBytes(t *testing.T) {
156156
exported++
157157
}
158158
for i := 0; i < 10; i++ {
159-
e.ExportSpan(makeSampleSpanData())
159+
e.ExportSpan(makeSampleSpanData(""))
160160
}
161161
close(waitCh)
162162
e.Flush()
@@ -165,13 +165,47 @@ func TestTraceSpansBufferMaxBytes(t *testing.T) {
165165
}
166166
}
167167

168-
func makeSampleSpanData() *trace.SpanData {
168+
func TestTraceSpansUserAgent(t *testing.T) {
169+
e := newTraceExporterWithClient(Options{
170+
UserAgent: "OpenCensus Service",
171+
Context: context.Background(),
172+
Timeout: 10 * time.Millisecond,
173+
}, nil)
174+
175+
var got string
176+
// set user-agent attribute based on provided option
177+
e.uploadFn = func(spans []*tracepb.Span) {
178+
got = spans[0].Attributes.AttributeMap[agentLabel].GetStringValue().Value
179+
}
180+
e.ExportSpan(makeSampleSpanData(""))
181+
e.Flush()
182+
if want := "OpenCensus Service"; want != got {
183+
t.Fatalf("UserAgent Attribute = %q; want %q", got, want)
184+
}
185+
186+
// if user-agent is already set, do not override
187+
e.uploadFn = func(spans []*tracepb.Span) {
188+
got = spans[0].Attributes.AttributeMap[agentLabel].GetStringValue().Value
189+
}
190+
e.ExportSpan(makeSampleSpanData("My Test Application"))
191+
e.Flush()
192+
if want := "My Test Application"; want != got {
193+
t.Fatalf("UserAgent Attribute = %q; want %q", got, want)
194+
}
195+
}
196+
197+
func makeSampleSpanData(userAgent string) *trace.SpanData {
169198
sd := &trace.SpanData{
170199
Annotations: make([]trace.Annotation, 32),
171200
Links: make([]trace.Link, 32),
172201
MessageEvents: make([]trace.MessageEvent, 128),
173202
Attributes: make(map[string]interface{}),
174203
}
204+
205+
if userAgent != "" {
206+
sd.Attributes[agentLabel] = userAgent
207+
}
208+
175209
for i := 0; i < 32; i++ {
176210
sd.Attributes[fmt.Sprintf("attribute-%d", i)] = ""
177211
}

0 commit comments

Comments
 (0)