lab7: TLS/mTLS по trust matrix, OpenBao (cert auth, KV, policies), роли БД, Argon2id+rehash, лимит входа, hardening, secprobe и тесты
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"github.com/exaring/otelpgx"
|
||||
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewPool создаёт пул соединений с PostgreSQL.
|
||||
// Параметры ограничены, чтобы не перегрузить БД.
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
return NewPoolFromConfig(ctx, cfg, maxConns)
|
||||
}
|
||||
|
||||
// NewPoolFromConfig — пул из готовой конфигурации (lab7: TLS verify-full и
|
||||
// credentials из OpenBao через BeforeConnect).
|
||||
func NewPoolFromConfig(ctx context.Context, cfg *pgxpool.Config, maxConns int32) (*pgxpool.Pool, error) {
|
||||
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = min(2, maxConns)
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
if cfg.MaxConnLifetime == 0 || cfg.MaxConnLifetime > 30*time.Minute {
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
}
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
// Трассы запросов (SQL-текст с плейсхолдерами, без значений параметров)
|
||||
// и ожидания соединения из пула (acquire) — видно, что медленная именно БД.
|
||||
cfg.ConnConfig.Tracer = otelpgx.NewTracer(otelpgx.WithTrimSQLInSpanName())
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
// Проверяем, что соединение работает.
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping: %w", err)
|
||||
}
|
||||
|
||||
// Метрики пула: pgxpool.acquired_connections, idle, max, empty_acquire (ожидания).
|
||||
if err := otelpgx.RecordStats(pool); err != nil {
|
||||
return nil, fmt.Errorf("pool metrics: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user