Use DNS server startup callbacks

Simplify waiting for the DNS server to start with the newer "NotifyStartedFunc"
callback.
This commit is contained in:
Matt Good 2015-03-31 16:48:48 -07:00
parent 70a71b9454
commit f5d27daf63

View file

@ -7,6 +7,7 @@ import (
"math/rand" "math/rand"
"net" "net"
"strings" "strings"
"sync"
"time" "time"
"github.com/hashicorp/consul/consul/structs" "github.com/hashicorp/consul/consul/structs"
@ -51,17 +52,21 @@ func NewDNSServer(agent *Agent, config *DNSConfig, logOutput io.Writer, domain s
// Construct the DNS components // Construct the DNS components
mux := dns.NewServeMux() mux := dns.NewServeMux()
var wg sync.WaitGroup
// Setup the servers // Setup the servers
server := &dns.Server{ server := &dns.Server{
Addr: bind, Addr: bind,
Net: "udp", Net: "udp",
Handler: mux, Handler: mux,
UDPSize: 65535, UDPSize: 65535,
NotifyStartedFunc: wg.Done,
} }
serverTCP := &dns.Server{ serverTCP := &dns.Server{
Addr: bind, Addr: bind,
Net: "tcp", Net: "tcp",
Handler: mux, Handler: mux,
NotifyStartedFunc: wg.Done,
} }
// Create the server // Create the server
@ -99,6 +104,8 @@ func NewDNSServer(agent *Agent, config *DNSConfig, logOutput io.Writer, domain s
mux.HandleFunc(".", srv.handleRecurse) mux.HandleFunc(".", srv.handleRecurse)
} }
wg.Add(2)
// Async start the DNS Servers, handle a potential error // Async start the DNS Servers, handle a potential error
errCh := make(chan error, 1) errCh := make(chan error, 1)
go func() { go func() {
@ -116,28 +123,11 @@ func NewDNSServer(agent *Agent, config *DNSConfig, logOutput io.Writer, domain s
} }
}() }()
// Check the server is running, do a test lookup // Wait for NotifyStartedFunc callbacks indicating server has started
checkCh := make(chan error, 1) startCh := make(chan struct{})
go func() { go func() {
// This is jank, but we have no way to edge trigger on wg.Wait()
// the start of our server, so we just wait and hope it is up. close(startCh)
time.Sleep(50 * time.Millisecond)
m := new(dns.Msg)
m.SetQuestion(testQuery, dns.TypeANY)
c := new(dns.Client)
in, _, err := c.Exchange(m, bind)
if err != nil {
checkCh <- fmt.Errorf("dns test query failed: %v", err)
return
}
if len(in.Answer) == 0 {
checkCh <- fmt.Errorf("no response to test message")
return
}
close(checkCh)
}() }()
// Wait for either the check, listen error, or timeout // Wait for either the check, listen error, or timeout
@ -146,8 +136,8 @@ func NewDNSServer(agent *Agent, config *DNSConfig, logOutput io.Writer, domain s
return srv, e return srv, e
case e := <-errChTCP: case e := <-errChTCP:
return srv, e return srv, e
case e := <-checkCh: case <-startCh:
return srv, e return srv, nil
case <-time.After(time.Second): case <-time.After(time.Second):
return srv, fmt.Errorf("timeout setting up DNS server") return srv, fmt.Errorf("timeout setting up DNS server")
} }