From 2a5692c0283fddf96e776cc73c2fc0d5caed1af6 Mon Sep 17 00:00:00 2001 From: Joe Adams Date: Tue, 10 Oct 2023 07:07:37 -0400 Subject: [PATCH] Adjust collector to use separate connection per scrape (#931) Fixes #921 Signed-off-by: Joe Adams --- collector/collector.go | 9 ++++++--- collector/instance.go | 7 +++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/collector/collector.go b/collector/collector.go index c643bd91..12112987 100644 --- a/collector/collector.go +++ b/collector/collector.go @@ -167,19 +167,22 @@ func (p PostgresCollector) Describe(ch chan<- *prometheus.Desc) { func (p PostgresCollector) Collect(ch chan<- prometheus.Metric) { ctx := context.TODO() + // copy the instance so that concurrent scrapes have independent instances + inst := p.instance.copy() + // Set up the database connection for the collector. - err := p.instance.setup() + err := inst.setup() if err != nil { level.Error(p.logger).Log("msg", "Error opening connection to database", "err", err) return } - defer p.instance.Close() + defer inst.Close() wg := sync.WaitGroup{} wg.Add(len(p.Collectors)) for name, c := range p.Collectors { go func(name string, c Collector) { - execute(ctx, name, c, p.instance, ch, p.logger) + execute(ctx, name, c, inst, ch, p.logger) wg.Done() }(name, c) } diff --git a/collector/instance.go b/collector/instance.go index 87eb0591..a365697d 100644 --- a/collector/instance.go +++ b/collector/instance.go @@ -43,6 +43,13 @@ func newInstance(dsn string) (*instance, error) { return i, nil } +// copy returns a copy of the instance. +func (i *instance) copy() *instance { + return &instance{ + dsn: i.dsn, + } +} + func (i *instance) setup() error { db, err := sql.Open("postgres", i.dsn) if err != nil {