-
Notifications
You must be signed in to change notification settings - Fork 0
/
nsip.go
95 lines (76 loc) · 2.01 KB
/
nsip.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
package nsip
import (
"context"
"fmt"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"net"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type Record struct {
Next plugin.Handler
Rules []rule
}
type rule struct {
zones []string
policies []policy
}
type policy struct {
ns string
ip string
}
func (a Record) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
querySourceIP := state.IP()
namespace, err := findPodNamespaceByIP(querySourceIP)
if err != nil {
log.Errorf("error searching for namespace: %v", err)
}
log.Info(fmt.Sprintf("query from namespace: %s", namespace))
m := new(dns.Msg)
m.SetReply(r)
rr := new(dns.A)
rr.Hdr = dns.RR_Header{Name: r.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 3600}
ipFound := false
for _, p := range a.Rules[0].policies {
if p.ns == namespace {
ipAddr := net.ParseIP(p.ip)
if ipAddr != nil {
rr.A = ipAddr
m.Answer = append(m.Answer, rr)
ipFound = true
break
}
}
}
if !ipFound {
return plugin.NextOrFailure(a.Name(), a.Next, ctx, w, r)
}
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
func (a Record) Name() string { return "nsip" }
func findPodNamespaceByIP(ip string) (string, error) {
config, err := rest.InClusterConfig()
if err != nil {
return "", fmt.Errorf("failed to get in-cluster configuration: %w", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return "", fmt.Errorf("failed to create Kubernetes client: %w", err)
}
pods, err := clientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{})
if err != nil {
return "", fmt.Errorf("failed to retrieve list of pods: %w", err)
}
for _, pod := range pods.Items {
if pod.Status.PodIP == ip {
return pod.Namespace, nil
}
}
return "", fmt.Errorf("pod with IP %s not found", ip)
}