Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contrib: add gorm.io/gorm #759

Merged
merged 27 commits into from
Jan 4, 2021
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
2 changes: 1 addition & 1 deletion contrib/database/sql/internal/dsn.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func ParseDSN(driverName, dsn string) (meta map[string]string, err error) {
if err != nil {
return
}
case "postgres":
case "postgres", "pgx":
meta, err = parsePostgresDSN(dsn)
if err != nil {
return
Expand Down
39 changes: 39 additions & 0 deletions contrib/gorm.io/gorm.v1/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// 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 2016-2020 Datadog, Inc.

package gorm_test

import (
"log"

sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"
gormtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gorm.io/gorm.v1"

"github.com/jackc/pgx/v4/stdlib"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)

func ExampleOpen() {
// Register augments the provided driver with tracing, enabling it to be loaded by gormtrace.Open.
sqltrace.Register("pgx", &stdlib.Driver{}, sqltrace.WithServiceName("my-service"))
sqlDb, err := sqltrace.Open("pgx", "postgres://pqgotest:password@localhost/pqgotest?sslmode=disable")
if err != nil {
log.Fatal(err)
}

db, err := gormtrace.Open(postgres.New(postgres.Config{Conn: sqlDb}), &gorm.Config{})
if err != nil {
log.Fatal(err)
}

user := struct {
gorm.Model
Name string
}{}

// All calls through gorm.DB are now traced.
db.Where("name = ?", "jinzhu").First(&user)
}
123 changes: 123 additions & 0 deletions contrib/gorm.io/gorm.v1/gorm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 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 2016-2020 Datadog, Inc.

// Package gorm provides helper functions for tracing the gorm.io/gorm package (https://github.com/go-gorm/gorm).
package gorm

import (
"context"
"math"
"time"

"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

"gorm.io/gorm"
)

type key string

const (
gormSpanStartTimeKey = key("dd-trace-go:span")
)

// Open opens a new (traced) database connection. The used driver must be formerly registered
// using (gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql).Register.
func Open(dialector gorm.Dialector, cfg *gorm.Config, opts ...Option) (*gorm.DB, error) {
db, err := gorm.Open(dialector, cfg)
if err != nil {
return db, err
}
return withCallbacks(db, opts...)
}

func withCallbacks(db *gorm.DB, opts ...Option) (*gorm.DB, error) {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}

afterFunc := func(operationName string) func(*gorm.DB) {
return func(db *gorm.DB) {
after(db, operationName, cfg)
}
}

cb := db.Callback()
err := cb.Create().Before("gorm:create").Register("dd-trace-go:before_create", before)
if err != nil {
return db, err
}
err = cb.Create().After("gorm:create").Register("dd-trace-go:after_create", afterFunc("gorm.create"))
if err != nil {
return db, err
}
err = cb.Update().Before("gorm:update").Register("dd-trace-go:before_update", before)
if err != nil {
return db, err
}
err = cb.Update().After("gorm:update").Register("dd-trace-go:after_update", afterFunc("gorm.update"))
if err != nil {
return db, err
}
err = cb.Delete().Before("gorm:delete").Register("dd-trace-go:before_delete", before)
if err != nil {
return db, err
}
err = cb.Delete().After("gorm:delete").Register("dd-trace-go:after_delete", afterFunc("gorm.delete"))
if err != nil {
return db, err
}
err = cb.Query().Before("gorm:query").Register("dd-trace-go:before_query", before)
if err != nil {
return db, err
}
err = cb.Query().After("gorm:query").Register("dd-trace-go:after_query", afterFunc("gorm.query"))
if err != nil {
return db, err
}
err = cb.Row().Before("gorm:query").Register("dd-trace-go:before_row_query", before)
if err != nil {
return db, err
}
err = cb.Row().After("gorm:query").Register("dd-trace-go:after_row_query", afterFunc("gorm.row_query"))
if err != nil {
return db, err
}
return db, nil
}

func before(scope *gorm.DB) {
if scope.Statement != nil && scope.Statement.Context != nil {
scope.Statement.Context = context.WithValue(scope.Statement.Context, gormSpanStartTimeKey, time.Now())
}
}

func after(db *gorm.DB, operationName string, cfg *config) {
if db.Statement == nil || db.Statement.Context == nil {
return
}

ctx := db.Statement.Context
t, ok := ctx.Value(gormSpanStartTimeKey).(time.Time)
if !ok {
return
}

opts := []ddtrace.StartSpanOption{
tracer.StartTime(t),
tracer.ServiceName(cfg.serviceName),
tracer.SpanType(ext.SpanTypeSQL),
tracer.ResourceName(db.Statement.SQL.String()),
}
if !math.IsNaN(cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}

span, _ := tracer.StartSpanFromContext(ctx, operationName, opts...)

Choose a reason for hiding this comment

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

If I understand correctly, this creates a span after an operation has finished. Doesn't this mean that any child spans created during the operation (e.g., for the raw database queries via database/sql) will have the wrong parent span?

Copy link
Contributor

Choose a reason for hiding this comment

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

It will be fine, the idea here is that the span has the tracer.StartTime option which places the span in the past, to when the operation started.

Choose a reason for hiding this comment

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

The span would have the correct time yes, but the context isn't updated in before so a child span would still have the wrong parent, no?

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah, right. I see what you mean. If someone were to use db.Statement.Context. In that case you are right, it wouldn't have this parent. But the question is - would you want it to? Any span started as a child of this span would start after this one finishes, which seems unusual but if you have a valid use case for it we can consider it.

Choose a reason for hiding this comment

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

Say you've enabled tracing for the database/sql connection underlying this gorm.DB. Then a child span here (e.g., postgres.db SELECT * from foo) would be created that would start and end within the gorm span but not have the gorm span as parent... I think.

Copy link
Contributor

Choose a reason for hiding this comment

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

I'll let the author jump in and hopefully explain the reasoning behind this approach @AdallomRoy

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hi @gbbr and @hatstand - Thanks for your comments.
I was trying to create this package as identical as possible to the gorm v1 package here: https://github.com/DataDog/dd-trace-go/blob/v1/contrib/gopkg.in/jinzhu/gorm.v1/gorm.go
so that if you upgrade you will have the same experience.
As far as I understand, this happens in the "after" func in that package as well. Do you think this would behave differently?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We could definitely start the span in the before func and save it as part of the context and grab it here for finish if we think that behavior is better

Copy link
Contributor

@gbbr gbbr Feb 18, 2021

Choose a reason for hiding this comment

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

My view is that we shouldn't make any premature improvements if this code has had no problems reported so far. As long as there is no issue, let's not fix it 🙂

@hatstand please feel free to open up an issue and describe how to reproduce the problem (if there is one), and we're happy to look into it. I initially didn't realise that this was just a copy of what was already there.

Choose a reason for hiding this comment

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

👍 Reproduced it here #849

span.Finish(tracer.WithError(db.Error))
}
Loading