fix datarace in input apache plugin

This commit is contained in:
Konstantin Kulikov 2016-06-17 23:14:29 +03:00
parent af0979cce5
commit d55fa88dd0
2 changed files with 10 additions and 7 deletions

View File

@ -8,7 +8,6 @@ import (
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
@ -38,8 +37,8 @@ func (n *Apache) Gather(acc telegraf.Accumulator) error {
n.Urls = []string{"http://localhost/server-status?auto"} n.Urls = []string{"http://localhost/server-status?auto"}
} }
var wg sync.WaitGroup
var outerr error var outerr error
var errch = make(chan error)
for _, u := range n.Urls { for _, u := range n.Urls {
addr, err := url.Parse(u) addr, err := url.Parse(u)
@ -47,14 +46,17 @@ func (n *Apache) Gather(acc telegraf.Accumulator) error {
return fmt.Errorf("Unable to parse address '%s': %s", u, err) return fmt.Errorf("Unable to parse address '%s': %s", u, err)
} }
wg.Add(1)
go func(addr *url.URL) { go func(addr *url.URL) {
defer wg.Done() errch <- n.gatherUrl(addr, acc)
outerr = n.gatherUrl(addr, acc)
}(addr) }(addr)
} }
wg.Wait() // Drain channel, waiting for all requests to finish and save last error.
for range n.Urls {
if err := <-errch; err != nil {
outerr = err
}
}
return outerr return outerr
} }

View File

@ -36,7 +36,8 @@ func TestHTTPApache(t *testing.T) {
defer ts.Close() defer ts.Close()
a := Apache{ a := Apache{
Urls: []string{ts.URL}, // Fetch it 2 times to catch possible data races.
Urls: []string{ts.URL, ts.URL},
} }
var acc testutil.Accumulator var acc testutil.Accumulator