Skip to content
Merged
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
32 changes: 27 additions & 5 deletions internal/collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"log/slog"
"pg-bash-exporter/internal/cache"
"pg-bash-exporter/internal/config"
"sync"
"time"
)

Expand Down Expand Up @@ -67,13 +68,34 @@ func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
func (c *Collector) Collect(ch chan<- prometheus.Metric) {
c.logger.Info("Metrics collection started")

wg := sync.WaitGroup{}

maxConcurrent := c.config.Global.MaxConcurrent
if maxConcurrent <= 0 {
maxConcurrent = config.DefaultMaxConcurrent
}
smph := make(chan struct{}, maxConcurrent)

for _, metricConfig := range c.config.Metrics {
if len(metricConfig.SubMetrics) == 0 {
c.collectSimpleMetric(ch, metricConfig)
} else {
c.collectComplicatedMetric(ch, metricConfig)
}
wg.Add(1)

go func(mc config.Metric) {
defer wg.Done()

Copilot AI Jul 16, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Goroutines that panic will not be recovered and could cause issues. Consider adding panic recovery with defer recover() to ensure the WaitGroup is properly decremented and semaphore is released even if collectSimpleMetric or collectComplicatedMetric panic.

Suggested change
defer wg.Done()
defer func() {
if r := recover(); r != nil {
c.logger.Error("Panic recovered in goroutine", "metric", mc.Name, "error", r)
}
wg.Done()
}()

Copilot uses AI. Check for mistakes.

smph <- struct{}{}
defer func() {
<-smph
}()

if len(mc.SubMetrics) == 0 {
c.collectSimpleMetric(ch, mc)
} else {
c.collectComplicatedMetric(ch, mc)
}
}(metricConfig)
Comment on lines +82 to +95

Copilot AI Jul 16, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The semaphore acquisition could block indefinitely if the context is cancelled or the operation needs to be interrupted. Consider using a select statement with context cancellation to make this interruptible.

Copilot uses AI. Check for mistakes.
}

wg.Wait()

c.logger.Info("Metrics collection finished")
Comment on lines +90 to 100

Copilot AI Jul 16, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The WaitGroup.Wait() call could block indefinitely if any goroutine panics or hangs. Consider adding a timeout or context cancellation to prevent the collector from hanging indefinitely.

Copilot uses AI. Check for mistakes.
}