2019-05-21 15:30:06 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package dbutil
|
|
|
|
|
2019-06-04 22:30:21 +01:00
|
|
|
import (
|
2020-10-29 08:11:02 +00:00
|
|
|
"context"
|
2020-01-15 07:25:26 +00:00
|
|
|
"database/sql"
|
2019-06-04 22:30:21 +01:00
|
|
|
"flag"
|
2020-01-17 20:07:00 +00:00
|
|
|
"time"
|
2019-06-04 22:30:21 +01:00
|
|
|
|
2019-11-08 20:40:39 +00:00
|
|
|
"github.com/spacemonkeygo/monkit/v3"
|
2019-06-04 22:30:21 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2020-07-08 18:59:42 +01:00
|
|
|
maxIdleConns = flag.Int("db.max_idle_conns", 1, "Maximum Amount of Idle Database connections, -1 means the stdlib default")
|
|
|
|
maxOpenConns = flag.Int("db.max_open_conns", 5, "Maximum Amount of Open Database connections, -1 means the stdlib default")
|
2020-08-28 16:50:57 +01:00
|
|
|
connMaxLifetime = flag.Duration("db.conn_max_lifetime", 30*time.Minute, "Maximum Database Connection Lifetime, -1ns means the stdlib default")
|
2019-06-04 22:30:21 +01:00
|
|
|
)
|
|
|
|
|
2020-01-17 20:07:00 +00:00
|
|
|
// ConfigurableDB contains methods for configuring a database.
|
|
|
|
type ConfigurableDB interface {
|
|
|
|
SetMaxIdleConns(int)
|
|
|
|
SetMaxOpenConns(int)
|
|
|
|
SetConnMaxLifetime(time.Duration)
|
|
|
|
Stats() sql.DBStats
|
|
|
|
}
|
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// Configure Sets Connection Boundaries and adds db_stats monitoring to monkit.
|
2020-10-29 08:11:02 +00:00
|
|
|
func Configure(ctx context.Context, db ConfigurableDB, dbName string, mon *monkit.Scope) {
|
2019-06-04 22:30:21 +01:00
|
|
|
if *maxIdleConns >= 0 {
|
|
|
|
db.SetMaxIdleConns(*maxIdleConns)
|
|
|
|
}
|
|
|
|
if *maxOpenConns >= 0 {
|
|
|
|
db.SetMaxOpenConns(*maxOpenConns)
|
|
|
|
}
|
|
|
|
if *connMaxLifetime >= 0 {
|
|
|
|
db.SetConnMaxLifetime(*connMaxLifetime)
|
|
|
|
}
|
2019-11-08 20:40:39 +00:00
|
|
|
mon.Chain(monkit.StatSourceFunc(
|
|
|
|
func(cb func(key monkit.SeriesKey, field string, val float64)) {
|
2020-03-23 19:58:36 +00:00
|
|
|
monkit.StatSourceFromStruct(monkit.NewSeriesKey("db_stats").WithTag("db_name", dbName), db.Stats()).Stats(cb)
|
2019-06-04 22:30:21 +01:00
|
|
|
}))
|
|
|
|
}
|