helpers

package
v1.15.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2024 License: Apache-2.0 Imports: 49 Imported by: 13

Documentation

Index

Constants

View Source
const (

	// CiliumPath is the path where cilium test code is located.
	CiliumPath = "/src/github.com/cilium/cilium/test"

	// K8sManifestBase tells ginkgo suite where to look for manifests
	K8sManifestBase = "k8s/manifests"

	// VM / Test suite constants.
	K8s     = "k8s"
	K8s1    = "k8s1"
	K8s2    = "k8s2"
	K8s3    = "k8s3"
	Runtime = "runtime"

	Enabled  = "enabled"
	Disabled = "disabled"
	Total    = "total"
	Public   = "public"
	Private  = "private"
	Name     = "Name"

	// CiliumAgentLabel is the label used for Cilium
	CiliumAgentLabel = "k8s-app=cilium"

	// CiliumOperatorLabel is the label used in the Cilium Operator deployment
	CiliumOperatorLabel = "io.cilium/app=operator"

	// HubbleRelayLabel is the label used for the Hubble Relay deployment
	HubbleRelayLabel = "k8s-app=hubble-relay"

	// PolicyEnforcement represents the PolicyEnforcement configuration option
	// for the Cilium agent.
	PolicyEnforcement = "PolicyEnforcement"

	// PolicyEnforcementDefault represents the default PolicyEnforcement mode
	// for Cilium.
	PolicyEnforcementDefault = "default"

	// PolicyEnforcementAlways represents the PolicyEnforcement mode
	// for Cilium in which traffic is denied by default even when no policy
	// is imported.
	PolicyEnforcementAlways = "always"

	// PolicyEnforcementNever represents the PolicyEnforcement mode
	// for Cilium in which traffic is always allowed even if there is a policy
	// selecting endpoints.
	PolicyEnforcementNever = "never"

	// CiliumDockerNetwork is the name of the Docker network which Cilium manages.
	CiliumDockerNetwork = "cilium-net"

	// HostDockerNetwork is the name of the host network driver.
	HostDockerNetwork = "host"

	// WorldDockerNetwork is the name of the docker network that is *not*
	// managed by Cilium, intended to be treated as "world" for identity
	// purposes (for policy tests).
	WorldDockerNetwork = "world"

	// Names of commonly used containers in tests.
	Httpd1      = "httpd1"
	Httpd2      = "httpd2"
	Httpd3      = "httpd3"
	App1        = "app1"
	App2        = "app2"
	App3        = "app3"
	Client      = "client"
	Server      = "server"
	Host        = "host"
	WorldHttpd1 = "WorldHttpd1"
	// Container lifecycle actions.
	Create = "create"
	Delete = "delete"

	// IP Address families.
	IPv4 = "IPv4"
	IPv6 = "IPv6"

	// LogPerm is the permission for files that are created by this framework
	// that contain logs, outputs of Cilium CLI commands, etc.
	LogPerm = os.FileMode(0666)

	OptionConntrackAccounting = "ConntrackAccounting"
	OptionConntrackLocal      = "ConntrackLocal"
	OptionDebug               = "Debug"
	OptionDropNotify          = "DropNotification"
	OptionTraceNotify         = "TraceNotification"
	OptionIngressPolicy       = "IngressPolicy"
	OptionEgressPolicy        = "EgressPolicy"
	OptionIngress             = "ingress"
	OptionEgress              = "egress"
	OptionNone                = "none"
	OptionDisabled            = "Disabled"
	OptionEnabled             = "Enabled"

	StateTerminating = "Terminating"
	StateRunning     = "Running"

	PingCount   = 5
	PingTimeout = 5

	// CurlConnectTimeout is the timeout for the connect() call that curl
	// invokes
	CurlConnectTimeout = 5

	// CurlMaxTimeout is the hard timeout. It starts when curl is invoked
	// and interrupts curl regardless of whether curl is currently
	// connecting or transferring data. CurlMaxTimeout should be at least 5
	// seconds longer than CurlConnectTimeout to provide some time to
	// actually transfer data.
	CurlMaxTimeout = 20

	DefaultNamespace       = "default"
	KubeSystemNamespace    = "kube-system"
	CiliumNamespaceDefault = KubeSystemNamespace

	TestResultsPath = "test_results/"
	RunDir          = "/var/run/cilium"
	LibDir          = "/var/lib/cilium"

	DaemonName             = "cilium"
	CiliumBugtool          = "cilium-bugtool"
	CiliumBugtoolArgs      = "--exclude-object-files"
	CiliumDockerDaemonName = "cilium-docker"
	AgentDaemon            = "cilium-agent"

	KubectlCreate = ResourceLifeCycleAction("create")
	KubectlDelete = ResourceLifeCycleAction("delete")
	KubectlApply  = ResourceLifeCycleAction("apply")

	KubectlPolicyNameLabel      = k8sConst.PolicyLabelName
	KubectlPolicyNameSpaceLabel = k8sConst.PolicyLabelNamespace

	// CiliumStableHelmChartVersion should be the chart version that points
	// to the v1.X branch
	CiliumStableHelmChartVersion = "1.14"
	CiliumStableVersion          = "v" + CiliumStableHelmChartVersion
	CiliumLatestHelmChartVersion = "1.15.0-dev"

	MonitorLogFileName = "monitor.log"

	// CiliumTestLog is the filename where the cilium logs that happens during
	// the test are saved.
	CiliumTestLog = "cilium-test.log"

	// HubbleRelayTestLog is the filename where the hubble relay logs that happens during
	// the test are saved.
	HubbleRelayTestLog = "hubble-relay-test.log"

	// CiliumOperatorTestLog is the filename where the cilium operator logs that happens during
	// the test are saved.
	CiliumOperatorTestLog = "cilium-operator-test.log"

	// FakeIPv4WorldAddress is an IP which is used in some datapath tests
	// for simulating external IPv4 connectivity.
	FakeIPv4WorldAddress = "192.168.254.254"

	// FakeIPv6WorldAddress is an IP which is used in some datapath tests
	// for simulating external IPv6 connectivity.
	FakeIPv6WorldAddress = "fdff::ff"

	// DockerBridgeIP is the IP on the docker0 bridge
	DockerBridgeIP = "172.17.0.1"

	// SecondaryIface is the name of the secondary iface which can be used to
	// communicate between nodes. The iface is used to attach bpf_netdev.o
	// to test NodePort with multiple devices.
	// Because the name is hardcoded, it cannot be used in tests which run on
	// on EKS/GKE or any other env which hasn't been provisioned with
	// test/Vagrantfile.
	SecondaryIface = "enp0s9"

	NACKreceived  = "NACK received for version" // from https://github.com/cilium/cilium/issues/4003
	RunInitFailed = "JoinEP: "                  // from https://github.com/cilium/cilium/pull/5052

	RemovingMapMsg = "Removing map to allow for property upgrade" // from https://github.com/cilium/cilium/pull/10626

	ClangErrorsMsg = " errors generated." // from https://github.com/cilium/cilium/issues/10857
	ClangErrorMsg  = "1 error generated." // from https://github.com/cilium/cilium/issues/10857

	// HelmTemplate is the location of the Helm templates to install Cilium
	HelmTemplate = "../install/kubernetes/cilium"

	// ServiceSuffix is the Kubernetes service suffix
	ServiceSuffix = "svc.cluster.local"
)
View Source
const (
	// ReservedIdentityHealth is equivalent to pkg/identity.ReservedIdentityHealth
	ReservedIdentityHealth = 4

	// ReservedIdentityHost is equivalent to pkg/identity.ReservedIdentityHost
	ReservedIdentityHost = 1
)

Re-definitions of stable constants in the API. The re-definition is on purpose to validate these values in the API. They may never change

View Source
const (
	// KubectlCmd Kubernetes controller command
	KubectlCmd = "kubectl"

	// DNSHelperTimeout is a predefined timeout value for K8s DNS commands. It
	// must be larger than 5 minutes because kubedns has a hardcoded resync
	// period of 5 minutes. We have experienced test failures because kubedns
	// needed this time to recover from a connection problem to kube-apiserver.
	// The kubedns resyncPeriod is defined at
	// https://github.com/kubernetes/dns/blob/80fdd88276adba36a87c4f424b66fdf37cd7c9a8/pkg/dns/dns.go#L53
	DNSHelperTimeout = 7 * time.Minute

	// CIIntegrationEKSChaining contains the constants to be used when running tests on EKS with aws-cni in chaining mode.
	CIIntegrationEKSChaining = "eks-chaining"

	// CIIntegrationEKS contains the constants to be used when running tests on EKS in ENI mode.
	CIIntegrationEKS = "eks"

	// CIIntegrationGKE contains the constants to be used when running tests on GKE.
	CIIntegrationGKE = "gke"

	// CIIntegrationAKS contains the constants to be used when running tests on AKS.
	CIIntegrationAKS = "aks"

	// CIIntegrationKind contains the constant to be used when running tests on kind.
	CIIntegrationKind = "kind"

	// CIIntegrationMicrok8s contains the constant to be used when running tests on microk8s.
	CIIntegrationMicrok8s = "microk8s"

	// CIIntegrationMicrok8s is the value to set CNI_INTEGRATION when running with minikube.
	CIIntegrationMinikube = "minikube"

	LogGathererSelector = "k8s-app=cilium-test-logs"
	CiliumSelector      = "k8s-app=cilium"

	IPv4NativeRoutingCIDR = "10.0.0.0/8"
	IPv6NativeRoutingCIDR = "fd02::/112"
)
View Source
const (
	// TCP_RR represents a netperf test for TCP Request/Response performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_RR = PerfTest("TCP_RR")

	// TCP_STREAM represents a netperf test for TCP throughput performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_STREAM = PerfTest("TCP_STREAM")

	// TCP_MAERTS represents a netperf test for TCP throughput performance (reverse direction of TCP_STREAM).
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_MAERTS = PerfTest("TCP_MAERTS")

	// TCP_CRR represents a netperf test that connects and sends single request/response
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	TCP_CRR = PerfTest("TCP_CRR")

	// UDP_RR represents a netperf test for UDP Request/Response performance.
	// For more information, consult : http://www.cs.kent.edu/~farrell/dist/ref/Netperf.html
	UDP_RR = PerfTest("UDP_RR")
)
View Source
const (
	// MaxRetries is the number of times that a loop should iterate until a
	// specified condition is not met
	MaxRetries = 30
)

Variables

View Source
var (
	// HelperTimeout is a predefined timeout value for commands.
	HelperTimeout = 4 * time.Minute

	// ShortCommandTimeout is a timeout for commands which should not take a
	// long time to execute.
	ShortCommandTimeout = 10 * time.Second

	// MidCommandTimeout is a timeout for commands which may take a bit longer
	// than ShortCommandTimeout, but less time than HelperTimeout to execute.
	MidCommandTimeout = 30 * time.Second

	// CiliumStartTimeout is a predefined timeout value for Cilium startup.
	CiliumStartTimeout = 100 * time.Second

	// CheckLogs newtes a new buffer where all the warnings and checks that
	// happens during the test are saved. This buffer will be printed in the
	// test output inside <checks> labels.
	CheckLogs = ginkgoext.NewWriter(new(bytes.Buffer))
)
View Source
var (
	// CiliumNamespace is where cilium should run.
	CiliumNamespace = CiliumNamespaceDefault

	// LogGathererNamespace is where log-gatherer should run. It follows cilium
	// for simplicity.
	LogGathererNamespace = CiliumNamespace
)
View Source
var (
	IsCiliumV1_8  = versioncheck.MustCompile(">=1.7.90 <1.9.0")
	IsCiliumV1_9  = versioncheck.MustCompile(">=1.8.90 <1.10.0")
	IsCiliumV1_10 = versioncheck.MustCompile(">=1.9.90 <1.11.0")
	IsCiliumV1_11 = versioncheck.MustCompile(">=1.10.90 <1.12.0")
	IsCiliumV1_12 = versioncheck.MustCompile(">=1.11.90 <1.13.0")
	IsCiliumV1_13 = versioncheck.MustCompile(">=1.12.90 <1.14.0")
	IsCiliumV1_14 = versioncheck.MustCompile(">=1.13.90 <1.15.0")
	IsCiliumV1_15 = versioncheck.MustCompile(">=1.14.90 <1.16.0")
	IsCiliumV1_16 = versioncheck.MustCompile(">=1.15.90 <1.17.0")
)
View Source
var (
	//LocalExecutorLogs is a buffer where all commands sent over ssh are saved.
	LocalExecutorLogs = ginkgoext.NewWriter(new(Buffer))
)
View Source
var (
	//SSHMetaLogs is a buffer where all commands sent over ssh are saved.
	SSHMetaLogs = ginkgoext.NewWriter(new(Buffer))
)
View Source
var UserDefinedScope string

UserDefinedScope in case that the test scope is defined by the user instead of the focus string.

Functions

func CMDSuccess

func CMDSuccess() types.GomegaMatcher

CMDSuccess return a new Matcher that expects a CmdRes is a successful run command.

func CanRunK8sVersion

func CanRunK8sVersion(ciliumVersion, k8sVersionStr string) (bool, error)

CanRunK8sVersion returns true if the givel ciliumVersion can run in the given Kubernetes version. If any version is unparsable, an error is returned.

func CiliumEndpointSliceFeatureEnabled

func CiliumEndpointSliceFeatureEnabled() bool

CiliumEndpointSliceFeatureEnabled returns true only if the environment has a kubernetes version greater than or equal to 1.21.

func CountValues

func CountValues(key string, data []string) (int, int)

CountValues returns the count of the occurrences of key in data, as well as the length of data.

func CreateLogFile

func CreateLogFile(filename string, data []byte) error

CreateLogFile creates the ReportDirectory if it is not present, writes the given data to the given filename.

func CreateReportDirectory

func CreateReportDirectory() (string, error)

CreateReportDirectory creates and returns the directory path to export all report commands that need to be run in the case that a test has failed. If the directory cannot be created it'll return an error

func CreateVM

func CreateVM(scope string) error

CreateVM creates a new vagrant server.Receives a scope which indicates the target server that needs to be created. In case of any error on vagrant [provision|up|ssh-config] error will be returned.

func CurlFail

func CurlFail(endpoint string, optionalValues ...interface{}) string

CurlFail returns the string representing the curl command with `-s` and `--fail` options enabled to curl the specified endpoint. It takes a variadic optionalValues argument. This is passed on to fmt.Sprintf() and used into the curl message. Note that `endpoint` is expected to be a format string (first argument to fmt.Sprintf()) if optionalValues are used.

func CurlFailNoStats

func CurlFailNoStats(endpoint string, optionalValues ...interface{}) string

CurlFailNoStats does the same as CurlFail() except that it does not print the stats info. See note about optionalValues on CurlFail().

func CurlTimeout

func CurlTimeout(endpoint string, timeout time.Duration, optionalValues ...interface{}) string

CurlTimeout does the same as CurlFail() except you can define the timeout. See note about optionalValues on CurlFail().

func CurlWithHTTPCode

func CurlWithHTTPCode(endpoint string, optionalValues ...interface{}) string

CurlWithHTTPCode retunrs the string representation of the curl command which only outputs the HTTP code returned by its execution against the specified endpoint. It takes a variadic optinalValues argument. This is passed on to fmt.Sprintf() and uses into the curl message. See note about optionalValues on CurlFail().

func CurlWithRetries

func CurlWithRetries(endpoint string, retries int, fail bool, optionalValues ...interface{}) string

CurlWithRetries returns the string representation of the curl command that retries the request if transient problems occur. The parameter "retries" indicates the maximum number of attempts. If flag "fail" is true, the function will call CurlFail() and add --retry flag at the end of the command and return. If flag "fail" is false, the function will generate the command with --retry flag and return. See note about optionalValues on CurlFail().

func DNSDeployment

func DNSDeployment(base string) string

DNSDeployment returns the manifest to install dns engine on the server.

func DestroyVM

func DestroyVM(scope string) error

DestroyVM destroys all running Vagrant VMs in the provided scope. It returns an error if deletion of either the VMs fails

func DoesNotExistNodeWithoutCilium

func DoesNotExistNodeWithoutCilium() bool

DoesNotExistNodeWithoutCilium is the complement function of ExistNodeWithoutCilium.

func DoesNotHaveHosts

func DoesNotHaveHosts(count int) func() bool

DoesNotHaveHosts returns a function which returns true if a CI job has less VMs than the given count.

func DoesNotRunOn419Kernel

func DoesNotRunOn419Kernel() bool

DoesNotRunOn419Kernel is the complement function of RunsOn419Kernel.

func DoesNotRunOn419OrLaterKernel

func DoesNotRunOn419OrLaterKernel() bool

DoesNotRunOn419OrLaterKernel is the complement function of RunsOn419OrLaterKernel.

func DoesNotRunOn54Kernel

func DoesNotRunOn54Kernel() bool

DoesNotRunOn54Kernel is the complement function of RunsOn54Kernel.

func DoesNotRunOn54OrLaterKernel

func DoesNotRunOn54OrLaterKernel() bool

DoesNotRunOn54OrLaterKernel is the complement function of RunsOn54OrLaterKernel

func DoesNotRunOnAKS

func DoesNotRunOnAKS() bool

DoesNotRunOnAKS is the complement function of DoesNotRunOnAKS.

func DoesNotRunOnEKS

func DoesNotRunOnEKS() bool

DoesNotRunOnEKS is the complement function of DoesNotRunOnEKS.

func DoesNotRunOnGKE

func DoesNotRunOnGKE() bool

DoesNotRunOnGKE is the complement function of DoesNotRunOnGKE.

func DoesNotRunOnNetNextKernel

func DoesNotRunOnNetNextKernel() bool

DoesNotRunOnNetNextKernel is the complement function of RunsOnNetNextKernel.

func DoesNotRunWithKubeProxyReplacement

func DoesNotRunWithKubeProxyReplacement() bool

DoesNotRunWithKubeProxyReplacement is the complement function of RunsWithKubeProxyReplacement.

func DualStackSupportBeta

func DualStackSupportBeta() bool

DualStackSupportBeta returns true if the environment has a Kubernetes version that has support for k8s DualStack beta API types.

func DualStackSupported

func DualStackSupported() bool

DualStackSupported returns whether the current environment has DualStack IPv6 enabled or not for the cluster.

func ExistNodeWithoutCilium

func ExistNodeWithoutCilium() bool

ExistNodeWithoutCilium returns true if there is a node in a cluster which does not run Cilium.

func Fail

func Fail(description string, callerSkip ...int)

Fail is a Ginkgo failure handler which raises a SIGSTOP for the test process when there is a failure, so that developers can debug the live environment. It is only triggered if the developer provides a commandline flag.

func GenerateNamespaceForTest

func GenerateNamespaceForTest(seed string) string

GenerateNamespaceForTest generates a namespace based off of the current test which is running. Note: Namespaces can only be 63 characters long (to comply with DNS). We ensure that the namespace here is shorter than that, but keep it unique by prefixing with timestamp

func GetAppPods

func GetAppPods(apps []string, namespace string, kubectl *Kubectl, appFmt string) map[string]string

GetAppPods fetches app pod names for a namespace. For Http based tests, we identify pods with format id=<pod_name>, while for Kafka based tests, we identify pods with the format app=<pod_name>.

func GetBPFPacketsCount

func GetBPFPacketsCount(kubectl *Kubectl, pod, reason, direction string) (int, error)

GetBPFPacketsCount returns the number of packets for a given drop reason and direction by parsing BPF metrics.

func GetBadLogMessages

func GetBadLogMessages() map[string][]string

GetBadLogMessages returns a deep copy of badLogMessages to allow removing messages for specific tests.

func GetCurrentIntegration

func GetCurrentIntegration() string

GetCurrentIntegration returns CI integration set up to run against Cilium.

func GetCurrentK8SEnv

func GetCurrentK8SEnv() string

GetCurrentK8SEnv returns the value of K8S_VERSION from the OS environment.

func GetFirstNodeWithoutCilium

func GetFirstNodeWithoutCilium() string

GetFirstNodeWithoutCilium returns the first node that does not run Cilium. It's the responsibility of the caller to check that there are nodes without Cilium.

func GetIPv4AddrForIface

func GetIPv4AddrForIface(kubectl *Kubectl, nodeName, iface string) (string, error)

func GetIPv6AddrForIface

func GetIPv6AddrForIface(kubectl *Kubectl, nodeName, iface string) (string, error)

func GetKubectlPath

func GetKubectlPath() string

func GetLatestImageVersion

func GetLatestImageVersion() string

GetLatestImageVersion infers which docker tag should be used

func GetNodesWithoutCilium

func GetNodesWithoutCilium() []string

GetNodesWithoutCilium returns a slice of names for nodes that do not run Cilium.

func GetScope

func GetScope() (string, error)

GetScope returns the scope for the currently running test.

func GetScopeWithVersion

func GetScopeWithVersion() string

GetScopeWithVersion returns the scope of the running test. If the scope is k8s, then it returns k8s scope along with the version of k8s that is running.

func GetVagrantSSHMetadata

func GetVagrantSSHMetadata(vmName string) ([]byte, error)

GetVagrantSSHMetadata returns a string containing the output of `vagrant ssh-config` for the provided Vagrant of name vmName. Returns an error if `vagrant ssh-config` fails to execute.

func HoldEnvironment

func HoldEnvironment(description ...string)

HoldEnvironment prints the current test status, then pauses the test execution. Developers who are writing tests may wish to invoke this function directly from test code to assist troubleshooting and test development.

func Init

func Init()

func IsIntegration

func IsIntegration(integration string) bool

IsIntegration returns true when integration matches the configuration of this test run

func IsNodeWithoutCilium

func IsNodeWithoutCilium(node string) bool

IsNodeWithoutCilium returns true if node node doesn't run Cilium.

func IsRunningOnJenkins

func IsRunningOnJenkins() bool

IsRunningOnJenkins detects if the currently running Ginkgo application is most likely running in a Jenkins environment. Returns true if certain environment variables that are present in Jenkins jobs are set, false otherwise.

func K8s1VMName

func K8s1VMName() string

K8s1VMName is the name of the Kubernetes master node when running K8s tests.

func K8s2VMName

func K8s2VMName() string

K8s2VMName is the name of the Kubernetes worker node when running K8s tests.

func MakeUID

func MakeUID() string

MakeUID returns a randomly generated string.

func ManifestGet

func ManifestGet(base, manifestFilename string) string

ManifestGet returns the full path of the given manifest corresponding to the Kubernetes version being tested, if such a manifest exists, if not it returns the global manifest file. The paths are checked in order: 1- base_path/integration/filename 2- base_path/k8s_version/integration/filename 3- base_path/k8s_version/filename 4- base_path/filename

func NativeRoutingCIDR

func NativeRoutingCIDR() string

func Netcat

func Netcat(endpoint string, optionalValues ...interface{}) string

Netcat returns the string representing the netcat command to the specified endpoint. It takes a variadic optionalValues arguments, This is passed to fmt.Sprintf uses in the netcat message. See note about optionalValues on CurlFail().

func Netperf

func Netperf(endpoint string, perfTest PerfTest, options string) string

Netperf returns the string representing the netperf command to use when testing connectivity between endpoints.

func OpenSSLShowCerts

func OpenSSLShowCerts(host string, port uint16, serverName string) string

OpenSSLShowCerts retrieve the TLS certificate presented at the given host:port when serverName is requested. The openssl cli is available in the Cilium pod.

func Ping

func Ping(endpoint string) string

Ping returns the string representing the ping command to ping the specified endpoint.

func Ping6

func Ping6(endpoint string) string

Ping6 returns the string representing the ping6 command to ping6 the specified endpoint.

func Ping6WithID

func Ping6WithID(endpoint string, icmpID uint16) string

func PingWithCount

func PingWithCount(endpoint string, count uint) string

PingWithCount returns the string representing the ping command to ping the specified endpoint, and takes a custom number of requests to send.

func PingWithID

func PingWithID(endpoint string, icmpID uint16) string

func PythonBind

func PythonBind(addr string, port uint16, proto string) string

PythonBind returns the string representing a python3 command which will try to bind a socket on the given address and port. Python is available in the log-gatherer pod.

func ReadFile

func ReadFile(path string) string

ReadFile returns the string representing a cat command to read the file at the give path.

func RenderTemplate

func RenderTemplate(tmplt string) (*bytes.Buffer, error)

RenderTemplate renders a text/template string into a buffer. Returns eturn an error if the template cannot be validated.

func RepeatUntilTrue

func RepeatUntilTrue(body func() bool, config *TimeoutConfig) error

RepeatUntilTrue repeatedly calls body until body returns true or the timeout expires

func RepeatUntilTrueDefaultTimeout

func RepeatUntilTrueDefaultTimeout(body func() bool) error

RepeatUntilTrueDefaultTimeout calls RepeatUntilTrue with the default timeout HelperTimeout

func ReportDirectoryPath

func ReportDirectoryPath() string

ReportDirectoryPath determines the directory path for exporting report commands in the case of test failure.

func RunsOn419Kernel

func RunsOn419Kernel() bool

RunsOn419Kernel checks whether a test case is running on the 4.19 kernel.

func RunsOn419OrLaterKernel

func RunsOn419OrLaterKernel() bool

RunsOn419OrLaterKernel checks whether a test case is running on 4.19.x (x > 57) or later kernel

func RunsOn54Kernel

func RunsOn54Kernel() bool

RunsOn54Kernel checks whether a test case is running on the 5.4 kernel.

func RunsOn54OrLaterKernel

func RunsOn54OrLaterKernel() bool

RunsOn54OrLaterKernel checks whether a test case is running on 5.4 or later kernel

func RunsOnAKS

func RunsOnAKS() bool

RunsOnAKS returns true if the tests are running on AKS.

func RunsOnEKS

func RunsOnEKS() bool

RunsOnEKS returns true if the tests are running on EKS.

func RunsOnGKE

func RunsOnGKE() bool

RunsOnGKE returns true if the tests are running on GKE.

func RunsOnJenkins

func RunsOnJenkins() bool

func RunsOnNetNextKernel

func RunsOnNetNextKernel() bool

RunsOnNetNextKernel checks whether a test case is running on the net-next kernel (depending on the image, it's the latest kernel either from net-next.git or bpf-next.git tree).

func RunsWithHostFirewall

func RunsWithHostFirewall() bool

RunsWithHostFirewall returns true is Cilium runs with the host firewall enabled.

func RunsWithKubeProxy

func RunsWithKubeProxy() bool

RunsWithKubeProxy returns true if cilium runs together with k8s' kube-proxy.

func RunsWithKubeProxyReplacement

func RunsWithKubeProxyReplacement() bool

RunsWithKubeProxyReplacement returns true if the kernel supports our kube-proxy replacement. Note that kube-proxy may still be running alongside Cilium.

func RunsWithoutKubeProxy

func RunsWithoutKubeProxy() bool

RunsWithoutKubeProxy is the complement function of RunsWithKubeProxy.

func SSHAgent

func SSHAgent() ssh.AuthMethod

SSHAgent returns the ssh.Authmethod using the Public keys. Returns nil if a connection to SSH_AUTH_SHOCK does not succeed.

func SkipK8sVersions

func SkipK8sVersions(k8sVersions string) bool

SkipK8sVersions returns true if the current K8s versions matched the constraints passed in argument.

func SkipQuarantined

func SkipQuarantined() bool

SkipQuarantined returns whether test under quarantine should be skipped

func SkipRaceDetectorEnabled

func SkipRaceDetectorEnabled() bool

SkipRaceDetectorEnabled returns whether tests failing with race detector enabled should be skipped.

func Sleep

func Sleep(delay time.Duration)

Sleep sleeps for the specified duration in seconds

func Status

func Status(key string) map[string]string

Status returns a mapping of Vagrant VM name to its status

func SuperNetperf

func SuperNetperf(sessions int, endpoint string, perfTest PerfTest, options string) string

SuperNetperf returns the string representing the super_netperf command to use when testing connectivity between endpoints.

func SupportIPv6Connectivity

func SupportIPv6Connectivity() bool

SupportIPv6Connectivity returns true if the CI environment supports IPv6 connectivity across pods.

func SupportIPv6ToOutside

func SupportIPv6ToOutside() bool

SupportIPv6ToOutside returns true if the CI environment supports IPv6 connectivity to the outside world.

func TimestampFilename

func TimestampFilename(name string) string

TimestampFilename appends a "timestamp" to the name. The goal is to make this name unique to avoid collisions in tests. The nanosecond precision should be more than enough for that.

func WithContext

func WithContext(ctx context.Context, f func(ctx context.Context) (bool, error), freq time.Duration) error

WithContext executes body with the given frequency. The function f is executed until bool returns true or the given context signalizes Done. `f` should stop if context is canceled.

func WithTimeout

func WithTimeout(body func() bool, msg string, config *TimeoutConfig) error

WithTimeout executes body using the time interval specified in config until the timeout in config is reached. Returns an error if the timeout is exceeded for body to execute successfully.

func WriteOrAppendToFile

func WriteOrAppendToFile(filename string, data []byte, perm os.FileMode) error

WriteOrAppendToFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm; otherwise WriteFile appends the data to the file

func WriteToReportFile

func WriteToReportFile(data []byte, filename string) error

WriteToReportFile writes data to filename. It appends to existing files.

func Wrk

func Wrk(endpoint string) string

Wrk runs a standard wrk test for http

Types

type ApplyOptions

type ApplyOptions struct {
	FilePath  string
	Namespace string
	Force     bool
	DryRun    bool
	Output    string
	Piped     string
}

ApplyOptions stores options for kubectl apply command

type BeSuccesfulMatcher

type BeSuccesfulMatcher struct{}

BeSuccesfulMatcher a new Ginkgo matcher for CmdRes struct

func (*BeSuccesfulMatcher) FailureMessage

func (matcher *BeSuccesfulMatcher) FailureMessage(actual interface{}) (message string)

FailureMessage it returns a pretty printed error message in the case of the command was not successful.

func (*BeSuccesfulMatcher) Match

func (matcher *BeSuccesfulMatcher) Match(actual interface{}) (success bool, err error)

Match validates that the given interface will be a `*CmdRes` struct and it was successful. In case of not a valid CmdRes will return an error. If the command was not successful it returns false.

func (*BeSuccesfulMatcher) NegatedFailureMessage

func (matcher *BeSuccesfulMatcher) NegatedFailureMessage(actual interface{}) (message string)

NegatedFailureMessage returns a pretty printed error message in case of the command is tested with a negative

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

A Buffer is a variable-sized buffer of bytes with Read and Write methods. The zero value for Buffer is an empty buffer ready to use.

func (*Buffer) Bytes

func (buf *Buffer) Bytes() []byte

Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Read, Write, Reset, or Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

func (*Buffer) Len

func (buf *Buffer) Len() int

Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

func (*Buffer) Reset

func (buf *Buffer) Reset()

Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

func (*Buffer) String

func (buf *Buffer) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

To build strings more efficiently, see the strings.Builder type.

func (*Buffer) Write

func (buf *Buffer) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

type CiliumDeployFunc

type CiliumDeployFunc func(kubectl *Kubectl, ciliumFilename string, options map[string]string)

CiliumDeployFunc is the function to use for deploying cilium.

type CmdRes

type CmdRes struct {
	// contains filtered or unexported fields
}

CmdRes contains a variety of data which results from running a command.

func (*CmdRes) ByLines

func (res *CmdRes) ByLines() []string

ByLines returns res's stdout split by the newline character and, if the stdout contains `\r\n`, it will be split by carriage return and new line characters.

func (*CmdRes) CombineOutput

func (res *CmdRes) CombineOutput() *bytes.Buffer

CombineOutput returns the combined output of stdout and stderr for res.

func (*CmdRes) CountLines

func (res *CmdRes) CountLines() int

CountLines return the number of lines in the stdout of res.

func (*CmdRes) ExpectContains

func (res *CmdRes) ExpectContains(data string, optionalDescription ...interface{}) bool

ExpectContains asserts a string into the stdout of the response of executed command. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectContainsFilterLine

func (res *CmdRes) ExpectContainsFilterLine(filter, expected string, optionalDescription ...interface{}) bool

ExpectContainsFilterLine applies the provided JSONPath filter to each line of stdout of the executed command and asserts that the expected string matches at least one of the lines. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectDoesNotContain

func (res *CmdRes) ExpectDoesNotContain(data string, optionalDescription ...interface{}) bool

ExpectDoesNotContain asserts that a string is not contained in the stdout of the executed command. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectDoesNotContainFilterLine

func (res *CmdRes) ExpectDoesNotContainFilterLine(filter, expected string, optionalDescription ...interface{}) bool

ExpectDoesNotContainFilterLine applies the provided JSONPath filter to each line of stdout of the executed command and asserts that the expected string does not matches any of the lines. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectDoesNotMatchRegexp

func (res *CmdRes) ExpectDoesNotMatchRegexp(regexp string, optionalDescription ...interface{}) bool

ExpectDoesNotMatchRegexp asserts that the stdout of the executed command doesn't match the regexp. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectEqual

func (res *CmdRes) ExpectEqual(expected string, optionalDescription ...interface{}) bool

ExpectEqual asserts whether cmdRes.Output().String() and expected are equal. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectFail

func (res *CmdRes) ExpectFail(optionalDescription ...interface{}) bool

ExpectFail asserts whether res failed to execute. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectFailWithError

func (res *CmdRes) ExpectFailWithError(data string, optionalDescription ...interface{}) bool

ExpectFailWithError asserts whether res failed to execute with the error output containing the given data. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectMatchesRegexp

func (res *CmdRes) ExpectMatchesRegexp(regexp string, optionalDescription ...interface{}) bool

ExpectMatchesRegexp asserts that the stdout of the executed command matches the regexp. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) ExpectSuccess

func (res *CmdRes) ExpectSuccess(optionalDescription ...interface{}) bool

ExpectSuccess asserts whether res executed successfully. It accepts an optional parameter that can be used to annotate failure messages.

func (*CmdRes) Filter

func (res *CmdRes) Filter(filter string) (*FilterBuffer, error)

Filter returns the contents of res's stdout filtered using the provided JSONPath filter in a buffer. Returns an error if the unmarshalling of the contents of res's stdout fails.

func (*CmdRes) FilterLines

func (res *CmdRes) FilterLines(filter string) ([]FilterBuffer, error)

FilterLines works like Filter, but applies the JSONPath filter to each line separately and returns returns a buffer for each line. An error is returned only for the first line which cannot be unmarshalled.

func (*CmdRes) FilterLinesJSONPath

func (res *CmdRes) FilterLinesJSONPath(filter *jsonpath.JSONPath) ([]FilterBuffer, error)

FilterLinesJSONPath decodes each line as JSON and applies the JSONPath filter to each line. Returns an array with the result for each line.

func (*CmdRes) FindResults

func (res *CmdRes) FindResults(filter string) ([]reflect.Value, error)

FindResults filters res's stdout using the provided JSONPath filter. It returns an array of the values that match the filter, and an error if the unmarshalling of the stdout of res fails. TODO - what exactly is the need for this vs. Filter function below?

func (*CmdRes) FloatOutput

func (res *CmdRes) FloatOutput() (float64, error)

FloatOutput returns the stdout of res as a float

func (*CmdRes) GetCmd

func (res *CmdRes) GetCmd() string

GetCmd returns res's cmd.

func (*CmdRes) GetDebugMessage

func (res *CmdRes) GetDebugMessage() string

GetDebugMessage returns executed command and its output

func (*CmdRes) GetErr

func (res *CmdRes) GetErr(context string) error

GetErr returns error created from program output if command is not successful

func (*CmdRes) GetError

func (res *CmdRes) GetError() error

GetError returns the error for this CmdRes.

func (*CmdRes) GetExitCode

func (res *CmdRes) GetExitCode() int

GetExitCode returns res's exitcode.

func (*CmdRes) GetStdErr

func (res *CmdRes) GetStdErr() *CmdStreamBuffer

GetStdErr returns res's stderr.

func (*CmdRes) GetStdOut

func (res *CmdRes) GetStdOut() *CmdStreamBuffer

GetStdOut returns res's stdout.

func (*CmdRes) InRange

func (res *CmdRes) InRange(min, max int) error

InRange returns nil if res matches the expected value range or error otherwise

func (*CmdRes) IntOutput

func (res *CmdRes) IntOutput() (int, error)

IntOutput returns the stdout of res as an integer

func (*CmdRes) KVOutput

func (res *CmdRes) KVOutput() map[string]string

KVOutput returns a map of the stdout of res split based on the separator '='. For example, the following strings would be split as follows:

a=1
b=2
c=3

func (*CmdRes) OutputPrettyPrint

func (res *CmdRes) OutputPrettyPrint() string

OutputPrettyPrint returns a string with the ExitCode, stdout and stderr in a pretty format.

func (*CmdRes) Reset

func (res *CmdRes) Reset()

Reset resets res's stdout buffer to be empty.

func (*CmdRes) SendToLog

func (res *CmdRes) SendToLog(quietMode bool)

SendToLog writes to `TestLogWriter` the debug message for the running command, if the quietMode argument is true will print only the command and the exitcode.

func (*CmdRes) SingleOut

func (res *CmdRes) SingleOut() string

SingleOut returns res's stdout as a string without any newline characters

func (*CmdRes) Stderr

func (res *CmdRes) Stderr() string

Stderr returns the contents of the stderr buffer of res as a string.

func (*CmdRes) Stdout

func (res *CmdRes) Stdout() string

Stdout returns the contents of the stdout buffer of res as a string.

func (*CmdRes) Unmarshal

func (res *CmdRes) Unmarshal(data interface{}) error

Unmarshal unmarshalls res's stdout into data. It assumes that the stdout of res is in JSON format. Returns an error if the unmarshalling fails.

func (*CmdRes) WaitUntilFinish

func (res *CmdRes) WaitUntilFinish()

WaitUntilFinish waits until the command context completes correctly

func (*CmdRes) WaitUntilMatch

func (res *CmdRes) WaitUntilMatch(substr string) error

WaitUntilMatch waits until the given substring is present in the `CmdRes.stdout` If the timeout is reached it will return an error.

func (*CmdRes) WaitUntilMatchFilterLine

func (res *CmdRes) WaitUntilMatchFilterLine(filter, expected string) error

WaitUntilMatchFilterLine applies the JSONPath 'filter' to each line of `CmdRes.stdout` and waits until a line matches the 'expected' output. If helpers.HelperTimout is reached it will return an error.

func (*CmdRes) WaitUntilMatchFilterLineTimeout

func (res *CmdRes) WaitUntilMatchFilterLineTimeout(filter, expected string, timeout time.Duration) error

WaitUntilMatchFilterLineTimeout applies the JSONPath 'filter' to each line of `CmdRes.stdout` and waits until a line matches the 'expected' output. If the 'timeout' is reached it will return an error.

func (*CmdRes) WaitUntilMatchRegexp

func (res *CmdRes) WaitUntilMatchRegexp(expr string, timeout time.Duration) error

WaitUntilMatchRegexp waits until the `CmdRes.stdout` matches the given regexp. If the timeout is reached it will return an error.

func (*CmdRes) WaitUntilMatchTimeout

func (res *CmdRes) WaitUntilMatchTimeout(substr string, timeout time.Duration) error

WaitUntilMatchTimeout is the same as WaitUntilMatch but with a user-provided timeout value.

func (*CmdRes) WasSuccessful

func (res *CmdRes) WasSuccessful() bool

WasSuccessful returns true if cmd completed successfully.

type CmdStreamBuffer

type CmdStreamBuffer struct {
	*Buffer
	// contains filtered or unexported fields
}

CmdStreamBuffer is a buffer that buffers the stream output of a command.

func (*CmdStreamBuffer) ByLines

func (b *CmdStreamBuffer) ByLines() []string

ByLines returns res's stdout split by the newline character and, if the stdout contains `\r\n`, it will be split by carriage return and new line characters.

func (CmdStreamBuffer) Cmd

func (b CmdStreamBuffer) Cmd() string

Cmd returns the command that generated the stream.

func (*CmdStreamBuffer) Filter

func (b *CmdStreamBuffer) Filter(filter string) (*FilterBuffer, error)

Filter returns the contents of res's stdout filtered using the provided JSONPath filter in a buffer. Returns an error if the unmarshalling of the contents of res's stdout fails.

func (*CmdStreamBuffer) FilterLines

func (b *CmdStreamBuffer) FilterLines(filter string) ([]FilterBuffer, error)

FilterLines works like Filter, but applies the JSONPath filter to each line separately and returns returns a Buffer for each line. An error is returned only for the first line which cannot be unmarshalled.

func (*CmdStreamBuffer) FilterLinesJSONPath

func (b *CmdStreamBuffer) FilterLinesJSONPath(filter *jsonpath.JSONPath) ([]FilterBuffer, error)

FilterLinesJSONPath decodes each line as JSON and applies the JSONPath filter to each line. Returns an array with the result for each line.

func (*CmdStreamBuffer) KVOutput

func (b *CmdStreamBuffer) KVOutput() map[string]string

KVOutput returns a map of the stdout of res split based on the separator '='. For example, the following strings would be split as follows:

a=1
b=2
c=3
a=1
b=2
c=3

type Deployment

type Deployment struct {
	// contains filtered or unexported fields
}

Deployment is a deployed manifest. The deployment binds the manifest to a particular namespace and records the number of nodes the deployment is spread over.

func (*Deployment) Delete

func (d *Deployment) Delete()

Delete deletes the deployment

func (*Deployment) WaitUntilReady

func (d *Deployment) WaitUntilReady()

WaitUntilReady waits until all pods of the deployment are up and in ready state

type DeploymentManager

type DeploymentManager struct {
	// contains filtered or unexported fields
}

DeploymentManager manages a set of deployments

func NewDeploymentManager

func NewDeploymentManager() *DeploymentManager

NewDeploymentManager returns a new deployment manager

func (*DeploymentManager) DeleteAll

func (m *DeploymentManager) DeleteAll()

DeleteAll deletes all deployments which have previously been deployed using this deployment manager

func (*DeploymentManager) DeleteCilium

func (m *DeploymentManager) DeleteCilium()

DeleteCilium deletes a Cilium deployment that was previously deployed with DeployCilium()

func (*DeploymentManager) Deploy

func (m *DeploymentManager) Deploy(namespace string, manifest Manifest)

Deploy deploys a manifest using the deployment manager and stores the deployment in the manager

func (*DeploymentManager) DeployCilium

func (m *DeploymentManager) DeployCilium(options map[string]string, deploy CiliumDeployFunc)

DeployCilium deploys Cilium using the provided options and waits for it to become ready

func (*DeploymentManager) DeployRandomNamespace

func (m *DeploymentManager) DeployRandomNamespace(manifest Manifest) string

DeployRandomNamespace deploys a manifest into a random namespace using the deployment manager and stores the deployment in the manager

func (*DeploymentManager) DeployRandomNamespaceShared

func (m *DeploymentManager) DeployRandomNamespaceShared(manifest Manifest) string

DeployRandomNamespaceShared is like DeployRandomNamespace but will check if the Manifest has already been deployed in any namespace. If so, returns the namespace the existing deployment is running in. If not, the manifest is deployed using DeployRandomNamespace.

func (*DeploymentManager) SetKubectl

func (m *DeploymentManager) SetKubectl(kubectl *Kubectl)

SetKubectl sets the kubectl client to use

func (*DeploymentManager) WaitUntilReady

func (m *DeploymentManager) WaitUntilReady()

WaitUntilReady waits until all deployments managed by this manager are up and ready

type ExecOptions

type ExecOptions struct {
	SkipLog bool
}

ExecOptions options to execute Exec and ExecWithContext

type Executor

type Executor interface {
	IsLocal() bool
	CloseSSHClient()
	Exec(cmd string, options ...ExecOptions) *CmdRes
	ExecContext(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes
	ExecContextShort(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes
	ExecInBackground(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes
	ExecMiddle(cmd string, options ...ExecOptions) *CmdRes
	ExecShort(cmd string, options ...ExecOptions) *CmdRes
	ExecWithSudo(cmd string, options ...ExecOptions) *CmdRes
	ExecuteContext(ctx context.Context, cmd string, stdout io.Writer, stderr io.Writer) error
	String() string
	BasePath() string
	RenderTemplateToFile(filename string, tmplt string, perm os.FileMode) error

	Logger() *logrus.Entry
	// contains filtered or unexported methods
}

Executor executes commands

type FilterBuffer

type FilterBuffer struct {
	*bytes.Buffer
}

FilterBuffer structs that extends buffer methods

func (*FilterBuffer) ByLines

func (buf *FilterBuffer) ByLines() []string

ByLines returns buf string plit by the newline characters

func (*FilterBuffer) KVOutput

func (buf *FilterBuffer) KVOutput() map[string]string

KVOutput returns a map of the buff string split based on the separator '='. For example, the following strings would be split as follows:

a=1
b=2
c=3

type JSONParseError added in v1.15.0

type JSONParseError struct {
	// contains filtered or unexported fields
}

func (*JSONParseError) Error added in v1.15.0

func (e *JSONParseError) Error() string

type Kubectl

type Kubectl struct {
	Executor
	// contains filtered or unexported fields
}

Kubectl is a wrapper around an SSHMeta. It is used to run Kubernetes-specific commands on the node which is accessible via the SSH metadata stored in its SSHMeta.

func CreateKubectl

func CreateKubectl(vmName string, log *logrus.Entry) (k *Kubectl)

CreateKubectl initializes a Kubectl helper with the provided vmName and log It marks the test as Fail if cannot get the ssh meta information or cannot execute a `ls` on the virtual machine.

func (*Kubectl) Action

func (kub *Kubectl) Action(action ResourceLifeCycleAction, filePath string, namespace ...string) *CmdRes

Action performs the specified ResourceLifeCycleAction on the Kubernetes manifest located at path filepath in the given namespace

func (*Kubectl) AddIPRoute

func (kub *Kubectl) AddIPRoute(nodeName, subnet, gw string, replace bool) *CmdRes

AddIPRoute adds a route to a given subnet address and a gateway on a given node via the iproute2 utility suite. The function takes in a flag called replace which will convert the action to replace the route being added if another route exists and matches. This allows for idempotency as the "replace" action will not fail if another matching route exists, whereas "add" will fail.

func (*Kubectl) AddRegistryCredentials

func (kub *Kubectl) AddRegistryCredentials(cred string, registry string) error

AddRegistryCredentials adds a registry credentials secret into the cluster

func (*Kubectl) AddVXLAN

func (kub *Kubectl) AddVXLAN(nodeName, remote, dev, addr string, vxlanId int) *CmdRes

func (*Kubectl) Apply

func (kub *Kubectl) Apply(options ApplyOptions) *CmdRes

Apply applies the Kubernetes manifest located at path filepath.

func (*Kubectl) ApplyDefault

func (kub *Kubectl) ApplyDefault(filePath string) *CmdRes

ApplyDefault applies give filepath with other options set to default

func (*Kubectl) CiliumCheckReport

func (kub *Kubectl) CiliumCheckReport(ctx context.Context)

CiliumCheckReport prints a few checks on the Junit output to provide more context to users. The list of checks that prints are the following: - Number of Kubernetes and Cilium policies installed. - Policy enforcement status by endpoint. - Controller, health, kvstore status.

func (*Kubectl) CiliumClusterwidePolicyAction

func (kub *Kubectl) CiliumClusterwidePolicyAction(filepath string, action ResourceLifeCycleAction, timeout time.Duration) (string, error)

CiliumClusterwidePolicyAction applies a clusterwide policy action as described in action argument. It then wait till timeout Duration for the policy to be applied to all the cilium endpoints.

func (*Kubectl) CiliumEndpointIPv6

func (kub *Kubectl) CiliumEndpointIPv6(pod string, endpoint string) map[string]string

CiliumEndpointIPv6 returns the IPv6 address of each endpoint which matches the given endpoint selector.

func (*Kubectl) CiliumEndpointWaitReady

func (kub *Kubectl) CiliumEndpointWaitReady() error

CiliumEndpointWaitReady waits until all endpoints managed by all Cilium pod are ready. Returns an error if the Cilium pods cannot be retrieved via Kubernetes, or endpoints are not ready after a specified timeout

func (*Kubectl) CiliumEndpointsList

func (kub *Kubectl) CiliumEndpointsList(ctx context.Context, pod string) *CmdRes

CiliumEndpointsList returns the result of `cilium endpoint list` from the specified pod.

func (*Kubectl) CiliumExecContext

func (kub *Kubectl) CiliumExecContext(ctx context.Context, pod string, cmd string) *CmdRes

CiliumExecContext runs cmd in the specified Cilium pod with the given context.

func (*Kubectl) CiliumExecMustSucceed

func (kub *Kubectl) CiliumExecMustSucceed(ctx context.Context, pod, cmd string, optionalDescription ...interface{}) *CmdRes

CiliumExecMustSucceed runs cmd in the specified Cilium pod. it causes a test failure if the command was not successful.

func (*Kubectl) CiliumExecMustSucceedOnAll

func (kub *Kubectl) CiliumExecMustSucceedOnAll(ctx context.Context, cmd string, optionalDescription ...interface{})

CiliumExecMustSucceedOnAll does the same as CiliumExecMustSucceed, just that it execs cmd on all cilium-agent pods.

func (*Kubectl) CiliumExecUntilMatch

func (kub *Kubectl) CiliumExecUntilMatch(pod, cmd, substr string) error

CiliumExecUntilMatch executes the specified command repeatedly for the specified Cilium pod until the given substring is present in stdout. If the timeout is reached it will return an error.

func (*Kubectl) CiliumInstall

func (kub *Kubectl) CiliumInstall(filename string, options map[string]string) error

CiliumInstall installs Cilium with the provided Helm options.

func (*Kubectl) CiliumIsPolicyLoaded

func (kub *Kubectl) CiliumIsPolicyLoaded(pod string, policyCmd string) bool

CiliumIsPolicyLoaded returns true if the policy is loaded in the given cilium Pod. it returns false in case that the policy is not in place

func (*Kubectl) CiliumNodesWait

func (kub *Kubectl) CiliumNodesWait() (bool, error)

CiliumNodesWait waits until all nodes in the Kubernetes cluster are annotated with Cilium annotations. Its runtime is bounded by a maximum of `HelperTimeout`. When a node is annotated with said annotations, it indicates that the tunnels in the nodes are set up and that cross-node traffic can be tested. Returns an error if the timeout is exceeded for waiting for the nodes to be annotated.

func (*Kubectl) CiliumOptions

func (kub *Kubectl) CiliumOptions() map[string]string

CiliumOptions returns the most recently used set of options for installing Cilium into the cluster.

func (*Kubectl) CiliumPolicyAction

func (kub *Kubectl) CiliumPolicyAction(namespace, filepath string, action ResourceLifeCycleAction, timeout time.Duration) (string, error)

CiliumPolicyAction performs the specified action in Kubernetes for the policy stored in path filepath and waits up until timeout seconds for the policy to be applied in all Cilium endpoints. Returns an error if the policy is not imported before the timeout is exceeded.

func (*Kubectl) CiliumPolicyRevision

func (kub *Kubectl) CiliumPolicyRevision(pod string) (int, error)

CiliumPolicyRevision returns the policy revision in the specified Cilium pod. Returns an error if the policy revision cannot be retrieved.

func (*Kubectl) CiliumPreFlightCheck

func (kub *Kubectl) CiliumPreFlightCheck() error

CiliumPreFlightCheck specify that it checks that various subsystems within Cilium are in a good state. If one of the multiple preflight fails it'll return an error.

func (*Kubectl) CiliumReport

func (kub *Kubectl) CiliumReport(commands ...string)

CiliumReport report the cilium pod to the log and appends the logs for the given commands.

func (*Kubectl) CiliumServiceAdd

func (kub *Kubectl) CiliumServiceAdd(pod string, id int64, frontend string, backends []string, svcType, trafficPolicy string) error

CiliumServiceAdd adds the given service on a 'pod' running Cilium

func (*Kubectl) CiliumServiceDel

func (kub *Kubectl) CiliumServiceDel(pod string, id int64) error

CiliumServiceDel deletes the service with 'id' on a 'pod' running Cilium

func (*Kubectl) CleanNamespace

func (kub *Kubectl) CleanNamespace(namespace string)

CleanNamespace removes all artifacts from a namespace

func (*Kubectl) CleanupCiliumComponents

func (kub *Kubectl) CleanupCiliumComponents()

CleanupCiliumComponents removes all the cilium related components from the cluster, including CRDs. This means that CiliumNode resources get deleted, too. This causes any new Cilium nodes to get reassigned IP allocation pools, which may be different than before. This then causes all endpoints to fail restore and get in a bad shape. This means that all Cilium-managed pods must also be deleted when this is called! This is best effort, any error occurring when deleting resources is ignored.

func (*Kubectl) CollectSysdump

func (kub *Kubectl) CollectSysdump(ctx context.Context)

func (*Kubectl) CopyFileToPod

func (kub *Kubectl) CopyFileToPod(namespace string, pod string, fromFile, toFile string) *CmdRes

CopyFileToPod copies a file to a pod's file-system.

func (*Kubectl) CountMissedTailCalls

func (kub *Kubectl) CountMissedTailCalls() (int, error)

CountMissedTailCalls returns the number of the sum of all drops due to missed tail calls that happened on all Cilium-managed nodes.

func (*Kubectl) Create

func (kub *Kubectl) Create(filePath string) *CmdRes

Create creates the Kubernetes kanifest located at path filepath.

func (*Kubectl) CreateResource

func (kub *Kubectl) CreateResource(resource, resourceName string) *CmdRes

CreateResource is a wrapper around `kubernetes create <resource> <resourceName>.

func (*Kubectl) CreateSecret

func (kub *Kubectl) CreateSecret(secretType, name, namespace, args string) *CmdRes

CreateSecret is a wrapper around `kubernetes create secret <resourceName>.

func (*Kubectl) DaemonSetIsReady

func (kub *Kubectl) DaemonSetIsReady(namespace, daemonset string) (int, error)

DaemonSetIsReady validate that a DaemonSet is scheduled on all required nodes and all pods are ready. If this condition is not met, an error is returned. If all pods are ready, then the number of pods is returned.

func (*Kubectl) DelIPRoute

func (kub *Kubectl) DelIPRoute(nodeName, subnet, gw string) *CmdRes

DelIPRoute deletes a route to a given IP address and a gateway on a given node via the iproute2 utility suite.

func (*Kubectl) DelVXLAN

func (kub *Kubectl) DelVXLAN(nodeName string, vxlanId int) *CmdRes

func (*Kubectl) Delete

func (kub *Kubectl) Delete(filePath string) *CmdRes

Delete deletes the Kubernetes manifest at path filepath.

func (*Kubectl) DeleteAllInNamespace

func (kub *Kubectl) DeleteAllInNamespace(name string) error

DeleteAllInNamespace deletes all k8s objects in a namespace

func (*Kubectl) DeleteAllNamespacesExcept

func (kub *Kubectl) DeleteAllNamespacesExcept(except []string) error

DeleteAllInNamespace deletes all namespaces except the ones provided in the exception list

func (*Kubectl) DeleteAllResourceInNamespace

func (kub *Kubectl) DeleteAllResourceInNamespace(namespace, resource string)

DeleteAllResourceInNamespace deletes all instances of a resource in a namespace

func (*Kubectl) DeleteAndWait

func (kub *Kubectl) DeleteAndWait(filePath string, ignoreNotFound bool) *CmdRes

DeleteAndWait deletes the Kubernetes manifest at path filePath and wait for the associated resources to be gone. If ignoreNotFound parameter is true we don't error if the resource to be deleted is not found in the cluster.

func (*Kubectl) DeleteCiliumDS

func (kub *Kubectl) DeleteCiliumDS() error

func (*Kubectl) DeleteHubbleRelay

func (kub *Kubectl) DeleteHubbleRelay(ns string) error

func (*Kubectl) DeleteInNamespace

func (kub *Kubectl) DeleteInNamespace(namespace, filePath string) *CmdRes

DeleteInNamespace deletes the Kubernetes manifest at path filepath in a particular namespace

func (*Kubectl) DeleteLong

func (kub *Kubectl) DeleteLong(filePath string) *CmdRes

DeleteLong deletes the Kubernetes manifest at path filepath with longer timeout.

func (*Kubectl) DeleteResource

func (kub *Kubectl) DeleteResource(resource, resourceName string) *CmdRes

DeleteResource is a wrapper around `kubernetes delete <resource> resourceName>.

func (*Kubectl) DeleteResourcesInAnyNamespace

func (kub *Kubectl) DeleteResourcesInAnyNamespace(resource string, names []string) error

DeleteResourceInAnyNamespace deletes all objects with the provided name of the specified resource type in all namespaces.

func (*Kubectl) DeployPatch

func (kub *Kubectl) DeployPatch(original, patchFileName string) error

DeployPatch deploys the original kubernetes descriptor with the given patch.

func (*Kubectl) DeployPatchStdIn

func (kub *Kubectl) DeployPatchStdIn(original, patch string) error

DeployPatchStdIn deploys the original kubernetes descriptor with the given patch.

func (*Kubectl) DeploymentIsReady

func (kub *Kubectl) DeploymentIsReady(namespace, deployment string) (int, error)

DeploymentIsReady validate that a deployment has at least one replica and that all replicas are: - up-to-date - ready

If the above condition is not met, an error is returned. If all replicas are ready, then the number of replicas is returned.

func (*Kubectl) DumpCiliumCommandOutput

func (kub *Kubectl) DumpCiliumCommandOutput(ctx context.Context, namespace string)

DumpCiliumCommandOutput runs a variety of commands (CiliumKubCLICommands) and writes the results to TestResultsPath

func (*Kubectl) EnsureNamespaceExists

func (kub *Kubectl) EnsureNamespaceExists(name string) error

EnsureNamespaceExists creates a namespace, ignoring the AlreadyExists error.

func (*Kubectl) ExecInFirstPod

func (kub *Kubectl) ExecInFirstPod(ctx context.Context, namespace, selector, cmd string, options ...ExecOptions) *CmdRes

ExecInFirstPod runs given command in one pod that matches given selector and namespace An error is returned if no pods can be found

func (*Kubectl) ExecInHostNetNS

func (kub *Kubectl) ExecInHostNetNS(ctx context.Context, node, cmd string) *CmdRes

ExecInHostNetNS runs given command in a pod running in a host network namespace

func (*Kubectl) ExecInHostNetNSByLabel

func (kub *Kubectl) ExecInHostNetNSByLabel(ctx context.Context, label, cmd string) (string, error)

ExecInHostNetNSByLabel runs given command in a pod running in a host network namespace. The pod's node is identified by the given label.

func (*Kubectl) ExecInHostNetNSInBackground

func (kub *Kubectl) ExecInHostNetNSInBackground(ctx context.Context, node, cmd string) (*CmdRes, func(), error)

ExecInHostNetNSInBackground runs given command in a pod running in a host network namespace but in background.

func (*Kubectl) ExecInPods

func (kub *Kubectl) ExecInPods(ctx context.Context, namespace, selector, cmd string, options ...ExecOptions) (results map[string]*CmdRes, err error)

ExecInPods runs given command on all pods in given namespace that match selector and returns map pod-name->CmdRes

func (*Kubectl) ExecKafkaPodCmd

func (kub *Kubectl) ExecKafkaPodCmd(namespace string, pod string, arg string) error

ExecKafkaPodCmd executes shell command with arguments arg in the specified pod residing in the specified namespace. It returns the stdout of the command that was executed. The kafka producer and consumer scripts do not return error if command leads to TopicAuthorizationException or any other error. Hence the function needs to also take into account the stderr messages returned.

func (*Kubectl) ExecPodCmd

func (kub *Kubectl) ExecPodCmd(namespace string, pod string, cmd string, options ...ExecOptions) *CmdRes

ExecPodCmd executes command cmd in the specified pod residing in the specified namespace. It returns a pointer to CmdRes with all the output

func (*Kubectl) ExecPodCmdBackground

func (kub *Kubectl) ExecPodCmdBackground(ctx context.Context, namespace string, pod, container string, cmd string, options ...ExecOptions) *CmdRes

ExecPodCmdBackground executes command cmd in background in the specified pod residing in the specified namespace. It returns a pointer to CmdRes with all the output

To receive the output of this function, the caller must invoke either kub.WaitUntilFinish() or kub.WaitUntilMatch() then subsequently fetch the output out of the result.

func (*Kubectl) ExecPodCmdContext

func (kub *Kubectl) ExecPodCmdContext(ctx context.Context, namespace string, pod string, cmd string, options ...ExecOptions) *CmdRes

ExecPodCmdContext synchronously executes command cmd in the specified pod residing in the specified namespace. It returns a pointer to CmdRes with all the output.

func (*Kubectl) ExecPodContainerCmd

func (kub *Kubectl) ExecPodContainerCmd(namespace, pod, container, cmd string, options ...ExecOptions) *CmdRes

ExecPodContainerCmd executes command cmd in the specified container residing in the specified namespace and pod. It returns a pointer to CmdRes with all the output

func (*Kubectl) ExecUntilMatch

func (kub *Kubectl) ExecUntilMatch(namespace, pod, cmd, substr string) (*CmdRes, error)

ExecUntilMatch executes the specified command repeatedly for the specified pod until the given substring is present in stdout. If the timeout is reached it will return an error.

func (*Kubectl) GatherCiliumCoreDumps

func (kub *Kubectl) GatherCiliumCoreDumps(ctx context.Context, ciliumPod string)

GatherCiliumCoreDumps copies core dumps if are present in the /tmp folder into the test report folder for further analysis.

func (*Kubectl) GatherLogs

func (kub *Kubectl) GatherLogs(ctx context.Context)

GatherLogs dumps kubernetes pods, services, DaemonSet to the testResultsPath directory

func (*Kubectl) GeneratePodLogGatheringCommands

func (kub *Kubectl) GeneratePodLogGatheringCommands(ctx context.Context, reportCmds map[string]string)

GeneratePodLogGatheringCommands generates the commands to gather logs for all pods in the Kubernetes cluster, and maps the commands to the filename in which they will be stored in reportCmds.

func (*Kubectl) Get

func (kub *Kubectl) Get(namespace string, command string) *CmdRes

Get retrieves the provided Kubernetes objects from the specified namespace.

func (*Kubectl) GetAllPods

func (kub *Kubectl) GetAllPods(ctx context.Context, options ...ExecOptions) ([]v1.Pod, error)

GetAllPods returns a slice of all pods present in Kubernetes cluster, along with an error if the pods could not be retrieved via `kubectl`, or if the pod objects are unable to be marshaled from JSON.

func (*Kubectl) GetCNP

func (kub *Kubectl) GetCNP(namespace string, cnp string) *cnpv2.CiliumNetworkPolicy

GetCNP retrieves the output of `kubectl get cnp` in the given namespace for the given CNP and return a CNP struct. If the CNP does not exists or cannot unmarshal the Json output will return nil.

func (*Kubectl) GetCiliumEndpoint

func (kub *Kubectl) GetCiliumEndpoint(namespace string, pod string) (*cnpv2.EndpointStatus, error)

GetCiliumEndpoint returns the CiliumEndpoint for the specified pod.

func (*Kubectl) GetCiliumHostEndpointID

func (kub *Kubectl) GetCiliumHostEndpointID(ciliumPod string) (int64, error)

GetCiliumHostEndpointID returns the ID of the host endpoint on a given node.

func (*Kubectl) GetCiliumHostEndpointState

func (kub *Kubectl) GetCiliumHostEndpointState(ciliumPod string) (string, error)

GetCiliumHostEndpointState returns the state of the host endpoint on a given node.

func (*Kubectl) GetCiliumIdentityForIP added in v1.15.0

func (kub *Kubectl) GetCiliumIdentityForIP(ciliumPod, ip string) (int, error)

GetCiliumIdentityForIP returns the numeric identity for a given IP address according to a node's BPF ipcache.

func (*Kubectl) GetCiliumPodOnNode

func (kub *Kubectl) GetCiliumPodOnNode(label string) (string, error)

GetCiliumPodOnNode returns the name of the Cilium pod that is running on node with cilium.io/ci-node label

func (*Kubectl) GetCiliumPodOnNodeByName

func (kub *Kubectl) GetCiliumPodOnNodeByName(nodeName string) (string, error)

GetCiliumPodOnNodeByName returns the name of the Cilium pod that is running on node with the given name.

func (*Kubectl) GetCiliumPods

func (kub *Kubectl) GetCiliumPods() ([]string, error)

GetCiliumPods returns a list of all Cilium pods in the specified namespace, and an error if the Cilium pods were not able to be retrieved.

func (*Kubectl) GetCiliumPodsContext

func (kub *Kubectl) GetCiliumPodsContext(ctx context.Context, namespace string) ([]string, error)

GetCiliumPodsContext returns a list of all Cilium pods in the specified namespace, and an error if the Cilium pods were not able to be retrieved.

func (*Kubectl) GetDNSProxyPort

func (kub *Kubectl) GetDNSProxyPort(ciliumPod string) int

GetDNSProxyPort returns the port the Cilium DNS proxy is listening on

func (*Kubectl) GetDefaultIface

func (kub *Kubectl) GetDefaultIface(ipv6 bool) (string, error)

GetDefaultIface returns an interface name which is used by a default route. Assumes that all nodes have identical interfaces.

func (*Kubectl) GetEndpoints

func (kub *Kubectl) GetEndpoints(namespace string, filter string) *CmdRes

GetEndpoints gets all of the endpoints in the given namespace that match the provided filter.

func (*Kubectl) GetFilePath

func (kub *Kubectl) GetFilePath(filename string) string

GetFilePath is a utility function which returns path to give fale relative to BasePath

func (*Kubectl) GetFirstNodeWithoutCiliumLabel

func (kub *Kubectl) GetFirstNodeWithoutCiliumLabel() string

GetFirstNodeWithoutCiliumLabel returns the ci-node label value of the first node which is running without Cilium.

func (*Kubectl) GetFromAllNS

func (kub *Kubectl) GetFromAllNS(kind string) *CmdRes

GetFromAllNS retrieves provided Kubernetes objects from all namespaces

func (*Kubectl) GetLoadBalancerIP

func (kub *Kubectl) GetLoadBalancerIP(namespace string, service string, timeout time.Duration) (string, error)

GetLoadBalancerIP waits until a loadbalancer IP addr has been assigned for the given service, and then returns the IP addr.

func (*Kubectl) GetNodeCILabel

func (kub *Kubectl) GetNodeCILabel(nodeName string) string

GetNodeCILabel returns the ci-node label value of the given node.

func (*Kubectl) GetNodeIPByLabel

func (kub *Kubectl) GetNodeIPByLabel(label string, external bool) (string, error)

GetNodeIPByLabel returns the IPv4 of the node with cilium.io/ci-node=label. An error is returned if a node cannot be found.

func (*Kubectl) GetNodeIPv6ByLabel

func (kub *Kubectl) GetNodeIPv6ByLabel(label string, external bool) (string, error)

GetNodeIPv6ByLabel returns the IPv6 of the node with cilium.io/ci-node=label. An error is returned if a node cannot be found.

func (*Kubectl) GetNodeInfo

func (kub *Kubectl) GetNodeInfo(label string) (nodeName, nodeIP string)

GetNodeInfo provides the node name and IP address based on the label (eg helpers.K8s1 or helpers.K8s2)

func (*Kubectl) GetNodeNameByLabel

func (kub *Kubectl) GetNodeNameByLabel(label string) (string, error)

GetNodeNameByLabel returns the names of the node with a matching cilium.io/ci-node label

func (*Kubectl) GetNodeNameByLabelContext

func (kub *Kubectl) GetNodeNameByLabelContext(ctx context.Context, label string) (string, error)

GetNodeNameByLabelContext returns the names of all nodes with a matching label

func (*Kubectl) GetNumCiliumNodes

func (kub *Kubectl) GetNumCiliumNodes() int

GetNumCiliumNodes returns the number of Kubernetes nodes running cilium

func (*Kubectl) GetPodNames

func (kub *Kubectl) GetPodNames(namespace string, label string) ([]string, error)

GetPodNames returns the names of all of the pods that are labeled with label in the specified namespace, along with an error if the pod names cannot be retrieved.

func (*Kubectl) GetPodNamesContext

func (kub *Kubectl) GetPodNamesContext(ctx context.Context, namespace string, label string) ([]string, error)

GetPodNamesContext returns the names of all of the pods that are labeled with label in the specified namespace, along with an error if the pod names cannot be retrieved.

func (*Kubectl) GetPodOnNodeLabeledWithOffset

func (kub *Kubectl) GetPodOnNodeLabeledWithOffset(label string, podFilter string, callOffset int) (string, string)

GetPodOnNodeLabeledWithOffset retrieves name and ip of a pod matching filter and residing on a node with label cilium.io/ci-node=<label>

func (*Kubectl) GetPods

func (kub *Kubectl) GetPods(namespace string, filter string) *CmdRes

GetPods gets all of the pods in the given namespace that match the provided filter.

func (*Kubectl) GetPodsHostIPs

func (kub *Kubectl) GetPodsHostIPs(namespace string, label string) (map[string]string, error)

GetPodsHostIPs returns a map with pod name as a key and host IP name as value. It only gets pods in the given namespace that match the provided filter. It returns an error if pods cannot be retrieved correctly

func (*Kubectl) GetPodsIPs

func (kub *Kubectl) GetPodsIPs(namespace string, filter string) (map[string]string, error)

GetPodsIPs returns a map with pod name as a key and pod IP name as value. It only gets pods in the given namespace that match the provided filter. It returns an error if pods cannot be retrieved correctly

func (*Kubectl) GetPodsNodes

func (kub *Kubectl) GetPodsNodes(namespace string, filter string) (map[string]string, error)

GetPodsNodes returns a map with pod name as a key and node name as value. It only gets pods in the given namespace that match the provided filter. It returns an error if pods cannot be retrieved correctly

func (*Kubectl) GetPrivateIface

func (kub *Kubectl) GetPrivateIface(label string) (string, error)

GetPrivateIface returns an interface name of a netdev which has InternalIP addr. Assumes that all nodes have identical interfaces.

func (*Kubectl) GetPublicIface

func (kub *Kubectl) GetPublicIface(label string) (string, error)

GetPublicIface returns an interface name of a netdev which has ExternalIP addr. Assumes that all nodes have identical interfaces.

func (*Kubectl) GetService

func (kub *Kubectl) GetService(namespace, service string) (*v1.Service, error)

func (*Kubectl) GetServiceClusterIPs

func (kub *Kubectl) GetServiceClusterIPs(namespace string, service string) ([]string, error)

GetServiceClusterIPs returns the list of cluster IPs associated with the service. The support for this is only present in later version of Kubernetes(>= 1.20).

func (*Kubectl) GetServiceHostPort

func (kub *Kubectl) GetServiceHostPort(namespace string, service string) (string, int, error)

GetServiceHostPort returns the host and the first port for the given service name. It will return an error if service cannot be retrieved.

func (*Kubectl) GetSvcIP

func (kub *Kubectl) GetSvcIP(ctx context.Context, namespace, name string) (string, error)

GetSvcIP returns the cluster IP for the given service. If the service does not contain a cluster IP, the function keeps retrying until it has or the context timesout.

func (*Kubectl) HasBPFNodePort

func (kub *Kubectl) HasBPFNodePort(pod string) bool

HasBPFNodePort returns true if the given Cilium pod has BPF NodePort enabled.

func (*Kubectl) HasSocketLB

func (kub *Kubectl) HasSocketLB(pod string) bool

HasSocketLB returns true if the given Cilium pod has TCP and/or UDP host reachable services are enabled.

func (*Kubectl) HelmAddCiliumRepo

func (kub *Kubectl) HelmAddCiliumRepo() *CmdRes

HelmAddCiliumRepo installs the repository that contain Cilium helm charts.

func (*Kubectl) HelmTemplate

func (kub *Kubectl) HelmTemplate(chartDir, namespace, filename string, options map[string]string) *CmdRes

HelmTemplate renders given helm template. TODO: use go helm library for that We use --validate with `helm template` to properly populate the built-in objects like .Capabilities.KubeVersion with the values from associated cluster. This comes with a caveat that the command might fail if helm is not able to validate the chart install on the cluster, like if a previous cilium install is not cleaned up properly from the cluster. For this the caller has to make sure that there are no leftover cilium components in the cluster.

func (*Kubectl) HubbleObserve

func (kub *Kubectl) HubbleObserve(pod string, args string) *CmdRes

HubbleObserve runs `hubble observe --output=jsonpb <args>` on 'ns/pod' and waits for its completion.

func (*Kubectl) HubbleObserveFollow

func (kub *Kubectl) HubbleObserveFollow(ctx context.Context, pod string, args string) (*CmdRes, error)

HubbleObserveFollow runs `hubble observe --follow --output=jsonpb <args>` on the Cilium pod 'ns/pod' in the background. The process is stopped when ctx is cancelled.

func (*Kubectl) JsonPatch

func (kub *Kubectl) JsonPatch(namespace, objType, objName, patch string) *CmdRes

JsonPatch patches the given object with the given patch in JSON format.

func (*Kubectl) KubeDNSPreFlightCheck

func (kub *Kubectl) KubeDNSPreFlightCheck() error

KubeDNSPreFlightCheck makes sure that kube-dns is plumbed into Cilium.

func (*Kubectl) KubernetesDNSCanResolve

func (kub *Kubectl) KubernetesDNSCanResolve(namespace, service string) error

func (*Kubectl) LoadedPolicyInFirstAgent

func (kub *Kubectl) LoadedPolicyInFirstAgent() (string, error)

LoadedPolicyInFirstAgent returns the policy as loaded in the first cilium agent that is found in the cluster

func (*Kubectl) Logs

func (kub *Kubectl) Logs(namespace string, pod string) *CmdRes

Logs returns a CmdRes with containing the resulting metadata from the execution of `kubectl logs <pod> -n <namespace>`.

func (*Kubectl) LogsPreviousWithLabel

func (kub *Kubectl) LogsPreviousWithLabel(namespace string, labelStr string) *CmdRes

LogsPreviousWithLabel returns a CmdRes with command output from the execution of `kubectl logs --previous=true -l <label string> -n <namespace>`.

func (*Kubectl) LogsStream

func (kub *Kubectl) LogsStream(namespace string, pod string, ctx context.Context) *CmdRes

LogsStream returns a CmdRes with command output from the execution of `kubectl logs -f <pod> -n <namespace>`.

func (*Kubectl) MonitorEndpointStart

func (kub *Kubectl) MonitorEndpointStart(pod string, epID int64) (res *CmdRes, cancel func())

MonitorEndpointStart runs cilium monitor only on a specified endpoint. This function is the same as MonitorStart.

func (*Kubectl) MonitorStart

func (kub *Kubectl) MonitorStart(pod string) (res *CmdRes, cancel func())

MonitorStart runs cilium monitor in the background and returns the command result, CmdRes, along with a cancel function. The cancel function is used to stop the monitor.

func (*Kubectl) NamespaceCreate

func (kub *Kubectl) NamespaceCreate(name string) *CmdRes

NamespaceCreate creates a new Kubernetes namespace with the given name

func (*Kubectl) NamespaceDelete

func (kub *Kubectl) NamespaceDelete(name string) *CmdRes

NamespaceDelete deletes a given Kubernetes namespace

func (*Kubectl) NamespaceLabel

func (kub *Kubectl) NamespaceLabel(namespace string, label string) *CmdRes

NamespaceLabel sets a label in a Kubernetes namespace

func (*Kubectl) NslookupInPod

func (kub *Kubectl) NslookupInPod(namespace, pod string, target string) (err error)

NslookupInPod executes 'nslookup' in the given pod until it succeeds or times out.

func (*Kubectl) NumNodes

func (kub *Kubectl) NumNodes() int

NumNodes returns the number of Kubernetes nodes

func (*Kubectl) OutsideNodeReport

func (kub *Kubectl) OutsideNodeReport(outsideNode string, commands ...string)

OutsideNodeReport collects command output on the outside node.

func (*Kubectl) ParallelResourceDelete

func (kub *Kubectl) ParallelResourceDelete(namespace, resource string, names []string)

ParallelResourceDelete deletes all instances of a resource in a namespace based on the list of names provided. Waits until all delete API calls return.

func (*Kubectl) Patch

func (kub *Kubectl) Patch(namespace, objType, objName, patch string) *CmdRes

Patch patches the given object with the given patch (string).

func (*Kubectl) PodsHaveCiliumIdentity

func (kub *Kubectl) PodsHaveCiliumIdentity(namespace, podSelector string) error

PodsHaveCiliumIdentity validates that all pods matching th podSelector have a CiliumEndpoint resource mirroring it and an identity is assigned to it. If any pods do not match this criteria, an error is returned.

func (*Kubectl) PprofReport

func (kub *Kubectl) PprofReport()

PprofReport runs pprof on cilium nodes each 5 minutes and saves the data into the test folder saved with pprof suffix.

func (*Kubectl) PrepareCluster

func (kub *Kubectl) PrepareCluster()

PrepareCluster will prepare the cluster to run tests. It will: - Delete all existing namespaces - Label all nodes so the tests can use them

func (*Kubectl) RedeployKubernetesDnsIfNecessary

func (kub *Kubectl) RedeployKubernetesDnsIfNecessary(force bool)

RedeployKubernetesDnsIfNecessary validates if the Kubernetes DNS is functional and re-deploys it if it is not and then waits for it to deploy successfully and become operational. See ValidateKubernetesDNS() for the list of conditions that must be met for Kubernetes DNS to be considered operational.

func (*Kubectl) RepeatCommandInBackground

func (kub *Kubectl) RepeatCommandInBackground(cmd string) (quit, run chan struct{})

RepeatCommandInBackground runs command on repeat in goroutine until quit channel is closed and closes run channel when command is first run

func (*Kubectl) RestartUnmanagedPodsInNamespace

func (kub *Kubectl) RestartUnmanagedPodsInNamespace(namespace string, excludePodPrefix ...string)

RestartUnmanagedPodsInNamespace restarts all pods in a namespace which are: * not host networking * not managed by Cilium already

func (*Kubectl) RunHelm

func (kub *Kubectl) RunHelm(action, repo, helmName, version, namespace string, options map[string]string) (*CmdRes, error)

RunHelm runs the helm command with the given options.

func (*Kubectl) ScaleDownDNS

func (kub *Kubectl) ScaleDownDNS() *CmdRes

ScaleDownDNS reduces the number of pods in the cluster performing kube-dns duties down to zero. May be reverted by calling ScaleUpDNS().

func (*Kubectl) ScaleUpDNS

func (kub *Kubectl) ScaleUpDNS() *CmdRes

ScaleUpDNS restores the number of replicas for kube-dns to the number prior to calling ScaleDownDNS(). Must be called after ScaleDownDNS().

func (*Kubectl) SetCiliumOperatorReplicas

func (kub *Kubectl) SetCiliumOperatorReplicas(nReplicas int) *CmdRes

SetCiliumOperatorReplicas sets the number of replicas for the cilium-operator.

func (*Kubectl) ValidateKubernetesDNS

func (kub *Kubectl) ValidateKubernetesDNS() error

ValidateKubernetesDNS validates that the Kubernetes DNS server has been deployed correctly and can resolve DNS names. The following validations are done:

  • The Kubernetes DNS deployment has at least one replica
  • All replicas are up-to-date and ready
  • All pods matching the deployment are represented by a CiliumEndpoint with an identity
  • The kube-system/kube-dns service is correctly pumbed in all Cilium agents
  • The service "default/kubernetes" can be resolved via the KubernetesDNS and the IP returned matches the ClusterIP in the service

func (*Kubectl) ValidateListOfErrorsInLogs

func (kub *Kubectl) ValidateListOfErrorsInLogs(duration time.Duration, blacklist map[string][]string)

ValidateListOfErrorsInLogs is similar to ValidateNoErrorsInLogs, but takes a blacklist of bad log messages instead of using the default list.

func (*Kubectl) ValidateNoErrorsInLogs

func (kub *Kubectl) ValidateNoErrorsInLogs(duration time.Duration)

ValidateNoErrorsInLogs checks that cilium logs since the given duration (By default `CurrentGinkgoTestDescription().Duration`) do not contain any of the known-bad messages (e.g., `deadlocks` or `segmentation faults`). In case of any of these messages, it'll mark the test as failed.

func (*Kubectl) ValidateServicePlumbing

func (kub *Kubectl) ValidateServicePlumbing(namespace, service string) error

ValidateServicePlumbing ensures that a service in a namespace successfully plumbed by all Cilium pods in the cluster: - The service and endpoints are found in `cilium service list` - The service and endpoints are found in `cilium bpf lb list`

func (*Kubectl) WaitForCEPIdentity

func (kub *Kubectl) WaitForCEPIdentity(ns, podName string) error

WaitForCEPIdentity waits for a particular CEP to have an identity present.

func (*Kubectl) WaitForCRDCount

func (kub *Kubectl) WaitForCRDCount(filter string, count int, timeout time.Duration) error

func (*Kubectl) WaitForCiliumInitContainerToFinish

func (kub *Kubectl) WaitForCiliumInitContainerToFinish() error

WaitForCiliumInitContainerToFinish waits for all Cilium init containers to finish

func (*Kubectl) WaitForCiliumReadiness

func (kub *Kubectl) WaitForCiliumReadiness(offset int, errMsg string)

WaitForCiliumReadiness waits for the Cilium DaemonSet to become ready. Readiness is achieved when all Cilium pods which are desired to run on a node are in ready state.

func (*Kubectl) WaitForEgressPolicyEntries

func (kub *Kubectl) WaitForEgressPolicyEntries(node string, expectedCount int) error

func (*Kubectl) WaitForIPCacheEntry

func (kub *Kubectl) WaitForIPCacheEntry(node, ipAddr string) error

WaitForIPCacheEntry waits until the given ipAddr appears in "cilium bpf ipcache list" on the given node.

func (*Kubectl) WaitForKubeDNSEntry

func (kub *Kubectl) WaitForKubeDNSEntry(serviceName, serviceNamespace string) error

WaitForKubeDNSEntry waits until the given DNS entry exists in the kube-dns service. If the container is not ready after timeout it returns an error. The name's format query should be `${name}.${namespace}`. If `svc.cluster.local` is not present, it appends to the given name and it checks the service's FQDN.

func (*Kubectl) WaitForServiceBackend

func (kub *Kubectl) WaitForServiceBackend(node, ipAddr string) error

WaitForServiceBackend waits until the service backend with the given ipAddr appears in "cilium bpf lb list --backends" on the given node.

func (*Kubectl) WaitForServiceEndpoints

func (kub *Kubectl) WaitForServiceEndpoints(namespace string, filter string, service string, timeout time.Duration) error

WaitForServiceEndpoints waits up until timeout seconds have elapsed for all endpoints in the specified namespace that match the provided JSONPath filter. Returns true if all pods achieve the aforementioned desired state within timeout seconds. Returns false and an error if the command failed or the timeout was exceeded.

func (*Kubectl) WaitForServiceFrontend

func (kub *Kubectl) WaitForServiceFrontend(nodeName, ipAddr string) error

WaitForServiceFrontend waits until the service frontend with the given ipAddr appears in "cilium bpf lb list --frontends" on the given node.

func (*Kubectl) WaitForSinglePod

func (kub *Kubectl) WaitForSinglePod(namespace, podname string, timeout time.Duration) error

WaitForSinglePod waits up until timeout seconds have elapsed for a single pod with name 'podname' in the specified namespace to have its containterStatus equal to "ready". Returns true if the pods achieves the aforementioned desired state within timeout seconds. Returns false and an error if the command failed or the timeout was exceeded.

func (*Kubectl) WaitKubeDNS

func (kub *Kubectl) WaitKubeDNS() error

WaitKubeDNS waits until the kubeDNS pods are ready. In case of exceeding the default timeout it returns an error.

func (*Kubectl) WaitPolicyDeleted

func (kub *Kubectl) WaitPolicyDeleted(pod string, policyName string) error

WaitPolicyDeleted waits for policy policyName to be deleted from the cilium-agent running in pod. Returns an error if policyName was unable to be deleted after some amount of time.

func (*Kubectl) WaitTerminatingPods

func (kub *Kubectl) WaitTerminatingPods(timeout time.Duration) error

func (*Kubectl) WaitTerminatingPodsInNs

func (kub *Kubectl) WaitTerminatingPodsInNs(ns string, timeout time.Duration) error

WaitTerminatingPodsInNs waits until all nodes that are in `Terminating` state are deleted correctly in the platform. In case of excedding the given timeout (in seconds) it returns an error.

func (*Kubectl) WaitTerminatingPodsInNsWithFilter

func (kub *Kubectl) WaitTerminatingPodsInNsWithFilter(ns, filter string, timeout time.Duration) error

WaitTerminatingPodsInNs waits until all nodes that are in `Terminating` state are deleted correctly in the platform. In case of excedding the given timeout (in seconds) it returns an error.

func (*Kubectl) WaitforNPods

func (kub *Kubectl) WaitforNPods(namespace string, filter string, minRequired int, timeout time.Duration) error

WaitforNPods waits up until timeout seconds have elapsed for at least minRequired pods in the specified namespace that match the provided JSONPath filter to have their containterStatuses equal to "ready". Returns no error if minRequired pods achieve the aforementioned desired state within timeout seconds. Returns an error if the command failed or the timeout was exceeded. When minRequired is 0, the function will derive required pod count from number of pods in the cluster for every iteration.

func (*Kubectl) WaitforNPodsRunning

func (kub *Kubectl) WaitforNPodsRunning(namespace string, filter string, minRequired int, timeout time.Duration) error

WaitforNPodsRunning waits up until timeout duration has elapsed for at least minRequired pods in the specified namespace that match the provided JSONPath filter to have their containterStatuses equal to "running". Returns no error if minRequired pods achieve the aforementioned desired state within timeout seconds. Returns an error if the command failed or the timeout was exceeded. When minRequired is 0, the function will derive required pod count from number of pods in the cluster for every iteration.

func (*Kubectl) WaitforPods

func (kub *Kubectl) WaitforPods(namespace string, filter string, timeout time.Duration) error

WaitforPods waits up until timeout seconds have elapsed for all pods in the specified namespace that match the provided JSONPath filter to have their containterStatuses equal to "ready". Returns true if all pods achieve the aforementioned desired state within timeout seconds. Returns false and an error if the command failed or the timeout was exceeded.

type LocalExecutor

type LocalExecutor struct {
	// contains filtered or unexported fields
}

LocalExecutor executes commands, implements Executor interface

func CreateLocalExecutor

func CreateLocalExecutor(env []string) *LocalExecutor

CreateLocalExecutor returns a local executor

func (*LocalExecutor) BasePath

func (s *LocalExecutor) BasePath() string

func (*LocalExecutor) CloseSSHClient

func (s *LocalExecutor) CloseSSHClient()

CloseSSHClient is a no-op

func (*LocalExecutor) Exec

func (s *LocalExecutor) Exec(cmd string, options ...ExecOptions) *CmdRes

Exec returns the results of executing the provided cmd via SSH.

func (*LocalExecutor) ExecContext

func (s *LocalExecutor) ExecContext(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecContext returns the results of executing the provided cmd via SSH.

func (*LocalExecutor) ExecContextShort

func (s *LocalExecutor) ExecContextShort(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecContextShort is a wrapper around ExecContext which creates a child context with a timeout of ShortCommandTimeout.

func (*LocalExecutor) ExecInBackground

func (s *LocalExecutor) ExecInBackground(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecInBackground returns the results of running cmd in the specified context. The command will be executed in the background until context.Context is canceled or the command has finish its execution.

func (*LocalExecutor) ExecMiddle

func (s *LocalExecutor) ExecMiddle(cmd string, options ...ExecOptions) *CmdRes

ExecMiddle runs command with the provided options. It will take up to MidCommandTimeout seconds to run the command before it times out.

func (*LocalExecutor) ExecShort

func (s *LocalExecutor) ExecShort(cmd string, options ...ExecOptions) *CmdRes

ExecShort runs command with the provided options. It will take up to ShortCommandTimeout seconds to run the command before it times out.

func (*LocalExecutor) ExecWithSudo

func (s *LocalExecutor) ExecWithSudo(cmd string, options ...ExecOptions) *CmdRes

ExecWithSudo returns the result of executing the provided cmd via SSH using sudo.

func (*LocalExecutor) ExecuteContext

func (s *LocalExecutor) ExecuteContext(ctx context.Context, command string, stdout io.Writer, stderr io.Writer) error

ExecuteContext executes the given `cmd` and writes the cmd's stdout and stderr into the given io.Writers. Returns an error if context Deadline() is reached or if there was an error executing the command.

func (*LocalExecutor) IsLocal

func (s *LocalExecutor) IsLocal() bool

IsLocal returns true if commands are executed on the Ginkgo host

func (*LocalExecutor) Logger

func (s *LocalExecutor) Logger() *logrus.Entry

Logger returns logger for executor

func (*LocalExecutor) RenderTemplateToFile

func (s *LocalExecutor) RenderTemplateToFile(filename string, tmplt string, perm os.FileMode) error

RenderTemplateToFile renders a text/template string into a target filename with specific persmisions. Returns an error if the template cannot be validated or the file cannot be created.

func (*LocalExecutor) String

func (s *LocalExecutor) String() string

type Manifest

type Manifest struct {
	// Filename is the file (not path) of the manifest. This must point to
	// a file that contains any number of Deployments, DaemonSets, ...
	Filename string

	// Alternate is an alternative file (not path) of the manifest that
	// takes the place of 'Filename' for single-node testing. It is
	// otherwise equivalent and must point to a file containing resources
	// to deploy.
	Alternate string

	// DaemonSetNames is the list of all daemonset names in the manifest
	DaemonSetNames []string

	// DeploymentNames is the list of all deployment names in the manifest
	DeploymentNames []string

	// NumPods is the number of pods expected in the manifest, not counting
	// any DaemonSets
	NumPods int

	// LabelSelector is the selector required to select *ALL* pods created
	// from this manifest
	LabelSelector string

	// Singleton marks a manifest as singleton. A singleton manifest can be
	// deployed exactly once into the cluster, regardless of the namespace
	// the manifest is deployed into. Singletons are required if the
	// deployment is using HostPorts, NodePorts or other resources which
	// may conflict if the deployment is scheduled multiple times onto the
	// same node.
	Singleton bool
}

Manifest represents a deployment manifest that can consist of an any number of Deployments, DaemonSets, Pods, etc.

func (Manifest) Deploy

func (m Manifest) Deploy(kubectl *Kubectl, namespace string) *Deployment

Deploy deploys the manifest. It will call ginkgoext.Fail() if any aspect of that fails.

func (Manifest) GetFilename

func (m Manifest) GetFilename() string

GetFilename resolves the filename for the manifest depending on whether the alternate filename is used (ie, single node testing YAMLs)

type NamespaceName

type NamespaceName string

NamespaceName represents a Kubernetes namespace name

func (NamespaceName) IsRandom

func (n NamespaceName) IsRandom() bool

IsRandom returns true if the namespace name has been generated with GenerateNamespaceForTest

func (NamespaceName) String

func (n NamespaceName) String() string

type NodesInfo

type NodesInfo struct {
	K8s1NodeName      string
	K8s2NodeName      string
	OutsideNodeName   string
	K8s1IP            string
	K8s2IP            string
	OutsideIP         string
	PrivateIface      string
	PrimaryK8s1IPv6   string
	PrimaryK8s2IPv6   string
	OutsideIPv6       string
	SecondaryK8s1IPv4 string
	SecondaryK8s2IPv4 string
	SecondaryK8s1IPv6 string
	SecondaryK8s2IPv6 string
}

func GetNodesInfo

func GetNodesInfo(kubectl *Kubectl) (*NodesInfo, error)

type PerfTest

type PerfTest string

PerfTest represents a type of test to run when running `netperf`.

type ResourceLifeCycleAction

type ResourceLifeCycleAction string

ResourceLifeCycleAction represents an action performed upon objects in Kubernetes.

type SSHClient

type SSHClient struct {
	Config *ssh.ClientConfig // ssh client configuration information.
	Host   string            // Ip/Host from the target virtualserver
	Port   int               // Port to connect to the target server
	// contains filtered or unexported fields
}

SSHClient stores the information needed to SSH into a remote location for running tests.

func GetSSHClient

func GetSSHClient(host string, port int, user string) *SSHClient

GetSSHClient initializes an SSHClient for the specified host/port/user combination.

func (*SSHClient) GetHostPort

func (cli *SSHClient) GetHostPort() string

GetHostPort returns the host port representation of the ssh client

func (*SSHClient) RunCommand

func (client *SSHClient) RunCommand(cmd *SSHCommand) error

RunCommand runs a SSHCommand using SSHClient client. The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

func (*SSHClient) RunCommandContext

func (client *SSHClient) RunCommandContext(ctx context.Context, cmd *SSHCommand) error

RunCommandContext runs an SSH command in a similar way to RunCommand but with a context. If context is canceled it will return the error of that given context.

func (*SSHClient) RunCommandInBackground

func (client *SSHClient) RunCommandInBackground(ctx context.Context, cmd *SSHCommand) error

RunCommandInBackground runs an SSH command in a similar way to RunCommandContext, but with a context which allows the command to be cancelled at any time. When cancel is called the error of the command is returned instead the context error.

func (*SSHClient) String

func (client *SSHClient) String() string

type SSHCommand

type SSHCommand struct {
	// TODO: path is not a clear name - rename to something more clear.
	Path   string
	Env    []string
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

SSHCommand stores the data associated with executing a command. TODO: this is poorly named in that it's not related to a command only ran over SSH - rename this.

type SSHConfig

type SSHConfig struct {
	// contains filtered or unexported fields
}

SSHConfig contains metadata for an SSH session.

func (*SSHConfig) GetSSHAgent

func (cfg *SSHConfig) GetSSHAgent() ssh.AuthMethod

GetSSHAgent returns the ssh.AuthMethod corresponding to SSHConfig cfg.

func (*SSHConfig) GetSSHClient

func (cfg *SSHConfig) GetSSHClient() *SSHClient

GetSSHClient initializes an SSHClient based on the provided SSHConfig

func (*SSHConfig) String

func (cfg *SSHConfig) String() string

type SSHConfigs

type SSHConfigs map[string]*SSHConfig

SSHConfigs maps the name of a host (VM) to its corresponding SSHConfiguration

func ImportSSHconfig

func ImportSSHconfig(config []byte) (SSHConfigs, error)

ImportSSHconfig imports the SSH configuration stored at the provided path. Returns an error if the SSH configuration could not be instantiated.

type SSHMeta

type SSHMeta struct {
	// contains filtered or unexported fields
}

SSHMeta contains metadata to SSH into a remote location to run tests, implements Executor interface

func CreateSSHMeta

func CreateSSHMeta(host string, port int, user string) *SSHMeta

CreateSSHMeta returns an SSHMeta with the specified host, port, and user, as well as an according SSHClient.

func GetVagrantSSHMeta

func GetVagrantSSHMeta(vmName string) *SSHMeta

GetVagrantSSHMeta returns a SSHMeta initialized based on the provided SSH-config target.

func InitRuntimeHelper

func InitRuntimeHelper(target string, log *logrus.Entry) *SSHMeta

InitRuntimeHelper returns SSHMeta helper for running the runtime tests on the provided VM target and using logger 'log'. It marks the test as Fail if it cannot get the ssh meta information or cannot execute a `ls` on the virtual machine.

func (*SSHMeta) AddIPToLoopbackDevice

func (s *SSHMeta) AddIPToLoopbackDevice(ip string) *CmdRes

AddIPToLoopbackDevice adds the specified IP (assumed to be in form <ip>/<mask>) to the loopback device on s.

func (*SSHMeta) BasePath

func (s *SSHMeta) BasePath() string

func (*SSHMeta) BpfIPCacheList

func (s *SSHMeta) BpfIPCacheList(localScopeOnly bool) (map[string]uint32, error)

BpfIPCacheList returns the output of `cilium bpf ipcache list -o json` as a map Key will be the CIDR (address with mask) and the value is the associated numeric security identity

func (*SSHMeta) BpfLBList

func (s *SSHMeta) BpfLBList(noDuplicates bool) (map[string][]string, error)

BpfLBList returns the output of `cilium bpf lb list -o json` as a map Key will be the frontend address and the value is an array with all backend addresses

func (*SSHMeta) CloseSSHClient

func (s *SSHMeta) CloseSSHClient()

CloseSSHClient closes all of the connections made by the SSH Client for this SSHMeta.

func (*SSHMeta) ContainerCreate

func (s *SSHMeta) ContainerCreate(name, image, net, options string, cmdParams ...string) *CmdRes

ContainerCreate is a wrapper for `docker run`. It runs an instance of the specified Docker image with the provided network, name, options and container startup commands.

func (*SSHMeta) ContainerExec

func (s *SSHMeta) ContainerExec(name string, cmd string, optionalArgs ...string) *CmdRes

ContainerExec executes cmd in the container with the provided name along with any other additional arguments needed.

func (*SSHMeta) ContainerInspect

func (s *SSHMeta) ContainerInspect(name string) *CmdRes

ContainerInspect runs `docker inspect` for the container with the provided name.

func (*SSHMeta) ContainerInspectNet

func (s *SSHMeta) ContainerInspectNet(name string) (map[string]string, error)

ContainerInspectNet returns a map of Docker networking information fields and their associated values for the container of the provided name. An error is returned if the networking information could not be retrieved.

func (*SSHMeta) ContainerInspectOtherNet

func (s *SSHMeta) ContainerInspectOtherNet(name string, network string) (map[string]string, error)

ContainerInspectOtherNet returns a map of Docker networking information fields and their associated values for the container of the provided name, on the specified docker network. An error is returned if the networking information could not be retrieved.

func (*SSHMeta) ContainerRm

func (s *SSHMeta) ContainerRm(name string) *CmdRes

ContainerRm is a wrapper around `docker rm -f`. It forcibly removes the Docker container of the provided name.

func (*SSHMeta) ContainerRun

func (s *SSHMeta) ContainerRun(name, image, net, options string, cmdParams ...string) *CmdRes

ContainerRun is a wrapper to a one execution docker run container. It runs an instance of the specific Docker image with the provided network, name and options.

func (*SSHMeta) DumpCiliumCommandOutput

func (s *SSHMeta) DumpCiliumCommandOutput()

DumpCiliumCommandOutput runs a variety of Cilium CLI commands and dumps their output to files. These files are gathered as part of each Jenkins job for postmortem debugging of build failures.

func (*SSHMeta) EndpointGet

func (s *SSHMeta) EndpointGet(id string) *models.Endpoint

EndpointGet returns the output of `cilium endpoint get` for the provided endpoint ID.

func (*SSHMeta) EndpointSetConfig

func (s *SSHMeta) EndpointSetConfig(id, option, value string) bool

EndpointSetConfig sets the provided configuration option to the provided value for the endpoint with the endpoint ID id. It returns true if the configuration update command returned successfully.

func (*SSHMeta) Exec

func (s *SSHMeta) Exec(cmd string, options ...ExecOptions) *CmdRes

Exec returns the results of executing the provided cmd via SSH.

func (*SSHMeta) ExecCilium

func (s *SSHMeta) ExecCilium(cmd string) *CmdRes

ExecCilium runs a Cilium CLI command and returns the resultant cmdRes.

func (*SSHMeta) ExecContext

func (s *SSHMeta) ExecContext(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecContext returns the results of executing the provided cmd via SSH.

func (*SSHMeta) ExecContextShort

func (s *SSHMeta) ExecContextShort(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecContextShort is a wrapper around ExecContext which creates a child context with a timeout of ShortCommandTimeout.

func (*SSHMeta) ExecInBackground

func (s *SSHMeta) ExecInBackground(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes

ExecInBackground returns the results of running cmd via SSH in the specified context. The command will be executed in the background until context.Context is canceled or the command has finish its execution.

func (*SSHMeta) ExecMiddle

func (s *SSHMeta) ExecMiddle(cmd string, options ...ExecOptions) *CmdRes

ExecMiddle runs command with the provided options. It will take up to MidCommandTimeout seconds to run the command before it times out.

func (*SSHMeta) ExecShort

func (s *SSHMeta) ExecShort(cmd string, options ...ExecOptions) *CmdRes

ExecShort runs command with the provided options. It will take up to ShortCommandTimeout seconds to run the command before it times out.

func (*SSHMeta) ExecWithSudo

func (s *SSHMeta) ExecWithSudo(cmd string, options ...ExecOptions) *CmdRes

ExecWithSudo returns the result of executing the provided cmd via SSH using sudo.

func (*SSHMeta) ExecuteContext

func (s *SSHMeta) ExecuteContext(ctx context.Context, cmd string, stdout io.Writer, stderr io.Writer) error

ExecuteContext executes the given `cmd` and writes the cmd's stdout and stderr into the given io.Writers. Returns an error if context Deadline() is reached or if there was an error executing the command.

func (*SSHMeta) FlushGlobalConntrackTable

func (s *SSHMeta) FlushGlobalConntrackTable() *CmdRes

FlushGlobalConntrackTable flushes the global connection tracking table.

func (*SSHMeta) GatherDockerLogs

func (s *SSHMeta) GatherDockerLogs()

GatherDockerLogs dumps docker containers logs output to the directory testResultsPath

func (*SSHMeta) GatherLogs

func (s *SSHMeta) GatherLogs()

GatherLogs dumps Cilium, Cilium Docker, key-value store logs, and gops output to the directory testResultsPath

func (*SSHMeta) GetAllEndpointsIds

func (s *SSHMeta) GetAllEndpointsIds() (map[string]string, error)

GetAllEndpointsIds returns a mapping of all Docker container name to to its corresponding endpoint ID, and an error if the list of endpoints cannot be retrieved via the Cilium CLI.

func (*SSHMeta) GetCopy

func (s *SSHMeta) GetCopy() *SSHMeta

GetCopy returns a copy of SSHMeta, useful for parallel requests

func (*SSHMeta) GetEndpointMutableConfigurationOption

func (s *SSHMeta) GetEndpointMutableConfigurationOption(endpointID, optionName string) (string, error)

GetEndpointMutableConfigurationOption returns the value of the mutable configuration option optionName for the endpoint with ID endpointID, or an error if optionName's corresponding value cannot be retrieved for the endpoint.

func (*SSHMeta) GetEndpointsIDMap

func (s *SSHMeta) GetEndpointsIDMap() (map[string]string, error)

GetEndpointsIDMap returns a mapping of an endpoint ID to Docker container name, and an error if the list of endpoints cannot be retrieved via the Cilium CLI.

func (*SSHMeta) GetEndpointsIdentityIds

func (s *SSHMeta) GetEndpointsIdentityIds() (map[string]string, error)

GetEndpointsIdentityIds returns a mapping of a Docker container name to it's corresponding endpoint's security identity, it will return an error if the list of endpoints cannot be retrieved via the Cilium CLI.

func (*SSHMeta) GetEndpointsIds

func (s *SSHMeta) GetEndpointsIds() (map[string]string, error)

GetEndpointsIds returns a mapping of a Docker container name to to its corresponding endpoint ID, and an error if the list of endpoints cannot be retrieved via the Cilium CLI.

func (*SSHMeta) GetEndpointsNames

func (s *SSHMeta) GetEndpointsNames() ([]string, error)

GetEndpointsNames returns the container-name field of each Cilium endpoint.

func (*SSHMeta) GetFilePath

func (s *SSHMeta) GetFilePath(filename string) string

GetFilePath is a utility function which returns path to give fale relative to BasePath

func (*SSHMeta) GetFullPath

func (s *SSHMeta) GetFullPath(name string) string

GetFullPath returns the path of file name prepended with the absolute path where manifests (YAMLs containing policies, DaemonSets, etc.) are stored.

func (*SSHMeta) HubbleObserve

func (s *SSHMeta) HubbleObserve(args ...string) *CmdRes

HubbleObserve runs `hubble observe --output=jsonpb <args>`. JSON output is enabled such that CmdRes.FilterLines may be used to grep for specific events in the output.

func (*SSHMeta) HubbleObserveFollow

func (s *SSHMeta) HubbleObserveFollow(ctx context.Context, args ...string) *CmdRes

HubbleObserveFollow runs `hubble observe --follow --output=jsonpb <args>`. The command is running in the background and will be terminated only once ctx is cancelled. JSON output is enabled such that CmdRes.WaitUntilMatchFilterLine may be used to wait for specific events in the output.

func (*SSHMeta) IsLocal

func (s *SSHMeta) IsLocal() bool

IsLocal returns true if commands are executed on the Ginkgo host

func (*SSHMeta) ListEndpoints

func (s *SSHMeta) ListEndpoints() *CmdRes

ListEndpoints returns the CmdRes resulting from executing `cilium endpoint list -o json`.

func (*SSHMeta) Logger

func (s *SSHMeta) Logger() *logrus.Entry

Logger returns logger for SSHMeta

func (*SSHMeta) ManifestsPath

func (s *SSHMeta) ManifestsPath() string

ManifestsPath returns the path of the directory where manifests (YAMLs containing policies, DaemonSets, etc.) are stored for the runtime tests. TODO: this can just be a constant; there's no need to have a function.

func (*SSHMeta) MonitorDebug

func (s *SSHMeta) MonitorDebug(on bool, epID string) bool

func (*SSHMeta) MonitorStart

func (s *SSHMeta) MonitorStart(opts ...string) (*CmdRes, func() error)

MonitorStart starts the monitor command in background and returns CmdREs and a callback function which stops the monitor when the user needs. When the callback is called the command will stop and monitor's output is saved on `monitorLogFileName` file.

func (*SSHMeta) NetworkCreate

func (s *SSHMeta) NetworkCreate(name string, subnet string) *CmdRes

NetworkCreate creates a Docker network of the provided name with the specified subnet. It is a wrapper around `docker network create`.

func (*SSHMeta) NetworkCreateWithOptions

func (s *SSHMeta) NetworkCreateWithOptions(name string, subnet string, ipv6 bool, opts string) *CmdRes

NetworkCreateWithOptions creates a Docker network of the provided name with the specified subnet, with custom specified options. It is a wrapper around `docker network create`.

func (*SSHMeta) NetworkDelete

func (s *SSHMeta) NetworkDelete(name string) *CmdRes

NetworkDelete deletes the Docker network of the provided name. It is a wrapper around `docker network rm`.

func (*SSHMeta) NetworkGet

func (s *SSHMeta) NetworkGet(name string) *CmdRes

NetworkGet returns all of the Docker network configuration for the provided network. It is a wrapper around `docker network inspect`.

func (*SSHMeta) PolicyDel

func (s *SSHMeta) PolicyDel(id string) *CmdRes

PolicyDel deletes the policy with the given ID from Cilium.

func (*SSHMeta) PolicyDelAll

func (s *SSHMeta) PolicyDelAll() *CmdRes

PolicyDelAll deletes all policy rules currently imported into Cilium.

func (*SSHMeta) PolicyEndpointsSummary

func (s *SSHMeta) PolicyEndpointsSummary() (map[string]int, error)

PolicyEndpointsSummary returns the count of whether policy enforcement is enabled, disabled, and the total number of endpoints, and an error if the Cilium endpoint metadata cannot be retrieved via the API.

func (*SSHMeta) PolicyGet

func (s *SSHMeta) PolicyGet(id string) *CmdRes

PolicyGet runs `cilium policy get <id>`, where id is the name of a specific policy imported into Cilium. It returns the resultant CmdRes from running the aforementioned command.

func (*SSHMeta) PolicyGetAll

func (s *SSHMeta) PolicyGetAll() *CmdRes

PolicyGetAll gets all policies that are imported in the Cilium agent.

func (*SSHMeta) PolicyGetRevision

func (s *SSHMeta) PolicyGetRevision() (int, error)

PolicyGetRevision retrieves the current policy revision number in the Cilium agent.

func (*SSHMeta) PolicyImport

func (s *SSHMeta) PolicyImport(path string) error

PolicyImport imports a new policy into Cilium.

func (*SSHMeta) PolicyImportAndWait

func (s *SSHMeta) PolicyImportAndWait(path string, timeout time.Duration) (int, error)

PolicyImportAndWait validates and imports a new policy into Cilium and waits until the policy revision number increments. Returns an error if the policy is invalid or could not be imported.

func (*SSHMeta) PolicyRenderAndImport

func (s *SSHMeta) PolicyRenderAndImport(policy string) (int, error)

PolicyRenderAndImport receives an string with a policy, renders it in the test root directory and imports the policy to cilium. It returns the new policy id. Returns an error if the file cannot be created or if the policy cannot be imported

func (*SSHMeta) PolicyWait

func (s *SSHMeta) PolicyWait(revisionNum int) *CmdRes

PolicyWait executes `cilium policy wait`, which waits until all endpoints are updated to the given policy revision.

func (*SSHMeta) PprofReport

func (s *SSHMeta) PprofReport()

PprofReport runs pprof each 5 minutes and saves the data into the test folder saved with pprof suffix.

func (*SSHMeta) RemoveIPFromLoopbackDevice

func (s *SSHMeta) RemoveIPFromLoopbackDevice(ip string) *CmdRes

RemoveIPFromLoopbackDevice removes the specified IP (assumed to be in form <ip>/<mask>) from the loopback device on s.

func (*SSHMeta) RenderTemplateToFile

func (s *SSHMeta) RenderTemplateToFile(filename string, tmplt string, perm os.FileMode) error

RenderTemplateToFile renders a text/template string into a target filename with specific persmisions. Returns an error if the template cannot be validated or the file cannot be created.

func (*SSHMeta) ReportFailed

func (s *SSHMeta) ReportFailed(commands ...string)

ReportFailed gathers relevant Cilium runtime data and logs for debugging purposes.

func (*SSHMeta) RestartCilium

func (s *SSHMeta) RestartCilium() error

RestartCilium reloads cilium on this host, then waits for it to become ready again.

func (*SSHMeta) SampleContainersActions

func (s *SSHMeta) SampleContainersActions(mode string, networkName string, createOptions ...string)

SampleContainersActions creates or deletes various containers used for testing Cilium and adds said containers to the provided Docker network.

func (*SSHMeta) SelectedIdentities

func (s *SSHMeta) SelectedIdentities(match string) string

SelectedIdentities returns filtered identities from the output of `cilium policy selectors list -o json` as a string

func (*SSHMeta) ServiceAdd

func (s *SSHMeta) ServiceAdd(id int, frontend string, backends []string) *CmdRes

ServiceAdd creates a new Cilium service with the provided ID, frontend, backends. Returns the result of creating said service.

func (*SSHMeta) ServiceDel

func (s *SSHMeta) ServiceDel(id int) *CmdRes

ServiceDel is a wrapper around `cilium service delete <id>`. It returns the result of deleting said service.

func (*SSHMeta) ServiceDelAll

func (s *SSHMeta) ServiceDelAll() *CmdRes

ServiceDelAll is a wrapper around `cilium service delete --all`. It returns the result of the command.

func (*SSHMeta) ServiceGet

func (s *SSHMeta) ServiceGet(id int) *CmdRes

ServiceGet is a wrapper around `cilium service get <id>`. It returns the result of retrieving said service.

func (*SSHMeta) ServiceGetFrontendAddress

func (s *SSHMeta) ServiceGetFrontendAddress(id int) (string, error)

ServiceGetFrontendAddress returns a string with the frontend address and port. It returns an error if the ID cannot be retrieved.

func (*SSHMeta) ServiceGetIds

func (s *SSHMeta) ServiceGetIds() ([]string, error)

ServiceGetIds returns an array with the IDs of all Cilium services. Returns an error if the IDs cannot be retrieved

func (*SSHMeta) ServiceIsSynced

func (s *SSHMeta) ServiceIsSynced(id int) (bool, error)

ServiceIsSynced checks that the Cilium service with the specified id has its metadata match that of the load balancer BPF maps

func (*SSHMeta) ServiceList

func (s *SSHMeta) ServiceList() *CmdRes

ServiceList returns the output of `cilium service list`

func (*SSHMeta) SetAndWaitForEndpointConfiguration

func (s *SSHMeta) SetAndWaitForEndpointConfiguration(endpointID, optionName, expectedValue string) error

SetAndWaitForEndpointConfiguration waits for the endpoint configuration to become a certain value

func (*SSHMeta) SetPolicyEnforcement

func (s *SSHMeta) SetPolicyEnforcement(status string) *CmdRes

SetPolicyEnforcement sets the PolicyEnforcement configuration value for the Cilium agent to the provided status.

func (*SSHMeta) SetPolicyEnforcementAndWait

func (s *SSHMeta) SetPolicyEnforcementAndWait(status string) bool

SetPolicyEnforcementAndWait and wait sets the PolicyEnforcement configuration value for the Cilium agent to the provided status, and then waits for all endpoints running in s to be ready. Returns whether setting of the configuration value was unsuccessful / if the endpoints go into ready state.

func (*SSHMeta) SetUpCilium

func (s *SSHMeta) SetUpCilium() error

SetUpCilium sets up Cilium as a systemd service with a hardcoded set of options. It returns an error if any of the operations needed to start Cilium fails.

func (*SSHMeta) SetUpCiliumWithHubble

func (s *SSHMeta) SetUpCiliumWithHubble() error

func (*SSHMeta) SetUpCiliumWithOptions

func (s *SSHMeta) SetUpCiliumWithOptions(ciliumOpts string) error

SetUpCiliumWithOptions sets up Cilium as a systemd service with a given set of options. It returns an error if any of the operations needed to start Cilium fail.

func (*SSHMeta) String

func (s *SSHMeta) String() string

func (*SSHMeta) ValidateEndpointsAreCorrect

func (s *SSHMeta) ValidateEndpointsAreCorrect(dockerNetwork string) error

ValidateEndpointsAreCorrect is a function that validates that all Docker container that are in the given docker network are correct as cilium endpoints.

func (*SSHMeta) ValidateNoErrorsInLogs

func (s *SSHMeta) ValidateNoErrorsInLogs(duration time.Duration)

ValidateNoErrorsInLogs checks in cilium logs since the given duration (By default `CurrentGinkgoTestDescription().Duration`) do not contain `panic`, `deadlocks` or `segmentation faults` messages . In case of any of these messages, it'll mark the test as failed.

func (*SSHMeta) WaitDockerPluginReady

func (s *SSHMeta) WaitDockerPluginReady() bool

WaitDockerPluginReady waits up until timeout reached for Cilium docker plugin to be ready

func (*SSHMeta) WaitEndpointsDeleted

func (s *SSHMeta) WaitEndpointsDeleted() bool

WaitEndpointsDeleted waits up until timeout reached for all endpoints to be deleted. Returns true if all endpoints have been deleted before HelperTimeout is exceeded, false otherwise.

func (*SSHMeta) WaitEndpointsReady

func (s *SSHMeta) WaitEndpointsReady() bool

WaitEndpointsReady waits up until timeout reached for all endpoints to not be in any regenerating or waiting-for-identity state. Returns true if all endpoints regenerate before HelperTimeout is exceeded, false otherwise.

func (*SSHMeta) WaitUntilReady

func (s *SSHMeta) WaitUntilReady(timeout time.Duration) error

WaitUntilReady waits until the output of `cilium status` returns with code zero. Returns an error if the output of `cilium status` returns a nonzero return code after the specified timeout duration has elapsed.

type SSHMetaError

type SSHMetaError struct {
	// contains filtered or unexported fields
}

SSHMetaError is a custom error that executes a callback function when its Error() function is invoked

func NewSSHMetaError

func NewSSHMetaError(errorString string, callback func() string) *SSHMetaError

NewSSHMetaError returns a new SSHMetaError with the given string and a callback function

func (*SSHMetaError) Error

func (e *SSHMetaError) Error() string

func (*SSHMetaError) String

func (e *SSHMetaError) String() string

type TimeoutConfig

type TimeoutConfig struct {
	Ticker  time.Duration // Check interval
	Timeout time.Duration // Limit for how long to spend in the command
}

TimeoutConfig represents the configuration for the timeout of a command.

func (*TimeoutConfig) Validate

func (c *TimeoutConfig) Validate() error

Validate ensuires that the parameters for the TimeoutConfig are reasonable for running in tests.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL