Fix race in helpers/prometheus/log_hook.go: Fire()

parent dbf70b85
package prometheus
import (
"sync"
"github.com/Sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
)
......@@ -9,6 +11,7 @@ var numErrorsDesc = prometheus.NewDesc("ci_runner_errors", "The number of catch
type LogHook struct {
errorsNumber map[logrus.Level]float64
lock sync.Mutex
}
func (lh *LogHook) Levels() []logrus.Level {
......@@ -21,7 +24,11 @@ func (lh *LogHook) Levels() []logrus.Level {
}
func (lh *LogHook) Fire(entry *logrus.Entry) error {
lh.lock.Lock()
defer lh.lock.Unlock()
lh.errorsNumber[entry.Level]++
return nil
}
......
package prometheus
import (
"testing"
"github.com/Sirupsen/logrus"
)
func callFireConcurrent(t *testing.T, lh *LogHook, repeats int, finish chan bool) {
for i := 0; i < repeats; i++ {
lh.Fire(&logrus.Entry{
Level: logrus.ErrorLevel,
})
finish <- true
}
}
func TestConcurrentFireCall(t *testing.T) {
lh := NewLogHook()
finish := make(chan bool)
times := 5
repeats := 100
total := times * repeats
for i := 0; i < times; i++ {
go callFireConcurrent(t, &lh, repeats, finish)
}
finished := 0
for {
if finished >= total {
break
}
<-finish
finished++
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment