-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
356 lines (285 loc) · 6.5 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/coreos/go-etcd/etcd"
"github.com/miekg/dns"
"github.com/spf13/cobra"
)
type (
server struct {
etcd *etcd.Client
domain string
prefix string
ttl uint32
}
)
// DNS requester types
const (
UnknownType = iota
NodeType
ServiceType
)
func nameError(w dns.ResponseWriter, req *dns.Msg) {
m := &dns.Msg{}
m.SetReply(req)
m.SetRcode(req, dns.RcodeNameError)
_ = w.WriteMsg(m)
}
func (s *server) GetNode(name string) (*node, error) {
name = strings.ToLower(name)
name = strings.TrimSuffix(name, ".nodes.")
key := filepath.Join("/", s.prefix, "nodes", name)
resp, err := s.etcd.Get(key, false, false)
if err != nil {
return nil, err
}
var n node
err = json.Unmarshal([]byte(resp.Node.Value), &n)
if err != nil {
return nil, err
}
if n.IP == nil {
log.WithField("node", name).Warn("node has no address")
return nil, nil
}
return &n, nil
}
func (s *server) GetService(name string) ([]*record, error) {
name = strings.TrimSuffix(name, ".services.")
key := filepath.Join("/", s.prefix, "services", name)
resp, err := s.etcd.Get(key, false, true)
if err != nil {
return nil, err
}
records := make([]*record, 0, len(resp.Node.Nodes))
for _, n := range resp.Node.Nodes {
var rec record
err := json.Unmarshal([]byte(n.Value), &rec)
if err != nil {
log.WithFields(log.Fields{
"key": n.Key,
"error": err,
}).Error("failed to unmarshal node json")
continue
}
// should match against a regex?
if rec.Target == "" {
continue
}
records = append(records, &rec)
}
return records, nil
}
func (s *server) ServicesA(w dns.ResponseWriter, r *dns.Msg, name string) (*dns.Msg, error) {
records, err := s.GetService(name)
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, nil
}
m := &dns.Msg{}
m.SetReply(r)
header := dns.RR_Header{
Name: r.Question[0].Name,
Rrtype: r.Question[0].Qtype,
Class: r.Question[0].Qclass,
Ttl: s.ttl,
}
m.Answer = make([]dns.RR, 0, len(records))
for _, record := range records {
// any target that contains a "." is assumed to not be a node
if strings.Contains(record.Target, ".") {
continue
}
node, err := s.GetNode(record.Target)
if err != nil {
continue
}
answer := &dns.A{
Hdr: header,
A: node.IP,
}
m.Answer = append(m.Answer, answer)
}
return m, nil
}
func (s *server) ServicesSRV(w dns.ResponseWriter, r *dns.Msg, name string) (*dns.Msg, error) {
records, err := s.GetService(name)
if err != nil {
return nil, err
}
if len(records) == 0 {
return nil, nil
}
m := &dns.Msg{}
m.SetReply(r)
header := dns.RR_Header{
Name: r.Question[0].Name,
Rrtype: r.Question[0].Qtype,
Class: r.Question[0].Qclass,
Ttl: s.ttl,
}
m.Answer = make([]dns.RR, 0, len(records))
m.Extra = make([]dns.RR, 0, len(records))
for _, record := range records {
isNode := false
target := strings.ToLower(record.Target)
if !strings.Contains(target, ".") {
target = strings.Join([]string{target, "nodes", s.domain}, ".")
isNode = true
// should we make sure it exists before we add it?
}
answer := &dns.SRV{
Hdr: header,
Priority: record.Priority,
Weight: record.Weight,
Port: record.Port,
Target: target,
}
m.Answer = append(m.Answer, answer)
if !isNode {
continue
}
node, err := s.GetNode(record.Target)
if err != nil {
// just skip it
continue
}
extra := &dns.A{
Hdr: dns.RR_Header{
Name: target,
Rrtype: dns.TypeA,
Class: r.Question[0].Qclass,
Ttl: s.ttl,
},
A: node.IP,
}
m.Extra = append(m.Extra, extra)
}
return m, nil
}
func (s *server) NodesA(w dns.ResponseWriter, r *dns.Msg, name string) (*dns.Msg, error) {
node, err := s.GetNode(name)
if err != nil {
return nil, err
}
m := &dns.Msg{}
m.SetReply(r)
header := dns.RR_Header{
Name: r.Question[0].Name,
Rrtype: r.Question[0].Qtype,
Class: r.Question[0].Qclass,
Ttl: s.ttl,
}
m.Answer = []dns.RR{
&dns.A{
Hdr: header,
A: node.IP,
},
}
return m, nil
}
func toType(s string) int {
switch s {
case "services":
return ServiceType
case "nodes":
return NodeType
}
return UnknownType
}
func checkName(qType uint16, name string) (string, int) {
parts := strings.Split(name, ".")
parts = parts[:len(parts)-1]
switch len(parts) {
case 2:
return parts[0], toType(parts[1])
case 3:
// horrible hack to munge _service._protocol.services.<domain> queries
if qType == dns.TypeSRV && parts[2] == "services" && (parts[1] == "_tcp" || parts[1] == "_udp") {
n := parts[0]
if len(n) > 1 && (string([]rune(n)[0]) == "_") {
return strings.TrimPrefix(n, "_"), ServiceType
}
}
}
// just horrible...
return "", UnknownType
}
func (s *server) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
question := strings.ToLower(r.Question[0].Name)
name := strings.TrimSuffix(question, s.domain)
qType := r.Question[0].Qtype
name, rType := checkName(qType, name)
if name == "" || rType == UnknownType {
log.WithField("query", question).Info("invalid dns query")
nameError(w, r)
return
}
var m *dns.Msg
var err error
switch rType {
case ServiceType:
switch qType {
case dns.TypeA:
m, err = s.ServicesA(w, r, name)
case dns.TypeSRV:
m, err = s.ServicesSRV(w, r, name)
}
case NodeType:
switch qType {
case dns.TypeA:
m, err = s.NodesA(w, r, name)
}
}
if err != nil {
log.WithFields(log.Fields{
"query": question,
"error": err,
}).Error("failed to serve valid dns response")
if isKeyNotFound(err) {
nameError(w, r)
} else {
dns.HandleFailed(w, r)
}
return
}
if m == nil {
log.WithField("query", question).Info("not found")
nameError(w, r)
return
}
_ = w.WriteMsg(m)
}
// TODO: start a simple http status interface. should be a different service?
func runServer(cmd *cobra.Command, args []string) {
e := etcd.NewClient(([]string{etcdAddress}))
parts := strings.Split(dnsDomain, ".")
dom := make([]string, 0, len(parts))
for _, p := range parts {
if len(p) > 0 {
dom = append(dom, p)
}
}
s := &server{
etcd: e,
domain: strings.ToLower(strings.Join(dom, ".") + "."),
prefix: etcdPrefix,
ttl: uint32(dnsTTL),
}
dns.Handle(s.domain, s)
server := &dns.Server{
Addr: fmt.Sprintf(":%d", dnsPort),
Net: "udp",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
err := server.ListenAndServe()
log.WithField("error", err).Fatal("server error")
}