2014-01-02 21:12:05 +00:00
|
|
|
package agent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
2014-02-14 20:26:51 +00:00
|
|
|
"math/rand"
|
2014-01-03 01:58:58 +00:00
|
|
|
"net"
|
|
|
|
"strings"
|
2015-03-31 23:48:48 +00:00
|
|
|
"sync"
|
2014-01-02 21:12:05 +00:00
|
|
|
"time"
|
2014-11-03 19:40:55 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/consul/consul/structs"
|
|
|
|
"github.com/miekg/dns"
|
2014-01-02 21:12:05 +00:00
|
|
|
)
|
|
|
|
|
2014-01-03 01:58:58 +00:00
|
|
|
const (
|
2014-02-14 22:22:49 +00:00
|
|
|
maxServiceResponses = 3 // For UDP only
|
2014-02-26 01:41:48 +00:00
|
|
|
maxRecurseRecords = 3
|
2014-01-03 01:58:58 +00:00
|
|
|
)
|
|
|
|
|
2014-01-02 21:12:05 +00:00
|
|
|
// DNSServer is used to wrap an Agent and expose various
|
|
|
|
// service discovery endpoints using a DNS interface.
|
|
|
|
type DNSServer struct {
|
2014-01-03 23:43:35 +00:00
|
|
|
agent *Agent
|
2014-06-08 22:49:24 +00:00
|
|
|
config *DNSConfig
|
2014-01-03 23:43:35 +00:00
|
|
|
dnsHandler *dns.ServeMux
|
|
|
|
dnsServer *dns.Server
|
|
|
|
dnsServerTCP *dns.Server
|
|
|
|
domain string
|
2014-10-31 19:19:41 +00:00
|
|
|
recursors []string
|
2014-01-03 23:43:35 +00:00
|
|
|
logger *log.Logger
|
2014-01-02 21:12:05 +00:00
|
|
|
}
|
|
|
|
|
2015-01-16 12:11:34 +00:00
|
|
|
// Shutdown stops the DNS Servers
|
|
|
|
func (d *DNSServer) Shutdown() {
|
|
|
|
if err := d.dnsServer.Shutdown(); err != nil {
|
|
|
|
d.logger.Printf("[ERR] dns: error stopping udp server: %v", err)
|
|
|
|
}
|
|
|
|
if err := d.dnsServerTCP.Shutdown(); err != nil {
|
|
|
|
d.logger.Printf("[ERR] dns: error stopping tcp server: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-02 21:12:05 +00:00
|
|
|
// NewDNSServer starts a new DNS server to provide an agent interface
|
2014-10-31 19:19:41 +00:00
|
|
|
func NewDNSServer(agent *Agent, config *DNSConfig, logOutput io.Writer, domain string, bind string, recursors []string) (*DNSServer, error) {
|
2014-01-03 01:58:58 +00:00
|
|
|
// Make sure domain is FQDN
|
|
|
|
domain = dns.Fqdn(domain)
|
|
|
|
|
2014-01-02 21:12:05 +00:00
|
|
|
// Construct the DNS components
|
|
|
|
mux := dns.NewServeMux()
|
|
|
|
|
2015-03-31 23:48:48 +00:00
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
2014-01-03 23:43:35 +00:00
|
|
|
// Setup the servers
|
2014-01-02 21:12:05 +00:00
|
|
|
server := &dns.Server{
|
2015-03-31 23:48:48 +00:00
|
|
|
Addr: bind,
|
|
|
|
Net: "udp",
|
|
|
|
Handler: mux,
|
|
|
|
UDPSize: 65535,
|
|
|
|
NotifyStartedFunc: wg.Done,
|
2014-01-02 21:12:05 +00:00
|
|
|
}
|
2014-01-03 23:43:35 +00:00
|
|
|
serverTCP := &dns.Server{
|
2015-03-31 23:48:48 +00:00
|
|
|
Addr: bind,
|
|
|
|
Net: "tcp",
|
|
|
|
Handler: mux,
|
|
|
|
NotifyStartedFunc: wg.Done,
|
2014-01-03 23:43:35 +00:00
|
|
|
}
|
2014-01-02 21:12:05 +00:00
|
|
|
|
|
|
|
// Create the server
|
|
|
|
srv := &DNSServer{
|
2014-01-03 23:43:35 +00:00
|
|
|
agent: agent,
|
2014-06-08 22:49:24 +00:00
|
|
|
config: config,
|
2014-01-03 23:43:35 +00:00
|
|
|
dnsHandler: mux,
|
|
|
|
dnsServer: server,
|
|
|
|
dnsServerTCP: serverTCP,
|
|
|
|
domain: domain,
|
2014-10-31 19:19:41 +00:00
|
|
|
recursors: recursors,
|
2014-01-03 23:43:35 +00:00
|
|
|
logger: log.New(logOutput, "", log.LstdFlags),
|
2014-01-02 21:12:05 +00:00
|
|
|
}
|
|
|
|
|
2014-11-23 08:16:37 +00:00
|
|
|
// Register mux handler, for reverse lookup
|
|
|
|
mux.HandleFunc("arpa.", srv.handlePtr)
|
|
|
|
|
2015-03-31 23:50:44 +00:00
|
|
|
// Register mux handlers
|
2014-01-03 01:58:58 +00:00
|
|
|
mux.HandleFunc(domain, srv.handleQuery)
|
2014-10-31 19:19:41 +00:00
|
|
|
if len(recursors) > 0 {
|
2014-11-03 19:40:55 +00:00
|
|
|
validatedRecursors := make([]string, len(recursors))
|
2014-10-31 19:19:41 +00:00
|
|
|
|
2014-11-03 19:40:55 +00:00
|
|
|
for idx, recursor := range recursors {
|
2014-10-31 19:19:41 +00:00
|
|
|
recursor, err := recursorAddr(recursor)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Invalid recursor address: %v", err)
|
|
|
|
}
|
2014-11-03 19:40:55 +00:00
|
|
|
validatedRecursors[idx] = recursor
|
2014-02-23 01:31:11 +00:00
|
|
|
}
|
2014-10-31 19:19:41 +00:00
|
|
|
|
|
|
|
srv.recursors = validatedRecursors
|
2014-01-03 23:43:35 +00:00
|
|
|
mux.HandleFunc(".", srv.handleRecurse)
|
|
|
|
}
|
2014-01-02 21:12:05 +00:00
|
|
|
|
2015-03-31 23:48:48 +00:00
|
|
|
wg.Add(2)
|
|
|
|
|
2014-01-03 23:43:35 +00:00
|
|
|
// Async start the DNS Servers, handle a potential error
|
2014-01-02 21:12:05 +00:00
|
|
|
errCh := make(chan error, 1)
|
|
|
|
go func() {
|
2015-01-16 12:11:34 +00:00
|
|
|
if err := server.ListenAndServe(); err != nil {
|
|
|
|
srv.logger.Printf("[ERR] dns: error starting udp server: %v", err)
|
|
|
|
errCh <- fmt.Errorf("dns udp setup failed: %v", err)
|
|
|
|
}
|
2014-01-02 21:12:05 +00:00
|
|
|
}()
|
|
|
|
|
2014-01-03 23:43:35 +00:00
|
|
|
errChTCP := make(chan error, 1)
|
|
|
|
go func() {
|
2015-01-16 12:11:34 +00:00
|
|
|
if err := serverTCP.ListenAndServe(); err != nil {
|
|
|
|
srv.logger.Printf("[ERR] dns: error starting tcp server: %v", err)
|
|
|
|
errChTCP <- fmt.Errorf("dns tcp setup failed: %v", err)
|
|
|
|
}
|
2014-01-03 23:43:35 +00:00
|
|
|
}()
|
|
|
|
|
2015-03-31 23:48:48 +00:00
|
|
|
// Wait for NotifyStartedFunc callbacks indicating server has started
|
|
|
|
startCh := make(chan struct{})
|
2014-01-02 21:12:05 +00:00
|
|
|
go func() {
|
2015-03-31 23:48:48 +00:00
|
|
|
wg.Wait()
|
|
|
|
close(startCh)
|
2014-01-02 21:12:05 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait for either the check, listen error, or timeout
|
|
|
|
select {
|
|
|
|
case e := <-errCh:
|
|
|
|
return srv, e
|
2014-01-03 23:43:35 +00:00
|
|
|
case e := <-errChTCP:
|
|
|
|
return srv, e
|
2015-03-31 23:48:48 +00:00
|
|
|
case <-startCh:
|
|
|
|
return srv, nil
|
2014-01-02 21:12:05 +00:00
|
|
|
case <-time.After(time.Second):
|
|
|
|
return srv, fmt.Errorf("timeout setting up DNS server")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-23 01:31:11 +00:00
|
|
|
// recursorAddr is used to add a port to the recursor if omitted.
|
|
|
|
func recursorAddr(recursor string) (string, error) {
|
|
|
|
// Add the port if none
|
|
|
|
START:
|
|
|
|
_, _, err := net.SplitHostPort(recursor)
|
|
|
|
if ae, ok := err.(*net.AddrError); ok && ae.Err == "missing port in address" {
|
|
|
|
recursor = fmt.Sprintf("%s:%d", recursor, 53)
|
|
|
|
goto START
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the address
|
|
|
|
addr, err := net.ResolveTCPAddr("tcp", recursor)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return string
|
|
|
|
return addr.String(), nil
|
|
|
|
}
|
|
|
|
|
2014-11-23 08:16:37 +00:00
|
|
|
// handlePtr is used to handle "reverse" DNS queries
|
|
|
|
func (d *DNSServer) handlePtr(resp dns.ResponseWriter, req *dns.Msg) {
|
|
|
|
q := req.Question[0]
|
|
|
|
defer func(s time.Time) {
|
|
|
|
d.logger.Printf("[DEBUG] dns: request for %v (%v)", q, time.Now().Sub(s))
|
|
|
|
}(time.Now())
|
|
|
|
|
|
|
|
// Setup the message response
|
|
|
|
m := new(dns.Msg)
|
|
|
|
m.SetReply(req)
|
|
|
|
m.Authoritative = true
|
|
|
|
m.RecursionAvailable = (len(d.recursors) > 0)
|
|
|
|
|
|
|
|
// Only add the SOA if requested
|
|
|
|
if req.Question[0].Qtype == dns.TypeSOA {
|
|
|
|
d.addSOA(d.domain, m)
|
|
|
|
}
|
|
|
|
|
|
|
|
datacenter := d.agent.config.Datacenter
|
|
|
|
|
|
|
|
// Get the QName without the domain suffix
|
|
|
|
qName := strings.ToLower(dns.Fqdn(req.Question[0].Name))
|
|
|
|
|
|
|
|
args := structs.DCSpecificRequest{
|
|
|
|
Datacenter: datacenter,
|
|
|
|
QueryOptions: structs.QueryOptions{AllowStale: d.config.AllowStale},
|
|
|
|
}
|
|
|
|
var out structs.IndexedNodes
|
|
|
|
|
2014-11-24 19:09:04 +00:00
|
|
|
// TODO: Replace ListNodes with an internal RPC that can do the filter
|
2014-12-04 23:25:06 +00:00
|
|
|
// server side to avoid transferring the entire node list.
|
2014-11-23 08:16:37 +00:00
|
|
|
if err := d.agent.RPC("Catalog.ListNodes", &args, &out); err == nil {
|
|
|
|
for _, n := range out.Nodes {
|
|
|
|
arpa, _ := dns.ReverseAddr(n.Address)
|
|
|
|
if arpa == qName {
|
|
|
|
ptr := &dns.PTR{
|
|
|
|
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: 0},
|
2015-01-08 18:24:49 +00:00
|
|
|
Ptr: fmt.Sprintf("%s.node.%s.%s", n.Node, datacenter, d.domain),
|
2014-11-23 08:16:37 +00:00
|
|
|
}
|
|
|
|
m.Answer = append(m.Answer, ptr)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write out the complete response
|
|
|
|
if err := resp.WriteMsg(m); err != nil {
|
|
|
|
d.logger.Printf("[WARN] dns: failed to respond: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-03 01:58:58 +00:00
|
|
|
// handleQUery is used to handle DNS queries in the configured domain
|
|
|
|
func (d *DNSServer) handleQuery(resp dns.ResponseWriter, req *dns.Msg) {
|
|
|
|
q := req.Question[0]
|
|
|
|
defer func(s time.Time) {
|
|
|
|
d.logger.Printf("[DEBUG] dns: request for %v (%v)", q, time.Now().Sub(s))
|
|
|
|
}(time.Now())
|
|
|
|
|
2014-02-14 22:22:49 +00:00
|
|
|
// Switch to TCP if the client is
|
|
|
|
network := "udp"
|
|
|
|
if _, ok := resp.RemoteAddr().(*net.TCPAddr); ok {
|
|
|
|
network = "tcp"
|
|
|
|
}
|
|
|
|
|
2014-01-03 01:58:58 +00:00
|
|
|
// Setup the message response
|
|
|
|
m := new(dns.Msg)
|
|
|
|
m.SetReply(req)
|
|
|
|
m.Authoritative = true
|
2014-10-31 19:19:41 +00:00
|
|
|
m.RecursionAvailable = (len(d.recursors) > 0)
|
2014-02-25 20:46:11 +00:00
|
|
|
|
|
|
|
// Only add the SOA if requested
|
|
|
|
if req.Question[0].Qtype == dns.TypeSOA {
|
|
|
|
d.addSOA(d.domain, m)
|
|
|
|
}
|
2014-01-03 01:58:58 +00:00
|
|
|
|
|
|
|
// Dispatch the correct handler
|
2014-02-14 22:22:49 +00:00
|
|
|
d.dispatch(network, req, m)
|
2014-01-03 23:43:35 +00:00
|
|
|
|
|
|
|
// Write out the complete response
|
|
|
|
if err := resp.WriteMsg(m); err != nil {
|
|
|
|
d.logger.Printf("[WARN] dns: failed to respond: %v", err)
|
|
|
|
}
|
2014-01-03 01:58:58 +00:00
|
|
|
}
|
|
|
|
|
2014-01-02 23:10:13 +00:00
|
|
|
// addSOA is used to add an SOA record to a message for the given domain
|
|
|
|
func (d *DNSServer) addSOA(domain string, msg *dns.Msg) {
|
|
|
|
soa := &dns.SOA{
|
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: domain,
|
|
|
|
Rrtype: dns.TypeSOA,
|
|
|
|
Class: dns.ClassINET,
|
|
|
|
Ttl: 0,
|
|
|
|
},
|
|
|
|
Ns: "ns." + domain,
|
|
|
|
Mbox: "postmaster." + domain,
|
|
|
|
Serial: uint32(time.Now().Unix()),
|
|
|
|
Refresh: 3600,
|
|
|
|
Retry: 600,
|
|
|
|
Expire: 86400,
|
|
|
|
Minttl: 0,
|
|
|
|
}
|
|
|
|
msg.Ns = append(msg.Ns, soa)
|
|
|
|
}
|
2014-01-03 01:58:58 +00:00
|
|
|
|
|
|
|
// dispatch is used to parse a request and invoke the correct handler
|
2014-02-14 22:22:49 +00:00
|
|
|
func (d *DNSServer) dispatch(network string, req, resp *dns.Msg) {
|
2014-01-03 01:58:58 +00:00
|
|
|
// By default the query is in the default datacenter
|
|
|
|
datacenter := d.agent.config.Datacenter
|
|
|
|
|
|
|
|
// Get the QName without the domain suffix
|
2014-07-23 08:28:54 +00:00
|
|
|
qName := strings.ToLower(dns.Fqdn(req.Question[0].Name))
|
2014-01-03 01:58:58 +00:00
|
|
|
qName = strings.TrimSuffix(qName, d.domain)
|
|
|
|
|
|
|
|
// Split into the label parts
|
|
|
|
labels := dns.SplitDomainName(qName)
|
|
|
|
|
|
|
|
// The last label is either "node", "service" or a datacenter name
|
|
|
|
PARSE:
|
2014-04-21 22:33:01 +00:00
|
|
|
n := len(labels)
|
|
|
|
if n == 0 {
|
2014-01-03 01:58:58 +00:00
|
|
|
goto INVALID
|
|
|
|
}
|
2014-04-21 22:33:01 +00:00
|
|
|
switch labels[n-1] {
|
2014-01-03 01:58:58 +00:00
|
|
|
case "service":
|
2014-04-21 22:33:01 +00:00
|
|
|
if n == 1 {
|
2014-01-03 01:58:58 +00:00
|
|
|
goto INVALID
|
|
|
|
}
|
|
|
|
|
2014-08-18 19:45:56 +00:00
|
|
|
// Support RFC 2782 style syntax
|
|
|
|
if n == 3 && strings.HasPrefix(labels[n-2], "_") && strings.HasPrefix(labels[n-3], "_") {
|
2014-04-21 22:33:01 +00:00
|
|
|
|
2014-08-18 19:45:56 +00:00
|
|
|
// Grab the tag since we make nuke it if it's tcp
|
|
|
|
tag := labels[n-2][1:]
|
|
|
|
|
|
|
|
// Treat _name._tcp.service.consul as a default, no need to filter on that tag
|
|
|
|
if tag == "tcp" {
|
|
|
|
tag = ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// _name._tag.service.consul
|
|
|
|
d.serviceLookup(network, datacenter, labels[n-3][1:], tag, req, resp)
|
2014-04-21 22:33:01 +00:00
|
|
|
|
2014-08-20 23:27:12 +00:00
|
|
|
// Consul 0.3 and prior format for SRV queries
|
2014-08-18 19:45:56 +00:00
|
|
|
} else {
|
|
|
|
|
|
|
|
// Support "." in the label, re-join all the parts
|
|
|
|
tag := ""
|
|
|
|
if n >= 3 {
|
|
|
|
tag = strings.Join(labels[:n-2], ".")
|
|
|
|
}
|
|
|
|
|
|
|
|
// tag[.tag].name.service.consul
|
|
|
|
d.serviceLookup(network, datacenter, labels[n-2], tag, req, resp)
|
|
|
|
}
|
2014-04-21 22:33:01 +00:00
|
|
|
|
2014-01-03 01:58:58 +00:00
|
|
|
case "node":
|
2014-04-21 22:33:01 +00:00
|
|
|
if len(labels) == 1 {
|
2014-01-03 01:58:58 +00:00
|
|
|
goto INVALID
|
|
|
|
}
|
2014-04-21 22:33:01 +00:00
|
|
|
// Allow a "." in the node name, just join all the parts
|
|
|
|
node := strings.Join(labels[:n-1], ".")
|
|
|
|
d.nodeLookup(network, datacenter, node, req, resp)
|
2014-01-03 01:58:58 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
// Store the DC, and re-parse
|
2014-04-21 22:33:01 +00:00
|
|
|
datacenter = labels[n-1]
|
|
|
|
labels = labels[:n-1]
|
2014-01-03 01:58:58 +00:00
|
|
|
goto PARSE
|
|
|
|
}
|
|
|
|
return
|
|
|
|
INVALID:
|
|
|
|
d.logger.Printf("[WARN] dns: QName invalid: %s", qName)
|
|
|
|
resp.SetRcode(req, dns.RcodeNameError)
|
|
|
|
}
|
|
|
|
|
|
|
|
// nodeLookup is used to handle a node query
|
2014-02-14 22:22:49 +00:00
|
|
|
func (d *DNSServer) nodeLookup(network, datacenter, node string, req, resp *dns.Msg) {
|
2014-01-03 01:58:58 +00:00
|
|
|
// Only handle ANY and A type requests
|
|
|
|
qType := req.Question[0].Qtype
|
|
|
|
if qType != dns.TypeANY && qType != dns.TypeA {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make an RPC request
|
2014-01-08 23:13:27 +00:00
|
|
|
args := structs.NodeSpecificRequest{
|
2014-06-08 22:49:24 +00:00
|
|
|
Datacenter: datacenter,
|
|
|
|
Node: node,
|
|
|
|
QueryOptions: structs.QueryOptions{AllowStale: d.config.AllowStale},
|
2014-01-03 01:58:58 +00:00
|
|
|
}
|
2014-02-05 22:36:13 +00:00
|
|
|
var out structs.IndexedNodeServices
|
2014-06-08 22:49:24 +00:00
|
|
|
RPC:
|
2014-01-03 01:58:58 +00:00
|
|
|
if err := d.agent.RPC("Catalog.NodeServices", &args, &out); err != nil {
|
|
|
|
d.logger.Printf("[ERR] dns: rpc error: %v", err)
|
|
|
|
resp.SetRcode(req, dns.RcodeServerFailure)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-06-08 22:49:24 +00:00
|
|
|
// Verify that request is not too stale, redo the request
|
|
|
|
if args.AllowStale && out.LastContact > d.config.MaxStale {
|
|
|
|
args.AllowStale = false
|
|
|
|
d.logger.Printf("[WARN] dns: Query results too stale, re-requesting")
|
|
|
|
goto RPC
|
|
|
|
}
|
|
|
|
|
2014-01-03 01:58:58 +00:00
|
|
|
// If we have no address, return not found!
|
2014-03-05 23:03:23 +00:00
|
|
|
if out.NodeServices == nil {
|
2014-01-03 01:58:58 +00:00
|
|
|
resp.SetRcode(req, dns.RcodeNameError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-02-25 20:07:20 +00:00
|
|
|
// Add the node record
|
2015-01-02 21:10:05 +00:00
|
|
|
records := d.formatNodeRecord(&out.NodeServices.Node, out.NodeServices.Node.Address,
|
|
|
|
req.Question[0].Name, qType, d.config.NodeTTL)
|
2014-02-26 01:41:48 +00:00
|
|
|
if records != nil {
|
|
|
|
resp.Answer = append(resp.Answer, records...)
|
2014-01-03 01:58:58 +00:00
|
|
|
}
|
2014-02-25 20:07:20 +00:00
|
|
|
}
|
2014-01-03 01:58:58 +00:00
|
|
|
|
2014-02-25 20:07:20 +00:00
|
|
|
// formatNodeRecord takes a Node and returns an A, AAAA, or CNAME record
|
2015-01-02 21:10:05 +00:00
|
|
|
func (d *DNSServer) formatNodeRecord(node *structs.Node, addr, qName string, qType uint16, ttl time.Duration) (records []dns.RR) {
|
2014-02-25 20:07:20 +00:00
|
|
|
// Parse the IP
|
2015-01-02 21:10:05 +00:00
|
|
|
ip := net.ParseIP(addr)
|
2014-02-25 20:07:20 +00:00
|
|
|
var ipv4 net.IP
|
|
|
|
if ip != nil {
|
|
|
|
ipv4 = ip.To4()
|
|
|
|
}
|
|
|
|
switch {
|
|
|
|
case ipv4 != nil && (qType == dns.TypeANY || qType == dns.TypeA):
|
2014-02-26 01:41:48 +00:00
|
|
|
return []dns.RR{&dns.A{
|
2014-02-25 20:07:20 +00:00
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: qName,
|
|
|
|
Rrtype: dns.TypeA,
|
|
|
|
Class: dns.ClassINET,
|
2014-06-08 23:01:06 +00:00
|
|
|
Ttl: uint32(ttl / time.Second),
|
2014-02-25 20:07:20 +00:00
|
|
|
},
|
|
|
|
A: ip,
|
2014-02-26 01:41:48 +00:00
|
|
|
}}
|
2014-02-25 20:07:20 +00:00
|
|
|
|
|
|
|
case ip != nil && ipv4 == nil && (qType == dns.TypeANY || qType == dns.TypeAAAA):
|
2014-02-26 01:41:48 +00:00
|
|
|
return []dns.RR{&dns.AAAA{
|
2014-02-25 20:07:20 +00:00
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: qName,
|
|
|
|
Rrtype: dns.TypeAAAA,
|
|
|
|
Class: dns.ClassINET,
|
2014-06-08 23:01:06 +00:00
|
|
|
Ttl: uint32(ttl / time.Second),
|
2014-02-25 20:07:20 +00:00
|
|
|
},
|
|
|
|
AAAA: ip,
|
2014-02-26 01:41:48 +00:00
|
|
|
}}
|
2014-01-03 01:58:58 +00:00
|
|
|
|
2014-02-26 01:41:48 +00:00
|
|
|
case ip == nil && (qType == dns.TypeANY || qType == dns.TypeCNAME ||
|
|
|
|
qType == dns.TypeA || qType == dns.TypeAAAA):
|
|
|
|
// Get the CNAME
|
|
|
|
cnRec := &dns.CNAME{
|
2014-02-25 20:07:20 +00:00
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: qName,
|
|
|
|
Rrtype: dns.TypeCNAME,
|
|
|
|
Class: dns.ClassINET,
|
2014-06-08 23:01:06 +00:00
|
|
|
Ttl: uint32(ttl / time.Second),
|
2014-02-25 20:07:20 +00:00
|
|
|
},
|
2015-01-02 21:10:05 +00:00
|
|
|
Target: dns.Fqdn(addr),
|
2014-02-25 20:07:20 +00:00
|
|
|
}
|
2014-02-26 01:41:48 +00:00
|
|
|
records = append(records, cnRec)
|
|
|
|
|
|
|
|
// Recurse
|
|
|
|
more := d.resolveCNAME(cnRec.Target)
|
|
|
|
extra := 0
|
|
|
|
MORE_REC:
|
|
|
|
for _, rr := range more {
|
|
|
|
switch rr.Header().Rrtype {
|
|
|
|
case dns.TypeA:
|
|
|
|
fallthrough
|
|
|
|
case dns.TypeAAAA:
|
|
|
|
records = append(records, rr)
|
|
|
|
extra++
|
|
|
|
if extra == maxRecurseRecords {
|
|
|
|
break MORE_REC
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-02-25 20:07:20 +00:00
|
|
|
}
|
2014-02-26 01:41:48 +00:00
|
|
|
return records
|
2014-01-03 01:58:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// serviceLookup is used to handle a service query
|
2014-02-14 22:22:49 +00:00
|
|
|
func (d *DNSServer) serviceLookup(network, datacenter, service, tag string, req, resp *dns.Msg) {
|
2014-01-03 21:00:03 +00:00
|
|
|
// Make an RPC request
|
2014-01-08 23:13:27 +00:00
|
|
|
args := structs.ServiceSpecificRequest{
|
2014-06-08 22:49:24 +00:00
|
|
|
Datacenter: datacenter,
|
|
|
|
ServiceName: service,
|
|
|
|
ServiceTag: tag,
|
|
|
|
TagFilter: tag != "",
|
|
|
|
QueryOptions: structs.QueryOptions{AllowStale: d.config.AllowStale},
|
2014-01-03 21:00:03 +00:00
|
|
|
}
|
2014-02-05 22:36:13 +00:00
|
|
|
var out structs.IndexedCheckServiceNodes
|
2014-06-08 22:49:24 +00:00
|
|
|
RPC:
|
2014-01-15 21:20:01 +00:00
|
|
|
if err := d.agent.RPC("Health.ServiceNodes", &args, &out); err != nil {
|
2014-01-03 21:00:03 +00:00
|
|
|
d.logger.Printf("[ERR] dns: rpc error: %v", err)
|
|
|
|
resp.SetRcode(req, dns.RcodeServerFailure)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-06-08 22:49:24 +00:00
|
|
|
// Verify that request is not too stale, redo the request
|
|
|
|
if args.AllowStale && out.LastContact > d.config.MaxStale {
|
|
|
|
args.AllowStale = false
|
|
|
|
d.logger.Printf("[WARN] dns: Query results too stale, re-requesting")
|
|
|
|
goto RPC
|
|
|
|
}
|
|
|
|
|
2014-01-03 21:00:03 +00:00
|
|
|
// If we have no nodes, return not found!
|
2014-02-05 22:36:13 +00:00
|
|
|
if len(out.Nodes) == 0 {
|
2014-01-03 21:00:03 +00:00
|
|
|
resp.SetRcode(req, dns.RcodeNameError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-06-08 23:01:06 +00:00
|
|
|
// Determine the TTL
|
|
|
|
var ttl time.Duration
|
|
|
|
if d.config.ServiceTTL != nil {
|
|
|
|
var ok bool
|
|
|
|
ttl, ok = d.config.ServiceTTL[service]
|
|
|
|
if !ok {
|
|
|
|
ttl = d.config.ServiceTTL["*"]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-15 21:30:04 +00:00
|
|
|
// Filter out any service nodes due to health checks
|
2014-02-05 22:36:13 +00:00
|
|
|
out.Nodes = d.filterServiceNodes(out.Nodes)
|
2014-01-15 21:30:04 +00:00
|
|
|
|
2014-02-14 20:26:51 +00:00
|
|
|
// Perform a random shuffle
|
|
|
|
shuffleServiceNodes(out.Nodes)
|
|
|
|
|
2014-02-14 22:22:49 +00:00
|
|
|
// If the network is not TCP, restrict the number of responses
|
|
|
|
if network != "tcp" && len(out.Nodes) > maxServiceResponses {
|
2014-02-14 20:26:51 +00:00
|
|
|
out.Nodes = out.Nodes[:maxServiceResponses]
|
2014-09-30 19:15:36 +00:00
|
|
|
// Flag that there are more records to return in the UDP response
|
|
|
|
if d.config.EnableTruncate == true {
|
|
|
|
resp.Truncated = true
|
|
|
|
}
|
2014-02-14 20:26:51 +00:00
|
|
|
}
|
|
|
|
|
2014-01-03 21:00:03 +00:00
|
|
|
// Add various responses depending on the request
|
|
|
|
qType := req.Question[0].Qtype
|
2014-06-08 23:01:06 +00:00
|
|
|
d.serviceNodeRecords(out.Nodes, req, resp, ttl)
|
2014-02-25 20:07:20 +00:00
|
|
|
|
2014-02-26 01:41:48 +00:00
|
|
|
if qType == dns.TypeSRV {
|
2014-06-08 23:01:06 +00:00
|
|
|
d.serviceSRVRecords(datacenter, out.Nodes, req, resp, ttl)
|
2014-01-03 21:00:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-15 21:30:04 +00:00
|
|
|
// filterServiceNodes is used to filter out nodes that are failing
|
|
|
|
// health checks to prevent routing to unhealthy nodes
|
|
|
|
func (d *DNSServer) filterServiceNodes(nodes structs.CheckServiceNodes) structs.CheckServiceNodes {
|
|
|
|
n := len(nodes)
|
2014-07-16 22:11:45 +00:00
|
|
|
OUTER:
|
2014-01-15 21:30:04 +00:00
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
node := nodes[i]
|
|
|
|
for _, check := range node.Checks {
|
2015-01-10 12:11:32 +00:00
|
|
|
if check.Status == structs.HealthCritical ||
|
|
|
|
(d.config.OnlyPassing && check.Status != structs.HealthPassing) {
|
2014-01-15 21:30:04 +00:00
|
|
|
d.logger.Printf("[WARN] dns: node '%s' failing health check '%s: %s', dropping from service '%s'",
|
|
|
|
node.Node.Node, check.CheckID, check.Name, node.Service.Service)
|
|
|
|
nodes[i], nodes[n-1] = nodes[n-1], structs.CheckServiceNode{}
|
|
|
|
n--
|
2014-02-24 02:04:12 +00:00
|
|
|
i--
|
2014-07-16 22:11:45 +00:00
|
|
|
continue OUTER
|
2014-01-15 21:30:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nodes[:n]
|
|
|
|
}
|
|
|
|
|
2014-02-14 20:26:51 +00:00
|
|
|
// shuffleServiceNodes does an in-place random shuffle using the Fisher-Yates algorithm
|
|
|
|
func shuffleServiceNodes(nodes structs.CheckServiceNodes) {
|
|
|
|
for i := len(nodes) - 1; i > 0; i-- {
|
|
|
|
j := rand.Int31() % int32(i+1)
|
|
|
|
nodes[i], nodes[j] = nodes[j], nodes[i]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-25 20:07:20 +00:00
|
|
|
// serviceNodeRecords is used to add the node records for a service lookup
|
2014-06-08 23:01:06 +00:00
|
|
|
func (d *DNSServer) serviceNodeRecords(nodes structs.CheckServiceNodes, req, resp *dns.Msg, ttl time.Duration) {
|
2014-02-25 20:07:20 +00:00
|
|
|
qName := req.Question[0].Name
|
|
|
|
qType := req.Question[0].Qtype
|
2014-01-06 22:56:41 +00:00
|
|
|
handled := make(map[string]struct{})
|
2014-01-03 21:00:03 +00:00
|
|
|
for _, node := range nodes {
|
2014-01-06 22:56:41 +00:00
|
|
|
// Avoid duplicate entries, possible if a node has
|
|
|
|
// the same service on multiple ports, etc.
|
2014-01-15 21:20:01 +00:00
|
|
|
addr := node.Node.Address
|
2015-01-02 21:10:05 +00:00
|
|
|
if node.Service.Address != "" {
|
|
|
|
addr = node.Service.Address
|
|
|
|
}
|
|
|
|
|
2014-01-15 21:20:01 +00:00
|
|
|
if _, ok := handled[addr]; ok {
|
2014-01-06 22:56:41 +00:00
|
|
|
continue
|
|
|
|
}
|
2014-01-15 21:20:01 +00:00
|
|
|
handled[addr] = struct{}{}
|
2014-01-06 22:56:41 +00:00
|
|
|
|
2014-02-25 20:07:20 +00:00
|
|
|
// Add the node record
|
2015-01-02 21:10:05 +00:00
|
|
|
records := d.formatNodeRecord(&node.Node, addr, qName, qType, ttl)
|
2014-02-26 01:41:48 +00:00
|
|
|
if records != nil {
|
|
|
|
resp.Answer = append(resp.Answer, records...)
|
2014-01-03 21:00:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// serviceARecords is used to add the SRV records for a service lookup
|
2014-06-08 23:01:06 +00:00
|
|
|
func (d *DNSServer) serviceSRVRecords(dc string, nodes structs.CheckServiceNodes, req, resp *dns.Msg, ttl time.Duration) {
|
2014-01-06 22:56:41 +00:00
|
|
|
handled := make(map[string]struct{})
|
2014-01-03 21:00:03 +00:00
|
|
|
for _, node := range nodes {
|
2014-01-06 22:56:41 +00:00
|
|
|
// Avoid duplicate entries, possible if a node has
|
|
|
|
// the same service the same port, etc.
|
2015-01-08 18:47:41 +00:00
|
|
|
tuple := fmt.Sprintf("%s:%s:%d", node.Node.Node, node.Service.Address, node.Service.Port)
|
2014-01-06 22:56:41 +00:00
|
|
|
if _, ok := handled[tuple]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
handled[tuple] = struct{}{}
|
|
|
|
|
|
|
|
// Add the SRV record
|
2014-01-03 21:00:03 +00:00
|
|
|
srvRec := &dns.SRV{
|
|
|
|
Hdr: dns.RR_Header{
|
|
|
|
Name: req.Question[0].Name,
|
|
|
|
Rrtype: dns.TypeSRV,
|
|
|
|
Class: dns.ClassINET,
|
2014-06-08 23:01:06 +00:00
|
|
|
Ttl: uint32(ttl / time.Second),
|
2014-01-03 21:00:03 +00:00
|
|
|
},
|
|
|
|
Priority: 1,
|
|
|
|
Weight: 1,
|
2014-01-15 21:20:01 +00:00
|
|
|
Port: uint16(node.Service.Port),
|
|
|
|
Target: fmt.Sprintf("%s.node.%s.%s", node.Node.Node, dc, d.domain),
|
2014-01-03 21:00:03 +00:00
|
|
|
}
|
|
|
|
resp.Answer = append(resp.Answer, srvRec)
|
|
|
|
|
2015-01-05 22:48:30 +00:00
|
|
|
// Determine advertised address
|
|
|
|
addr := node.Node.Address
|
|
|
|
if node.Service.Address != "" {
|
|
|
|
addr = node.Service.Address
|
|
|
|
}
|
|
|
|
|
2014-02-25 20:07:20 +00:00
|
|
|
// Add the extra record
|
2015-01-05 22:48:30 +00:00
|
|
|
records := d.formatNodeRecord(&node.Node, addr, srvRec.Target, dns.TypeANY, ttl)
|
2014-02-26 01:41:48 +00:00
|
|
|
if records != nil {
|
|
|
|
resp.Extra = append(resp.Extra, records...)
|
2014-01-03 21:00:03 +00:00
|
|
|
}
|
|
|
|
}
|
2014-01-03 01:58:58 +00:00
|
|
|
}
|
2014-01-03 23:43:35 +00:00
|
|
|
|
|
|
|
// handleRecurse is used to handle recursive DNS queries
|
|
|
|
func (d *DNSServer) handleRecurse(resp dns.ResponseWriter, req *dns.Msg) {
|
|
|
|
q := req.Question[0]
|
|
|
|
network := "udp"
|
|
|
|
defer func(s time.Time) {
|
|
|
|
d.logger.Printf("[DEBUG] dns: request for %v (%s) (%v)", q, network, time.Now().Sub(s))
|
|
|
|
}(time.Now())
|
|
|
|
|
|
|
|
// Switch to TCP if the client is
|
|
|
|
if _, ok := resp.RemoteAddr().(*net.TCPAddr); ok {
|
|
|
|
network = "tcp"
|
|
|
|
}
|
|
|
|
|
|
|
|
// Recursively resolve
|
|
|
|
c := &dns.Client{Net: network}
|
2014-11-03 19:40:55 +00:00
|
|
|
var r *dns.Msg
|
|
|
|
var rtt time.Duration
|
|
|
|
var err error
|
|
|
|
for _, recursor := range d.recursors {
|
|
|
|
r, rtt, err = c.Exchange(req, recursor)
|
|
|
|
if err == nil {
|
|
|
|
// Forward the response
|
|
|
|
d.logger.Printf("[DEBUG] dns: recurse RTT for %v (%v)", q, rtt)
|
|
|
|
if err := resp.WriteMsg(r); err != nil {
|
|
|
|
d.logger.Printf("[WARN] dns: failed to respond: %v", err)
|
|
|
|
}
|
2014-10-31 19:19:41 +00:00
|
|
|
return
|
|
|
|
}
|
2014-11-03 19:40:55 +00:00
|
|
|
d.logger.Printf("[ERR] dns: recurse failed: %v", err)
|
2014-01-03 23:43:35 +00:00
|
|
|
}
|
2014-11-03 19:40:55 +00:00
|
|
|
|
|
|
|
// If all resolvers fail, return a SERVFAIL message
|
|
|
|
d.logger.Printf("[ERR] dns: all resolvers failed for %v", q)
|
|
|
|
m := &dns.Msg{}
|
|
|
|
m.SetReply(req)
|
|
|
|
m.RecursionAvailable = true
|
|
|
|
m.SetRcode(req, dns.RcodeServerFailure)
|
|
|
|
resp.WriteMsg(m)
|
2014-01-03 23:43:35 +00:00
|
|
|
}
|
2014-02-25 20:46:11 +00:00
|
|
|
|
|
|
|
// resolveCNAME is used to recursively resolve CNAME records
|
|
|
|
func (d *DNSServer) resolveCNAME(name string) []dns.RR {
|
|
|
|
// Do nothing if we don't have a recursor
|
2014-11-03 19:40:55 +00:00
|
|
|
if len(d.recursors) == 0 {
|
2014-02-25 20:46:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ask for any A records
|
|
|
|
m := new(dns.Msg)
|
|
|
|
m.SetQuestion(name, dns.TypeA)
|
|
|
|
|
|
|
|
// Make a DNS lookup request
|
|
|
|
c := &dns.Client{Net: "udp"}
|
2014-11-03 19:40:55 +00:00
|
|
|
var r *dns.Msg
|
|
|
|
var rtt time.Duration
|
|
|
|
var err error
|
|
|
|
for _, recursor := range d.recursors {
|
|
|
|
r, rtt, err = c.Exchange(m, recursor)
|
|
|
|
if err == nil {
|
|
|
|
d.logger.Printf("[DEBUG] dns: cname recurse RTT for %v (%v)", name, rtt)
|
|
|
|
return r.Answer
|
2014-10-31 19:19:41 +00:00
|
|
|
}
|
2014-11-03 19:40:55 +00:00
|
|
|
d.logger.Printf("[ERR] dns: cname recurse failed for %v: %v", name, err)
|
2014-02-25 20:46:11 +00:00
|
|
|
}
|
2014-11-03 19:40:55 +00:00
|
|
|
d.logger.Printf("[ERR] dns: all resolvers failed for %v", name)
|
2014-10-31 19:19:41 +00:00
|
|
|
return nil
|
2014-02-25 20:46:11 +00:00
|
|
|
}
|