Skip to content

Commit

Permalink
Adjust collector to use separate connection per scrape
Browse files Browse the repository at this point in the history
Fixes prometheus-community#921

Signed-off-by: Joe Adams <github@joeadams.io>
  • Loading branch information
sysadmind committed Oct 10, 2023
1 parent f0f051c commit 3948c5c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
9 changes: 6 additions & 3 deletions collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
7 changes: 7 additions & 0 deletions collector/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 3948c5c

Please sign in to comment.