Skip to content

Commit

Permalink
migrate gocql
Browse files Browse the repository at this point in the history
  • Loading branch information
rarguelloF committed Aug 20, 2024
1 parent f7a1e2a commit 7bfb222
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 82 deletions.
12 changes: 6 additions & 6 deletions contrib/gocql/gocql/gocql.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ import (

"github.com/DataDog/dd-trace-go/v2/ddtrace/ext"
"github.com/DataDog/dd-trace-go/v2/ddtrace/tracer"
"github.com/DataDog/dd-trace-go/v2/internal/log"
"github.com/DataDog/dd-trace-go/v2/internal/telemetry"
"github.com/DataDog/dd-trace-go/v2/instrumentation"

"github.com/gocql/gocql"
)

const componentName = "gocql/gocql"

var instr *instrumentation.Instrumentation

func init() {
telemetry.LoadIntegration(componentName)
tracer.MarkIntegrationImported("github.com/gocql/gocql")
instr = instrumentation.Load(instrumentation.PackageGoCQL)
}

// ClusterConfig embeds gocql.ClusterConfig and keeps information relevant to tracing.
Expand Down Expand Up @@ -129,7 +129,7 @@ func wrapQuery(q *gocql.Query, hosts []string, opts ...WrapOption) *Query {
if len(hosts) > 0 {
p.clusterContactPoints = strings.Join(hosts, ",")
}
log.Debug("contrib/gocql/gocql: Wrapping Query: %#v", cfg)
instr.Logger().Debug("contrib/gocql/gocql: Wrapping Query: %#v", cfg)
tq := &Query{Query: q, params: p, ctx: q.Context()}
return tq
}
Expand Down Expand Up @@ -310,7 +310,7 @@ func wrapBatch(b *gocql.Batch, hosts []string, opts ...WrapOption) *Batch {
if len(hosts) > 0 {
p.clusterContactPoints = strings.Join(hosts, ",")
}
log.Debug("contrib/gocql/gocql: Wrapping Batch: %#v", cfg)
instr.Logger().Debug("contrib/gocql/gocql: Wrapping Batch: %#v", cfg)
tb := &Batch{Batch: b, params: p, ctx: b.Context()}
return tb
}
Expand Down
70 changes: 7 additions & 63 deletions contrib/gocql/gocql/gocql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,14 @@ import (
"context"
"fmt"
"log"
"math"
"os"
"testing"
"time"

"github.com/DataDog/dd-trace-go/v2/ddtrace/ext"
"github.com/DataDog/dd-trace-go/v2/ddtrace/mocktracer"
"github.com/DataDog/dd-trace-go/v2/ddtrace/tracer"
"github.com/DataDog/dd-trace-go/v2/internal/contrib/namingschematest"
"github.com/DataDog/dd-trace-go/v2/internal/globalconfig"
"github.com/DataDog/dd-trace-go/v2/instrumentation/testutils"

"github.com/gocql/gocql"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -212,7 +210,7 @@ func TestErrNotFound(t *testing.T) {
}

func TestAnalyticsSettings(t *testing.T) {
assertRate := func(t *testing.T, mt mocktracer.Tracer, rate float64, opts ...WrapOption) {
assertRate := func(t *testing.T, mt mocktracer.Tracer, rate any, opts ...WrapOption) {
cluster := newCassandraCluster()
session, err := cluster.CreateSession()
assert.Nil(t, err)
Expand All @@ -235,27 +233,23 @@ func TestAnalyticsSettings(t *testing.T) {
spans := mt.FinishedSpans()
assert.Len(t, spans, 3)
for _, s := range spans {
if !math.IsNaN(rate) {
assert.Equal(t, rate, s.Tag(ext.EventSampleRate))
}
assert.Equal(t, rate, s.Tag(ext.EventSampleRate))
}
}

t.Run("defaults", func(t *testing.T) {
mt := mocktracer.Start()
defer mt.Stop()

assertRate(t, mt, globalconfig.AnalyticsRate())
assertRate(t, mt, nil)
})

t.Run("global", func(t *testing.T) {
t.Skip("global flag disabled")
mt := mocktracer.Start()
defer mt.Stop()

rate := globalconfig.AnalyticsRate()
defer globalconfig.SetAnalyticsRate(rate)
globalconfig.SetAnalyticsRate(0.4)
testutils.SetGlobalAnalyticsRate(t, 0.4)

assertRate(t, mt, 0.4)
})
Expand All @@ -271,16 +265,14 @@ func TestAnalyticsSettings(t *testing.T) {
mt := mocktracer.Start()
defer mt.Stop()

assertRate(t, mt, math.NaN(), WithAnalytics(false))
assertRate(t, mt, nil, WithAnalytics(false))
})

t.Run("override", func(t *testing.T) {
mt := mocktracer.Start()
defer mt.Stop()

rate := globalconfig.AnalyticsRate()
defer globalconfig.SetAnalyticsRate(rate)
globalconfig.SetAnalyticsRate(0.4)
testutils.SetGlobalAnalyticsRate(t, 0.4)

assertRate(t, mt, 0.23, WithAnalyticsRate(0.23))
})
Expand Down Expand Up @@ -505,51 +497,3 @@ func TestWithCustomTag(t *testing.T) {
assert.Equal(t, "value", s0.Tag("custom_tag"))
})
}

func TestNamingSchema(t *testing.T) {
genSpans := namingschematest.GenSpansFn(func(t *testing.T, serviceOverride string) []*mocktracer.Span {
var opts []WrapOption
if serviceOverride != "" {
opts = append(opts, WithService(serviceOverride))
}
mt := mocktracer.Start()
defer mt.Stop()

cluster := newTracedCassandraCluster(opts...)
session, err := cluster.CreateSession()
require.NoError(t, err)

stmt := "INSERT INTO trace.person (name, age, description) VALUES (?, ?, ?)"

// generate query span
err = session.Query(stmt, "name", 30, "description").Exec()
require.NoError(t, err)

// generate batch span
tb := session.NewBatch(gocql.UnloggedBatch)

tb.Query(stmt, "Kate", 80, "Cassandra's sister running in kubernetes")
tb.Query(stmt, "Lucas", 60, "Another person")
err = tb.ExecuteBatch(session.Session)
require.NoError(t, err)

return mt.FinishedSpans()
})
assertOpV0 := func(t *testing.T, spans []*mocktracer.Span) {
require.Len(t, spans, 2)
assert.Equal(t, "cassandra.query", spans[0].OperationName())
assert.Equal(t, "cassandra.batch", spans[1].OperationName())
}
assertOpV1 := func(t *testing.T, spans []*mocktracer.Span) {
require.Len(t, spans, 2)
assert.Equal(t, "cassandra.query", spans[0].OperationName())
assert.Equal(t, "cassandra.query", spans[1].OperationName())
}
wantServiceNameV0 := namingschematest.ServiceNameAssertions{
WithDefaults: []string{"gocql.query", "gocql.query"},
WithDDService: []string{"gocql.query", "gocql.query"},
WithDDServiceAndOverride: []string{namingschematest.TestServiceOverride, namingschematest.TestServiceOverride},
}
t.Run("ServiceName", namingschematest.NewServiceNameTest(genSpans, wantServiceNameV0))
t.Run("SpanName", namingschematest.NewSpanNameTest(genSpans, assertOpV0, assertOpV1))
}
20 changes: 7 additions & 13 deletions contrib/gocql/gocql/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@ package gocql
import (
"math"

"github.com/DataDog/dd-trace-go/v2/internal"
"github.com/DataDog/dd-trace-go/v2/internal/namingschema"
"github.com/DataDog/dd-trace-go/v2/instrumentation"
)

const defaultServiceName = "gocql.query"

type queryConfig struct {
serviceName, resourceName string
querySpanName, batchSpanName string
Expand All @@ -37,15 +34,12 @@ func (fn WrapOptionFn) apply(cfg *queryConfig) {

func defaultConfig() *queryConfig {
cfg := &queryConfig{}
cfg.serviceName = namingschema.ServiceNameOverrideV0(defaultServiceName, defaultServiceName)
cfg.querySpanName = namingschema.OpName(namingschema.CassandraOutbound)
cfg.batchSpanName = namingschema.OpNameOverrideV0(namingschema.CassandraOutbound, "cassandra.batch")
// cfg.analyticsRate = globalconfig.AnalyticsRate()
if internal.BoolEnv("DD_TRACE_GOCQL_ANALYTICS_ENABLED", false) {
cfg.analyticsRate = 1.0
} else {
cfg.analyticsRate = math.NaN()
}
cfg.serviceName = instr.ServiceName(instrumentation.ComponentDefault, nil)
cfg.querySpanName = instr.OperationName(instrumentation.ComponentDefault, nil)
cfg.batchSpanName = instr.OperationName(instrumentation.ComponentDefault, instrumentation.OperationContext{
"operationType": "batch",
})
cfg.analyticsRate = instr.AnalyticsRate(false)
cfg.errCheck = func(error) bool { return true }
return cfg
}
Expand Down
70 changes: 70 additions & 0 deletions instrumentation/internal/namingschematest/gocql_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// 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 2024 Datadog, Inc.

package namingschematest

import (
"testing"
"time"

"github.com/gocql/gocql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

gocqltrace "github.com/DataDog/dd-trace-go/contrib/gocql/gocql/v2"
"github.com/DataDog/dd-trace-go/instrumentation/internal/namingschematest/harness"
"github.com/DataDog/dd-trace-go/v2/ddtrace/mocktracer"
"github.com/DataDog/dd-trace-go/v2/instrumentation"
)

var gocqlTest = harness.TestCase{
Name: instrumentation.PackageGoCQL,
GenSpans: func(t *testing.T, serviceOverride string) []*mocktracer.Span {
var opts []gocqltrace.WrapOption
if serviceOverride != "" {
opts = append(opts, gocqltrace.WithService(serviceOverride))
}
mt := mocktracer.Start()
defer mt.Stop()

cluster := gocqltrace.NewCluster([]string{"127.0.0.1:9042"}, opts...)
cluster.ConnectTimeout = 2 * time.Second
cluster.Timeout = 2 * time.Second

session, err := cluster.CreateSession()
require.NoError(t, err)

stmt := "INSERT INTO trace.person (name, age, description) VALUES (?, ?, ?)"

// generate query span
err = session.Query(stmt, "name", 30, "description").Exec()
require.NoError(t, err)

// generate batch span
tb := session.NewBatch(gocql.UnloggedBatch)

tb.Query(stmt, "Kate", 80, "Cassandra's sister running in kubernetes")
tb.Query(stmt, "Lucas", 60, "Another person")
err = tb.ExecuteBatch(session.Session)
require.NoError(t, err)

return mt.FinishedSpans()
},
WantServiceNameV0: harness.ServiceNameAssertions{
Defaults: []string{"gocql.query", "gocql.query"},
DDService: []string{"gocql.query", "gocql.query"},
ServiceOverride: []string{harness.TestServiceOverride, harness.TestServiceOverride},
},
AssertOpV0: func(t *testing.T, spans []*mocktracer.Span) {
require.Len(t, spans, 2)
assert.Equal(t, "cassandra.query", spans[0].OperationName())
assert.Equal(t, "cassandra.batch", spans[1].OperationName())
},
AssertOpV1: func(t *testing.T, spans []*mocktracer.Span) {
require.Len(t, spans, 2)
assert.Equal(t, "cassandra.query", spans[0].OperationName())
assert.Equal(t, "cassandra.query", spans[1].OperationName())
},
}
1 change: 1 addition & 0 deletions instrumentation/internal/namingschematest/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func TestNamingSchema(t *testing.T) {
goRedisV1Test,
goRedisV7Test,
goRedisV8Test,
gocqlTest,
netHTTPServer,
netHTTPClient,
gomemcache,
Expand Down
18 changes: 18 additions & 0 deletions instrumentation/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const (
PackageGoRedis Package = "go-redis/redis"
PackageGoRedisV7 Package = "go-redis/redis.v7"
PackageGoRedisV8 Package = "go-redis/redis.v8"
PackageGoCQL Package = "gocql/gocql"

// TODO: ...

Expand Down Expand Up @@ -354,6 +355,23 @@ var packages = map[Package]PackageInfo{
},
},
},
PackageGoCQL: {
TracedPackage: "github.com/gocql/gocql",
EnvVarPrefix: "GOCQL",
naming: map[Component]componentNames{
ComponentDefault: {
useDDServiceV0: false,
buildServiceNameV0: staticName("gocql.query"),
buildOpNameV0: func(opCtx OperationContext) string {
if opCtx["operationType"] == "batch" {
return "cassandra.batch"
}
return "cassandra.query"
},
buildOpNameV1: staticName("cassandra.query"),
},
},
},
PackageNetHTTP: {
TracedPackage: "net/http",
EnvVarPrefix: "HTTP",
Expand Down

0 comments on commit 7bfb222

Please sign in to comment.