<commit_before>/*
 * This file is part of the kubevirt project
 *
 * 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.
 *
 * Copyright 2022 Red Hat, Inc.
 *
 */

package network

import (
	"fmt"
	"time"

	expect "github.com/google/goexpect"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	k8sv1 "k8s.io/api/core/v1"

	v1 "kubevirt.io/api/core/v1"
	"kubevirt.io/client-go/kubecli"

	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
	"kubevirt.io/kubevirt/tests"
	"kubevirt.io/kubevirt/tests/console"
	"kubevirt.io/kubevirt/tests/flags"
	"kubevirt.io/kubevirt/tests/framework/checks"
	"kubevirt.io/kubevirt/tests/libnet"
	"kubevirt.io/kubevirt/tests/libvmi"
	"kubevirt.io/kubevirt/tests/util"
)

var _ = SIGDescribe("[Serial] Passt", func() {
	var err error
	var virtClient kubecli.KubevirtClient

	BeforeEach(func() {
		checks.SkipTestIfNoFeatureGate(virtconfig.PasstGate)
	})

	BeforeEach(func() {
		virtClient, err = kubecli.GetKubevirtClient()
		util.PanicOnError(err)
	})

	Context("VirtualMachineInstance with passt binding mechanism", func() {

		It("should report the IP to the status", func() {
			vmi := libvmi.NewAlpineWithTestTooling(
				withPasstInterfaceWithPort(),
				libvmi.WithNetwork(v1.DefaultPodNetwork()),
			)

			vmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
			Expect(err).ToNot(HaveOccurred())
			vmi = tests.WaitUntilVMIReady(vmi, console.LoginToAlpine)

			Expect(vmi.Status.Interfaces).To(HaveLen(1))
			Expect(vmi.Status.Interfaces[0].IPs).NotTo(BeEmpty())
			Expect(vmi.Status.Interfaces[0].IP).NotTo(BeEmpty())
		})

		Context("should allow regular network connection", func() {
			Context("should have client server connectivity", func() {
				var clientVMI *v1.VirtualMachineInstance
				var serverVMI *v1.VirtualMachineInstance

				startServerVMI := func(ports []v1.Port) {
					serverVMI = libvmi.NewAlpineWithTestTooling(
						libvmi.WithInterface(libvmi.InterfaceDeviceWithPasstBinding(ports...)),
						libvmi.WithNetwork(v1.DefaultPodNetwork()),
						withPasstExtendedResourceMemory(ports...),
					)

					serverVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(serverVMI)
					Expect(err).ToNot(HaveOccurred())
					serverVMI = tests.WaitForSuccessfulVMIStartIgnoreWarnings(serverVMI)
					Expect(console.LoginToAlpine(serverVMI)).To(Succeed())
				}

				Context("TCP", func() {
					checkConnectionToServer := func(serverIP string, port int, expectSuccess bool) []expect.Batcher {
						expectResult := console.ShellFail
						if expectSuccess {
							expectResult = console.ShellSuccess
						}

						clientCommand := fmt.Sprintf("echo test | nc %s %d -i 1 -w 1 1> /dev/null\n", serverIP, port)

						return []expect.Batcher{
							&expect.BSnd{S: "\n"},
							&expect.BExp{R: console.PromptExpression},
							&expect.BSnd{S: clientCommand},
							&expect.BExp{R: console.PromptExpression},
							&expect.BSnd{S: tests.EchoLastReturnValue},
							&expect.BExp{R: expectResult},
						}
					}

					verifyClientServerConnectivity := func(clientVMI *v1.VirtualMachineInstance, serverVMI *v1.VirtualMachineInstance, tcpPort int, ipFamily k8sv1.IPFamily) error {
						serverIP := libnet.GetVmiPrimaryIPByFamily(serverVMI, ipFamily)
						err := libnet.PingFromVMConsole(clientVMI, serverIP)
						if err != nil {
							return err
						}

						By("Connecting from the client VM")
						err = console.SafeExpectBatch(clientVMI, checkConnectionToServer(serverIP, tcpPort, true), 30)
						if err != nil {
							return err
						}

						return nil
					}

					startClientVMI := func() {
						clientVMI = libvmi.NewAlpineWithTestTooling(
							withPasstInterfaceWithPort(),
							libvmi.WithNetwork(v1.DefaultPodNetwork()),
						)

						clientVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(clientVMI)
						Expect(err).ToNot(HaveOccurred())
						clientVMI = tests.WaitForSuccessfulVMIStartIgnoreWarnings(clientVMI)
						Expect(console.LoginToAlpine(clientVMI)).To(Succeed())
					}
					DescribeTable("Client server connectivity", func(ports []v1.Port, tcpPort int, ipFamily k8sv1.IPFamily) {
						libnet.SkipWhenClusterNotSupportIPFamily(virtClient, ipFamily)

						By("starting a client VMI")
						startClientVMI()

						By("starting a server VMI")
						startServerVMI(ports)

						By("starting a TCP server")
						tests.StartTCPServer(serverVMI, tcpPort, console.LoginToAlpine)

						Expect(verifyClientServerConnectivity(clientVMI, serverVMI, tcpPort, ipFamily)).To(Succeed())

						if len(ports) != 0 {
							By("starting a TCP server on a port not specified on the VM spec")
							vmPort := int(ports[0].Port)
							serverIP := libnet.GetVmiPrimaryIPByFamily(serverVMI, ipFamily)

							tests.StartTCPServer(serverVMI, vmPort+1, console.LoginToAlpine)

							By("Connecting from the client VM to a port not specified on the VM spec")
							Expect(console.SafeExpectBatch(clientVMI, checkConnectionToServer(serverIP, tcpPort+1, true), 30)).To(Not(Succeed()))
						}
					},
						Entry("with a specific port number [IPv4]", []v1.Port{{Name: "http", Port: 8080, Protocol: "TCP"}}, 8080, k8sv1.IPv4Protocol),
						Entry("without a specific port number [IPv4]", []v1.Port{}, 8080, k8sv1.IPv4Protocol),
						Entry("with a specific port number [IPv6]", []v1.Port{{Name: "http", Port: 8080, Protocol: "TCP"}}, 8080, k8sv1.IPv6Protocol),
						Entry("without a specific port number [IPv6]", []v1.Port{}, 8080, k8sv1.IPv6Protocol),
					)
				})

				Context("UDP", func() {
					startAndVerifyUDPClient := func(vmi *v1.VirtualMachineInstance, serverIP string, serverPort int, ipFamily k8sv1.IPFamily) error {<commit_msg>passt,e2e: test connection to lower port (<1024)<commit_after>/*
 * This file is part of the kubevirt project
 *
 * 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.
 *
 * Copyright 2022 Red Hat, Inc.
 *
 */

package network

import (
	"fmt"
	"time"

	expect "github.com/google/goexpect"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	k8sv1 "k8s.io/api/core/v1"

	v1 "kubevirt.io/api/core/v1"
	"kubevirt.io/client-go/kubecli"

	virtconfig "kubevirt.io/kubevirt/pkg/virt-config"
	"kubevirt.io/kubevirt/tests"
	"kubevirt.io/kubevirt/tests/console"
	"kubevirt.io/kubevirt/tests/flags"
	"kubevirt.io/kubevirt/tests/framework/checks"
	"kubevirt.io/kubevirt/tests/libnet"
	"kubevirt.io/kubevirt/tests/libvmi"
	"kubevirt.io/kubevirt/tests/util"
)

var _ = SIGDescribe("[Serial] Passt", func() {
	var err error
	var virtClient kubecli.KubevirtClient

	BeforeEach(func() {
		checks.SkipTestIfNoFeatureGate(virtconfig.PasstGate)
	})

	BeforeEach(func() {
		virtClient, err = kubecli.GetKubevirtClient()
		util.PanicOnError(err)
	})

	Context("VirtualMachineInstance with passt binding mechanism", func() {

		It("should report the IP to the status", func() {
			vmi := libvmi.NewAlpineWithTestTooling(
				withPasstInterfaceWithPort(),
				libvmi.WithNetwork(v1.DefaultPodNetwork()),
			)

			vmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)
			Expect(err).ToNot(HaveOccurred())
			vmi = tests.WaitUntilVMIReady(vmi, console.LoginToAlpine)

			Expect(vmi.Status.Interfaces).To(HaveLen(1))
			Expect(vmi.Status.Interfaces[0].IPs).NotTo(BeEmpty())
			Expect(vmi.Status.Interfaces[0].IP).NotTo(BeEmpty())
		})

		Context("should allow regular network connection", func() {
			Context("should have client server connectivity", func() {
				var clientVMI *v1.VirtualMachineInstance
				var serverVMI *v1.VirtualMachineInstance

				startServerVMI := func(ports []v1.Port) {
					serverVMI = libvmi.NewAlpineWithTestTooling(
						libvmi.WithInterface(libvmi.InterfaceDeviceWithPasstBinding(ports...)),
						libvmi.WithNetwork(v1.DefaultPodNetwork()),
						withPasstExtendedResourceMemory(ports...),
					)

					serverVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(serverVMI)
					Expect(err).ToNot(HaveOccurred())
					serverVMI = tests.WaitForSuccessfulVMIStartIgnoreWarnings(serverVMI)
					Expect(console.LoginToAlpine(serverVMI)).To(Succeed())
				}

				Context("TCP", func() {
					checkConnectionToServer := func(serverIP string, port int, expectSuccess bool) []expect.Batcher {
						expectResult := console.ShellFail
						if expectSuccess {
							expectResult = console.ShellSuccess
						}

						clientCommand := fmt.Sprintf("echo test | nc %s %d -i 1 -w 1 1> /dev/null\n", serverIP, port)

						return []expect.Batcher{
							&expect.BSnd{S: "\n"},
							&expect.BExp{R: console.PromptExpression},
							&expect.BSnd{S: clientCommand},
							&expect.BExp{R: console.PromptExpression},
							&expect.BSnd{S: tests.EchoLastReturnValue},
							&expect.BExp{R: expectResult},
						}
					}

					verifyClientServerConnectivity := func(clientVMI *v1.VirtualMachineInstance, serverVMI *v1.VirtualMachineInstance, tcpPort int, ipFamily k8sv1.IPFamily) error {
						serverIP := libnet.GetVmiPrimaryIPByFamily(serverVMI, ipFamily)
						err := libnet.PingFromVMConsole(clientVMI, serverIP)
						if err != nil {
							return err
						}

						By("Connecting from the client VM")
						err = console.SafeExpectBatch(clientVMI, checkConnectionToServer(serverIP, tcpPort, true), 30)
						if err != nil {
							return err
						}

						return nil
					}

					startClientVMI := func() {
						clientVMI = libvmi.NewAlpineWithTestTooling(
							withPasstInterfaceWithPort(),
							libvmi.WithNetwork(v1.DefaultPodNetwork()),
						)

						clientVMI, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(clientVMI)
						Expect(err).ToNot(HaveOccurred())
						clientVMI = tests.WaitForSuccessfulVMIStartIgnoreWarnings(clientVMI)
						Expect(console.LoginToAlpine(clientVMI)).To(Succeed())
					}
					DescribeTable("Client server connectivity", func(ports []v1.Port, tcpPort int, ipFamily k8sv1.IPFamily) {
						libnet.SkipWhenClusterNotSupportIPFamily(virtClient, ipFamily)

						By("starting a client VMI")
						startClientVMI()

						By("starting a server VMI")
						startServerVMI(ports)

						By("starting a TCP server")
						tests.StartTCPServer(serverVMI, tcpPort, console.LoginToAlpine)

						Expect(verifyClientServerConnectivity(clientVMI, serverVMI, tcpPort, ipFamily)).To(Succeed())

						if len(ports) != 0 {
							By("starting a TCP server on a port not specified on the VM spec")
							vmPort := int(ports[0].Port)
							serverIP := libnet.GetVmiPrimaryIPByFamily(serverVMI, ipFamily)

							tests.StartTCPServer(serverVMI, vmPort+1, console.LoginToAlpine)

							By("Connecting from the client VM to a port not specified on the VM spec")
							Expect(console.SafeExpectBatch(clientVMI, checkConnectionToServer(serverIP, tcpPort+1, true), 30)).To(Not(Succeed()))
						}
					},
						Entry("with a specific port number [IPv4]", []v1.Port{{Name: "http", Port: 8080, Protocol: "TCP"}}, 8080, k8sv1.IPv4Protocol),
						Entry("with a specific lower port number [IPv4]", []v1.Port{{Name: "http", Port: 80, Protocol: "TCP"}}, 80, k8sv1.IPv4Protocol),
						Entry("without a specific port number [IPv4]", []v1.Port{}, 8080, k8sv1.IPv4Protocol),
						Entry("with a specific port number [IPv6]", []v1.Port{{Name: "http", Port: 8080, Protocol: "TCP"}}, 8080, k8sv1.IPv6Protocol),
						Entry("without a specific port number [IPv6]", []v1.Port{}, 8080, k8sv1.IPv6Protocol),
					)
				})

				Context("UDP", func() {
					startAndVerifyUDPClient := func(vmi *v1.VirtualMachineInstance, serverIP string, serverPort int, ipFamily k8sv1.IPFamily) error {
{'fraction_non_alphanumeric': 0.12101000476417341, 'fraction_numerical': 0.015245354930919485, 'mean_word_length': 3.935344827586207, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3920476', 'n_tokens_mistral': 5096, 'n_tokens_neox': 4143, 'n_words': 865}