forked from ori-edge/k8s_gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
320 lines (262 loc) · 7.28 KB
/
gateway.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
package gateway
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/fall"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
type lookupFunc func(indexKeys []string) []netip.Addr
type resourceWithIndex struct {
name string
lookup lookupFunc
}
var noop lookupFunc = func([]string) (result []netip.Addr) { return }
var orderedResources = []*resourceWithIndex{
{
name: "HTTPRoute",
lookup: noop,
},
{
name: "TLSRoute",
lookup: noop,
},
{
name: "GRPCRoute",
lookup: noop,
},
{
name: "VirtualServer",
lookup: noop,
},
{
name: "Ingress",
lookup: noop,
},
{
name: "Service",
lookup: noop,
},
}
var (
ttlDefault = uint32(60)
ttlSOA = uint32(60)
defaultApex = "dns1.kube-system"
defaultHostmaster = "hostmaster"
defaultSecondNS = ""
)
// Gateway stores all runtime configuration of a plugin
type Gateway struct {
Next plugin.Handler
Zones []string
Resources []*resourceWithIndex
ttlLow uint32
ttlSOA uint32
Controller *KubeController
apex string
hostmaster string
secondNS string
configFile string
configContext string
ExternalAddrFunc func(request.Request) []dns.RR
Fall fall.F
}
func newGateway() *Gateway {
return &Gateway{
Resources: orderedResources,
ttlLow: ttlDefault,
ttlSOA: ttlSOA,
apex: defaultApex,
secondNS: defaultSecondNS,
hostmaster: defaultHostmaster,
}
}
func lookupResource(resource string) *resourceWithIndex {
for _, r := range orderedResources {
if r.name == resource {
return r
}
}
return nil
}
func (gw *Gateway) updateResources(newResources []string) {
gw.Resources = []*resourceWithIndex{}
for _, name := range newResources {
if resource := lookupResource(name); resource != nil {
gw.Resources = append(gw.Resources, resource)
}
}
}
// ServeDNS implements the plugin.Handle interface.
func (gw *Gateway) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
//log.Infof("Incoming query %s", state.QName())
qname := state.QName()
zone := plugin.Zones(gw.Zones).Matches(qname)
if zone == "" {
log.Debugf("Request %s has not matched any zones %v", qname, gw.Zones)
return plugin.NextOrFailure(gw.Name(), gw.Next, ctx, w, r)
}
zone = qname[len(qname)-len(zone):] // maintain case of original query
state.Zone = zone
// Indexer cache can be built from `name.namespace` without zone
zonelessQuery := stripDomain(qname, zone)
// Computing keys to look up in cache
var indexKeys []string
strippedQName := stripClosingDot(state.QName())
if len(zonelessQuery) != 0 && zonelessQuery != strippedQName {
indexKeys = []string{strippedQName, zonelessQuery}
} else {
indexKeys = []string{strippedQName}
}
log.Debugf("Computed Index Keys %v", indexKeys)
if !gw.Controller.HasSynced() {
// TODO maybe there's a better way to do this? e.g. return an error back to the client?
return dns.RcodeServerFailure, plugin.Error(thisPlugin, fmt.Errorf("Could not sync required resources"))
}
var isRootZoneQuery bool
for _, z := range gw.Zones {
if state.Name() == z { // apex query
isRootZoneQuery = true
break
}
if dns.IsSubDomain(gw.apex+"."+z, state.Name()) {
// dns subdomain test for ns. and dns. queries
ret, err := gw.serveSubApex(state)
return ret, err
}
}
var addrs []netip.Addr
// Iterate over supported resources and lookup DNS queries
// Stop once we've found at least one match
for _, resource := range gw.Resources {
addrs = resource.lookup(indexKeys)
if len(addrs) > 0 {
break
}
}
log.Debugf("Computed response addresses %v", addrs)
// Fall through if no host matches
if len(addrs) == 0 && gw.Fall.Through(qname) {
return plugin.NextOrFailure(gw.Name(), gw.Next, ctx, w, r)
}
m := new(dns.Msg)
m.SetReply(state.Req)
var ipv4Addrs []netip.Addr
var ipv6Addrs []netip.Addr
for _, addr := range addrs {
if addr.Is4() {
ipv4Addrs = append(ipv4Addrs, addr)
}
if addr.Is6() {
ipv6Addrs = append(ipv6Addrs, addr)
}
}
switch state.QType() {
case dns.TypeA:
if len(ipv4Addrs) == 0 {
if !isRootZoneQuery {
// No match, return NXDOMAIN
m.Rcode = dns.RcodeNameError
}
m.Ns = []dns.RR{gw.soa(state)}
} else {
m.Answer = gw.A(state.Name(), ipv4Addrs)
}
case dns.TypeAAAA:
if len(ipv6Addrs) == 0 {
if !isRootZoneQuery {
// No match, return NXDOMAIN
m.Rcode = dns.RcodeNameError
}
// as per rfc4074 #3
if len(ipv4Addrs) > 0 {
m.Rcode = dns.RcodeSuccess
}
m.Ns = []dns.RR{gw.soa(state)}
} else {
m.Answer = gw.AAAA(state.Name(), ipv6Addrs)
}
case dns.TypeSOA:
m.Answer = []dns.RR{gw.soa(state)}
case dns.TypeNS:
if isRootZoneQuery {
m.Answer = gw.nameservers(state)
addr := gw.ExternalAddrFunc(state)
for _, rr := range addr {
rr.Header().Ttl = gw.ttlSOA
m.Extra = append(m.Extra, rr)
}
} else {
m.Ns = []dns.RR{gw.soa(state)}
}
default:
m.Ns = []dns.RR{gw.soa(state)}
}
// Force to true to fix broken behaviour of legacy glibc `getaddrinfo`.
// See https://github.com/coredns/coredns/pull/3573
m.Authoritative = true
if err := w.WriteMsg(m); err != nil {
log.Errorf("Failed to send a response: %s", err)
}
return dns.RcodeSuccess, nil
}
// Name implements the Handler interface.
func (gw *Gateway) Name() string { return thisPlugin }
// A does the A-record lookup in ingress indexer
func (gw *Gateway) A(name string, results []netip.Addr) (records []dns.RR) {
dup := make(map[string]struct{})
for _, result := range results {
if _, ok := dup[result.String()]; !ok {
dup[result.String()] = struct{}{}
records = append(records, &dns.A{Hdr: dns.RR_Header{Name: name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: gw.ttlLow}, A: net.ParseIP(result.String())})
}
}
return records
}
func (gw *Gateway) AAAA(name string, results []netip.Addr) (records []dns.RR) {
dup := make(map[string]struct{})
for _, result := range results {
if _, ok := dup[result.String()]; !ok {
dup[result.String()] = struct{}{}
records = append(records, &dns.AAAA{Hdr: dns.RR_Header{Name: name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: gw.ttlLow}, AAAA: net.ParseIP(result.String())})
}
}
return records
}
// SelfAddress returns the address of the local k8s_gateway service
func (gw *Gateway) SelfAddress(state request.Request) (records []dns.RR) {
var addrs1, addrs2 []netip.Addr
for _, resource := range gw.Resources {
results := resource.lookup([]string{gw.apex})
if len(results) > 0 {
addrs1 = append(addrs1, results...)
}
results = resource.lookup([]string{gw.secondNS})
if len(results) > 0 {
addrs2 = append(addrs2, results...)
}
}
records = append(records, gw.A(gw.apex+"."+state.Zone, addrs1)...)
if state.QType() == dns.TypeNS {
records = append(records, gw.A(gw.secondNS+"."+state.Zone, addrs2)...)
}
return records
//return records
}
// Strips the zone from FQDN and return a hostname
func stripDomain(qname, zone string) string {
hostname := qname[:len(qname)-len(zone)]
return stripClosingDot(hostname)
}
// Strips the closing dot unless it's "."
func stripClosingDot(s string) string {
if len(s) > 1 {
return strings.TrimSuffix(s, ".")
}
return s
}