-
Notifications
You must be signed in to change notification settings - Fork 165
/
dns.go
415 lines (358 loc) · 12.6 KB
/
dns.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package e2e
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"fmt"
"io"
"regexp"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/Azure/go-autorest/autorest/to"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"github.com/Azure/ARO-RP/pkg/util/azureclient/mgmt/network"
"github.com/Azure/ARO-RP/pkg/util/ready"
"github.com/Azure/ARO-RP/pkg/util/stringutils"
)
var (
nameserverRegex = regexp.MustCompile("nameserver [0-9.]*")
resolvConfJobIsCompleteTimeout = 2 * time.Minute
resolvConfJobIsCompletePolling = 5 * time.Second
verifyResolvConfTimeout = 30 * time.Second
verifyResolvConfPollInterval = 1 * time.Second
nodesReadyPollInterval = 2 * time.Second
nicUpdateWaitTime = 5 * time.Second
)
const (
maxObjNameLen = 63
resolvConfContainerName = "read-resolv-conf"
)
var _ = Describe("ARO cluster DNS", func() {
BeforeEach(skipIfNotInDevelopmentEnv)
It("must not be adversely affected by Azure host servicing", func(ctx context.Context) {
By("creating a test namespace")
testNamespace := fmt.Sprintf("test-e2e-%d", GinkgoParallelProcess())
p := BuildNewProject(ctx, clients.Kubernetes, clients.Project, testNamespace)
By("verifying the namespace is ready")
Eventually(func(ctx context.Context) error {
return p.VerifyProjectIsReady(ctx)
}).WithContext(ctx).WithTimeout(DefaultEventuallyTimeout).Should(BeNil())
DeferCleanup(func(ctx context.Context) {
By("deleting the test namespace")
p.CleanUp(ctx)
})
By("listing all cluster nodes to retrieve the names of the worker nodes")
workerNodes := map[string]string{}
nodeList := ListK8sObjectWithRetry(
ctx, clients.Kubernetes.CoreV1().Nodes().List, metav1.ListOptions{},
)
for _, node := range nodeList.Items {
name := node.ObjectMeta.Name
if isWorkerNode(node) {
workerNodes[name] = ""
}
}
By("getting each worker node's private IP address")
oc, err := clients.OpenshiftClusters.Get(ctx, vnetResourceGroup, clusterName)
Expect(err).NotTo(HaveOccurred())
clusterResourceGroup := stringutils.LastTokenByte(*oc.OpenShiftClusterProperties.ClusterProfile.ResourceGroupID, '/')
for wn := range workerNodes {
nic, err := clients.Interfaces.Get(ctx, clusterResourceGroup, nicName(wn), "")
Expect(err).NotTo(HaveOccurred())
Expect(nic.InterfacePropertiesFormat).NotTo(BeNil())
Expect(nic.IPConfigurations).NotTo(BeNil())
Expect(*nic.IPConfigurations).To(HaveLen(1))
Expect((*nic.IPConfigurations)[0].InterfaceIPConfigurationPropertiesFormat).NotTo(BeNil())
Expect((*nic.IPConfigurations)[0].PrivateIPAddress).NotTo(BeNil())
workerNodes[wn] = *(*nic.IPConfigurations)[0].PrivateIPAddress
}
By("preparing to read resolv.conf from each of the worker nodes by allowing the test namespace's ServiceAccount to use the hostmount-anyuid SecurityContextConstraint")
sccName := fmt.Sprintf("system:serviceaccount:%s:default", testNamespace)
// This is wrapped in an Eventually call with some retries to avoid test flakes on the off chance that
// OCP happens to be trying to do stuff to the SecurityContextConstraint at the same time as us.
Eventually(func() error {
scc, err := clients.SecurityClient.SecurityV1().SecurityContextConstraints().Get(ctx, "hostmount-anyuid", metav1.GetOptions{})
if err != nil {
return err
}
if scc.Users == nil {
scc.Users = []string{}
}
scc.Users = append(scc.Users, sccName)
_, err = clients.SecurityClient.SecurityV1().SecurityContextConstraints().Update(ctx, scc, metav1.UpdateOptions{})
return err
}).WithContext(ctx).
WithTimeout(10 * time.Second).
WithPolling(1 * time.Second).
Should(Succeed())
DeferCleanup(func(ctx context.Context) {
By("removing the test namespace's ServiceAccount's ability to use the hostmount-anyuid SecurityContextConstraint")
Eventually(func() error {
scc, err := clients.SecurityClient.SecurityV1().SecurityContextConstraints().Get(ctx, "hostmount-anyuid", metav1.GetOptions{})
if err != nil {
return err
}
if scc.Users == nil {
scc.Users = []string{}
}
idx := -1
for i, u := range scc.Users {
if u == sccName {
idx = i
break
}
}
if idx >= 0 {
users := []string{}
for i, u := range scc.Users {
if i == idx {
continue
}
users = append(users, u)
}
scc.Users = users
_, err = clients.SecurityClient.SecurityV1().SecurityContextConstraints().Update(ctx, scc, metav1.UpdateOptions{})
return err
}
return nil
}).WithContext(ctx).
WithTimeout(10 * time.Second).
WithPolling(1 * time.Second).
Should(Succeed())
})
By("verifying each worker node's resolv.conf via a one-shot Job per node")
for wn, ip := range workerNodes {
createResolvConfJob(ctx, clients.Kubernetes, wn, testNamespace)
resolvConfJobIsComplete(ctx, clients.Kubernetes, wn, testNamespace)
Eventually(verifyResolvConf).
WithContext(ctx).
WithTimeout(verifyResolvConfTimeout).
WithPolling(verifyResolvConfPollInterval).
WithArguments(clients.Kubernetes, wn, testNamespace, ip).
Should(Succeed())
deleteResolvConfJob(ctx, clients.Kubernetes, wn, testNamespace)
}
By("stopping all three worker VMs")
for wn := range workerNodes {
err = clients.VirtualMachines.StopAndWait(ctx, clusterResourceGroup, wn, false)
Expect(err).NotTo(HaveOccurred())
}
By("disabling accelerated networking on all three worker VMs to simulate host servicing")
for wn := range workerNodes {
err = toggleAcceleratedNetworking(ctx, clients.Interfaces, clusterResourceGroup, wn, false)
Expect(err).NotTo(HaveOccurred())
}
// A small buffer here will help us be confident that the NIC API call to toggle accelerated
// networking will have taken full effect before we move forward under the assumption
// that it has.
time.Sleep(nicUpdateWaitTime)
By("restarting the three worker VMs")
for wn := range workerNodes {
err = clients.VirtualMachines.StartAndWait(ctx, clusterResourceGroup, wn)
Expect(err).NotTo(HaveOccurred())
}
By("waiting for all nodes to return to a Ready state")
Eventually(workerNodesReady).
WithContext(ctx).
WithTimeout(DefaultEventuallyTimeout).
WithPolling(nodesReadyPollInterval).
WithArguments(clients.Kubernetes).
Should(Succeed())
By("verifying each worker node's resolv.conf is still correct after simulating host servicing, again via a one-shot Job per node")
for wn, ip := range workerNodes {
createResolvConfJob(ctx, clients.Kubernetes, wn, testNamespace)
resolvConfJobIsComplete(ctx, clients.Kubernetes, wn, testNamespace)
Eventually(verifyResolvConf).
WithContext(ctx).
WithTimeout(verifyResolvConfTimeout).
WithPolling(verifyResolvConfPollInterval).
WithArguments(clients.Kubernetes, wn, testNamespace, ip).
Should(Succeed())
deleteResolvConfJob(ctx, clients.Kubernetes, wn, testNamespace)
}
By("stopping all three worker VMs")
for wn := range workerNodes {
err = clients.VirtualMachines.StopAndWait(ctx, clusterResourceGroup, wn, false)
Expect(err).NotTo(HaveOccurred())
}
By("re-enabling accelerated networking on all three worker VMs")
for wn := range workerNodes {
err = toggleAcceleratedNetworking(ctx, clients.Interfaces, clusterResourceGroup, wn, true)
Expect(err).NotTo(HaveOccurred())
}
time.Sleep(nicUpdateWaitTime)
By("restarting the three worker VMs")
for wn := range workerNodes {
err = clients.VirtualMachines.StartAndWait(ctx, clusterResourceGroup, wn)
Expect(err).NotTo(HaveOccurred())
}
By("waiting for all nodes to return to a Ready state")
Eventually(workerNodesReady).
WithContext(ctx).
WithTimeout(DefaultEventuallyTimeout).
WithPolling(nodesReadyPollInterval).
WithArguments(clients.Kubernetes).
Should(Succeed())
})
})
func nicName(nodeName string) string {
return fmt.Sprintf("%s-nic", nodeName)
}
func resolvConfJobName(nodeName string) string {
jobName := fmt.Sprintf("read-resolv-conf-%s", nodeName)
if len(jobName) > maxObjNameLen {
jobName = jobName[:maxObjNameLen]
}
return jobName
}
func createResolvConfJob(ctx context.Context, cli kubernetes.Interface, nodeName string, namespace string) {
hpt := corev1.HostPathFile
job := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: resolvConfJobName(nodeName),
},
Spec: batchv1.JobSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
NodeName: nodeName,
Containers: []corev1.Container{
{
Name: resolvConfContainerName,
Image: "busybox",
Command: []string{
"/bin/sh",
"-c",
"cat /tmp/resolv.conf",
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "resolv-conf",
MountPath: "/tmp/resolv.conf",
ReadOnly: true,
},
},
},
},
Volumes: []corev1.Volume{
{
Name: "resolv-conf",
VolumeSource: corev1.VolumeSource{
HostPath: &corev1.HostPathVolumeSource{
Path: "/etc/resolv.conf",
Type: &hpt,
},
},
},
},
RestartPolicy: corev1.RestartPolicyOnFailure,
},
},
},
}
CreateK8sObjectWithRetry(ctx, cli.BatchV1().Jobs(namespace).Create, job, metav1.CreateOptions{})
}
func resolvConfJobIsComplete(ctx context.Context, cli kubernetes.Interface, nodeName string, namespace string) {
Eventually(func(ctx context.Context) (bool, error) {
job, err := cli.BatchV1().Jobs(namespace).Get(ctx, resolvConfJobName(nodeName), metav1.GetOptions{})
if err != nil {
return false, err
}
return job.Status.Succeeded == 1, nil
}).
WithContext(ctx).
WithTimeout(resolvConfJobIsCompleteTimeout).
WithPolling(resolvConfJobIsCompletePolling).
Should(BeTrue())
}
func deleteResolvConfJob(ctx context.Context, cli kubernetes.Interface, nodeName string, namespace string) {
dpb := metav1.DeletePropagationBackground
deleteFunc := cli.BatchV1().Jobs(namespace).Delete
DeleteK8sObjectWithRetry(ctx, deleteFunc, resolvConfJobName(nodeName), metav1.DeleteOptions{
PropagationPolicy: &dpb,
})
}
func verifyResolvConf(
ctx context.Context, cli kubernetes.Interface, nodeName string, namespace string, nodeIp string,
) error {
jobName := resolvConfJobName(nodeName)
podList := ListK8sObjectWithRetry(ctx, cli.CoreV1().Pods(namespace).List, metav1.ListOptions{
LabelSelector: fmt.Sprintf("job-name=%s", jobName),
})
if len(podList.Items) != 1 {
return fmt.Errorf("found %v Pods associated with the Job, but there should be exactly 1", len(podList.Items))
}
podName := podList.Items[0].ObjectMeta.Name
tailLines := int64(10)
podLogOptions := &corev1.PodLogOptions{
Container: resolvConfContainerName,
Follow: false,
TailLines: &tailLines,
}
podLogRequest := cli.CoreV1().Pods(namespace).GetLogs(podName, podLogOptions)
stream, err := podLogRequest.Stream(ctx)
if err != nil {
return err
}
defer stream.Close()
logs := []string{}
for {
buf := make([]byte, 2000)
numBytes, err := stream.Read(buf)
if numBytes == 0 {
break
}
if err == io.EOF {
break
}
if err != nil {
return err
}
logs = append(logs, string(buf[:numBytes]))
}
log := strings.Join(logs, "\n")
if log == "" {
return fmt.Errorf("pod didn't have any logs")
}
nameserverLine := nameserverRegex.FindString(log)
if nameserverLine == "" {
return fmt.Errorf("didn't find nameserver in resolv.conf")
}
_, nameserverIp, _ := strings.Cut(nameserverLine, " ")
if nameserverIp != nodeIp {
return fmt.Errorf("nameserver specified in resolv.conf does not match node's IP address")
}
return nil
}
func toggleAcceleratedNetworking(ctx context.Context, interfaces network.InterfacesClient, clusterResourceGroup string, nodeName string, enabled bool) error {
nic, err := interfaces.Get(ctx, clusterResourceGroup, nicName(nodeName), "")
if err != nil {
return err
}
nic.EnableAcceleratedNetworking = to.BoolPtr(enabled)
err = clients.Interfaces.CreateOrUpdateAndWait(ctx, clusterResourceGroup, nicName(nodeName), nic)
return err
}
func isWorkerNode(node corev1.Node) bool {
ok := false
if node.ObjectMeta.Labels != nil {
_, ok = node.ObjectMeta.Labels["node-role.kubernetes.io/worker"]
}
return ok
}
func workerNodesReady(ctx context.Context, cli kubernetes.Interface) error {
nodeList, err := cli.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
for _, node := range nodeList.Items {
if isWorkerNode(node) && !ready.NodeIsReady(&node) {
return fmt.Errorf("a worker node is not yet ready")
}
}
return nil
}