-
Notifications
You must be signed in to change notification settings - Fork 2
/
setup.go
221 lines (199 loc) · 4.91 KB
/
setup.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
package kubepods
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/miekg/dns"
core "k8s.io/api/core/v1"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/kubeapi"
)
const pluginName = "kubepods"
var log = clog.NewWithPlugin(pluginName)
func init() { plugin.Register(pluginName, setup) }
func setup(c *caddy.Controller) error {
k, err := parse(c)
if err != nil {
return plugin.Error(pluginName, err)
}
if k.mode != modeEchoIP {
k.setWatch(context.Background())
c.OnStartup(startWatch(k, dnsserver.GetConfig(c)))
c.OnShutdown(stopWatch(k))
}
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
k.Next = next
return k
})
return nil
}
func parse(c *caddy.Controller) (*KubePods, error) {
var (
kns *KubePods
err error
)
i := 0
for c.Next() {
if i > 0 {
return nil, plugin.ErrOnce
}
i++
kns, err = parseStanza(c)
if err != nil {
return kns, err
}
}
return kns, nil
}
// parseStanza parses a kubepods stanza
func parseStanza(c *caddy.Controller) (*KubePods, error) {
kps := New(plugin.OriginsFromArgsOrServerBlock(c.RemainingArgs(), c.ServerBlockKeys))
kps.mode = modeName
for c.NextBlock() {
switch c.Val() {
// TODO: operation modes
case "fallthrough":
kps.Fall.SetZonesFromArgs(c.RemainingArgs())
case "names":
args := c.RemainingArgs()
if len(args) != 1 {
return nil, c.ArgErr()
}
switch args[0] {
case "echo-ip":
kps.mode = modeEchoIP
case "ip":
kps.mode = modeIP
case "name":
kps.mode = modeName
case "name-and-ip":
kps.mode = modeNameAndIP
}
case "ttl":
args := c.RemainingArgs()
if len(args) == 0 {
return nil, c.ArgErr()
}
t, err := strconv.Atoi(args[0])
if err != nil {
return nil, err
}
if t < 0 || t > 3600 {
return nil, c.Errf("ttl must be in range [0, 3600]: %d", t)
}
kps.ttl = uint32(t)
default:
return nil, c.Errf("unknown property '%s'", c.Val())
}
}
if kps.mode != modeEchoIP {
// retrieve search zones for autopath
resolv, err := dns.ClientConfigFromFile("/etc/resolv.conf")
if err != nil {
return nil, err
}
plugin.Zones(resolv.Search).Normalize()
kps.autoPathSearch = resolv.Search
}
return kps, nil
}
func (k *KubePods) setWatch(ctx context.Context) {
// define Pod controller and reverse lookup indexer
k.indexer, k.controller = cache.NewIndexerInformer(
&cache.ListWatch{
ListFunc: func(o meta.ListOptions) (runtime.Object, error) {
return k.client.CoreV1().Pods(core.NamespaceAll).List(ctx, o)
},
WatchFunc: func(o meta.ListOptions) (watch.Interface, error) {
return k.client.CoreV1().Pods(core.NamespaceAll).Watch(ctx, o)
},
},
&core.Pod{},
0,
cache.ResourceEventHandlerFuncs{},
cache.Indexers{
// reverse for reverse lookups
"reverse": func(obj interface{}) ([]string, error) {
pod, ok := obj.(*core.Pod)
if !ok {
return nil, errors.New("unexpected obj type")
}
var idx []string
for _, addr := range pod.Status.PodIPs {
idx = append(idx, addr.IP)
}
return idx, nil
},
// namespace for lookups without pod name
"namespace": func(obj interface{}) ([]string, error) {
pod, ok := obj.(*core.Pod)
if !ok {
return nil, errors.New("unexpected obj type")
}
return []string{pod.Namespace}, nil
},
// dashedip for lookups with dashed IP as name
"dashedip": func(obj interface{}) ([]string, error) {
pod, ok := obj.(*core.Pod)
if !ok {
return nil, errors.New("unexpected obj type")
}
var idx []string
for _, addr := range pod.Status.PodIPs {
idx = append(idx, strings.Join([]string{pod.Namespace, dashIP(addr.IP)}, "/"))
}
return idx, nil
},
},
)
}
func startWatch(k *KubePods, config *dnsserver.Config) func() error {
return func() error {
// retrieve client from kubeapi plugin
var err error
k.client, err = kubeapi.Client(config)
if err != nil {
return err
}
// start the informer
go k.controller.Run(k.stopCh)
return nil
}
}
func stopWatch(k *KubePods) func() error {
return func() error {
k.stopLock.Lock()
defer k.stopLock.Unlock()
if !k.shutdown {
close(k.stopCh)
k.shutdown = true
return nil
}
return fmt.Errorf("shutdown already in progress")
}
}
func undashIP(name string) (ip string) {
if strings.Count(name, "-") == 3 && !strings.Contains(name, "--") {
ip = strings.ReplaceAll(name, "-", ".")
} else {
ip = strings.ReplaceAll(name, "-", ":")
}
return ip
}
func dashIP(ip string) (name string) {
if strings.Count(ip, ".") == 3 && !strings.Contains(ip, "::") {
name = strings.ReplaceAll(ip, ".", "-")
} else {
name = strings.ReplaceAll(ip, ":", "-")
}
return name
}