Skip to content

Commit

Permalink
contrib/database/sql: Disable DBStats if statsd client initialization…
Browse files Browse the repository at this point in the history
… fails (#2682)

Co-authored-by: Dario Castañé <[email protected]>
  • Loading branch information
mtoffl01 and darccio authored May 8, 2024
1 parent 93ee25e commit b4d38fc
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 7 deletions.
7 changes: 2 additions & 5 deletions contrib/database/sql/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,9 @@ const (
var interval = 10 * time.Second

// pollDBStats calls (*DB).Stats on the db at a predetermined interval. It pushes the DBStats off to the statsd client.
// the caller should always ensure that db & statsd are non-nil
func pollDBStats(statsd internal.StatsdClient, db *sql.DB) {
if db == nil {
log.Debug("No traced DB connection found; cannot pull DB stats.")
return
}
log.Debug("Traced DB connection found: DB stats will be gathered and sent every %v.", interval)
log.Debug("DB stats will be gathered and sent every %v.", interval)
for range time.NewTicker(interval).C {
log.Debug("Reporting DB.Stats metrics...")
stat := db.Stats()
Expand Down
4 changes: 3 additions & 1 deletion contrib/database/sql/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,10 @@ func (c *config) checkStatsdRequired() {
sc, err := internal.NewStatsdClient(globalconfig.DogstatsdAddr(), statsTags(c))
if err == nil {
c.statsdClient = sc
log.Debug("Metrics from the database/sql contrib will be sent to %v", globalconfig.DogstatsdAddr())
} else {
log.Warn("Error creating statsd client for database/sql contrib package; DB Stats will be dropped: %v", err)
log.Warn("Error creating statsd client for database/sql contrib; DB Stats disabled: %v", err)
c.dbStats = false
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions contrib/database/sql/option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,12 @@ func TestCheckStatsdRequired(t *testing.T) {
_, ok := cfg.statsdClient.(*statsd.Client)
assert.True(t, ok)
})
t.Run("invalid address", func(t *testing.T) {
globalconfig.SetDogstatsdAddr("unreachable/socket/path/dsd.socket")
cfg := new(config)
cfg.dbStats = true
cfg.checkStatsdRequired()
assert.Nil(t, cfg.statsdClient)
assert.False(t, cfg.dbStats)
})
}
2 changes: 1 addition & 1 deletion contrib/database/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func OpenDB(c driver.Connector, opts ...Option) *sql.DB {
cfg: cfg,
}
db := sql.OpenDB(tc)
if cfg.dbStats {
if cfg.dbStats && cfg.statsdClient != nil {
go pollDBStats(cfg.statsdClient, db)
}
return db
Expand Down

0 comments on commit b4d38fc

Please sign in to comment.