-
Notifications
You must be signed in to change notification settings - Fork 435
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
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
631b8bb
Add gormv2
5409af1
gofmt, migrate to pgx since this is what gorm is using
d4deca2
Fix gofmt, driverName might be different from dialect name so unfortu…
9dc8f09
Fix missing parameter
30ed1a7
Revert test driver
96af79b
Add pq for sql common preparation
6cb16ce
Fix expected name
a696be8
Add pgx to switch case
b8a8801
Tests should now pass
e33a7d5
Fix directory structure according to conventions, run gofmt
fef0120
Fixed callback tests
42f471a
Use context instead of Set in order to receive the non-cloned db
ab5adcc
CR
725ee40
Merge remote-tracking branch 'upstream/v1' into v1
96e0a07
Fixed test, removed unnecessary one
8ecbf28
Use a type for context key
3ba11c3
Minor fix for time conversion
a69c474
CR notes
d2853e1
Adjusted tests to changed in gorm
84b6a8c
Fix tests
12a80fb
Merge branch 'v1' of https://github.com/DataDog/dd-trace-go into v1
84812bf
CR pt. 1
476fbce
Some test improvements
13ac0ed
CR formatting requirements
5b69cc4
Order imports
AdallomRoy 4eee8df
CR: directory rename
AdallomRoy 281b07d
CR: changing import path in test
AdallomRoy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...) | ||
span.Finish(tracer.WithError(db.Error)) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?There was a problem hiding this comment.
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.There was a problem hiding this comment.
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?There was a problem hiding this comment.
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.There was a problem hiding this comment.
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 thisgorm.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.There was a problem hiding this comment.
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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 Reproduced it here #849