framework

package
v1.4.13 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2024 License: Apache-2.0 Imports: 80 Imported by: 0

Documentation

Overview

Package framework implements test framework common methods.

Index

Constants

View Source
const (
	// DefaultFsmGrafanaPort is the default Grafana port
	DefaultFsmGrafanaPort = 3000
	// DefaultFsmPrometheusPort default FSM prometheus port
	DefaultFsmPrometheusPort = 7070

	// FsmGrafanaAppLabel is the FSM Grafana deployment app label
	FsmGrafanaAppLabel = "fsm-grafana"
	// FsmPrometheusAppLabel is the FSM Prometheus deployment app label
	FsmPrometheusAppLabel = "fsm-prometheus"

	// MeshDetails is dashboard uuid and name as we have them load in Grafana
	MeshDetails string = "PLyKJcHGz/mesh-and-sidecar-details"

	// MemRSSPanel is the ID of the MemRSS panel on FSM's MeshDetails dashboard
	MemRSSPanel int = 13

	// CPUPanel is the ID of the CPU panel on FSM's MeshDetails dashboard
	CPUPanel int = 14
)
View Source
const (
	// DefaultUpstreamServicePort is the default port on which the server apps listen for connections from client apps.
	// Note: Port 80 should not be used because it does not work on OpenShift.
	DefaultUpstreamServicePort = 14001
)
View Source
const OSCrossPlatform string = "Cross-platform"

OSCrossPlatform indicates that a test can run on all operating systems.

View Source
const (
	// StatusCodeWord is an identifier used on curl commands to print and parse REST Status codes
	StatusCodeWord = "StatusCode"
)

Variables

View Source
var (
	// FsmCtlLabels is the list of app labels for FSM CTL
	FsmCtlLabels = []string{constants.FSMControllerName, FsmGrafanaAppLabel, FsmPrometheusAppLabel, constants.FSMInjectorName, constants.FSMBootstrapName}

	// NginxIngressSvc is the namespaced name of the nginx ingress service
	NginxIngressSvc = types.NamespacedName{Namespace: "ingress-ns", Name: "ingress-nginx-controller"}
)
View Source
var HttpbinCmd = []string{"gunicorn", "-b", fmt.Sprintf("0.0.0.0:%d", DefaultUpstreamServicePort), "httpbin:app", "-k", "gevent"}

HttpbinCmd is the command to be used for httpbin applications in e2es

View Source
var PodCommandDefault = []string{}

PodCommandDefault is the default pod command (nothing)

Functions

func FSMDescribe

func FSMDescribe(name string, opts FSMDescribeInfo, body func()) bool

FSMDescribe givens the description of an e2e test

func RandomNameWithPrefix

func RandomNameWithPrefix(prefix string) string

RandomNameWithPrefix generates a random string with the given prefix.

If the prefix is empty, the default prefix "test" will be used

Types

type CleanupType

type CleanupType string

CleanupType identifies what triggered the cleanup

const (
	// Test is to mark after-test cleanup
	Test CleanupType = "test"

	//Suite is to mark after-suite cleanup
	Suite CleanupType = "suite"
)

type CollectLogsType

type CollectLogsType string

CollectLogsType defines if/when to collect logs

const (
	// CollectLogs is used to force log collection
	CollectLogs CollectLogsType = "yes"

	// CollectLogsIfErrorOnly will collect logs only when test errors out
	CollectLogsIfErrorOnly CollectLogsType = "ifError"

	// NoCollectLogs will not collect logs
	NoCollectLogs CollectLogsType = "no"

	// ControlPlaneOnly will collect logs only for control plane processes
	ControlPlaneOnly CollectLogsType = "controlPlaneOnly"
)

type DataHandle

type DataHandle struct {
	// Test start time
	TestStartTime time.Time

	// Prometheus and Grafana handles
	PromHandle *Prometheus
	GrafHandle *Grafana

	// Result output files, allows setting multiple descriptors to write results
	ResultsOut []*os.File

	// Defines the resources to keep track across iterations
	TrackAppLabels []TrackedLabel
	// Defines the panels to save upon WrapUp invocation
	GrafanaPanelsToSave []GrafanaPanel

	// Set of names to track exact resources that were observed at any point in time
	// during the test
	SeenResources map[Resource]bool

	// Scale iterations data
	Iterations  int
	ItStartTime []time.Time
	ItEndTime   []time.Time
}

DataHandle is the handle to specific resource information during a test

func NewDataHandle

func NewDataHandle(pHandle *Prometheus, gHandle *Grafana, trackResources []TrackedLabel, saveDashboards []GrafanaPanel) *DataHandle

NewDataHandle Returns an initialized scale data

func (*DataHandle) Iterate

func (sd *DataHandle) Iterate(f func())

Iterate wrapper to loop and track various resources across iterations (time, mem consumption, iteration num, etc.)

func (*DataHandle) IterateTrackedPods

func (sd *DataHandle) IterateTrackedPods(f func(pod *corev1.Pod))

IterateTrackedPods is a Helper to iterate pods selected by the Tracked labels

func (*DataHandle) OutputIteration

func (sd *DataHandle) OutputIteration(iterNumber int, f *os.File)

OutputIteration prints on file <f> the results of iteration <iterNumber> The CpuAvg is taken from the duration of the iteration itself, and uses prometheus `rate` which has extrapolation of both sides of the bucket. Mem RSS is simply the Mem RSS value at the end of the iteration.

func (*DataHandle) OutputIterationTable

func (sd *DataHandle) OutputIterationTable(f *os.File)

OutputIterationTable Print all iteration statistics in table format. For Duration and Memory values, relative distance to previous iteration is computed. For CPU, the CPU load average over the iteration time is computed (using prometheus rate).

func (*DataHandle) OutputMemPerPod

func (sd *DataHandle) OutputMemPerPod(f *os.File)

OutputMemPerPod outputs the per-pod mem delta for the tracked resources over the test and outputs it in table format, example: The output requires at least 2 iterations to compare, as the MemRSS initial value is taken from the end of the first iteration, to avoid counting overhead of the application itself.

func (*DataHandle) OutputTestResults

func (sd *DataHandle) OutputTestResults(f *os.File)

OutputTestResults Print all available results

func (*DataHandle) WrapUp

func (sd *DataHandle) WrapUp()

WrapUp is a callback to execute after the test is done. Will output all iteration results, compute some relative usages between iterations and save grafana dashboards if any are to be saved

type DockerConfig

type DockerConfig map[string]DockerConfigEntry

DockerConfig and other configs are docker-specific container registry secret structures. Most of it is taken or referenced from kubectl source itself

type DockerConfigEntry

type DockerConfigEntry struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Email    string `json:"email,omitempty"`
	Auth     string `json:"auth,omitempty"`
}

DockerConfigEntry is a struct for docker-specific container registry secret structures

type DockerConfigJSON

type DockerConfigJSON struct {
	Auths       DockerConfig      `json:"auths"`
	HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
}

DockerConfigJSON is a struct for docker-specific config

type FSMDescribeInfo

type FSMDescribeInfo struct {
	// Tier represents the priority of the test. Lower value indicates higher priority.
	Tier int

	// Bucket indicates in which test Bucket the test will run in for CI. Each
	// Bucket is run in parallel while tests in the same Bucket run sequentially.
	Bucket int

	// OS indicates which OS the test can run on.
	OS string
}

FSMDescribeInfo is a struct to represent the Tier and Bucket of a given e2e test

func (FSMDescribeInfo) String

func (o FSMDescribeInfo) String() string

type FortioGRPCLoadTestDef

type FortioGRPCLoadTestDef struct {
	GRPCRequestDef
	FortioLoadTestSpec
}

FortioGRPCLoadTestDef defines a Fortio GRPC load test intent

type FortioHTTPLoadTestDef

type FortioHTTPLoadTestDef struct {
	HTTPRequestDef
	FortioLoadTestSpec
}

FortioHTTPLoadTestDef defines a Fortio HTTP load test intent

type FortioLoadResult

type FortioLoadResult struct {
	ReturnCodes   map[string]FortioReturnCodeEntry
	DurationHist  map[float64]float64
	TotalRequests int32

	Err error
}

FortioLoadResult represents Fortio load test result

func (*FortioLoadResult) AllReturnCodes

func (result *FortioLoadResult) AllReturnCodes() []string

AllReturnCodes returns all the load test return codes as an array of strings.

func (*FortioLoadResult) HasFailedHTTPRequests

func (result *FortioLoadResult) HasFailedHTTPRequests() bool

HasFailedHTTPRequests checks if there is return code not smaller than 400. Non-numeric return code will be skipped. This is suitable for checking the result of Fortio HTTP load test.

type FortioLoadTestSpec

type FortioLoadTestSpec struct {
	// QPS is the number of requests per second. Negative number means no wait maximum rate. The default is 8
	QPS int

	// Connections is the number of connections/goroutines. The default is 4
	Connections int

	// Calls is the number of requests. Default is 0, which uses duration.
	Calls int

	// Duration is the duration of the test. Default is 5 seconds.
	Duration string
}

FortioLoadTestSpec defines the Fortio load test specification. Request definition is not included.

type FortioReturnCodeEntry

type FortioReturnCodeEntry struct {
	ReturnCode string
	Count      int
	Percentage float64
}

FortioReturnCodeEntry is a data entry for a single Fortio load test return code with related stats.

type FortioTCPLoadTestDef

type FortioTCPLoadTestDef struct {
	TCPRequestDef
	FortioLoadTestSpec
}

FortioTCPLoadTestDef defines a Fortio TCP load test intent

type FsmTestData

type FsmTestData struct {
	T           ginkgo.GinkgoTInterface // for common test logging
	TestID      uint64                  // uint randomized for every test. GinkgoRandomSeed can't be used as is per-suite.
	TestDirBase string                  // Test directory base, default "/tmp", can be variable overridden
	TestDirName string                  // Autogenerated, based on test ID

	CleanupTest          bool            // Cleanup test-related resources once finished
	WaitForCleanup       bool            // Forces test to wait for effective deletion of resources upon cleanup
	IgnoreRestarts       bool            // Ignore control plane processes restarts, if any
	InstType             InstallType     // Install type
	CollectLogs          CollectLogsType // Collect logs type
	InitialRestartValues map[string]int  // Captures properly if an FSM instance have restarted during a NoInstall test

	FsmNamespace      string
	FsmMeshConfigName string
	FsmImageTag       string
	EnableNsMetricTag bool

	// Container registry related vars
	CtrRegistryUser     string // registry login
	CtrRegistryPassword string // registry password, if any
	CtrRegistryServer   string // server name. Has to be network reachable

	// Kind cluster related vars
	ClusterName                    string // Kind cluster name (used if kindCluster)
	CleanupKindClusterBetweenTests bool   // Clean and re-create kind cluster between tests
	CleanupKindCluster             bool   // Cleanup kind cluster upon test finish
	ClusterVersion                 string // Kind cluster version, ex. v1.20.2

	ClusterOS string // The operating system of the working nodes in the cluster. Mixed OS traffic is not supported.

	ReqSuccessTimeout time.Duration // ReqSuccessTimeout timeout duration that the test expects for all requests from the client to server to succeed.

	// Cluster handles and rest config
	Env             *cli.EnvSettings
	RestConfig      *rest.Config
	Client          *kubernetes.Clientset
	APIServerClient *clientset.Clientset

	SmiClients *smiClients

	// FSM's API clients
	PolicyClient     *versioned.Clientset
	ConfigClient     *versioned2.Clientset
	GatewayAPIClient gatewayApiClientset.Interface
	NsigClient       nsigClientset.Interface

	ClusterProvider *cluster.Provider // provider, used when kindCluster is used

	DeployOnOpenShift bool // Determines whether to configure tests for OpenShift

	RetryAppPodCreation bool // Whether to retry app pod creation due to issue #3973
}

FsmTestData stores common state, variables and flags for the test at hand

var Td FsmTestData

Td the global context for test.

func (*FsmTestData) AddNsToMesh

func (td *FsmTestData) AddNsToMesh(enableSidecarInjection bool, ns ...string) error

AddNsToMesh Adds monitored namespaces to the FSM mesh

func (*FsmTestData) AddOpenShiftSCC

func (td *FsmTestData) AddOpenShiftSCC(scc, serviceAccount, namespace string) error

AddOpenShiftSCC adds the specified SecurityContextConstraint to the given service account

func (*FsmTestData) AreRegistryCredsPresent

func (td *FsmTestData) AreRegistryCredsPresent() bool

AreRegistryCredsPresent checks if Registry Credentials are present It's usually used to factor if a docker registry secret and ImagePullSecret should be installed when creating namespaces and application templates

func (*FsmTestData) Cleanup

func (td *FsmTestData) Cleanup(ct CleanupType)

Cleanup is Used to cleanup resources once the test is done Cyclomatic complexity is disabled in cleanup, as it check a large number of conditions nolint:gocyclo

func (*FsmTestData) CreateConfigMap added in v1.3.0

func (td *FsmTestData) CreateConfigMap(ns string, cm corev1.ConfigMap) (*corev1.ConfigMap, error)

CreateConfigMap is a wrapper to create a config map

func (*FsmTestData) CreateDeployment

func (td *FsmTestData) CreateDeployment(ns string, deployment appsv1.Deployment) (*appsv1.Deployment, error)

CreateDeployment is a wrapper to create a deployment

func (*FsmTestData) CreateDockerRegistrySecret

func (td *FsmTestData) CreateDockerRegistrySecret(ns string)

CreateDockerRegistrySecret creates a secret named `RegistrySecretName` in namespace <ns>, based on ctrRegistry variables

func (*FsmTestData) CreateGateway added in v1.3.0

func (td *FsmTestData) CreateGateway(ns string, gw gwv1.Gateway) (*gwv1.Gateway, error)

CreateGateway Creates a Gateway

func (*FsmTestData) CreateGatewayAPIGRPCRoute added in v1.3.0

func (td *FsmTestData) CreateGatewayAPIGRPCRoute(ns string, r gwv1.GRPCRoute) (*gwv1.GRPCRoute, error)

CreateGatewayAPIGRPCRoute Creates a GRPCRoute

func (*FsmTestData) CreateGatewayAPIHTTPRoute added in v1.3.0

func (td *FsmTestData) CreateGatewayAPIHTTPRoute(ns string, r gwv1.HTTPRoute) (*gwv1.HTTPRoute, error)

CreateGatewayAPIHTTPRoute Creates a HTTPRoute

func (*FsmTestData) CreateGatewayAPIReferenceGrant added in v1.3.0

func (td *FsmTestData) CreateGatewayAPIReferenceGrant(ns string, r gwv1beta1.ReferenceGrant) (*gwv1beta1.ReferenceGrant, error)

CreateGatewayAPIReferenceGrant Creates a ReferenceGrant

func (*FsmTestData) CreateGatewayAPITCPRoute added in v1.3.0

func (td *FsmTestData) CreateGatewayAPITCPRoute(ns string, r gwv1alpha2.TCPRoute) (*gwv1alpha2.TCPRoute, error)

CreateGatewayAPITCPRoute Creates a TCPRoute

func (*FsmTestData) CreateGatewayAPITLSRoute added in v1.3.0

func (td *FsmTestData) CreateGatewayAPITLSRoute(ns string, r gwv1alpha2.TLSRoute) (*gwv1alpha2.TLSRoute, error)

CreateGatewayAPITLSRoute Creates a TLSRoute

func (*FsmTestData) CreateGatewayAPIUDPRoute added in v1.3.0

func (td *FsmTestData) CreateGatewayAPIUDPRoute(ns string, r gwv1alpha2.UDPRoute) (*gwv1alpha2.UDPRoute, error)

CreateGatewayAPIUDPRoute Creates a UDPRoute

func (*FsmTestData) CreateHTTPRouteGroup

func (td *FsmTestData) CreateHTTPRouteGroup(ns string, rg smiSpecs.HTTPRouteGroup) (*smiSpecs.HTTPRouteGroup, error)

CreateHTTPRouteGroup Creates an SMI HTTPRouteGroup

func (*FsmTestData) CreateIngress added in v1.3.0

func (td *FsmTestData) CreateIngress(ns string, ing networkingv1.Ingress) (*networkingv1.Ingress, error)

CreateIngress is a wrapper to create an ingress

func (*FsmTestData) CreateMultipleNs

func (td *FsmTestData) CreateMultipleNs(nsName ...string) error

CreateMultipleNs simple CreateNs for multiple NS creation

func (*FsmTestData) CreateMutatingWebhook

CreateMutatingWebhook is a wrapper to create a mutating webhook configuration

func (*FsmTestData) CreateNamespacedIngress added in v1.3.0

func (td *FsmTestData) CreateNamespacedIngress(ns string, ing nsigv1alpha1.NamespacedIngress) (*nsigv1alpha1.NamespacedIngress, error)

CreateNamespacedIngress is a wrapper to create an ingress

func (*FsmTestData) CreateNs

func (td *FsmTestData) CreateNs(nsName string, labels map[string]string) error

CreateNs creates a Namespace. Will automatically add Docker registry creds if provided

func (*FsmTestData) CreatePod

func (td *FsmTestData) CreatePod(ns string, pod corev1.Pod) (*corev1.Pod, error)

CreatePod is a wrapper to create a pod

func (*FsmTestData) CreateService

func (td *FsmTestData) CreateService(ns string, svc corev1.Service) (*corev1.Service, error)

CreateService is a wrapper to create a service

func (*FsmTestData) CreateServiceAccount

func (td *FsmTestData) CreateServiceAccount(ns string, svcAccount *corev1.ServiceAccount) (*corev1.ServiceAccount, error)

CreateServiceAccount is a wrapper to create a service account If creating on OpenShift, add privileged SCC

func (*FsmTestData) CreateSimpleAllowPolicy

func (td *FsmTestData) CreateSimpleAllowPolicy(def SimpleAllowPolicy) (smiSpecs.HTTPRouteGroup, smiAccess.TrafficTarget)

CreateSimpleAllowPolicy returns basic allow policy from source to destination, on a HTTP all-wildcard fashion

func (*FsmTestData) CreateSimpleTCPAllowPolicy

func (td *FsmTestData) CreateSimpleTCPAllowPolicy(def SimpleAllowPolicy, port int) (smiSpecs.TCPRoute, smiAccess.TrafficTarget)

CreateSimpleTCPAllowPolicy returns an allow policy to allow all TCP traffic from source to destination

func (*FsmTestData) CreateSimpleTrafficSplit

func (td *FsmTestData) CreateSimpleTrafficSplit(def TrafficSplitDef) (smiSplit.TrafficSplit, error)

CreateSimpleTrafficSplit Creates an SMI TrafficTarget

func (*FsmTestData) CreateTCPRoute

func (td *FsmTestData) CreateTCPRoute(ns string, route smiSpecs.TCPRoute) (*smiSpecs.TCPRoute, error)

CreateTCPRoute Creates an SMI TCPRoute

func (*FsmTestData) CreateTrafficSplit

func (td *FsmTestData) CreateTrafficSplit(ns string, tar smiSplit.TrafficSplit) (*smiSplit.TrafficSplit, error)

CreateTrafficSplit Creates an SMI TrafficSplit

func (*FsmTestData) CreateTrafficTarget

func (td *FsmTestData) CreateTrafficTarget(ns string, tar smiAccess.TrafficTarget) (*smiAccess.TrafficTarget, error)

CreateTrafficTarget Creates an SMI TrafficTarget

func (*FsmTestData) DeleteHelmRelease

func (td *FsmTestData) DeleteHelmRelease(name, namespace string) error

DeleteHelmRelease uninstalls a particular helm release

func (*FsmTestData) DeleteNs

func (td *FsmTestData) DeleteNs(nsName string) error

DeleteNs deletes a test NS

func (*FsmTestData) FortioGRPCLoadTest

func (td *FsmTestData) FortioGRPCLoadTest(req FortioGRPCLoadTestDef) FortioLoadResult

FortioGRPCLoadTest runs a Fortio load test with GRPC protocol according to given FortioGRPCLoadTestDef and returns a FortioLoadResult

func (*FsmTestData) FortioHTTPLoadTest

func (td *FsmTestData) FortioHTTPLoadTest(ht FortioHTTPLoadTestDef) FortioLoadResult

FortioHTTPLoadTest runs a Fortio load test with HTTP protocol according to given FortioHTTPLoadTestDef and returns a FortioLoadResult

func (*FsmTestData) FortioTCPLoadTest

func (td *FsmTestData) FortioTCPLoadTest(req FortioTCPLoadTestDef) FortioLoadResult

FortioTCPLoadTest runs a Fortio load test with TCP protocol according to given FortioTCPLoadTestDef and returns a FortioLoadResult

func (*FsmTestData) GRPCRequest

func (td *FsmTestData) GRPCRequest(req GRPCRequestDef) GRPCRequestResult

GRPCRequest runs a GRPC request to run the GRPCRequestDef and return a GRPCRequestResult

func (*FsmTestData) GetBugReport

func (td *FsmTestData) GetBugReport() error

GetBugReport runs the "fsm support bug-report" command

func (*FsmTestData) GetFSMGrafanaHandle

func (td *FsmTestData) GetFSMGrafanaHandle() (*Grafana, error)

GetFSMGrafanaHandle convenience wrapper, will get the Grafana instance regularly deployed by FSM installation in test <FsmNamespace>

func (*FsmTestData) GetFSMInstallOpts

func (td *FsmTestData) GetFSMInstallOpts(options ...InstallFsmOpt) InstallFSMOpts

GetFSMInstallOpts initializes install options for FSM

func (*FsmTestData) GetFSMPrometheusHandle

func (td *FsmTestData) GetFSMPrometheusHandle() (*Prometheus, error)

GetFSMPrometheusHandle convenience wrapper, will get the Prometheus instance regularly deployed by FSM installation in test <FsmNamespace>

func (*FsmTestData) GetFsmCtlComponentRestarts

func (td *FsmTestData) GetFsmCtlComponentRestarts() map[string]int

GetFsmCtlComponentRestarts gets the number of restarts of FSM CTL processes back in a map

func (*FsmTestData) GetGrafanaPodHandle

func (td *FsmTestData) GetGrafanaPodHandle(ns string, grafanaPodName string, port uint16) (*Grafana, error)

GetGrafanaPodHandle generic func to forward a grafana pod and returns a handler pointing to the locally forwarded resource

func (*FsmTestData) GetMeshConfig

func (td *FsmTestData) GetMeshConfig(namespace string) (*configv1alpha3.MeshConfig, error)

GetMeshConfig is a wrapper to get a MeshConfig by name in a particular namespace

func (*FsmTestData) GetMutatingWebhook

func (td *FsmTestData) GetMutatingWebhook(mwhcName string) (*admissionregv1.MutatingWebhookConfiguration, error)

GetMutatingWebhook is a wrapper to get a mutating webhook configuration

func (*FsmTestData) GetOSSpecificHTTPBinPod

func (td *FsmTestData) GetOSSpecificHTTPBinPod(podName string, namespace string, customCommand ...string) (corev1.ServiceAccount, corev1.Pod, corev1.Service, error)

GetOSSpecificHTTPBinPod returns a OS pod that runs httpbin.

func (*FsmTestData) GetOSSpecificSleepPod

func (td *FsmTestData) GetOSSpecificSleepPod(sourceNs string) (corev1.ServiceAccount, corev1.Pod, corev1.Service, error)

GetOSSpecificSleepPod returns a simple OS specific busy loop pod.

func (*FsmTestData) GetOSSpecificTCPEchoPod

func (td *FsmTestData) GetOSSpecificTCPEchoPod(podName string, namespace string, destinationPort int) (corev1.ServiceAccount, corev1.Pod, corev1.Service, error)

GetOSSpecificTCPEchoPod returns a simple OS specific tcp-echo pod.

func (*FsmTestData) GetPodsForLabel

func (td *FsmTestData) GetPodsForLabel(ns string, labelSel metav1.LabelSelector) ([]corev1.Pod, error)

GetPodsForLabel returns the Pods matching a specific `appLabel`

func (*FsmTestData) GetPrometheusPodHandle

func (td *FsmTestData) GetPrometheusPodHandle(ns string, prometheusPodName string, port uint16) (*Prometheus, error)

GetPrometheusPodHandle generic func to forward a prometheus pod and returns a handler pointing to the locally forwarded resource

func (*FsmTestData) GetSidecarClass

func (td *FsmTestData) GetSidecarClass(namespace string) string

GetSidecarClass is a wrapper to get sidecarClass in a particular namespace

func (*FsmTestData) GetTestDirPath

func (td *FsmTestData) GetTestDirPath() string

GetTestDirPath Returns absolute TestDirPath

func (*FsmTestData) GetTestFilePath

func (td *FsmTestData) GetTestFilePath(filename string) string

GetTestFilePath Returns absolute filepath for a filename. Will ensure TestFolder already exists. Convenience function used to get a proper filepath when creating a file in TestDir

func (*FsmTestData) GetTestNamespaceSelectorMap

func (td *FsmTestData) GetTestNamespaceSelectorMap() map[string]string

GetTestNamespaceSelectorMap returns a string-based selector used to refer/select all namespace resources for this test

func (*FsmTestData) GrabLogs

func (td *FsmTestData) GrabLogs() error

GrabLogs Collects logs on test folder for td.FsmNamespace

func (*FsmTestData) HTTPRequest

func (td *FsmTestData) HTTPRequest(ht HTTPRequestDef) HTTPRequestResult

HTTPRequest runs a synchronous call to run the HTTPRequestDef and return a HTTPRequestResult

func (*FsmTestData) HelmInstallFSM

func (td *FsmTestData) HelmInstallFSM(release, namespace string) error

HelmInstallFSM installs an fsm control plane using the fsm chart which lives in charts/fsm

func (*FsmTestData) InitSMIClients

func (td *FsmTestData) InitSMIClients() error

InitSMIClients initializes SMI clients on FsmTestData structure

func (*FsmTestData) InitTestData

func (td *FsmTestData) InitTestData(t GinkgoTInterface) error

InitTestData Initializes the test structures Called by Ginkgo BeforeEach

func (*FsmTestData) InstallFSM

func (td *FsmTestData) InstallFSM(instOpts InstallFSMOpts) error

InstallFSM installs FSM. The behavior of this function is dependant on installType and instOpts

func (*FsmTestData) InstallNginxIngress

func (td *FsmTestData) InstallNginxIngress() (string, error)

InstallNginxIngress installs the k8s Nginx Ingress controller and returns the IP address that clients can send traffic to for ingress

func (*FsmTestData) LoadFSMImagesIntoKind

func (td *FsmTestData) LoadFSMImagesIntoKind() error

LoadFSMImagesIntoKind loads the FSM images to the node for Kind clusters

func (*FsmTestData) LoadImagesToKind

func (td *FsmTestData) LoadImagesToKind(imageNames []string) error

LoadImagesToKind loads the list of images to the node for Kind clusters

func (*FsmTestData) LocalGRPCRequest added in v1.3.0

func (td *FsmTestData) LocalGRPCRequest(req GRPCRequestDef) GRPCRequestResult

LocalGRPCRequest runs a GRPC request to run the GRPCRequestDef and return a GRPCRequestResult

func (*FsmTestData) LocalHTTPRequest added in v1.3.0

func (td *FsmTestData) LocalHTTPRequest(ht HTTPRequestDef) HTTPRequestResult

LocalHTTPRequest runs a synchronous call to run the HTTPRequestDef and return a HTTPRequestResult

func (*FsmTestData) LocalTCPRequest added in v1.3.0

func (td *FsmTestData) LocalTCPRequest(req TCPRequestDef) TCPRequestResult

LocalTCPRequest runs a synchronous TCP request to run the TCPRequestDef and return a TCPRequestResult

func (*FsmTestData) LocalUDPRequest added in v1.3.0

func (td *FsmTestData) LocalUDPRequest(req UDPRequestDef) UDPRequestResult

LocalUDPRequest runs a synchronous UDP request to run the UDPRequestDef and return a UDPRequestResult

func (*FsmTestData) MultipleHTTPRequest

func (td *FsmTestData) MultipleHTTPRequest(requests *HTTPMultipleRequest) HTTPMultipleResults

MultipleHTTPRequest will issue a list of requests concurrently and return results when all requests have returned

func (*FsmTestData) PrettyPrintHTTPResults

func (td *FsmTestData) PrettyPrintHTTPResults(results *HTTPMultipleResults)

PrettyPrintHTTPResults prints pod results per namespace

func (*FsmTestData) RestartFSMController

func (td *FsmTestData) RestartFSMController(instOpts InstallFSMOpts) error

RestartFSMController restarts the fsm-controller pod in the installed controller's namespace

func (*FsmTestData) RetryFuncOnError

func (td *FsmTestData) RetryFuncOnError(f RetryOnErrorFunc, retryTimes int, sleepBetweenRetries time.Duration) error

RetryFuncOnError runs the given function and retries for the given number of times if an error is encountered

func (*FsmTestData) RunLocal

func (td *FsmTestData) RunLocal(path string, args ...string) (*bytes.Buffer, *bytes.Buffer, error)

RunLocal Executes command on local

func (*FsmTestData) RunRemote

func (td *FsmTestData) RunRemote(
	ns string, podName string, containerName string,
	command []string) (string, string, error)

RunRemote runs command in remote container

func (*FsmTestData) SimpleDeploymentApp

SimpleDeploymentApp creates returns a set of k8s typed definitions for a deployment-based k8s definition. Includes Deployment, Service and ServiceAccount types

func (*FsmTestData) SimplePodApp

SimplePodApp returns a set of k8s typed definitions for a pod-based k8s definition. Includes Pod, Service and ServiceAccount types

func (*FsmTestData) SimpleServiceAccount

func (td *FsmTestData) SimpleServiceAccount(name string, namespace string) corev1.ServiceAccount

SimpleServiceAccount returns a k8s typed definition for a service account.

func (*FsmTestData) TCPRequest

func (td *FsmTestData) TCPRequest(req TCPRequestDef) TCPRequestResult

TCPRequest runs a synchronous TCP request to run the TCPRequestDef and return a TCPRequestResult

func (*FsmTestData) UpdateFSMConfig

func (td *FsmTestData) UpdateFSMConfig(meshConfig *configv1alpha3.MeshConfig) (*configv1alpha3.MeshConfig, error)

UpdateFSMConfig updates FSM MeshConfig

func (*FsmTestData) ValidateStringParams

func (td *FsmTestData) ValidateStringParams() error

ValidateStringParams validates input string parameters are valid

func (*FsmTestData) VerifyRestarts

func (td *FsmTestData) VerifyRestarts() bool

VerifyRestarts ensure no crashes on fsm-namespace instances for FSM CTL processes

func (*FsmTestData) WaitForNamespacesDeleted

func (td *FsmTestData) WaitForNamespacesDeleted(namespaces []string, timeout time.Duration) error

WaitForNamespacesDeleted waits for the namespaces to be deleted. Reference impl taken from https://github.com/kubernetes/kubernetes/blob/master/test/e2e/framework/util.go#L258

func (*FsmTestData) WaitForPodsDeleted

func (td *FsmTestData) WaitForPodsDeleted(pods *corev1.PodList, namespace string, timeout time.Duration) error

WaitForPodsDeleted waits for the pods to be deleted.

func (*FsmTestData) WaitForPodsRunningReady

func (td *FsmTestData) WaitForPodsRunningReady(ns string, nExpectedRunningPods int, labelSelector *metav1.LabelSelector) error

WaitForPodsRunningReady waits for a <n> number of pods on an NS to be running and ready `labelSelector` can be optionally passed to further select the pods to wait for

func (*FsmTestData) WaitForRepeatedSuccess

func (td *FsmTestData) WaitForRepeatedSuccess(f SuccessFunction, minItForSuccess int, maxWaitTime time.Duration) bool

WaitForRepeatedSuccess runs and expects a certain result for a certain operation a set number of consecutive times over a set amount of time.

func (*FsmTestData) WaitForSuccessAfterInitialFailure

func (td *FsmTestData) WaitForSuccessAfterInitialFailure(f SuccessFunction, minItForSuccess int, maxWaitTime time.Duration) bool

WaitForSuccessAfterInitialFailure runs and expects a certain result for a certain operation a set number of consecutive times but requires only success after the first success.

type GRPCRequestDef

type GRPCRequestDef struct {
	// Source pod where to run the GRPC request from
	SourceNs        string
	SourcePod       string
	SourceContainer string

	// The entire destination URL processed by curl, including host name and
	// optionally protocol, port, and path
	Destination string

	// JSONRequest is the JSON request body
	JSONRequest string

	// Symbol is the fully qualified grpc service name, ex. hello.HelloService/SayHello
	Symbol string

	// UseTLS indicates if the request should be encrypted with TLS
	UseTLS bool

	// CertFile is the path to the certificate file
	CertFile string

	// ProtoFile
	ProtoFile string
}

GRPCRequestDef defines a remote GRPC request intent

type GRPCRequestResult

type GRPCRequestResult struct {
	Response string
	Err      error
}

GRPCRequestResult represents the result of a GRPCRequest call

type Grafana

type Grafana struct {
	Schema   string
	Hostname string
	Port     uint16
	User     string
	Password string
	// contains filtered or unexported fields
}

Grafana is a simple handler to represent a target Grafana endpoint to run queries against

func (*Grafana) PanelPNGSnapshot

func (g *Grafana) PanelPNGSnapshot(dashboard string, panelID int, fromMinutes int, saveFilepath string) error

PanelPNGSnapshot takes a snapshot from a Grafana dashboard or panel and saves it in local in <filename> in png format, using it's remote rendering HTTP API.

func (*Grafana) Stop

func (g *Grafana) Stop()

Stop gracefully stops the port forwarding to Grafana

type GrafanaPanel

type GrafanaPanel struct {
	Filename  string
	Dashboard string
	Panel     int
}

GrafanaPanel identifies a target Panel to be saved at the end of the test

type HTTPMultipleRequest

type HTTPMultipleRequest struct {
	// Request
	Sources []HTTPRequestDef
}

HTTPMultipleRequest takes multiple HTTP request defs to issue them concurrently

type HTTPMultipleResults

type HTTPMultipleResults map[string]map[string]HTTPRequestResult

HTTPMultipleResults represents results from a multiple HTTP request call results come back as a map["srcNs/srcPod"]["dstNs/dstPod"] -> HTTPResults

type HTTPRequestDef

type HTTPRequestDef struct {
	// Source pod where to run the HTTP request from
	SourceNs        string
	SourcePod       string
	SourceContainer string

	// The entire destination URL processed by curl, including host name and
	// optionally protocol, port, and path
	Destination string

	// UseTLS indicates if the request should be encrypted with TLS
	UseTLS bool

	// CertFile is the path to the certificate file
	CertFile string

	// IsTLSPassthrough indicates if the request should be TLS passthrough
	IsTLSPassthrough bool

	// PassthroughHost is the host to passthrough
	PassthroughHost string

	// PassthroughPort is the port to passthrough
	PassthroughPort int
}

HTTPRequestDef defines a remote HTTP request intent

type HTTPRequestResult

type HTTPRequestResult struct {
	StatusCode int
	Headers    map[string]string
	Err        error
}

HTTPRequestResult represents results of an HTTPRequest call

type InstallFSMOpts

type InstallFSMOpts struct {
	ControlPlaneNS          string
	CertManager             string
	ContainerRegistryLoc    string
	ContainerRegistrySecret string
	FsmImagetag             string
	DeployGrafana           bool
	DeployPrometheus        bool
	DeployJaeger            bool
	DeployFluentbit         bool
	EnableReconciler        bool
	EnableIngress           bool
	IngressHTTPPort         int32
	EnableIngressTLS        bool
	IngressTLSPort          int32
	EnableNamespacedIngress bool
	EnableGateway           bool
	EnableFLB               bool
	EnableServiceLB         bool
	EnableEgressGateway     bool

	VaultHost            string
	VaultProtocol        string
	VaultPort            int
	VaultToken           string
	VaultRole            string
	VaultTokenSecretName string
	VaultTokenSecretKey  string

	CertmanagerIssuerGroup string
	CertmanagerIssuerKind  string
	CertmanagerIssuerName  string
	CertKeyBitSize         int
	CertValidtyDuration    time.Duration

	EgressEnabled        bool
	EnablePermissiveMode bool
	FSMLogLevel          string
	SidecarLogLevel      string
	SidecarClass         string
	LocalProxyMode       configv1alpha3.LocalProxyMode
	EnableDebugServer    bool

	SetOverrides []string

	EnablePrivilegedInitContainer bool
	EnableIngressBackendPolicy    bool
	EnableAccessControlPolicy     bool
	EnableRetryPolicy             bool
}

InstallFSMOpts describes install options for FSM

type InstallFsmOpt

type InstallFsmOpt func(*InstallFSMOpts)

InstallFsmOpt is a function type for setting install options

func WithLocalProxyMode

func WithLocalProxyMode(mode configv1alpha3.LocalProxyMode) InstallFsmOpt

WithLocalProxyMode sets the LocalProxyMode for FSM

type InstallType

type InstallType string

InstallType defines several FSM test deployment scenarios

const (
	// SelfInstall uses current kube cluster, installs FSM using CLI
	SelfInstall InstallType = "SelfInstall"

	// KindCluster Creates Kind cluster on docker and uses it as cluster, FSM installs through CLI
	KindCluster InstallType = "KindCluster"

	// NoInstall uses current kube cluster, assumes an FSM is present in `FsmNamespace`
	NoInstall InstallType = "NoInstall"

	// RegistrySecretName is the default name for the container registry secret
	RegistrySecretName = "acr-creds"
)

type PodCommand

type PodCommand []string

PodCommand describes a command for a pod

type Prometheus

type Prometheus struct {
	Client api.Client
	API    v1.API
	// contains filtered or unexported fields
}

Prometheus is a simple handler to represent a target Prometheus endpoint to run queries against

func (*Prometheus) GetCPULoadAvgforContainer

func (p *Prometheus) GetCPULoadAvgforContainer(ns string, podName string, containerName string,
	period time.Duration, t time.Time) (float64, error)

GetCPULoadAvgforContainer returns CPU load average for a period <duration> just before time <t>

func (*Prometheus) GetCPULoadsForContainer

func (p *Prometheus) GetCPULoadsForContainer(ns string, podName string, containerName string, t time.Time) (float64, float64, float64, error)

GetCPULoadsForContainer convenience wrapper to get 1m, 5m and 15m cpu loads for a resource

func (*Prometheus) GetMemRSSforContainer

func (p *Prometheus) GetMemRSSforContainer(ns string, podName string, containerName string, t time.Time) (float64, error)

GetMemRSSforContainer returns RSS memory footprint for a given NS/podname/containerName at a certain point in time

func (*Prometheus) GetNumSidecarsInMesh

func (p *Prometheus) GetNumSidecarsInMesh(t time.Time) (int, error)

GetNumSidecarsInMesh Gets the Number of in-mesh pods (or sidecars) in the mesh as seen by prometheus at a certain point in time.

func (*Prometheus) Stop

func (p *Prometheus) Stop()

Stop gracefully stops the port forwarding to Prometheus

func (*Prometheus) VectorQuery

func (p *Prometheus) VectorQuery(query string, t time.Time) (float64, error)

VectorQuery runs a query at time <t>, expects single vector type and single result. Returns expected first and only <SampleValue> as a float64 Returns 0 and err<Empty result from prometheus>, if no values are seen on prometheus (but query did succeed)

type Resource

type Resource struct {
	Namespace     string
	PodName       string
	ContainerName string
}

Resource is used to store seen tracked resources during the test

type RetryOnErrorFunc

type RetryOnErrorFunc func() error

RetryOnErrorFunc is a function type passed to RetryFuncOnError() to execute

type SimpleAllowPolicy

type SimpleAllowPolicy struct {
	RouteGroupName string

	TrafficTargetName string

	SourceSVCAccountName string
	SourceNamespace      string

	DestinationSvcAccountName string
	DestinationNamespace      string
}

SimpleAllowPolicy is a simplified struct to later get basic SMI allow policy

type SimpleDeploymentAppDef

type SimpleDeploymentAppDef struct {
	Namespace          string
	DeploymentName     string
	ServiceName        string
	ContainerName      string
	ServiceAccountName string
	Image              string
	ReplicaCount       int32
	Command            PodCommand
	Args               []string
	Ports              []int
	AppProtocol        string
	OS                 string
	Labels             map[string]string
}

SimpleDeploymentAppDef defines some parametrization to create a deployment-based application from template

type SimplePodAppDef

type SimplePodAppDef struct {
	Namespace          string
	PodName            string
	ServiceName        string
	ServiceAccountName string
	ContainerName      string
	Image              string
	Command            []string
	Args               []string
	Ports              []int
	AppProtocol        string
	OS                 string
	Labels             map[string]string
}

SimplePodAppDef defines some parametrization to create a pod-based application from template

type SuccessFunction

type SuccessFunction func() bool

SuccessFunction is a simple definition for a success function. True as success, false otherwise

type TCPRequestDef

type TCPRequestDef struct {
	// Source pod where to run the TCP request from
	SourceNs        string
	SourcePod       string
	SourceContainer string

	// The destination server host (FQDN or IP address) and port the request is directed to
	DestinationHost string
	DestinationPort int

	// Message to send as a part of the request
	Message string
}

TCPRequestDef defines a remote TCP request intent

type TCPRequestResult

type TCPRequestResult struct {
	Response string
	Err      error
}

TCPRequestResult represents the result of a TCPRequest call

type TrackedLabel

type TrackedLabel struct {
	Namespace string
	Label     metav1.LabelSelector
}

TrackedLabel defines resources to track and monitor during the test

type TrafficSplitBackend

type TrafficSplitBackend struct {
	Name   string
	Weight int
}

TrafficSplitBackend is a simple define to refer to a TrafficSplit backend

type TrafficSplitDef

type TrafficSplitDef struct {
	Name      string
	Namespace string

	TrafficSplitServiceName string
	Backends                []TrafficSplitBackend
}

TrafficSplitDef is a simplified struct to get a TrafficSplit typed definition

type UDPRequestDef added in v1.3.0

type UDPRequestDef struct {
	// Source pod where to run the UDP request from
	SourceNs        string
	SourcePod       string
	SourceContainer string

	// The destination server host (FQDN or IP address) and port the request is directed to
	DestinationHost string
	DestinationPort int

	// Message to send as a part of the request
	Message string
}

UDPRequestDef defines a remote UDP request intent

type UDPRequestResult added in v1.3.0

type UDPRequestResult struct {
	Response string
	Err      error
}

UDPRequestResult represents the result of a UDPRequest call

Jump to

Keyboard shortcuts

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