From cc917aee7f95fb1fe6601a8c26c6ea83f7aa6dba Mon Sep 17 00:00:00 2001 From: sev3ryn Date: Thu, 5 Apr 2018 11:41:09 +0200 Subject: [PATCH] fix of endless loop while doing Consul service discovery. (#4044) Reloading Prometheus configs doesn't make loop end. It produced a goroutine leak --- discovery/consul/consul.go | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/discovery/consul/consul.go b/discovery/consul/consul.go index e2592054c5..266b0c5030 100644 --- a/discovery/consul/consul.go +++ b/discovery/consul/consul.go @@ -302,17 +302,22 @@ func (d *Discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { if len(d.watchedServices) == 0 || d.watchedTag != "" { // We need to watch the catalog. ticker := time.NewTicker(d.refreshInterval) - go func() { - // Watched services and their cancellation functions. - services := make(map[string]func()) - var lastIndex uint64 - for ; true; <-ticker.C { + // Watched services and their cancellation functions. + services := make(map[string]func()) + var lastIndex uint64 + + for { + select { + case <-ctx.Done(): + ticker.Stop() + return + default: d.watchServices(ctx, ch, &lastIndex, services) + <-ticker.C } - }() - <-ctx.Done() - ticker.Stop() + } + } else { // We only have fully defined services. for _, name := range d.watchedServices { @@ -417,11 +422,16 @@ func (d *Discovery) watchService(ctx context.Context, ch chan<- []*targetgroup.G ticker := time.NewTicker(d.refreshInterval) var lastIndex uint64 catalog := srv.client.Catalog() - for ; true; <-ticker.C { - srv.watch(ctx, ch, catalog, &lastIndex) + for { + select { + case <-ctx.Done(): + ticker.Stop() + return + default: + srv.watch(ctx, ch, catalog, &lastIndex) + <-ticker.C + } } - <-ctx.Done() - ticker.Stop() }() }