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

Add ability to set Global tags using code and environment variables #30

Merged
merged 8 commits into from
Apr 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ Requires:
### Configuration
Configuration values can be set either from environmental variables or code:

`SIGNALFX_SERVICE_NAME` / [WithServiceName](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithServiceName) Name identifying the service as a whole (defaults to `SignalFx-Tracing`)

`SIGNALFX_ENDPOINT_URL` / [WithEndpointURL](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithEndpointURL) URL to send traces to (defaults to `http://localhost:9080/v1/trace`)

`SIGNALFX_ACCESS_TOKEN` / [WithAccessToken](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithAccessToken) (no default)
| Code | Environment Variable | Default Value | Notes |
| --- | --- | --- | --- |
| [WithServiceName](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithServiceName) | `SIGNALFX_SERVICE_NAME` | `SignalFx-Tracing` | The name of the service. |
| [WithEndpointURL](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithEndpointURL) | `SIGNALFX_ENDPOINT_URL` | `http://localhost:9080/v1/trace` | The URL to send traces to. |
| [WithAccessToken](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithAccessToken) | `SIGNALFX_ACCESS_TOKEN` | none | |
| [WithGlobalTag](https://godoc.org/github.com/signalfx/signalfx-go-tracing/tracing/#WithGlobalTag) | `SIGNALFX_SPAN_TAGS` | none | Comma-separated list of tags included in every reported span. For example, "key1:val1,key2:val2". Note: The current transport format is Zipkin which only supports string values for tags.|

Note: The current transport format is Zipkin which only supports string values for tags.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is for SIGNALFX_SPAN_TAGS, let's move it to the note for that config value.


### Getting Started
When your application starts enable tracing globally with
Expand Down
65 changes: 63 additions & 2 deletions tracing/opentracing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/signalfx/signalfx-go-tracing/zipkinserver"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"testing"
)

Expand Down Expand Up @@ -79,13 +80,73 @@ func TestOpenTracingParentSpan(t *testing.T) {
}

func TestEmptyContext(t *testing.T) {
assert := assert.New(t)
zipkin := zipkinserver.Start()
defer zipkin.Stop()

Start(WithEndpointURL(zipkin.URL()))

span, _ := opentracing.StartSpanFromContext(context.Background(), "session")
sessionName := "session"
span, _ := opentracing.StartSpanFromContext(context.Background(), sessionName)
span.Finish()

tracer.ForceFlush()
spans := zipkin.WaitForSpans(t, 1)
assert.Equal(sessionName, *spans[0].Name)
}

func TestWithGlobalTags(t *testing.T) {
require := require.New(t)

zipkin := zipkinserver.Start()
defer zipkin.Stop()

Start(WithEndpointURL(zipkin.URL()),
WithGlobalTag("abc-test", "1234"),
WithGlobalTag("test", "value"))

span := tracer.StartSpan("test")
span.Finish()

tracer.ForceFlush()
spans := zipkin.WaitForSpans(t, 1)

tags := spans[0].Tags
require.Equal(2, len(tags))
require.Equal("value",tags["test"], )
require.Equal("1234", tags["abc-test"])
}

func TestEnvironmentVariables(t *testing.T) {
assert := assert.New(t)
require := require.New(t)

// There will be no " " key with value "silentjay" as Zipkin states empty keys are not valid.
err := os.Setenv(signalfxSpanTags, "a:b, c :d , bob:, : silentjay")
require.Nil(err)
defer os.Unsetenv(signalfxSpanTags)

zipkin := zipkinserver.Start()
defer zipkin.Stop()

Start(WithServiceName("MyService"),
WithEndpointURL(zipkin.URL()),
WithGlobalTag("abc-test", "1234"),
WithGlobalTag("test", "value"))

span := tracer.StartSpan("test")
span.Finish()

tracer.ForceFlush()
zipkin.WaitForSpans(t, 1)
spans := zipkin.WaitForSpans(t, 1)

assert.Equal("MyService", *spans[0].LocalEndpoint.ServiceName)

tags := spans[0].Tags
require.Equal(5, len(tags))
assert.Equal("value",tags["test"])
assert.Equal("1234", tags["abc-test"])
assert.Equal("b", tags["a"])
assert.Equal("d", tags["c"])
assert.Equal("", tags["bob"])
}
56 changes: 54 additions & 2 deletions tracing/tracing.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import (
"github.com/signalfx/signalfx-go-tracing/ddtrace/opentracer"
"github.com/signalfx/signalfx-go-tracing/ddtrace/tracer"
"os"
"strings"
)

const (
signalfxServiceName = "SIGNALFX_SERVICE_NAME"
signalfxEndpointURL = "SIGNALFX_ENDPOINT_URL"
signalfxAccessToken = "SIGNALFX_ACCESS_TOKEN"
signalfxSpanTags = "SIGNALFX_SPAN_TAGS"
)

var defaults = map[string]string{
Expand All @@ -23,6 +25,10 @@ type config struct {
serviceName string
accessToken string
url string
// Because there can be multiple global tags added via environment variable
// or calls to WithGlobalTag, store them in the required StartOption format to
// call tracer.Start() in the variadic format.
globalTags []tracer.StartOption
}

// StartOption is a function that configures an option for Start
Expand All @@ -33,9 +39,41 @@ func defaultConfig() *config {
serviceName: envOrDefault(signalfxServiceName),
accessToken: envOrDefault(signalfxAccessToken),
url: envOrDefault(signalfxEndpointURL),
globalTags: envGlobalTags(),
}
}

// envGlobalTags extract global tags from the environment variable and parses the value in the expected format
// key1:value1,
func envGlobalTags() []tracer.StartOption {
var globalTags []tracer.StartOption
Copy link
Contributor

@rmfitzpatrick rmfitzpatrick Apr 21, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be a good opportunity to tag the library and version by default:
signalfx.tracing.library: "go-tracing" *
signalfx.tracing.version: someNewConstantWeUpdateWithEachGitTag.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do that in a separate PR.

var val string

if val = os.Getenv(signalfxSpanTags); val == "" {
return globalTags
}

tags := strings.Split(val, ",")
for _, tag := range tags {
// TODO: Currently this assumes "<stringb>" where "<stringa>:<stringb>" has no ":" in the
// string. The TODO is to fix this logic to allow for "<stringb> to have colons, ":', in it.
pair :=strings.Split(tag, ":")
if len(pair) == 2 {
key := strings.TrimSpace(pair[0])
value := strings.TrimSpace(pair[1])
// Empty keys aren't valid in Zipkin.
// https://github.com/openzipkin/zipkin-api/blob/d3324ac79d1aa8f5c6f0ea4febb299402e50480f/zipkin-jsonv2.proto#L50-L51
if key == "" {
continue
}
globalTag := tracer.WithGlobalTag(key, value)
globalTags = append(globalTags, globalTag)
}
}

return globalTags
}

// envOrDefault gets the given environment variable if set otherwise a default value.
func envOrDefault(envVar string) string {
if val := os.Getenv(envVar); val != "" {
Expand Down Expand Up @@ -65,16 +103,30 @@ func WithEndpointURL(url string) StartOption {
}
}

// WithGlobalTag sets a tag with the given key/value on all spans created by the
// tracer. This option may be used multiple times.
// Note: Since the underlying transport is Zipkin, only values with strings
// are accepted.
func WithGlobalTag(k string, v string) StartOption {
return func(c *config) {
globalTag := tracer.WithGlobalTag(k, v)
c.globalTags = append(c.globalTags, globalTag)
}
}

// Start tracing globally
func Start(opts ...StartOption) {
c := defaultConfig()
for _, fn := range opts {
fn(c)
}

startOptions := append(c.globalTags, tracer.WithServiceName(c.serviceName))
startOptions = append(startOptions, tracer.WithZipkin(c.serviceName, c.url, c.accessToken))
tracer.Start(
tracer.WithServiceName(c.serviceName),
tracer.WithZipkin(c.serviceName, c.url, c.accessToken))
startOptions...
pjanotti marked this conversation as resolved.
Show resolved Hide resolved
)

opentracing.SetGlobalTracer(opentracer.New())
}

Expand Down