forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dig_dns_resolver.go
75 lines (60 loc) · 1.45 KB
/
dig_dns_resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package infrastructure
import (
"errors"
"fmt"
"net"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
const digDNSResolverLogTag = "Dig DNS Resolver"
type DigDNSResolver struct {
runner boshsys.CmdRunner
logger boshlog.Logger
}
func NewDigDNSResolver(runner boshsys.CmdRunner, logger boshlog.Logger) DigDNSResolver {
return DigDNSResolver{
runner: runner,
logger: logger,
}
}
func (res DigDNSResolver) LookupHost(dnsServers []string, host string) (string, error) {
if host == "localhost" {
return "127.0.0.1", nil
}
ip := net.ParseIP(host)
if ip != nil {
return host, nil
}
var err error
var ipString string
if len(dnsServers) == 0 {
err = errors.New("No DNS servers provided")
}
for _, dnsServer := range dnsServers {
ipString, err = res.lookupHostWithDNSServer(dnsServer, host)
if err == nil {
return ipString, nil
}
}
return "", err
}
func (res DigDNSResolver) lookupHostWithDNSServer(dnsServer string, host string) (ipString string, err error) {
stdout, _, _, err := res.runner.RunCommand(
"dig",
fmt.Sprintf("@%s", dnsServer),
host,
"+short",
"+time=1",
)
if err != nil {
return "", bosherr.WrapError(err, "Shelling out to dig")
}
ipString = strings.Split(stdout, "\n")[0]
ip := net.ParseIP(ipString)
if ip == nil {
return "", errors.New("Resolving host")
}
return ipString, nil
}