Skip to content

Commit 116ca0d

Browse files
author
wafuwafu13
committed
check Rcode
1 parent a5f3efa commit 116ca0d

File tree

2 files changed

+68
-4
lines changed

2 files changed

+68
-4
lines changed

check-dns/lib/check_dns.go

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,65 @@ package checkdns
33
import (
44
"fmt"
55
"net"
6+
"os"
67
"strconv"
8+
9+
"github.com/jessevdk/go-flags"
10+
"github.com/mackerelio/checkers"
11+
"github.com/miekg/dns"
712
)
813

14+
type dnsOpts struct {
15+
Host string `short:"H" long:"host" required:"true" description:"The name or address you want to query"`
16+
Server string `short:"s" long:"server" description:"DNS server you want to use for the lookup"`
17+
Port int `short:"p" long:"port" default:"53" description:"Port number you want to use"`
18+
}
19+
20+
// Do the plugin
921
func Do() {
10-
nameserver, err := adapterAddress()
22+
Run(os.Args[1:])
23+
}
24+
25+
func parseArgs(args []string) (*dnsOpts, error) {
26+
opts := &dnsOpts{}
27+
_, err := flags.ParseArgs(opts, args)
28+
return opts, err
29+
}
30+
31+
func Run(args []string) *checkers.Checker {
32+
opts, err := parseArgs(args)
33+
if err != nil {
34+
os.Exit(1)
35+
}
36+
var nameserver string
37+
if opts.Server != "" {
38+
nameserver = opts.Server
39+
} else {
40+
nameserver, err = adapterAddress()
41+
if err != nil {
42+
return checkers.Critical(err.Error())
43+
}
44+
}
45+
nameserver = net.JoinHostPort(nameserver, strconv.Itoa(opts.Port))
46+
47+
c := new(dns.Client)
48+
m := &dns.Msg{
49+
MsgHdr: dns.MsgHdr{
50+
Opcode: dns.OpcodeQuery,
51+
},
52+
Question: []dns.Question{{Name: dns.Fqdn(opts.Host), Qtype: dns.TypeA, Qclass: uint16(dns.ClassINET)}},
53+
}
54+
55+
r, _, err := c.Exchange(m, nameserver)
1156
if err != nil {
12-
fmt.Println(err)
57+
return checkers.Critical(err.Error())
58+
}
59+
60+
checkSt := checkers.OK
61+
if r.MsgHdr.Rcode != dns.RcodeSuccess {
62+
checkSt = checkers.CRITICAL
1363
}
14-
nameserver = net.JoinHostPort(nameserver, strconv.Itoa(53))
15-
fmt.Println(nameserver)
64+
msg := fmt.Sprintf("%s", r)
65+
66+
return checkers.NewChecker(checkSt, msg)
1667
}

check-dns/lib/check_dns_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ package checkdns
22

33
import (
44
"net"
5+
"strings"
56
"testing"
7+
8+
"github.com/mackerelio/checkers"
9+
"github.com/stretchr/testify/assert"
610
)
711

812
func TestNameServer(t *testing.T) {
@@ -16,3 +20,12 @@ func TestNameServer(t *testing.T) {
1620
t.Errorf("nameserver is invalid IP")
1721
}
1822
}
23+
24+
func TestDnsStatus(t *testing.T) {
25+
ckr := Run([]string{"-H", "example.com", "-s", "8.8.8.8"})
26+
assert.Equal(t, checkers.OK, ckr.Status, "should be OK")
27+
t.Logf(ckr.Message)
28+
if !strings.Contains(ckr.Message, "status: NOERROR") {
29+
t.Errorf("status is not NOERROR")
30+
}
31+
}

0 commit comments

Comments
 (0)