Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 66a72265ce | |||
| 94b718a925 | |||
| 283d3936f6 | |||
| 7291f00f48 | |||
| 2670d25b52 |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.aider*
|
||||
28
.mcp.json
Normal file
28
.mcp.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"context7": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"@upstash/context7-mcp@1.0.0"
|
||||
],
|
||||
"env": {}
|
||||
},
|
||||
"serena": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": [
|
||||
"--from",
|
||||
"git+https://github.com/oraios/serena@v0.1.4",
|
||||
"serena",
|
||||
"start-mcp-server",
|
||||
"--context",
|
||||
"ide-assistant",
|
||||
"--project",
|
||||
"."
|
||||
],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
20
.pre-commit-config.yaml
Normal file
20
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v5.0.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-added-large-files
|
||||
args: ["--maxkb=400"]
|
||||
- id: check-case-conflict
|
||||
- id: check-executables-have-shebangs
|
||||
- id: check-shebang-scripts-are-executable
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
|
||||
- repo: https://github.com/adrienverge/yamllint
|
||||
rev: v1.35.1
|
||||
hooks:
|
||||
- id: yamllint
|
||||
args: [-c=.yamllint]
|
||||
14
.yamllint
Normal file
14
.yamllint
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
extends: relaxed
|
||||
|
||||
rules:
|
||||
braces:
|
||||
level: error
|
||||
brackets:
|
||||
level: error
|
||||
|
||||
truthy:
|
||||
level: warning
|
||||
|
||||
#ignore: |
|
||||
# - ...
|
||||
@@ -39,6 +39,8 @@ type Config struct {
|
||||
webHostnames []string
|
||||
webTLS bool
|
||||
|
||||
poolDomain string `accessor:"getter"`
|
||||
|
||||
valid bool `accessor:"getter"`
|
||||
}
|
||||
|
||||
@@ -52,6 +54,7 @@ type Config struct {
|
||||
// - web_hostname: Comma-separated web hostnames (first becomes primary)
|
||||
// - manage_tls: Management interface TLS setting
|
||||
// - web_tls: Web interface TLS setting
|
||||
// - pool_domain: NTP pool domain (default: pool.ntp.org)
|
||||
func New() *Config {
|
||||
c := Config{}
|
||||
c.deploymentMode = os.Getenv("deployment_mode")
|
||||
@@ -69,6 +72,11 @@ func New() *Config {
|
||||
c.manageTLS = parseBool(os.Getenv("manage_tls"))
|
||||
c.webTLS = parseBool(os.Getenv("web_tls"))
|
||||
|
||||
c.poolDomain = os.Getenv("pool_domain")
|
||||
if c.poolDomain == "" {
|
||||
c.poolDomain = "pool.ntp.org"
|
||||
}
|
||||
|
||||
return &c
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,13 @@ func (c *Config) WebHostname() string {
|
||||
return c.webHostname
|
||||
}
|
||||
|
||||
func (c *Config) PoolDomain() string {
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
return c.poolDomain
|
||||
}
|
||||
|
||||
func (c *Config) Valid() bool {
|
||||
if c == nil {
|
||||
return false
|
||||
|
||||
@@ -50,7 +50,7 @@ func createConnector(configFile string) CreateConnectorFunc {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer dbFile.Close()
|
||||
defer func() { _ = dbFile.Close() }()
|
||||
|
||||
dec := yaml.NewDecoder(dbFile)
|
||||
cfg := Config{}
|
||||
|
||||
@@ -7,9 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// Mock types for testing SQLC integration patterns
|
||||
type mockQueries struct {
|
||||
db DBTX
|
||||
}
|
||||
type mockQueries struct{}
|
||||
|
||||
type mockQueriesTx struct {
|
||||
*mockQueries
|
||||
@@ -58,7 +56,7 @@ func TestSQLCIntegration(t *testing.T) {
|
||||
|
||||
// Verify our DB interface is compatible with what SQLC expects
|
||||
var dbInterface DB[*mockQueriesTx]
|
||||
var mockDB *mockQueries = &mockQueries{}
|
||||
mockDB := &mockQueries{}
|
||||
dbInterface = mockDB
|
||||
|
||||
// Test that our transaction helper can work with this pattern
|
||||
|
||||
@@ -3,10 +3,10 @@ package database
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"go.ntppool.org/common/logger"
|
||||
)
|
||||
|
||||
// DatabaseMetrics holds the Prometheus metrics for database connection pool monitoring
|
||||
@@ -16,6 +16,10 @@ type DatabaseMetrics struct {
|
||||
ConnectionsInUse prometheus.Gauge
|
||||
ConnectionsWaitCount prometheus.Counter
|
||||
ConnectionsWaitDuration prometheus.Histogram
|
||||
|
||||
// Track last values for delta calculation (cumulative stats from sql.DBStats)
|
||||
lastWaitCount int64
|
||||
lastWaitDuration time.Duration
|
||||
}
|
||||
|
||||
// NewDatabaseMetrics creates a new set of database metrics and registers them
|
||||
@@ -67,26 +71,44 @@ func monitorConnectionPool(ctx context.Context, db *sql.DB, registerer prometheu
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
log := logger.FromContext(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.InfoContext(ctx, "database connection pool monitor stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
stats := db.Stats()
|
||||
|
||||
// Update gauge metrics (current state)
|
||||
metrics.ConnectionsOpen.Set(float64(stats.OpenConnections))
|
||||
metrics.ConnectionsIdle.Set(float64(stats.Idle))
|
||||
metrics.ConnectionsInUse.Set(float64(stats.InUse))
|
||||
metrics.ConnectionsWaitCount.Add(float64(stats.WaitCount))
|
||||
|
||||
if stats.WaitDuration > 0 {
|
||||
metrics.ConnectionsWaitDuration.Observe(stats.WaitDuration.Seconds())
|
||||
// Update counter with delta (WaitCount is cumulative in sql.DBStats)
|
||||
waitCountDelta := stats.WaitCount - metrics.lastWaitCount
|
||||
if waitCountDelta > 0 {
|
||||
metrics.ConnectionsWaitCount.Add(float64(waitCountDelta))
|
||||
metrics.lastWaitCount = stats.WaitCount
|
||||
}
|
||||
|
||||
// Update histogram with delta (WaitDuration is cumulative in sql.DBStats)
|
||||
waitDurationDelta := stats.WaitDuration - metrics.lastWaitDuration
|
||||
if waitDurationDelta > 0 {
|
||||
metrics.ConnectionsWaitDuration.Observe(waitDurationDelta.Seconds())
|
||||
metrics.lastWaitDuration = stats.WaitDuration
|
||||
}
|
||||
|
||||
// Log connection pool stats for high usage or waiting
|
||||
if stats.OpenConnections > 20 || stats.WaitCount > 0 {
|
||||
fmt.Printf("Connection pool stats: open=%d idle=%d in_use=%d wait_count=%d wait_duration=%s\n",
|
||||
stats.OpenConnections, stats.Idle, stats.InUse, stats.WaitCount, stats.WaitDuration)
|
||||
if stats.OpenConnections > 20 || waitCountDelta > 0 {
|
||||
log.WarnContext(ctx, "high database connection usage",
|
||||
"open", stats.OpenConnections,
|
||||
"idle", stats.Idle,
|
||||
"in_use", stats.InUse,
|
||||
"wait_count", stats.WaitCount,
|
||||
"wait_duration", stats.WaitDuration,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +93,34 @@ sslmode: prefer
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `DATABASE_URI` - PostgreSQL connection URI (takes precedence over config files)
|
||||
- `DATABASE_CONFIG_FILE` - Override config file location
|
||||
|
||||
### URI Format
|
||||
|
||||
Standard PostgreSQL URI format:
|
||||
```
|
||||
postgresql://user:password@host:port/database?sslmode=require&pool_max_conns=10
|
||||
```
|
||||
|
||||
Pool settings can be included in the URI query string:
|
||||
- `pool_max_conns`, `pool_min_conns`
|
||||
- `pool_max_conn_lifetime`, `pool_max_conn_idle_time`
|
||||
- `pool_health_check_period`
|
||||
|
||||
When using `DATABASE_URI`, `PoolOptions` are ignored and all settings come from the URI.
|
||||
|
||||
Example with CloudNativePG:
|
||||
```yaml
|
||||
# Mount the secret's 'uri' key as DATABASE_URI
|
||||
env:
|
||||
- name: DATABASE_URI
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: mydb-app
|
||||
key: uri
|
||||
```
|
||||
|
||||
## When to Use
|
||||
|
||||
**Use `pgdb.OpenPool()`** (this package) when:
|
||||
|
||||
@@ -27,15 +27,10 @@ func CreatePoolConfig(cfg *database.PostgresConfig) (*pgxpool.Config, error) {
|
||||
"require": true, "verify-ca": true, "verify-full": true,
|
||||
}
|
||||
if cfg.SSLMode != "" && !validSSLModes[cfg.SSLMode] {
|
||||
return nil, fmt.Errorf("postgres: invalid sslmode: %s", cfg.SSLMode)
|
||||
}
|
||||
|
||||
// Set defaults
|
||||
host := cfg.Host
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
return nil, fmt.Errorf("postgres: invalid sslmode: %s (valid: disable, allow, prefer, require, verify-ca, verify-full)", cfg.SSLMode)
|
||||
}
|
||||
|
||||
// Apply defaults for optional fields (host is validated as required above)
|
||||
port := cfg.Port
|
||||
if port == 0 {
|
||||
port = 5432
|
||||
@@ -49,7 +44,7 @@ func CreatePoolConfig(cfg *database.PostgresConfig) (*pgxpool.Config, error) {
|
||||
// Build connection string WITHOUT password
|
||||
// We'll set the password separately in the config
|
||||
connString := fmt.Sprintf("host=%s port=%d user=%s dbname=%s sslmode=%s",
|
||||
host, port, cfg.User, cfg.Name, sslmode)
|
||||
cfg.Host, port, cfg.User, cfg.Name, sslmode)
|
||||
|
||||
// Parse the connection string
|
||||
poolConfig, err := pgxpool.ParseConfig(connString)
|
||||
|
||||
@@ -2,12 +2,14 @@ package pgdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.ntppool.org/common/database"
|
||||
"go.ntppool.org/common/logger"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -40,7 +42,7 @@ type PoolOptions struct {
|
||||
// DefaultPoolOptions returns sensible defaults for pgxpool
|
||||
func DefaultPoolOptions() PoolOptions {
|
||||
return PoolOptions{
|
||||
ConfigFiles: getConfigFiles(),
|
||||
ConfigFiles: GetConfigFiles(),
|
||||
MinConns: 0,
|
||||
MaxConns: 25,
|
||||
MaxConnLifetime: time.Hour,
|
||||
@@ -51,25 +53,66 @@ func DefaultPoolOptions() PoolOptions {
|
||||
|
||||
// OpenPool opens a native pgx connection pool with the specified configuration
|
||||
// This is the primary and recommended way to connect to PostgreSQL
|
||||
//
|
||||
// Configuration precedence (highest to lowest):
|
||||
// 1. DATABASE_URI environment variable (pool settings can be included in URI)
|
||||
// 2. DATABASE_CONFIG_FILE environment variable (YAML)
|
||||
// 3. Default config files (database.yaml, /vault/secrets/database.yaml)
|
||||
//
|
||||
// When using DATABASE_URI, pool settings (pool_max_conns, pool_min_conns, etc.)
|
||||
// can be specified in the URI query string and PoolOptions are ignored.
|
||||
// When using config files, PoolOptions are applied.
|
||||
func OpenPool(ctx context.Context, options PoolOptions) (*pgxpool.Pool, error) {
|
||||
// Find and read config file
|
||||
pgCfg, err := findAndParseConfig(options.ConfigFiles)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
log := logger.FromContext(ctx)
|
||||
|
||||
// Validate PoolOptions
|
||||
if options.MaxConns <= 0 {
|
||||
return nil, fmt.Errorf("pgdb: MaxConns must be positive, got: %d", options.MaxConns)
|
||||
}
|
||||
if options.MinConns < 0 {
|
||||
return nil, fmt.Errorf("pgdb: MinConns must be non-negative, got: %d", options.MinConns)
|
||||
}
|
||||
if options.MinConns > options.MaxConns {
|
||||
return nil, fmt.Errorf("pgdb: MinConns (%d) cannot exceed MaxConns (%d)", options.MinConns, options.MaxConns)
|
||||
}
|
||||
|
||||
// Create pool config from PostgreSQL config
|
||||
poolConfig, err := CreatePoolConfig(pgCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var poolConfig *pgxpool.Config
|
||||
var err error
|
||||
|
||||
// Apply pool-specific settings
|
||||
poolConfig.MinConns = options.MinConns
|
||||
poolConfig.MaxConns = options.MaxConns
|
||||
poolConfig.MaxConnLifetime = options.MaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = options.MaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = options.HealthCheckPeriod
|
||||
// Check DATABASE_URI environment variable first (highest priority)
|
||||
if uri := os.Getenv("DATABASE_URI"); uri != "" {
|
||||
poolConfig, err = pgxpool.ParseConfig(uri)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse DATABASE_URI: %w", err)
|
||||
}
|
||||
|
||||
// Log when PoolOptions differ from defaults (they will be ignored)
|
||||
defaults := DefaultPoolOptions()
|
||||
if options.MaxConns != defaults.MaxConns || options.MinConns != defaults.MinConns {
|
||||
log.WarnContext(ctx, "DATABASE_URI is set; PoolOptions are ignored (use URI query parameters for pool settings)",
|
||||
"ignored_max_conns", options.MaxConns,
|
||||
"ignored_min_conns", options.MinConns,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Fall back to config file approach
|
||||
pgCfg, _, err := FindConfig(options.ConfigFiles)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
poolConfig, err = CreatePoolConfig(pgCfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply pool-specific settings from PoolOptions (config files don't support these)
|
||||
poolConfig.MinConns = options.MinConns
|
||||
poolConfig.MaxConns = options.MaxConns
|
||||
poolConfig.MaxConnLifetime = options.MaxConnLifetime
|
||||
poolConfig.MaxConnIdleTime = options.MaxConnIdleTime
|
||||
poolConfig.HealthCheckPeriod = options.HealthCheckPeriod
|
||||
}
|
||||
|
||||
// Create the pool
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
@@ -79,7 +122,7 @@ func OpenPool(ctx context.Context, options PoolOptions) (*pgxpool.Pool, error) {
|
||||
|
||||
// Test the connection
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
pool.Close() // pgxpool.Pool.Close() doesn't return an error
|
||||
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
@@ -94,39 +137,54 @@ func OpenPoolWithConfigFile(ctx context.Context, configFile string) (*pgxpool.Po
|
||||
return OpenPool(ctx, options)
|
||||
}
|
||||
|
||||
// findAndParseConfig searches for and parses the first existing config file
|
||||
func findAndParseConfig(configFiles []string) (*database.PostgresConfig, error) {
|
||||
var firstErr error
|
||||
// FindConfig searches for and parses the first existing config file.
|
||||
// Returns the PostgresConfig, the path to the config file used, and any error.
|
||||
// If DATABASE_URI env var is set, returns nil config with empty path (use ParseURIConfig instead).
|
||||
func FindConfig(configFiles []string) (*database.PostgresConfig, string, error) {
|
||||
// Check if DATABASE_URI takes precedence
|
||||
if os.Getenv("DATABASE_URI") != "" {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
var errs []error
|
||||
var triedFiles []string
|
||||
|
||||
for _, configFile := range configFiles {
|
||||
if configFile == "" {
|
||||
continue
|
||||
}
|
||||
triedFiles = append(triedFiles, configFile)
|
||||
|
||||
// Check if file exists
|
||||
if _, err := os.Stat(configFile); err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
errs = append(errs, fmt.Errorf("%s: %w", configFile, err))
|
||||
continue
|
||||
}
|
||||
|
||||
// Try to read and parse the file
|
||||
pgCfg, err := parseConfigFile(configFile)
|
||||
if err != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
errs = append(errs, fmt.Errorf("%s: %w", configFile, err))
|
||||
continue
|
||||
}
|
||||
|
||||
return pgCfg, nil
|
||||
return pgCfg, configFile, nil
|
||||
}
|
||||
|
||||
if firstErr != nil {
|
||||
return nil, fmt.Errorf("no config file found: %w", firstErr)
|
||||
if len(errs) > 0 {
|
||||
return nil, "", fmt.Errorf("no valid config file found (tried: %v): %w", triedFiles, errors.Join(errs...))
|
||||
}
|
||||
return nil, fmt.Errorf("no valid config files provided")
|
||||
return nil, "", fmt.Errorf("no valid config files provided")
|
||||
}
|
||||
|
||||
// ParseURIConfig extracts connection info from DATABASE_URI environment variable.
|
||||
// Returns nil if DATABASE_URI is not set.
|
||||
func ParseURIConfig() (*pgxpool.Config, error) {
|
||||
uri := os.Getenv("DATABASE_URI")
|
||||
if uri == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return pgxpool.ParseConfig(uri)
|
||||
}
|
||||
|
||||
// parseConfigFile reads and parses a YAML config file
|
||||
@@ -135,7 +193,7 @@ func parseConfigFile(configFile string) (*database.PostgresConfig, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open config file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer func() { _ = file.Close() }()
|
||||
|
||||
dec := yaml.NewDecoder(file)
|
||||
cfg := database.Config{}
|
||||
@@ -164,8 +222,9 @@ func parseConfigFile(configFile string) (*database.PostgresConfig, error) {
|
||||
return nil, fmt.Errorf("no PostgreSQL configuration found in %s", configFile)
|
||||
}
|
||||
|
||||
// getConfigFiles returns the list of config files to search
|
||||
func getConfigFiles() []string {
|
||||
// GetConfigFiles returns the list of config files to search for database configuration.
|
||||
// Checks DATABASE_CONFIG_FILE env var first, otherwise returns default paths.
|
||||
func GetConfigFiles() []string {
|
||||
if configFile := os.Getenv("DATABASE_CONFIG_FILE"); configFile != "" {
|
||||
return []string{configFile}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package pgdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -149,3 +152,63 @@ func TestCreatePoolConfigDefaults(t *testing.T) {
|
||||
t.Errorf("Expected default Port=5432, got %d", poolCfg.ConnConfig.Port)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenPoolWithDatabaseURI(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test")
|
||||
}
|
||||
|
||||
// This test requires a running PostgreSQL instance
|
||||
uri := os.Getenv("TEST_DATABASE_URI")
|
||||
if uri == "" {
|
||||
t.Skip("TEST_DATABASE_URI not set")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
t.Setenv("DATABASE_URI", uri)
|
||||
|
||||
pool, err := OpenPool(ctx, DefaultPoolOptions())
|
||||
if err != nil {
|
||||
t.Fatalf("OpenPool failed: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
// Verify connection works
|
||||
var result int
|
||||
err = pool.QueryRow(ctx, "SELECT 1").Scan(&result)
|
||||
if err != nil {
|
||||
t.Fatalf("query failed: %v", err)
|
||||
}
|
||||
if result != 1 {
|
||||
t.Errorf("expected 1, got %d", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseURIPrecedence(t *testing.T) {
|
||||
// Test that DATABASE_URI takes precedence over config files
|
||||
// We use localhost with a port that's unlikely to have postgres running
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Set DATABASE_URI to a parseable URI pointing to a non-listening port
|
||||
t.Setenv("DATABASE_URI", "postgres://testuser:testpass@127.0.0.1:59999/testdb?connect_timeout=1")
|
||||
|
||||
// Set config files to a nonexistent path - if this were used, we'd get
|
||||
// "config file not found" error instead of connection refused
|
||||
opts := DefaultPoolOptions()
|
||||
opts.ConfigFiles = []string{"/nonexistent/path/database.yaml"}
|
||||
|
||||
_, err := OpenPool(ctx, opts)
|
||||
|
||||
// Should fail with connection error (not config file error)
|
||||
// This proves DATABASE_URI was used instead of config files
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
|
||||
// The error should be about connection failure, not about missing config file
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "config file") || strings.Contains(errStr, "no such file") {
|
||||
t.Errorf("expected connection error, got config file error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,9 +51,9 @@ func OpenDBWithConfigFile(ctx context.Context, configFile string) (*sql.DB, erro
|
||||
|
||||
// OpenDBMonitor opens a database connection with monitor-specific defaults
|
||||
// This is a convenience function for Monitor package compatibility
|
||||
func OpenDBMonitor() (*sql.DB, error) {
|
||||
func OpenDBMonitor(ctx context.Context) (*sql.DB, error) {
|
||||
options := MonitorConfigOptions()
|
||||
return OpenDB(context.Background(), options)
|
||||
return OpenDB(ctx, options)
|
||||
}
|
||||
|
||||
// findConfigFile searches for the first existing config file from the list
|
||||
|
||||
24
go.mod
24
go.mod
@@ -1,6 +1,6 @@
|
||||
module go.ntppool.org/common
|
||||
|
||||
go 1.23.5
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/abh/certman v0.4.0
|
||||
@@ -33,9 +33,9 @@ require (
|
||||
go.opentelemetry.io/otel/sdk/log v0.9.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.33.0
|
||||
go.opentelemetry.io/otel/trace v1.33.0
|
||||
golang.org/x/mod v0.22.0
|
||||
golang.org/x/net v0.33.0
|
||||
golang.org/x/sync v0.13.0
|
||||
golang.org/x/mod v0.28.0
|
||||
golang.org/x/net v0.44.0
|
||||
golang.org/x/sync v0.17.0
|
||||
google.golang.org/grpc v1.69.2
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
@@ -45,6 +45,7 @@ require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dmarkham/enumer v1.6.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.8.0 // indirect
|
||||
github.com/go-logr/logr v1.4.2 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
@@ -56,14 +57,17 @@ require (
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/masaushi/accessory v0.6.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pascaldekloe/name v1.0.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.22 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/prometheus/common v0.61.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/samber/lo v1.47.0 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
@@ -74,11 +78,17 @@ require (
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.4.0 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
golang.org/x/crypto v0.42.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/time v0.8.0 // indirect
|
||||
golang.org/x/tools v0.37.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20241223144023-3abc09e42ca8 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 // indirect
|
||||
google.golang.org/protobuf v1.36.1 // indirect
|
||||
)
|
||||
|
||||
tool (
|
||||
github.com/dmarkham/enumer
|
||||
github.com/masaushi/accessory
|
||||
)
|
||||
|
||||
36
go.sum
36
go.sum
@@ -4,6 +4,8 @@ github.com/abh/certman v0.4.0 h1:XHoDtb0YyRQPclaHMrBDlKTVZpNjTK6vhB0S3Bd/Sbs=
|
||||
github.com/abh/certman v0.4.0/go.mod h1:x8QhpKVZifmV1Hdiwdg9gLo2GMPAxezz1s3zrVnPs+I=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bradleyjkemp/cupaloy/v2 v2.8.0 h1:any4BmKE+jGIaMpnU8YgH/I2LPiLBufr6oMMlVBbn9M=
|
||||
github.com/bradleyjkemp/cupaloy/v2 v2.8.0/go.mod h1:bm7JXdkRd4BHJk9HpwqAI8BoAY1lps46Enkdqw6aRX0=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
@@ -12,6 +14,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dmarkham/enumer v1.6.1 h1:aSc9awYtZL07TUueWs40QcHtxTvHTAwG0EqrNsK45w4=
|
||||
github.com/dmarkham/enumer v1.6.1/go.mod h1:yixql+kDDQRYqcuBM2n9Vlt7NoT9ixgXhaXry8vmRg8=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
@@ -54,6 +58,8 @@ github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaa
|
||||
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/masaushi/accessory v0.6.0 h1:HYAzxkuhfvlbaQwinxXTxsSPbFabAnwHt8K6I/DvNBU=
|
||||
github.com/masaushi/accessory v0.6.0/go.mod h1:8GZMgq3wcIapVZWt7VVQCh5+onPc/8gJeHb8WRXezvQ=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
@@ -63,6 +69,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU=
|
||||
github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
|
||||
github.com/pascaldekloe/name v1.0.0 h1:n7LKFgHixETzxpRv2R77YgPUFo85QHGZKrdaYm7eY5U=
|
||||
github.com/pascaldekloe/name v1.0.0/go.mod h1:Z//MfYJnH4jVpQ9wkclwu2I2MkHmXTlT9wR5UZScttM=
|
||||
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
|
||||
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
|
||||
@@ -92,6 +100,8 @@ github.com/samber/slog-multi v1.2.4 h1:k9x3JAWKJFPKffx+oXZ8TasaNuorIW4tG+TXxkt6R
|
||||
github.com/samber/slog-multi v1.2.4/go.mod h1:ACuZ5B6heK57TfMVkVknN2UZHoFfjCwRxR0Q2OXKHlo=
|
||||
github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUanQQB0=
|
||||
github.com/segmentio/kafka-go v0.4.47/go.mod h1:HjF6XbOKh0Pjlkr5GVZxt6CsjjwnmhVOfURM5KMd8qg=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
@@ -170,25 +180,25 @@ go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4=
|
||||
golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
|
||||
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -199,8 +209,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -213,14 +223,16 @@ golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
|
||||
golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
|
||||
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20241223144023-3abc09e42ca8 h1:st3LcW/BPi75W4q1jJTEor/QWwbNlPlDG0JTn6XhZu0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20241223144023-3abc09e42ca8/go.mod h1:klhJGKFyG8Tn50enBn7gizg4nXGXJ+jqEREdCWaPcV4=
|
||||
|
||||
@@ -3,6 +3,24 @@
|
||||
// This package implements a dedicated metrics server that exposes application metrics
|
||||
// via HTTP. It uses a custom Prometheus registry to avoid conflicts with other metric
|
||||
// collectors and provides graceful shutdown capabilities.
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// Create a new metrics server and register your metrics with its Registry():
|
||||
//
|
||||
// m := metricsserver.New()
|
||||
// myCounter := prometheus.NewCounter(...)
|
||||
// m.Registry().MustRegister(myCounter)
|
||||
//
|
||||
// When you need a Gatherer (for example, to pass to other libraries), use the Gatherer() method
|
||||
// instead of prometheus.DefaultGatherer to ensure your custom metrics are collected:
|
||||
//
|
||||
// gatherer := m.Gatherer() // Returns the custom registry as a Gatherer
|
||||
//
|
||||
// To use the default Prometheus gatherer alongside your custom registry:
|
||||
//
|
||||
// m := metricsserver.NewWithDefaultGatherer()
|
||||
// m.Gatherer() // Returns prometheus.DefaultGatherer
|
||||
package metricsserver
|
||||
|
||||
import (
|
||||
@@ -21,15 +39,32 @@ import (
|
||||
// Metrics provides a custom Prometheus registry and HTTP handlers for metrics exposure.
|
||||
// It isolates application metrics from the default global registry.
|
||||
type Metrics struct {
|
||||
r *prometheus.Registry
|
||||
r *prometheus.Registry
|
||||
useDefaultGatherer bool
|
||||
}
|
||||
|
||||
// New creates a new Metrics instance with a custom Prometheus registry.
|
||||
// Use this when you want isolated metrics that don't interfere with the default registry.
|
||||
func New() *Metrics {
|
||||
r := prometheus.NewRegistry()
|
||||
|
||||
m := &Metrics{
|
||||
r: r,
|
||||
r: r,
|
||||
useDefaultGatherer: false,
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
// NewWithDefaultGatherer creates a new Metrics instance that uses the default Prometheus gatherer.
|
||||
// This is useful when you want to expose metrics from the default registry alongside your custom metrics.
|
||||
// The custom registry will still be available via Registry() but Gatherer() will return prometheus.DefaultGatherer.
|
||||
func NewWithDefaultGatherer() *Metrics {
|
||||
r := prometheus.NewRegistry()
|
||||
|
||||
m := &Metrics{
|
||||
r: r,
|
||||
useDefaultGatherer: true,
|
||||
}
|
||||
|
||||
return m
|
||||
@@ -41,6 +76,23 @@ func (m *Metrics) Registry() *prometheus.Registry {
|
||||
return m.r
|
||||
}
|
||||
|
||||
// Gatherer returns the Prometheus gatherer to use for collecting metrics.
|
||||
// This returns the custom registry's Gatherer by default, ensuring your registered
|
||||
// metrics are collected. If the instance was created with NewWithDefaultGatherer(),
|
||||
// this returns prometheus.DefaultGatherer instead.
|
||||
//
|
||||
// Use this method when you need a prometheus.Gatherer interface, for example when
|
||||
// configuring other libraries that need to collect metrics.
|
||||
//
|
||||
// IMPORTANT: Do not use prometheus.DefaultGatherer directly if you want to collect
|
||||
// metrics registered with this instance's Registry(). Always use this Gatherer() method.
|
||||
func (m *Metrics) Gatherer() prometheus.Gatherer {
|
||||
if m.useDefaultGatherer {
|
||||
return prometheus.DefaultGatherer
|
||||
}
|
||||
return m.r
|
||||
}
|
||||
|
||||
// Handler returns an HTTP handler for the /metrics endpoint with OpenMetrics support.
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
log := logger.NewStdLog("prom http", false, nil)
|
||||
|
||||
@@ -67,6 +67,47 @@ func TestRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatherer(t *testing.T) {
|
||||
metrics := New()
|
||||
|
||||
gatherer := metrics.Gatherer()
|
||||
if gatherer == nil {
|
||||
t.Fatal("Gatherer() returned nil")
|
||||
}
|
||||
|
||||
// Register a test metric
|
||||
counter := prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Name: "test_gatherer_counter",
|
||||
Help: "A test counter for gatherer",
|
||||
})
|
||||
|
||||
metrics.Registry().MustRegister(counter)
|
||||
counter.Inc()
|
||||
|
||||
// Test that the gatherer collects our custom metric
|
||||
metricFamilies, err := gatherer.Gather()
|
||||
if err != nil {
|
||||
t.Errorf("failed to gather metrics: %v", err)
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, mf := range metricFamilies {
|
||||
if mf.GetName() == "test_gatherer_counter" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
t.Error("registered metric not found via Gatherer()")
|
||||
}
|
||||
|
||||
// Verify gatherer is the same as registry
|
||||
if gatherer != metrics.r {
|
||||
t.Error("Gatherer() should return the same object as the registry for custom registry mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandler(t *testing.T) {
|
||||
metrics := New()
|
||||
|
||||
@@ -212,6 +253,45 @@ func TestListenAndServeContextCancellation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewWithDefaultGatherer(t *testing.T) {
|
||||
metrics := NewWithDefaultGatherer()
|
||||
|
||||
if metrics == nil {
|
||||
t.Fatal("NewWithDefaultGatherer returned nil")
|
||||
}
|
||||
|
||||
if !metrics.useDefaultGatherer {
|
||||
t.Error("useDefaultGatherer should be true")
|
||||
}
|
||||
|
||||
gatherer := metrics.Gatherer()
|
||||
if gatherer == nil {
|
||||
t.Fatal("Gatherer() returned nil")
|
||||
}
|
||||
|
||||
// Verify it returns the default gatherer
|
||||
if gatherer != prometheus.DefaultGatherer {
|
||||
t.Error("Gatherer() should return prometheus.DefaultGatherer when useDefaultGatherer is true")
|
||||
}
|
||||
|
||||
// Verify the custom registry is still available and separate
|
||||
if metrics.Registry() == nil {
|
||||
t.Error("Registry() should still return a custom registry")
|
||||
}
|
||||
|
||||
// Test that registering in custom registry doesn't affect default gatherer check
|
||||
counter := prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Name: "test_default_gatherer_counter",
|
||||
Help: "A test counter",
|
||||
})
|
||||
metrics.Registry().MustRegister(counter)
|
||||
|
||||
// The gatherer should still be the default one, not our custom registry
|
||||
if metrics.Gatherer() != prometheus.DefaultGatherer {
|
||||
t.Error("Gatherer() should continue to return prometheus.DefaultGatherer")
|
||||
}
|
||||
}
|
||||
|
||||
// Benchmark the metrics handler response time
|
||||
func BenchmarkMetricsHandler(b *testing.B) {
|
||||
metrics := New()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
go install github.com/goreleaser/goreleaser/v2@v2.11.0
|
||||
go install github.com/goreleaser/goreleaser/v2@v2.12.3
|
||||
|
||||
if [ ! -z "${harbor_username:-}" ]; then
|
||||
DOCKER_FILE=~/.docker/config.json
|
||||
|
||||
Reference in New Issue
Block a user