From c19763c03f6c42ce64c778a1280da505532f297f Mon Sep 17 00:00:00 2001 From: "Johan T. Halseth" Date: Mon, 28 Jan 2019 12:16:34 +0100 Subject: [PATCH] autopilot/agent: don't block Stop on pending connetion To ensure a call to ConnectToPeer doesn't block the agent from shutting down, we'll launch it in a non-waitgrouped goroutine, that will signal when a result is returned. --- autopilot/agent.go | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/autopilot/agent.go b/autopilot/agent.go index 8d346b9e..2ff5cf0b 100644 --- a/autopilot/agent.go +++ b/autopilot/agent.go @@ -667,7 +667,40 @@ func (a *Agent) executeDirective(directive AttachmentDirective) { return } - alreadyConnected, err := a.cfg.ConnectToPeer(pub, directive.Addrs) + connected := make(chan bool) + errChan := make(chan error) + + // To ensure a call to ConnectToPeer doesn't block the agent from + // shutting down, we'll launch it in a non-waitgrouped goroutine, that + // will signal when a result is returned. + // TODO(halseth): use DialContext to cancel on transport level. + go func() { + alreadyConnected, err := a.cfg.ConnectToPeer( + pub, directive.Addrs, + ) + if err != nil { + select { + case errChan <- err: + case <-a.quit: + } + return + } + + select { + case connected <- alreadyConnected: + case <-a.quit: + return + } + }() + + var alreadyConnected bool + select { + case alreadyConnected = <-connected: + case err = <-errChan: + case <-a.quit: + return + } + if err != nil { log.Warnf("Unable to connect to %x: %v", pub.SerializeCompressed(), err)