forked from openshift/origin
/
serviceresolver.go
385 lines (335 loc) · 10.9 KB
/
serviceresolver.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package dns
import (
"encoding/json"
"fmt"
"hash/fnv"
"net"
"strings"
etcd "github.com/coreos/etcd/client"
"github.com/golang/glog"
kapi "k8s.io/kubernetes/pkg/api"
kendpoints "k8s.io/kubernetes/pkg/api/endpoints"
"k8s.io/kubernetes/pkg/api/errors"
kclient "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/util/validation"
"github.com/skynetservices/skydns/msg"
"github.com/skynetservices/skydns/server"
)
// ServiceResolver is a SkyDNS backend that will serve lookups for DNS entries
// based on Kubernetes service entries. The default DNS name for each service
// will be `<name>.<namespace>.<base>` where base can be an arbitrary depth
// DNS suffix. Queries not recognized within this base will return an error.
type ServiceResolver struct {
config *server.Config
accessor ServiceAccessor
endpoints kclient.EndpointsNamespacer
base string
fallback FallbackFunc
}
// ServiceResolver implements server.Backend
var _ server.Backend = &ServiceResolver{}
// TODO: abstract in upstream SkyDNS
var errNoSuchName = etcd.Error{Code: etcd.ErrorCodeKeyNotFound}
type FallbackFunc func(name string, exact bool) (string, bool)
// NewServiceResolver creates an object that will return DNS record entries for
// SkyDNS based on service names.
func NewServiceResolver(config *server.Config, accessor ServiceAccessor, endpoints kclient.EndpointsNamespacer, fn FallbackFunc) *ServiceResolver {
domain := config.Domain
if !strings.HasSuffix(domain, ".") {
domain = domain + "."
}
return &ServiceResolver{
config: config,
accessor: accessor,
endpoints: endpoints,
base: domain,
fallback: fn,
}
}
// Records implements the SkyDNS Backend interface and returns standard records for
// a name.
//
// The standard pattern is <prefix>.<service_name>.<namespace>.(svc|endpoints|pod).<base>
//
// * prefix may be any series of prefix values
// * _endpoints is a special prefix that returns the same as <service_name>.<namespace>.svc.<base>
// * service_name and namespace must locate a real service
// * unless a fallback is defined, in which case the fallback name will be looked up
// * svc indicates standard service rules apply (clusterIP or endpoints as A records)
// * reverse lookup of IP is only possible for clusterIP
// * SRV records are returned for each host+port combination as:
// _<port_name>._<port_protocol>.<dns>
// _<port_name>.<endpoint_id>.<dns>
// * endpoints always returns each individual endpoint as A records
// * SRV records for endpoints are similar to SVC, but are prefixed with a single label
// that is a hash of the endpoint IP
// * pods is of the form <IP_with_dashes>.<namespace>.pod.<base> and resolves to <IP>
//
func (b *ServiceResolver) Records(dnsName string, exact bool) ([]msg.Service, error) {
if !strings.HasSuffix(dnsName, b.base) {
return nil, errNoSuchName
}
prefix := strings.Trim(strings.TrimSuffix(dnsName, b.base), ".")
segments := strings.Split(prefix, ".")
for i, j := 0, len(segments)-1; i < j; i, j = i+1, j-1 {
segments[i], segments[j] = segments[j], segments[i]
}
if len(segments) == 0 {
return nil, errNoSuchName
}
glog.V(4).Infof("Answering query %s:%t", dnsName, exact)
switch base := segments[0]; base {
case "pod":
if len(segments) != 3 {
return nil, errNoSuchName
}
namespace, encodedIP := segments[1], segments[2]
ip := convertDashIPToIP(encodedIP)
if net.ParseIP(ip) == nil {
return nil, errNoSuchName
}
return []msg.Service{
{
Host: ip,
Port: 0,
Priority: 10,
Weight: 10,
Ttl: 30,
Key: msg.Path(buildDNSName(b.base, "pod", namespace, getHash(ip))),
},
}, nil
case "svc", "endpoints":
if len(segments) < 3 {
return nil, errNoSuchName
}
namespace, name := segments[1], segments[2]
svc, err := b.accessor.Services(namespace).Get(name)
if err != nil {
if errors.IsNotFound(err) && b.fallback != nil {
if fallback, ok := b.fallback(prefix, exact); ok {
return b.Records(fallback+b.base, exact)
}
return nil, errNoSuchName
}
return nil, errNoSuchName
}
// no clusterIP and not headless, no DNS
if len(svc.Spec.ClusterIP) == 0 {
return nil, errNoSuchName
}
subdomain := buildDNSName(b.base, base, namespace, name)
endpointPrefix := base == "endpoints"
retrieveEndpoints := endpointPrefix || (len(segments) > 3 && segments[3] == "_endpoints")
includePorts := len(segments) > 3 && hasAllPrefixedSegments(segments[3:], "_") && segments[3] != "_endpoints"
// if has a portal IP and looking at svc
if svc.Spec.ClusterIP != kapi.ClusterIPNone && !retrieveEndpoints {
defaultService := msg.Service{
Host: svc.Spec.ClusterIP,
Port: 0,
Priority: 10,
Weight: 10,
Ttl: 30,
}
defaultHash := getHash(defaultService.Host)
defaultName := buildDNSName(subdomain, defaultHash)
defaultService.Key = msg.Path(defaultName)
if len(svc.Spec.Ports) == 0 || !includePorts {
return []msg.Service{defaultService}, nil
}
services := []msg.Service{}
protocolMatch, portMatch := segments[3], "*"
if len(segments) > 4 {
portMatch = segments[4]
}
for _, p := range svc.Spec.Ports {
portSegment, protocolSegment, ok := matchesPortAndProtocol(p.Name, string(p.Protocol), portMatch, protocolMatch)
if !ok {
continue
}
port := p.Port
if port == 0 {
port = int32(p.TargetPort.IntVal)
}
keyName := buildDNSName(defaultName, protocolSegment, portSegment)
services = append(services,
msg.Service{
Host: svc.Spec.ClusterIP,
Port: int(port),
Priority: 10,
Weight: 10,
Ttl: 30,
TargetStrip: 2,
Key: msg.Path(keyName),
},
)
}
if len(services) == 0 {
services = append(services, defaultService)
}
glog.V(4).Infof("Answered %s:%t with %#v", dnsName, exact, services)
return services, nil
}
// return endpoints
endpoints, err := b.endpoints.Endpoints(namespace).Get(name)
if err != nil {
return nil, errNoSuchName
}
hostnameMappings := noHostnameMappings
if savedHostnames := endpoints.Annotations[kendpoints.PodHostnamesAnnotation]; len(savedHostnames) > 0 {
mapped := make(map[string]kendpoints.HostRecord)
if err = json.Unmarshal([]byte(savedHostnames), &mapped); err == nil {
hostnameMappings = mapped
}
}
matchHostname := len(segments) > 3 && !hasAllPrefixedSegments(segments[3:4], "_")
services := make([]msg.Service, 0, len(endpoints.Subsets)*4)
for _, s := range endpoints.Subsets {
for _, a := range s.Addresses {
defaultService := msg.Service{
Host: a.IP,
Port: 0,
Priority: 10,
Weight: 10,
Ttl: 30,
}
var endpointName string
if hostname, ok := getHostname(&a, hostnameMappings); ok {
endpointName = hostname
} else {
endpointName = getHash(defaultService.Host)
}
if matchHostname && endpointName != segments[3] {
continue
}
defaultName := buildDNSName(subdomain, endpointName)
defaultService.Key = msg.Path(defaultName)
if !includePorts {
services = append(services, defaultService)
continue
}
protocolMatch, portMatch := segments[3], "*"
if len(segments) > 4 {
portMatch = segments[4]
}
for _, p := range s.Ports {
portSegment, protocolSegment, ok := matchesPortAndProtocol(p.Name, string(p.Protocol), portMatch, protocolMatch)
if !ok || p.Port == 0 {
continue
}
keyName := buildDNSName(defaultName, protocolSegment, portSegment)
services = append(services, msg.Service{
Host: a.IP,
Port: int(p.Port),
Priority: 10,
Weight: 10,
Ttl: 30,
TargetStrip: 2,
Key: msg.Path(keyName),
})
}
}
}
glog.V(4).Infof("Answered %s:%t with %#v", dnsName, exact, services)
return services, nil
}
return nil, errNoSuchName
}
// ReverseRecord implements the SkyDNS Backend interface and returns standard records for
// a name.
func (b *ServiceResolver) ReverseRecord(name string) (*msg.Service, error) {
clusterIP, ok := extractIP(name)
if !ok {
return nil, fmt.Errorf("does not support reverse lookup with %s", name)
}
svc, err := b.accessor.ServiceByClusterIP(clusterIP)
if err != nil {
return nil, err
}
port := 0
if len(svc.Spec.Ports) > 0 {
port = int(svc.Spec.Ports[0].Port)
}
hostName := buildDNSName(b.base, "svc", svc.Namespace, svc.Name)
return &msg.Service{
Host: hostName,
Port: port,
Priority: 10,
Weight: 10,
Ttl: 30,
Key: msg.Path(name),
}, nil
}
// arpaSuffix is the standard suffix for PTR IP reverse lookups.
const arpaSuffix = ".in-addr.arpa."
func matchesPortAndProtocol(name, protocol, matchPortSegment, matchProtocolSegment string) (portSegment string, protocolSegment string, match bool) {
if len(name) == 0 {
return "", "", false
}
portSegment = "_" + name
if portSegment != matchPortSegment && matchPortSegment != "*" {
return "", "", false
}
protocolSegment = "_" + strings.ToLower(string(protocol))
if protocolSegment != matchProtocolSegment && matchProtocolSegment != "*" {
return "", "", false
}
return portSegment, protocolSegment, true
}
// extractIP turns a standard PTR reverse record lookup name
// into an IP address
func extractIP(reverseName string) (string, bool) {
if !strings.HasSuffix(reverseName, arpaSuffix) {
return "", false
}
search := strings.TrimSuffix(reverseName, arpaSuffix)
// reverse the segments and then combine them
segments := strings.Split(search, ".")
for i := 0; i < len(segments)/2; i++ {
j := len(segments) - i - 1
segments[i], segments[j] = segments[j], segments[i]
}
return strings.Join(segments, "."), true
}
// buildDNSName reverses the labels order and joins them with dots.
func buildDNSName(labels ...string) string {
var res string
for _, label := range labels {
if len(res) == 0 {
res = label
} else {
res = fmt.Sprintf("%s.%s", label, res)
}
}
return res
}
// getHostname returns true if the provided address has a hostname, or false otherwise.
func getHostname(address *kapi.EndpointAddress, podHostnames map[string]kendpoints.HostRecord) (string, bool) {
if len(address.Hostname) > 0 {
return address.Hostname, true
}
if hostRecord, exists := podHostnames[address.IP]; exists && len(validation.IsDNS1123Label(hostRecord.HostName)) == 0 {
return hostRecord.HostName, true
}
return "", false
}
// return a hash for the key name
func getHash(text string) string {
h := fnv.New32a()
h.Write([]byte(text))
return fmt.Sprintf("%x", h.Sum32())
}
// convertDashIPToIP takes an encoded IP (with dashes) and replaces them with
// dots.
func convertDashIPToIP(ip string) string {
return strings.Join(strings.Split(ip, "-"), ".")
}
// hasAllPrefixedSegments returns true if all provided segments have the given prefix.
func hasAllPrefixedSegments(segments []string, prefix string) bool {
for _, s := range segments {
if !strings.HasPrefix(s, prefix) {
return false
}
}
return true
}
var noHostnameMappings = map[string]kendpoints.HostRecord{}