Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,41 @@ package collector

import (
"context"
"database/sql"
"net"
"strings"
"time"

"github.com/go-sql-driver/mysql"
"github.com/grafana/alloy/internal/component/database_observability"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
)

const ConnectionInfoName = "connection_info"
const (
ConnectionInfoName = "connection_info"
connectionInfoInterval = 5 * time.Minute
)

type ConnectionInfoArguments struct {
DB *sql.DB
DSN string
Registry *prometheus.Registry
EngineVersion string
CloudProvider *database_observability.CloudProvider
}

type ConnectionInfo struct {
dbConnection *sql.DB
DSN string
Registry *prometheus.Registry
EngineVersion string
InfoMetric *prometheus.GaugeVec
CloudProvider *database_observability.CloudProvider

running *atomic.Bool
ctx context.Context
cancel context.CancelFunc
}

func NewConnectionInfo(args ConnectionInfoArguments) (*ConnectionInfo, error) {
Expand All @@ -37,9 +46,8 @@ func NewConnectionInfo(args ConnectionInfoArguments) (*ConnectionInfo, error) {
Help: "Information about the connection",
}, []string{"provider_name", "provider_region", "provider_account", "db_instance_identifier", "engine", "engine_version"})

args.Registry.MustRegister(infoMetric)

return &ConnectionInfo{
dbConnection: args.DB,
DSN: args.DSN,
Registry: args.Registry,
EngineVersion: args.EngineVersion,
Expand All @@ -54,6 +62,41 @@ func (c *ConnectionInfo) Name() string {
}

func (c *ConnectionInfo) Start(ctx context.Context) error {
labels, err := c.buildLabels()
if err != nil {
return err
}

c.running.Store(true)
ctx, cancel := context.WithCancel(ctx)
c.ctx = ctx
c.cancel = cancel

c.ping(ctx, labels)

go func() {
defer func() {
c.Registry.Unregister(c.InfoMetric)
c.running.Store(false)
}()

ticker := time.NewTicker(connectionInfoInterval)
defer ticker.Stop()

for {
select {
case <-c.ctx.Done():
return
case <-ticker.C:
c.ping(c.ctx, labels)
}
}
}()

return nil
}

func (c *ConnectionInfo) buildLabels() (prometheus.Labels, error) {
var (
providerName = "unknown"
providerRegion = "unknown"
Expand Down Expand Up @@ -82,9 +125,8 @@ func (c *ConnectionInfo) Start(ctx context.Context) error {
} else {
cfg, err := mysql.ParseDSN(c.DSN)
if err != nil {
return err
return nil, err
}

host, _, err := net.SplitHostPort(cfg.Addr)
if err == nil && host != "" {
if strings.HasSuffix(host, "rds.amazonaws.com") {
Expand All @@ -103,17 +145,32 @@ func (c *ConnectionInfo) Start(ctx context.Context) error {
}
}
}
c.running.Store(true)

c.InfoMetric.WithLabelValues(providerName, providerRegion, providerAccount, dbInstanceIdentifier, engine, c.EngineVersion).Set(1)
return nil
return prometheus.Labels{
"provider_name": providerName,
"provider_region": providerRegion,
"provider_account": providerAccount,
"db_instance_identifier": dbInstanceIdentifier,
"engine": engine,
"engine_version": c.EngineVersion,
}, nil
}

func (c *ConnectionInfo) ping(ctx context.Context, labels prometheus.Labels) {
if err := c.dbConnection.PingContext(ctx); err != nil {
c.Registry.Unregister(c.InfoMetric)
return
}
_ = c.Registry.Register(c.InfoMetric)
c.InfoMetric.With(labels).Set(1)
}

func (c *ConnectionInfo) Stopped() bool {
return !c.running.Load()
}

func (c *ConnectionInfo) Stop() {
c.Registry.Unregister(c.InfoMetric)
c.running.Store(false)
if c.cancel != nil {
c.cancel()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"
"testing"

"github.com/DATA-DOG/go-sqlmock"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
Expand Down Expand Up @@ -85,9 +86,16 @@ func TestConnectionInfo(t *testing.T) {
}

for _, tc := range testCases {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual), sqlmock.MonitorPingsOption(true))
require.NoError(t, err)
defer db.Close()

mock.ExpectPing()

reg := prometheus.NewRegistry()

collector, err := NewConnectionInfo(ConnectionInfoArguments{
DB: db,
DSN: tc.dsn,
Registry: reg,
EngineVersion: tc.engineVersion,
Expand All @@ -98,8 +106,10 @@ func TestConnectionInfo(t *testing.T) {

err = collector.Start(t.Context())
require.NoError(t, err)
defer collector.Stop()

err = testutil.GatherAndCompare(reg, strings.NewReader(tc.expectedMetrics))
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,7 @@ func (c *Component) startCollectors(serverID string, engineVersion string, parse

// Connection Info collector is always enabled
ciCollector, err := collector.NewConnectionInfo(collector.ConnectionInfoArguments{
DB: c.dbConnection,
DSN: string(c.args.DataSourceName),
Registry: c.registry,
EngineVersion: engineVersion,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,42 @@ package collector

import (
"context"
"database/sql"
"regexp"
"strings"
"time"

"github.com/grafana/alloy/internal/component/database_observability"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
)

const ConnectionInfoName = "connection_info"
const (
ConnectionInfoName = "connection_info"
connectionInfoInterval = 5 * time.Minute
)

var engineVersionRegex = regexp.MustCompile(`(?P<version>^[1-9]+\.[1-9]+)(?P<suffix>.*)?$`)

type ConnectionInfoArguments struct {
DB *sql.DB
DSN string
Registry *prometheus.Registry
EngineVersion string
CloudProvider *database_observability.CloudProvider
}

type ConnectionInfo struct {
dbConnection *sql.DB
DSN string
Registry *prometheus.Registry
EngineVersion string
InfoMetric *prometheus.GaugeVec
CloudProvider *database_observability.CloudProvider

running *atomic.Bool
ctx context.Context
cancel context.CancelFunc
}

func NewConnectionInfo(args ConnectionInfoArguments) (*ConnectionInfo, error) {
Expand All @@ -38,9 +47,8 @@ func NewConnectionInfo(args ConnectionInfoArguments) (*ConnectionInfo, error) {
Help: "Information about the connection",
}, []string{"provider_name", "provider_region", "provider_account", "db_instance_identifier", "engine", "engine_version"})

args.Registry.MustRegister(infoMetric)

return &ConnectionInfo{
dbConnection: args.DB,
DSN: args.DSN,
Registry: args.Registry,
EngineVersion: args.EngineVersion,
Expand All @@ -55,6 +63,41 @@ func (c *ConnectionInfo) Name() string {
}

func (c *ConnectionInfo) Start(ctx context.Context) error {
labels, err := c.buildLabels()
if err != nil {
return err
}

c.running.Store(true)
ctx, cancel := context.WithCancel(ctx)
c.ctx = ctx
c.cancel = cancel

c.ping(ctx, labels)

go func() {
defer func() {
c.Registry.Unregister(c.InfoMetric)
c.running.Store(false)
}()

ticker := time.NewTicker(connectionInfoInterval)
defer ticker.Stop()

for {
select {
case <-c.ctx.Done():
return
case <-ticker.C:
c.ping(c.ctx, labels)
}
}
}()

return nil
}

func (c *ConnectionInfo) buildLabels() (prometheus.Labels, error) {
var (
providerName = "unknown"
providerRegion = "unknown"
Expand Down Expand Up @@ -84,7 +127,7 @@ func (c *ConnectionInfo) Start(ctx context.Context) error {
} else {
parts, err := ParseURL(c.DSN)
if err != nil {
return err
return nil, err
}
if host, ok := parts["host"]; ok {
if strings.HasSuffix(host, "rds.amazonaws.com") {
Expand All @@ -109,17 +152,31 @@ func (c *ConnectionInfo) Start(ctx context.Context) error {
engineVersion = matches[1]
}

c.running.Store(true)
return prometheus.Labels{
"provider_name": providerName,
"provider_region": providerRegion,
"provider_account": providerAccount,
"db_instance_identifier": dbInstanceIdentifier,
"engine": engine,
"engine_version": engineVersion,
}, nil
}

c.InfoMetric.WithLabelValues(providerName, providerRegion, providerAccount, dbInstanceIdentifier, engine, engineVersion).Set(1)
return nil
func (c *ConnectionInfo) ping(ctx context.Context, labels prometheus.Labels) {
if err := c.dbConnection.PingContext(ctx); err != nil {
c.Registry.Unregister(c.InfoMetric)
return
}
_ = c.Registry.Register(c.InfoMetric)
c.InfoMetric.With(labels).Set(1)
}

func (c *ConnectionInfo) Stopped() bool {
return !c.running.Load()
}

func (c *ConnectionInfo) Stop() {
c.Registry.Unregister(c.InfoMetric)
c.running.Store(false)
if c.cancel != nil {
c.cancel()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"
"testing"

"github.com/DATA-DOG/go-sqlmock"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
Expand Down Expand Up @@ -87,9 +88,16 @@ func TestConnectionInfo(t *testing.T) {
}

for _, tc := range testCases {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual), sqlmock.MonitorPingsOption(true))
require.NoError(t, err)
defer db.Close()

mock.ExpectPing()

reg := prometheus.NewRegistry()

collector, err := NewConnectionInfo(ConnectionInfoArguments{
DB: db,
DSN: tc.dsn,
Registry: reg,
EngineVersion: tc.engineVersion,
Expand All @@ -100,8 +108,10 @@ func TestConnectionInfo(t *testing.T) {

err = collector.Start(t.Context())
require.NoError(t, err)
defer collector.Stop()

err = testutil.GatherAndCompare(reg, strings.NewReader(tc.expectedMetrics))
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ func (c *Component) startCollectors(systemID string, engineVersion string, cloud

// Connection Info collector is always enabled
ciCollector, err := collector.NewConnectionInfo(collector.ConnectionInfoArguments{
DB: c.dbConnection,
DSN: string(c.args.DataSourceName),
Registry: c.registry,
EngineVersion: engineVersion,
Expand Down
Loading