github.com/rudderlabs/rudder-go-kit@v0.30.0/sqlutil/monitor.go (about)

     1  package sqlutil
     2  
     3  import (
     4  	"context"
     5  	"database/sql"
     6  	"time"
     7  
     8  	"github.com/rudderlabs/rudder-go-kit/config"
     9  	"github.com/rudderlabs/rudder-go-kit/stats"
    10  )
    11  
    12  // MonitorDatabase collects database connection pool metrics at regular intervals synchronously until the context is canceled.
    13  func MonitorDatabase(
    14  	ctx context.Context,
    15  	conf *config.Config,
    16  	statsFactory stats.Stats,
    17  	db *sql.DB,
    18  	identifier string,
    19  ) {
    20  	statsReportInterval := conf.GetDurationVar(10, time.Second, "Database.statsReportInterval")
    21  
    22  	tags := stats.Tags{
    23  		"identifier": identifier,
    24  	}
    25  
    26  	maxOpenConnectionsStat := statsFactory.NewTaggedStat("db_max_open_connections", stats.GaugeType, tags)
    27  	openConnectionsStat := statsFactory.NewTaggedStat("db_open_connections", stats.GaugeType, tags)
    28  	inUseStat := statsFactory.NewTaggedStat("db_in_use", stats.GaugeType, tags)
    29  	idleStat := statsFactory.NewTaggedStat("db_idle", stats.GaugeType, tags)
    30  	waitCountStat := statsFactory.NewTaggedStat("db_wait_count", stats.GaugeType, tags)
    31  	waitDurationStat := statsFactory.NewTaggedStat("db_wait_duration", stats.TimerType, tags)
    32  	maxIdleClosedStat := statsFactory.NewTaggedStat("db_max_idle_closed", stats.GaugeType, tags)
    33  	maxIdleTimeClosedStat := statsFactory.NewTaggedStat("db_max_idle_time_closed", stats.GaugeType, tags)
    34  	maxLifetimeClosedStat := statsFactory.NewTaggedStat("db_max_lifetime_closed", stats.GaugeType, tags)
    35  
    36  	for {
    37  		select {
    38  		case <-ctx.Done():
    39  			return
    40  		case <-time.After(statsReportInterval):
    41  			dbStats := db.Stats()
    42  
    43  			maxOpenConnectionsStat.Gauge(dbStats.MaxOpenConnections)
    44  			openConnectionsStat.Gauge(dbStats.OpenConnections)
    45  			inUseStat.Gauge(dbStats.InUse)
    46  			idleStat.Gauge(dbStats.Idle)
    47  			waitCountStat.Gauge(int(dbStats.WaitCount))
    48  			waitDurationStat.SendTiming(dbStats.WaitDuration)
    49  			maxIdleClosedStat.Gauge(int(dbStats.MaxIdleClosed))
    50  			maxIdleTimeClosedStat.Gauge(int(dbStats.MaxIdleTimeClosed))
    51  			maxLifetimeClosedStat.Gauge(int(dbStats.MaxLifetimeClosed))
    52  		}
    53  	}
    54  }