-
Notifications
You must be signed in to change notification settings - Fork 368
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
initial commit for e2e test for #6229 #6695
Draft
hkiiita
wants to merge
17
commits into
antrea-io:main
Choose a base branch
from
hkiiita:fqdn-e2e-test
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
ab09340
initial commit for e2e test for #6229
hkiiita e63de57
Refactored to remove nginx and include agnHost. Also Updated dig comm…
hkiiita 34a0a15
refactored with changes provided in review
hkiiita 5412d1f
fix: update policy build in code to ensure tests run successfully
hkiiita 5fe77ef
used eventual assertions and removed using podwait for running status…
hkiiita 0081010
removed podWaitForIPs where not needed.
hkiiita d1a8227
added function to annotate pods.
hkiiita e2e5466
accomodate ipv4 and ipv6 and change annotation patch function
hkiiita bc91964
merge generateCoreFile to createDnsConfig making use of closures.
hkiiita 2ef3fd1
Removed not needed globally defined constants.
hkiiita df67bb5
using pod builder to create toolbox and added some logs for verbosity…
hkiiita 36102ba
reduced verbosity and refactored createConfigMap function
hkiiita 894ff32
Made significant changes to the e2e test by improving readability and…
hkiiita 839f690
reduced helper functions
hkiiita 7cd15c7
Improved e2e test for FQDN:
hkiiita b7c92c0
corrected initialisms for FQDN, IP
hkiiita 9e76e44
Set reload value for dns config and added an explanatory comment besi…
hkiiita File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,314 @@ | ||
// Copyright 2024 Antrea Authors. | ||
// | ||
// 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 e2e | ||
|
||
import ( | ||
antoninbas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"bytes" | ||
"fmt" | ||
"strconv" | ||
"strings" | ||
"testing" | ||
"text/template" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
corev1 "k8s.io/api/core/v1" | ||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
"k8s.io/utils/ptr" | ||
|
||
crdv1beta1 "antrea.io/antrea/pkg/apis/crd/v1beta1" | ||
agentconfig "antrea.io/antrea/pkg/config/agent" | ||
"antrea.io/antrea/test/e2e/utils" | ||
) | ||
|
||
func TestFQDNPolicyWithCachedDNS(t *testing.T) { | ||
Dyanngg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const ( | ||
testFQDN = "fqdn-test-pod.lfx.test" | ||
dnsPort = 53 | ||
dnsTTL = 5 | ||
) | ||
|
||
skipIfAntreaPolicyDisabled(t) | ||
skipIfNotIPv4Cluster(t) | ||
skipIfIPv6Cluster(t) | ||
antoninbas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
skipIfNotRequired(t, "mode-irrelevant") | ||
|
||
data, err := setupTest(t) | ||
if err != nil { | ||
t.Fatalf("Error when setting up test: %v", err) | ||
} | ||
defer teardownTest(t, data) | ||
|
||
// create two agnHost Pods and get their IPv4 addresses. The IP of these Pods will be mapped against the FQDN. | ||
podCount := 2 | ||
agnHostPodIPs := make([]*PodIPs, podCount) | ||
for i := 0; i < podCount; i++ { | ||
agnHostPodIPs[i] = createHttpAgnHostPod(t, data) | ||
} | ||
|
||
// get IPv4 addresses of the agnHost pods created. | ||
agnHostPodOneIP, _ := agnHostPodIPs[0].AsStrings() | ||
agnHostPodTwoIP, _ := agnHostPodIPs[1].AsStrings() | ||
|
||
// create customDNS service and get its ClusterIP. | ||
customDnsService, err := data.CreateServiceWithAnnotations("custom-dns-service", data.testNamespace, dnsPort, | ||
dnsPort, corev1.ProtocolUDP, map[string]string{"app": "custom-dns"}, false, | ||
false, corev1.ServiceTypeClusterIP, ptr.To[corev1.IPFamily](corev1.IPv4Protocol), map[string]string{}) | ||
require.NoError(t, err, "Error creating custom DNS Service") | ||
dnsServiceIP := customDnsService.Spec.ClusterIP | ||
|
||
// create a ConfigMap for the custom DNS server, mapping IP of agnHost Pod 1 to the FQDN. | ||
configMap := &corev1.ConfigMap{ | ||
ObjectMeta: metav1.ObjectMeta{ | ||
Name: "custom-dns-config", | ||
Namespace: data.testNamespace, | ||
}, | ||
Data: createDnsConfig(t, map[string]string{agnHostPodOneIP: testFQDN}, dnsTTL), | ||
} | ||
customDnsConfigMap, err := data.CreateConfigMap(configMap) | ||
require.NoError(t, err, "failed to create custom DNS ConfigMap") | ||
|
||
createCustomDnsPod(t, data, configMap.Name) | ||
|
||
// set the custom DNS server IP address in Antrea configMap. | ||
setDnsServerAddressInAntrea(t, data, dnsServiceIP) | ||
defer setDnsServerAddressInAntrea(t, data, "") //reset after the test. | ||
|
||
createFqdnPolicyInNamespace(t, data, testFQDN, "test-anp-fqdn", "custom-dns", "fqdn-cache-test") | ||
createToolboxPod(t, data, dnsServiceIP) | ||
curlTarget := testFQDN | ||
curlFQDN := func() (string, error) { | ||
cmd := []string{"curl", curlTarget} | ||
stdout, stderr, err := data.RunCommandFromPod(data.testNamespace, toolboxPodName, toolboxContainerName, cmd) | ||
if err != nil { | ||
return "", fmt.Errorf("error when running command '%s' on Pod '%s': %v, stdout: <%v>, stderr: <%v>", | ||
strings.Join(cmd, " "), toolboxPodName, err, stdout, stderr) | ||
} | ||
return stdout, nil | ||
} | ||
|
||
assert.EventuallyWithT(t, func(collect *assert.CollectT) { | ||
stdout, err := curlFQDN() | ||
assert.NoError(t, err) | ||
t.Logf("Response of curl to FQDN: %s", stdout) | ||
}, 2*time.Second, 100*time.Millisecond, "trying to curl the FQDN: ", testFQDN) | ||
|
||
// confirm that the FQDN resolves to the expected IP address and store it to simulate caching of this IP associated with the FQDN. | ||
t.Logf("Resolving FQDN to simulate caching the current IP inside Toolbox Pod...") | ||
resolvedIP, err := data.runDNSQuery(toolboxPodName, toolboxContainerName, data.testNamespace, testFQDN, false, dnsServiceIP) | ||
fqdnIP := resolvedIP.String() | ||
require.NoError(t, err, "failed to resolve FQDN to an IP from toolbox Pod") | ||
require.Equalf(t, agnHostPodOneIP, fqdnIP, "The IP set against the FQDN in the DNS server should be the same, but got %s instead of %s", fqdnIP, agnHostPodOneIP) | ||
t.Logf("Successfully received the expected IP %s using the dig command against the FQDN", fqdnIP) | ||
|
||
// update the IP address mapped to the FQDN in the custom DNS ConfigMap. | ||
t.Logf("Updating host mapping in DNS server config to use new IP: %s", agnHostPodTwoIP) | ||
customDnsConfigMap.Data = createDnsConfig(t, map[string]string{agnHostPodTwoIP: testFQDN}, dnsTTL) | ||
require.NoError(t, data.UpdateConfigMap(customDnsConfigMap), "failed to update configmap with new IP") | ||
t.Logf("Successfully updated DNS ConfigMap with new IP: %s", agnHostPodTwoIP) | ||
|
||
// try to trigger an immediate refresh of the configmap by setting annotations in custom DNS server Pod, this way | ||
// we try to bypass the kubelet sync period which may be as long as (1 minute by default) + TTL of ConfigMaps. | ||
// Ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#mounted-configmaps-are-updated-automatically | ||
require.NoError(t, data.setPodAnnotation(data.testNamespace, "custom-dns-server", "test.antrea.io/random-value", | ||
randSeq(8)), "failed to update custom DNS Pod annotation.") | ||
|
||
curlTarget = fqdnIP | ||
// finally verify that Curling the previously cached IP fails after DNS update. | ||
// The wait time here should be slightly longer than the reload value specified in the custom DNS configuration. | ||
assert.EventuallyWithT(t, func(collectT *assert.CollectT) { | ||
t.Logf("Trying to curl the existing cached IP of the domain: %s", fqdnIP) | ||
stdout, err := curlFQDN() | ||
if err != nil { | ||
t.Logf("Curling the cached IP failed") | ||
} else { | ||
t.Logf("Response of curl to cached IP: %+v", stdout) | ||
} | ||
assert.Error(collectT, err) | ||
}, 10*time.Second, 1*time.Second) | ||
} | ||
|
||
// setDnsServerAddressInAntrea sets or resets the custom DNS server IP address in Antrea configMap. | ||
func setDnsServerAddressInAntrea(t *testing.T, data *TestData, dnsServiceIP string) { | ||
agentChanges := func(config *agentconfig.AgentConfig) { | ||
config.DNSServerOverride = dnsServiceIP | ||
} | ||
err := data.mutateAntreaConfigMap(nil, agentChanges, false, true) | ||
require.NoError(t, err, "Error when setting up custom DNS server IP in Antrea configmap") | ||
|
||
if dnsServiceIP == "" { | ||
t.Logf("Removing DNS server IP from antrea agent as part of teardown") | ||
} else { | ||
t.Logf("DNS server value set to %s in antrea \n", dnsServiceIP) | ||
} | ||
|
||
} | ||
|
||
// createFqdnPolicyInNamespace creates an FQDN policy in the specified namespace. | ||
func createFqdnPolicyInNamespace(t *testing.T, data *TestData, testFQDN string, fqdnPolicyName, customDnsLabelValue, fqdnPodSelectorLabelValue string) { | ||
podSelectorLabel := map[string]string{ | ||
"app": fqdnPodSelectorLabelValue, | ||
} | ||
port := int32(80) | ||
udpPort := int32(53) | ||
builder := &utils.AntreaNetworkPolicySpecBuilder{} | ||
builder = builder.SetName(data.testNamespace, fqdnPolicyName). | ||
SetTier(defaultTierName). | ||
SetPriority(1.0). | ||
SetAppliedToGroup([]utils.ANNPAppliedToSpec{{PodSelector: podSelectorLabel}}) | ||
builder.AddFQDNRule(testFQDN, utils.ProtocolTCP, &port, nil, nil, "AllowForFQDN", nil, | ||
crdv1beta1.RuleActionAllow) | ||
builder.AddEgress(utils.ProtocolUDP, &udpPort, nil, nil, nil, nil, | ||
nil, nil, nil, nil, map[string]string{"app": customDnsLabelValue}, | ||
nil, nil, nil, nil, | ||
nil, nil, crdv1beta1.RuleActionAllow, "", "AllowDnsQueries") | ||
builder.AddEgress(utils.ProtocolTCP, nil, nil, nil, nil, nil, | ||
nil, nil, nil, nil, nil, | ||
nil, nil, nil, nil, | ||
nil, nil, crdv1beta1.RuleActionReject, "", "DropAllRemainingTraffic") | ||
|
||
annp, err := data.CreateOrUpdateANNP(builder.Get()) | ||
require.NoError(t, err, "error while deploying antrea policy") | ||
require.NoError(t, data.waitForANNPRealized(t, annp.Namespace, annp.Name, 10*time.Second)) | ||
} | ||
|
||
// createToolBoxPod creates the toolbox Pod with custom DNS settings for test purpose. | ||
func createToolboxPod(t *testing.T, data *TestData, dnsServiceIP string) { | ||
mutateSpecForAddingCustomDNS := func(pod *corev1.Pod) { | ||
pod.Spec.DNSPolicy = corev1.DNSNone | ||
if pod.Spec.DNSConfig == nil { | ||
pod.Spec.DNSConfig = &corev1.PodDNSConfig{} | ||
} | ||
pod.Spec.DNSConfig.Nameservers = []string{dnsServiceIP} | ||
|
||
} | ||
require.NoError(t, NewPodBuilder(toolboxPodName, data.testNamespace, ToolboxImage). | ||
WithLabels(map[string]string{"app": "fqdn-cache-test"}). | ||
WithContainerName(toolboxContainerName). | ||
WithMutateFunc(mutateSpecForAddingCustomDNS). | ||
Create(data)) | ||
require.NoError(t, data.podWaitForRunning(defaultTimeout, toolboxPodName, data.testNamespace)) | ||
} | ||
|
||
// createHttpAgnHostPod creates an agnHost Pod that serves HTTP requests and returns the IP of Pod created. | ||
func createHttpAgnHostPod(t *testing.T, data *TestData) *PodIPs { | ||
const ( | ||
agnHostPort = 80 | ||
agnHostPodNamePreFix = "agnhost-" | ||
) | ||
podName := randName(agnHostPodNamePreFix) | ||
args := []string{"netexec", "--http-port=" + strconv.Itoa(agnHostPort)} | ||
ports := []corev1.ContainerPort{ | ||
{ | ||
Name: "http", | ||
ContainerPort: agnHostPort, | ||
Protocol: corev1.ProtocolTCP, | ||
}, | ||
} | ||
|
||
require.NoError(t, NewPodBuilder(podName, data.testNamespace, agnhostImage). | ||
WithArgs(args). | ||
WithPorts(ports). | ||
WithLabels(map[string]string{"app": "agnhost"}). | ||
Create(data)) | ||
podIPs, err := data.podWaitForIPs(defaultTimeout, podName, data.testNamespace) | ||
require.NoError(t, err) | ||
return podIPs | ||
} | ||
|
||
// createDnsPod creates the CoreDNS Pod configured to use the custom DNS ConfigMap. | ||
func createCustomDnsPod(t *testing.T, data *TestData, configName string) { | ||
volume := []corev1.Volume{ | ||
{ | ||
Name: "config-volume", | ||
VolumeSource: corev1.VolumeSource{ | ||
ConfigMap: &corev1.ConfigMapVolumeSource{ | ||
LocalObjectReference: corev1.LocalObjectReference{ | ||
Name: configName, | ||
}, | ||
Items: []corev1.KeyToPath{ | ||
{ | ||
Key: "Corefile", | ||
Path: "Corefile", | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
} | ||
|
||
volumeMount := []corev1.VolumeMount{ | ||
{ | ||
Name: "config-volume", | ||
MountPath: "/etc/coredns", | ||
}, | ||
} | ||
|
||
require.NoError(t, NewPodBuilder("custom-dns-server", data.testNamespace, "coredns/coredns:1.11.3"). | ||
WithLabels(map[string]string{"app": "custom-dns"}). | ||
WithContainerName("coredns"). | ||
WithArgs([]string{"-conf", "/etc/coredns/Corefile"}). | ||
AddVolume(volume).AddVolumeMount(volumeMount). | ||
Create(data)) | ||
require.NoError(t, data.podWaitForRunning(defaultTimeout, "custom-dns-server", data.testNamespace)) | ||
} | ||
|
||
// createDnsConfig generates a DNS configuration for the specified IP address and domain name. | ||
func createDnsConfig(t *testing.T, hosts map[string]string, ttl int) map[string]string { | ||
const coreFileTemplate = `lfx.test:53 { | ||
errors | ||
log | ||
health | ||
hosts { | ||
{{ range $IP, $FQDN := .Hosts }}{{ $IP }} {{ $FQDN }}{{ end }} | ||
no_reverse | ||
pods verified | ||
ttl {{ .TTL }} | ||
} | ||
loop | ||
reload 2s | ||
}` | ||
|
||
generateConfigData := func() (string, error) { | ||
|
||
data := struct { | ||
Hosts map[string]string | ||
TTL int | ||
}{ | ||
Hosts: hosts, | ||
TTL: ttl, | ||
} | ||
|
||
tmpl, err := template.New("configMapData").Parse(coreFileTemplate) | ||
if err != nil { | ||
return "", err | ||
} | ||
var output bytes.Buffer | ||
err = tmpl.Execute(&output, data) | ||
if err != nil { | ||
return "", err | ||
} | ||
return strings.TrimSpace(output.String()), nil | ||
} | ||
|
||
configMapData, err := generateConfigData() | ||
require.NoError(t, err, "error processing configData template for DNS") | ||
configData := map[string]string{ | ||
"Corefile": configMapData, | ||
} | ||
|
||
return configData | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure we would want a dedicated file for this test (we could have it in antreapolicy_test.go), but that can wait until we are a bit further in the review process.