forked from vitessio/vitess
/
pdns.go
362 lines (325 loc) · 9.59 KB
/
pdns.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package main
// To be used with PowerDNS (pdns) as a "pipe backend" CoProcess.
//
// Protocol description:
// http://downloads.powerdns.com/documentation/html/backends-detail.html#PIPEBACKEND.
//
// Mainly the resolver has to interpret zkns addresses in a way that
// is helpful for DNS. This involves approximating CNAME/A records
// when appropriate.
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"path"
"strings"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/exit"
"github.com/youtube/vitess/go/netutil"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/zk"
"github.com/youtube/vitess/go/zk/zkns"
)
var (
GREETING_ABI_V2 = []byte("HELO\t2")
GREETING_REPLY = "OK\tzkns2pdns\n"
END_REPLY = "END\n"
FAIL_REPLY = "FAIL\n"
)
var (
errLongLine = errors.New("pdns line too long")
errBadLine = errors.New("pdns line unparseable")
)
const (
KIND_AXFR = "AXFR" // ignored for now
KIND_Q = "Q"
KIND_PING = "PING"
)
const (
defaultTTL = "1"
defaultId = "1"
defaultPriority = 0
defaultWeight = 0
)
type zknsResolver struct {
zconn zk.Conn
fqdn string // The fqdn of this machine.
zknsDomain string // The chunk of naming hierarchy to serve.
zkRoot string // The root path from which to resolve.
}
func newZknsResolver(zconn zk.Conn, fqdn, zknsDomain, zkRoot string) *zknsResolver {
if fqdn[len(fqdn)-1] == '.' {
fqdn = fqdn[:len(fqdn)-1]
}
if zknsDomain[len(zknsDomain)-1] == '.' {
zknsDomain = zknsDomain[:len(zknsDomain)-1]
}
if zknsDomain[0] != '.' {
zknsDomain = "." + zknsDomain
}
return &zknsResolver{zconn, fqdn, zknsDomain, zkRoot}
}
func (rz *zknsResolver) getResult(qtype, qname string) ([]*pdnsReply, error) {
if !strings.HasSuffix(qname, rz.zknsDomain) {
return nil, fmt.Errorf("invalid domain for query: %v", qname)
}
switch qtype {
case "SOA":
// primary hostmaster serial refresh retry expire default_ttl
content := fmt.Sprintf("%v hostmaster@%v 0 1800 600 3600 300", rz.fqdn, rz.fqdn)
return []*pdnsReply{&pdnsReply{qname, "IN", qtype, defaultTTL, defaultId, content}}, nil
case "SRV":
return rz.getSRV(qname)
case "CNAME":
return rz.getCNAME(qname)
case "A":
return rz.getA(qname)
}
return nil, nil
}
// Reverse a slice in place. Return the same slice for convenience.
func reverse(p []string) []string {
i := 0
j := len(p) - 1
for i < j {
p[i], p[j] = p[j], p[i]
i++
j = len(p) - i - 1
}
return p
}
func (rz *zknsResolver) getSRV(qname string) ([]*pdnsReply, error) {
if !strings.HasSuffix(qname, rz.zknsDomain) {
return nil, fmt.Errorf("invalid domain for query: %v", qname)
}
zkname := qname[:len(qname)-len(rz.zknsDomain)]
nameParts := strings.Split(zkname, ".")
portName := nameParts[0]
if portName[0] != '_' {
// Since PDNS probes for all types, this isn't really an error worth mentioning.
// fmt.Errorf("invalid port name for query: %v", portName)
log.V(6).Infof("skipping SRV query: %v", qname)
return nil, nil
}
nameParts = reverse(nameParts[1:])
zkPath := path.Join(rz.zkRoot, path.Join(nameParts...))
addrs, err := zkns.ReadAddrs(rz.zconn, zkPath)
if err != nil {
return nil, err
}
replies := make([]*pdnsReply, 0, 16)
for _, addr := range addrs.Entries {
content := fmt.Sprintf("%v\t%v %v %v", defaultPriority, defaultWeight, addr.PortMap[portName], addr.Host)
replies = append(replies, &pdnsReply{qname, "IN", "SRV", defaultTTL, defaultId, content})
}
return replies, nil
}
// An CNAME record is generated when there is only one ZknsAddr, it
// has no port component.
func (rz *zknsResolver) getCNAME(qname string) ([]*pdnsReply, error) {
if !strings.HasSuffix(qname, rz.zknsDomain) {
return nil, fmt.Errorf("invalid domain for query: %v", qname)
}
if qname[0] == '_' {
// Since PDNS probes for all types, use some heuristics to limit error noise.
log.V(6).Infof("skipping CNAME query: %v", qname)
return nil, nil
}
zkname := qname[:len(qname)-len(rz.zknsDomain)]
nameParts := reverse(strings.Split(zkname, "."))
zkPath := path.Join(rz.zkRoot, path.Join(nameParts...))
addrs, err := zkns.ReadAddrs(rz.zconn, zkPath)
if err != nil {
return nil, err
}
if len(addrs.Entries) != 1 {
// Since PDNS probes for all types, this isn't really an error worth mentioning.
// return nil, fmt.Errorf("invalid response for CNAME query: %v", qname)
return nil, nil
}
return []*pdnsReply{&pdnsReply{qname, "IN", "CNAME", defaultTTL, defaultId, addrs.Entries[0].Host}}, nil
}
// An A record is generated when there is only one ZknsAddr, it
// has no port component and provides an IPv4 address.
func (rz *zknsResolver) getA(qname string) ([]*pdnsReply, error) {
if !strings.HasSuffix(qname, rz.zknsDomain) {
return nil, fmt.Errorf("invalid domain for query: %v", qname)
}
if qname[0] == '_' {
// Since PDNS probes for all types, use some heuristics to limit error noise.
log.V(6).Infof("skipping A query: %v", qname)
return nil, nil
}
zkname := qname[:len(qname)-len(rz.zknsDomain)]
nameParts := reverse(strings.Split(zkname, "."))
zkPath := path.Join(rz.zkRoot, path.Join(nameParts...))
addrs, err := zkns.ReadAddrs(rz.zconn, zkPath)
if err != nil {
return nil, err
}
if len(addrs.Entries) != 1 || addrs.Entries[0].IPv4 == "" {
// Since PDNS probes for all types, this isn't really an error worth mentioning.
// return nil, fmt.Errorf("invalid response for CNAME query: %v", qname)
return nil, nil
}
return []*pdnsReply{&pdnsReply{qname, "IN", "A", defaultTTL, defaultId, addrs.Entries[0].IPv4}}, nil
}
type pdns struct {
zr *zknsResolver
}
type pdnsReq struct {
kind string
qname string
qclass string // always "IN"
qtype string // almost always "ANY"
id string
remoteIp string
localIp string
}
type pdnsReply struct {
qname string
qclass string
qtype string
ttl string
id string
content string // may be other tab-separated data based on SRV/MX records
}
func (pr *pdnsReply) fmtReply() string {
return fmt.Sprintf("DATA\t%v\t%v\t%v\t%v\t%v\t%v\n", pr.qname, pr.qclass, pr.qtype, pr.ttl, pr.id, pr.content)
}
func parseReq(line []byte) (*pdnsReq, error) {
tokens := bytes.Split(line, []byte("\t"))
kind := string(tokens[0])
switch kind {
case KIND_Q:
if len(tokens) < 7 {
return nil, errBadLine
}
return &pdnsReq{kind, string(tokens[1]), string(tokens[2]), string(tokens[3]), string(tokens[4]), string(tokens[5]), string(tokens[6])}, nil
case KIND_PING, KIND_AXFR:
return &pdnsReq{kind: kind}, nil
default:
return nil, errBadLine
}
}
// PDNS will query for "ANY" no matter what record type the client
// has asked for. Thus, we need to return data for all record
// types. PDNS will then filter for what the client needs. PDNS is
// sensitive to the order in which records are returned. If you
// return a CNAME first, it returns the CNAME for all queries.
// The DNS spec says you should not have conflicts between
// CNAME/SRV records, so this really shouldn't be an issue.
func (pd *pdns) handleQReq(req *pdnsReq) (lines []string, err error) {
qtypes := []string{"SRV", "A", "SOA", "CNAME"}
if req.qtype != "ANY" {
qtypes = []string{req.qtype}
}
lines = make([]string, 0, 16)
for _, qtype := range qtypes {
replies, err := pd.zr.getResult(qtype, req.qname)
if err != nil {
log.Errorf("query failed %v %v: %v", qtype, req.qname, err)
continue
}
for _, reply := range replies {
lines = append(lines, reply.fmtReply())
}
}
if len(lines) == 0 {
emptyCount.Add(1)
log.Warningf("no results for %v %v", req.qtype, req.qname)
}
return lines, nil
}
func write(w io.Writer, line string) {
_, err := io.WriteString(w, line)
if err != nil {
log.Errorf("write failed: %v", err)
}
}
var (
requestCount = stats.NewInt("PdnsRequestCount")
errorCount = stats.NewInt("PdnsErrorCount")
emptyCount = stats.NewInt("PdnsEmptyCount")
)
func (pd *pdns) Serve(r io.Reader, w io.Writer) {
log.Infof("starting zkns resolver")
bufr := bufio.NewReader(r)
needHandshake := true
for {
line, isPrefix, err := bufr.ReadLine()
if err == nil && isPrefix {
err = errLongLine
}
if err == io.EOF {
return
}
if err != nil {
log.Errorf("failed reading request: %v", err)
continue
}
if needHandshake {
if !bytes.Equal(line, GREETING_ABI_V2) {
log.Errorf("handshake failed: %v != %v", line, GREETING_ABI_V2)
write(w, FAIL_REPLY)
} else {
needHandshake = false
write(w, GREETING_REPLY)
}
continue
}
requestCount.Add(1)
req, err := parseReq(line)
if err != nil {
errorCount.Add(1)
log.Errorf("failed parsing request: %v", err)
write(w, FAIL_REPLY)
continue
}
switch req.kind {
case KIND_Q:
respLines, err := pd.handleQReq(req)
if err != nil {
errorCount.Add(1)
log.Errorf("failed query: %v %v", req.qname, err)
write(w, FAIL_REPLY)
continue
}
for _, line := range respLines {
write(w, line)
}
case KIND_AXFR:
// FIXME(mike) unimplemented
}
write(w, END_REPLY)
}
}
func main() {
defer exit.Recover()
defer logutil.Flush()
zknsDomain := flag.String("zkns-domain", "", "The naming hierarchy portion to serve")
zknsRoot := flag.String("zkns-root", "", "The root path from which to resolve")
bindAddr := flag.String("bind-addr", ":31981", "Bind the debug http server")
flag.Parse()
if *bindAddr != "" {
go func() {
err := http.ListenAndServe(*bindAddr, nil)
if err != nil {
log.Errorf("ListenAndServe: %s", err)
exit.Return(1)
}
}()
}
zconn := zk.NewMetaConn()
fqdn := netutil.FullyQualifiedHostnameOrPanic()
zr1 := newZknsResolver(zconn, fqdn, *zknsDomain, *zknsRoot)
pd := &pdns{zr1}
pd.Serve(os.Stdin, os.Stdout)
os.Stdout.Close()
}