/
coredns.go
274 lines (245 loc) · 5.87 KB
/
coredns.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
// Copyright 2023 Ant Group Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package modules
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"k8s.io/client-go/kubernetes"
"github.com/secretflow/kuscia/cmd/kuscia/confloader"
"github.com/secretflow/kuscia/pkg/common"
"github.com/secretflow/kuscia/pkg/coredns"
"github.com/secretflow/kuscia/pkg/utils/network"
"github.com/secretflow/kuscia/pkg/utils/nlog"
"github.com/secretflow/kuscia/pkg/utils/paths"
)
var directives = []string{
"metadata",
"cancel",
"reload",
"nsid",
"bufsize",
"root",
"bind",
"debug",
"ready",
"health",
"pprof",
"prometheus",
"errors",
"log",
"dnstap",
"acl",
"any",
"chaos",
"loadbalance",
"cache",
"rewrite",
"dnssec",
"autopath",
"template",
"transfer",
"hosts",
"route53",
"file",
"auto",
"secondary",
"kuscia",
"loop",
"forward",
"erratic",
"whoami",
"on",
"sign",
}
const (
serverType = "dns"
)
type CorednsModule struct {
rootDir string
namespace string
envoyIP string
readyChan chan struct{}
coreDNSInstance *coredns.KusciaCoreDNS
}
func NewCoreDNS(conf *confloader.KusciaConfig) Module {
return &CorednsModule{
rootDir: conf.RootDir,
namespace: conf.DomainID,
envoyIP: conf.EnvoyIP,
readyChan: make(chan struct{}),
}
}
func (s *CorednsModule) Run(ctx context.Context) error {
defer close(s.readyChan)
if err := prepareResolvConf(s.rootDir); err != nil {
nlog.Errorf("Failed to prepare coredns resolv.conf, %v", err)
return err
}
plugin.Register(
"kuscia",
func(c *caddy.Controller) error {
e, err := coredns.KusciaParse(c, s.namespace, s.envoyIP)
if err != nil {
return plugin.Error("kuscia", err)
}
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
e.Next = next
return e
})
s.coreDNSInstance = e
return nil
},
)
dnsserver.Directives = directives
contents, err := os.ReadFile(filepath.Join(s.rootDir, common.ConfPrefix, "corefile"))
if err != nil {
return err
}
// Start your engines
instance, err := caddy.Start(caddy.CaddyfileInput{
Contents: contents,
ServerTypeName: serverType,
})
if err != nil {
return err
}
s.readyChan <- struct{}{}
// Twiddle your thumbs
instance.Wait()
return nil
}
func (s *CorednsModule) WaitReady(ctx context.Context) error {
select {
case <-s.readyChan:
return ctx.Err()
case <-ctx.Done():
return ctx.Err()
}
}
func (s *CorednsModule) Name() string {
return "coredns"
}
func RunCoreDNS(ctx context.Context, cancel context.CancelFunc, conf *confloader.KusciaConfig) Module {
m := NewCoreDNS(conf)
go func() {
if err := m.Run(ctx); err != nil {
nlog.Error(err)
cancel()
}
}()
if err := m.WaitReady(ctx); err != nil {
nlog.Error(err)
cancel()
} else {
nlog.Info("coredns is ready")
}
return m
}
func (s *CorednsModule) StartControllers(ctx context.Context, kubeclient kubernetes.Interface) {
s.coreDNSInstance.StartControllers(ctx, kubeclient)
}
func prepareResolvConf(rootDir string) error {
nlog.Infof("Start preparing coredns resolv.conf, root dir %v", rootDir)
hostIP, err := network.GetHostIP()
if err != nil {
return err
}
resolvConf := "/etc/resolv.conf"
backupResolvConf := filepath.Join(rootDir, common.TmpPrefix, "resolv.conf")
exist := paths.CheckFileExist(backupResolvConf)
if !exist {
if err = paths.CopyFile(resolvConf, backupResolvConf); err != nil {
return err
}
if err = updateResolvConf(backupResolvConf, hostIP, false); err != nil {
return err
}
}
if err = updateResolvConf(resolvConf, hostIP, true); err != nil {
return err
}
nlog.Info("Finish preparing coredns resolv.conf")
return nil
}
func updateResolvConf(fileName, hostIP string, add bool) error {
lines, err := getFileContent(fileName)
if err != nil {
return err
}
var finalContent []string
content := fmt.Sprintf("nameserver %s", hostIP)
switch add {
// add specific content
case true:
if len(lines) == 1 && strings.Contains(lines[0], content) {
return nil
}
finalContent = append(finalContent, content)
// delete specific content
default:
for i := range lines {
if !strings.Contains(lines[i], content) {
finalContent = append(finalContent, lines[i])
}
}
// Coredns server would check whether the nameserver exist in backup resolv.conf.
// If not, the coredns server will crash.
// So if finalContent doesn't include nameserver, skip updating the file.
foundNameserver := false
for _, c := range finalContent {
if strings.Contains(c, "nameserver") {
foundNameserver = true
break
}
}
if !foundNameserver {
nlog.Warnf("Due to the backup resolv.conf content %v doesn't include nameserver after removing %q, skip updating it", lines, content)
return nil
}
}
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
for _, c := range finalContent {
if _, err = fmt.Fprintln(file, c); err != nil {
return err
}
}
return nil
}
func getFileContent(fileName string) ([]string, error) {
var lines []string
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if scanner.Err() != nil {
return nil, err
}
return lines, nil
}