utils

package
v0.0.0-...-9e9d5e8 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: 47 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OperatorURL = baseConfigURL + "manifests/default.yaml"
	BrokerURL   = baseConfigURL + "samples/meshplay_v1alpha1_broker.yaml"
	MeshsyncURL = baseConfigURL + "samples/meshplay_v1alpha1_meshsync.yaml"

	// Meshplay Server Location
	EndpointProtocol = "http"
)
View Source
const (
	HelmChartURL          = "https://khulnasoft.com/charts/"
	HelmChartName         = "meshplay"
	HelmChartOperatorName = "meshplay-operator"
)

Variables

View Source
var (
	ErrFailRequestCode        = "1163"
	ErrInvalidTokenCode       = "1164"
	ErrFailReqStatusCode      = "1165"
	ErrAttachAuthTokenCode    = "1166"
	ErrUnmarshalCode          = "1167"
	ErrFileReadCode           = "1168"
	ErrCreatingRequestCode    = "1169"
	ErrMarshalCode            = "1170"
	ErrReadResponseBodyCode   = "1171"
	ErrParsingUrlCode         = "1172"
	ErrNotFoundCode           = "1173"
	ErrUnauthenticatedCode    = "1174"
	ErrInvalidFileCode        = "1175"
	ErrInvalidNameOrIDCode    = "1176"
	ErrInvalidAPIResponseCode = "1177"
	ErrReadConfigFileCode     = "1178"
	ErrMarshalIndentCode      = "1179"
	ErrLoadConfigCode         = "1180"
	ErrResponseStatusBodyCode = "1181"
	ErrResponseStatusCode     = "1182"
	ErrJSONToYAMLCode         = "1183"
	ErrOutFormatFlagCode      = "1184"
	ErrParseGithubFileCode    = "1185"
	ErrReadTokenCode          = "1186"
	ErrRequestResponseCode    = "1187"
)

Please reference the following before contributing an error code: https://docs.khulnasoft.com/project/contributing/contributing-error https://github.com/khulnasoft/meshkit/blob/master/errors/errors.go

View Source
var (
	// ResetFlag indicates if a reset is required
	ResetFlag bool
	// SkipResetFlag indicates if fetching the updated manifest files is required
	SkipResetFlag bool
	// MeshplayDefaultHost is the default host on which Meshplay is exposed
	MeshplayDefaultHost = "localhost"
	// MeshplayDefaultPort is the default port on which Meshplay is exposed
	MeshplayDefaultPort = 9081
	// MeshplayEndpoint is the default URL in which Meshplay is exposed
	MeshplayEndpoint = fmt.Sprintf("http://%s:%v", MeshplayDefaultHost, MeshplayDefaultPort)
	// MeshplayFolder is the default relative location of the meshplay config
	// related configuration files.
	MeshplayFolder = ".meshplay"
	// DockerComposeFile is the default location within the MeshplayFolder
	// where the docker compose file is located.
	DockerComposeFile = "meshplay.yaml"
	// AuthConfigFile is the location of the auth file for performing perf testing
	AuthConfigFile = "auth.json"
	// DefaultConfigPath is the detail path to meshplayctl config
	DefaultConfigPath = "config.yaml"
	// MeshplayNamespace is the namespace to which Meshplay is deployed in the Kubernetes cluster
	MeshplayNamespace = "meshplay"
	// MeshplayDeployment is the name of a Kubernetes manifest file required to setup Meshplay
	// check https://github.com/khulnasoft/meshplay/tree/master/install/deployment_yamls/k8s
	MeshplayDeployment = "meshplay-deployment.yaml"
	// MeshplayService is the name of a Kubernetes manifest file required to setup Meshplay
	// check https://github.com/khulnasoft/meshplay/tree/master/install/deployment_yamls/k8s
	MeshplayService = "meshplay-service.yaml"
	//MeshplayOperator is the file for default Meshplay operator
	//check https://github.com/khulnasoft/meshplay-operator/blob/master/config/manifests/default.yaml
	MeshplayOperator = "default.yaml"
	//MeshplayOperatorBroker is the file for the Meshplay broker
	//check https://github.com/khulnasoft/meshplay-operator/blob/master/config/samples/meshplay_v1alpha1_broker.yaml
	MeshplayOperatorBroker = "meshplay_v1alpha1_broker.yaml"
	//MeshplayOperatorMeshsync is the file for the Meshplay Meshsync Operator
	//check https://github.com/khulnasoft/meshplay-operator/blob/master/config/samples/meshplay_v1alpha1_meshsync.yaml
	MeshplayOperatorMeshsync = "meshplay_v1alpha1_meshsync.yaml"
	// ServiceAccount is the name of a Kubernetes manifest file required to setup Meshplay
	// check https://github.com/khulnasoft/meshplay/tree/master/install/deployment_yamls/k8s
	ServiceAccount = "service-account.yaml"
	// To upload with param name
	ParamName = "k8sfile"
	// kubeconfig file name
	KubeConfigYaml = "kubeconfig.yaml"
	// ViperCompose is an instance of viper for docker-compose
	ViperCompose = viper.New()
	// ViperMeshconfig is an instance of viper for the meshconfig file
	ViperMeshconfig = viper.New()
	// SilentFlag skips waiting for user input and proceeds with default options
	SilentFlag bool
	// PlatformFlag sets the platform for the initial config file
	PlatformFlag string
	// Paths to kubeconfig files
	ConfigPath string
	KubeConfig string
	// KeepNamespace indicates if the namespace should be kept when Meshplay is uninstalled
	KeepNamespace bool
	// TokenFlag sets token location passed by user with --token
	TokenFlag = "Not Set"
	// global logger variable
	Log logger.Handler
)
View Source
var (
	// ManifestsFolder is where the Kubernetes manifests are stored
	ManifestsFolder = "manifests"
	ReleaseTag      string
)
View Source
var CfgFile string
View Source
var ListOfComponents = []string{}

ListOfComponents returns the list of components available

View Source
var Services = map[string]Service{
	"meshplay": {
		Image:  "khulnasoft/meshplay:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Environment: []string{
			"PROVIDER_BASE_URLS=https://meshplay.khulnasoft.com",
			"ADAPTER_URLS=meshplay-istio:10000 meshplay-linkerd:10001 meshplay-consul:10002 meshplay-nsm:10004 meshplay-app-mesh:10005 meshplay-kuma:10007 meshplay-osm:10009 meshplay-traefik-mesh:10006 meshplay-nginx-sm:10010 meshplay-cilium:10012",
			"EVENT=meshplayLocal",
			"PORT=9081",
		},
		Volumes: []string{"$HOME/.kube:/home/appuser/.kube:ro", "$HOME/.minikube:$HOME/.minikube:ro"},
		Ports:   []string{"9081:9081"},
	},
	"meshplay-istio": {
		Image:  "khulnasoft/meshplay-istio:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10000:10000"},
	},
	"meshplay-linkerd": {
		Image:  "khulnasoft/meshplay-linkerd:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10001:10001"},
	},
	"meshplay-consul": {
		Image:  "khulnasoft/meshplay-consul:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10002:10002"},
	},
	"meshplay-nsm": {
		Image:  "khulnasoft/meshplay-nsm:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10004:10004"},
	},
	"meshplay-app-mesh": {
		Image:  "khulnasoft/meshplay-app-mesh:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10005:10005"},
	},
	"meshplay-traefik-mesh": {
		Image:  "khulnasoft/meshplay-traefik-mesh:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10006:10006"},
	},
	"meshplay-kuma": {
		Image:  "khulnasoft/meshplay-kuma:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10007:10007"},
	},
	"meshplay-osm": {
		Image:  "khulnasoft/meshplay-osm:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10009:10009"},
	},
	"meshplay-nginx-sm": {
		Image:  "khulnasoft/meshplay-nginx-sm:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10010:10010"},
	},
	"meshplay-cilium": {
		Image:  "khulnasoft/meshplay-cilium:stable-latest",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
		Ports:  []string{"10012:10012"},
	},
	"watchtower": {
		Image:  "containrrr/watchtower",
		Labels: []string{"com.centurylinklabs.watchtower.enable=true"},
	},
}
View Source
var TemplateContext = config.Context{
	Endpoint:   EndpointProtocol + "://localhost:9081",
	Token:      "default",
	Platform:   "kubernetes",
	Components: ListOfComponents,
	Channel:    "stable",
	Version:    "latest",
	Provider:   "Meshplay",
}

TemplateContext is the template context provided when creating a config file

View Source
var TemplateToken = config.Token{
	Name:     "default",
	Location: AuthConfigFile,
}

TemplateToken is the template token provided when creating a config file

Functions

func AddAuthDetails

func AddAuthDetails(req *http.Request, filepath string) error

AddAuthDetails Adds authentication cookies to the request

func AppError

func AppError(msg string) string

AppError returns a formatted error message with a link to 'app' command usage page in addition to the error message

func AppViewError

func AppViewError(msg string) string

AppError returns a formatted error message with a link to 'app view' command usage page in addition to the error message

func ApplyManifest

func ApplyManifest(manifest []byte, client *meshkitkube.Client, update bool, delete bool) error

ApplyManifest is a wrapper function for client.ApplyManifest

func ApplyManifestFiles

func ApplyManifestFiles(manifestArr []Manifest, requestedAdapters []string, client *meshkitkube.Client, update bool, delete bool) error

ApplyManifestFiles applies/updates/deletes all the required manifests into the Kubernetes cluster

func ApplyOperatorManifest

func ApplyOperatorManifest(client *meshkitkube.Client, update bool, delete bool) error

ApplyOperatorManifest applies/updates/deletes the operator manifest

func AreAllPodsRunning

func AreAllPodsRunning() (bool, error)

AreAllPodsRunning checks if all the deployment pods under kubernetes are running

func AreMeshplayComponentsRunning

func AreMeshplayComponentsRunning(currPlatform string) (bool, error)

AreMeshplayComponentsRunning checks if the meshplay containers are up and running

func AskForConfirmation

func AskForConfirmation(s string) bool

AskForConfirmation asks the user for confirmation. A user must type in "yes" or "no" and then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as confirmations. If the input is not recognized, it will ask again. The function does not return until it gets a valid response from the user.

func AskForInput

func AskForInput(prompt string, allowed []string) string

AskForInput asks the user for an input and checks if it is in the available values

func BackupConfigFile

func BackupConfigFile(cfgFile string)

func CanUseCachedManifests

func CanUseCachedManifests(currCtx *(config.Context)) error

CanUseCachedManifests returns an error if it is not possible to use cached manifests

func CanUseCachedOperatorManifests

func CanUseCachedOperatorManifests(_ *config.Context) error

CanUseCachedOperatorManifests returns an error if it is not possible to use cached operator manifests

func ChangeManifestVersion

func ChangeManifestVersion(channel, version, filePath string) error

ChangeManifestVersion changes the tag of the images in the manifest according to the pinned version

func CheckFileExists

func CheckFileExists(name string) (bool, error)

CheckFileExists checks if the given file exists in system or not

func CheckK8sVersion

func CheckK8sVersion(versionInfo *version.Info) error

func CheckKubectlVersion

func CheckKubectlVersion() error

CheckKubectlVersion validates whether the installed kubectl version is running a minimum kubectl version.

func CheckMeshplayNsDelete

func CheckMeshplayNsDelete() (bool, error)

CheckMeshplayNsDelete waits for Meshplay namespace to be deleted, returns (done, error)

func ContainsStringPrefix

func ContainsStringPrefix(arr []string, str string) bool

ContainsStringPrefix takes a string slice and a string and returns true if it is present

func ContentTypeIsHTML

func ContentTypeIsHTML(resp *http.Response) bool

ContentTypeIsHTML Checks if the response is an HTML resposnse

func ConvertMapInterfaceMapString

func ConvertMapInterfaceMapString(v interface{}) interface{}

ConvertMapInterfaceMapString converts map[interface{}]interface{} => map[string]interface{}

It will also convert []interface{} => []string

func ConvertRespToSSE

func ConvertRespToSSE(resp *http.Response) (chan Event, error)

ConvertRespToSSE converts a connection to a stream of server sent events

func CreateConfigFile

func CreateConfigFile() error

CreateConfigFile creates config file in Meshplay Folder

func CreateDefaultSpinner

func CreateDefaultSpinner(suffix string, finalMsg string) *spinner.Spinner

Indicate an ongoing Process at a given time on CLI

func CreateManifestsFolder

func CreateManifestsFolder() error

CreateManifestsFolder creates a new folder (.meshplay/manifests)

func CreateTempAuthServer

func CreateTempAuthServer(fn func(http.ResponseWriter, *http.Request)) (*http.Server, int, error)

CreateTempAuthServer creates a temporary http server

It implements a custom mux and has a catch all route, the function passed as the parameter is binded to the catch all route

func DeleteConfiguration

func DeleteConfiguration(meshplayServerUrl, id, configuration string) error

Delete configuration from meshplay server endpoint /api/{configurations}/{id}

func DownloadDockerComposeFile

func DownloadDockerComposeFile(ctx *config.Context, force bool) error

DownloadDockerComposeFile fetches docker-compose.yaml based on passed context if it does not exists. Use force to override download anyway

func DownloadManifests

func DownloadManifests(manifestArr []Manifest, rawManifestsURL string) error

DownloadManifests downloads all the Kubernetes manifest files

func DownloadOperatorManifest

func DownloadOperatorManifest() error

DownloadOperatorManifest downloads the operator manifest files

func Equals

func Equals(tb testing.TB, exp, act interface{})

equals fails the test if exp is not equal to act.

func ErrAttachAuthToken

func ErrAttachAuthToken(err error) error

func ErrCreatingRequest

func ErrCreatingRequest(err error) error

func ErrFailReqStatus

func ErrFailReqStatus(statusCode int) error

func ErrFailRequest

func ErrFailRequest(err error) error

func ErrFileRead

func ErrFileRead(err error) error

func ErrInvalidAPIResponse

func ErrInvalidAPIResponse(err error) error

func ErrInvalidFile

func ErrInvalidFile(err error) error

func ErrInvalidNameOrID

func ErrInvalidNameOrID(err error) error

func ErrInvalidToken

func ErrInvalidToken() error

func ErrJSONToYAML

func ErrJSONToYAML(err error) error

func ErrLoadConfig

func ErrLoadConfig(err error) error

func ErrMarshal

func ErrMarshal(err error) error

func ErrMarshalIndent

func ErrMarshalIndent(err error) error

func ErrNotFound

func ErrNotFound(err error) error

func ErrOutFormatFlag

func ErrOutFormatFlag() error

func ErrParseGithubFile

func ErrParseGithubFile(err error, URL string) error

func ErrParsingUrl

func ErrParsingUrl(err error) error

func ErrReadConfigFile

func ErrReadConfigFile(err error) error

func ErrReadResponseBody

func ErrReadResponseBody(err error) error

func ErrReadToken

func ErrReadToken(err error) error

func ErrRequestResponse

func ErrRequestResponse(err error) error

func ErrResponseStatus

func ErrResponseStatus(statusCode int) error

func ErrResponseStatusBody

func ErrResponseStatusBody(statusCode int, body string) error

func ErrUnauthenticated

func ErrUnauthenticated() error

func ErrUnmarshal

func ErrUnmarshal(err error) error

func ExpError

func ExpError(msg string) string

ExpError returns a formatted error message with a link to 'exp' command usage page in addition to the error message

func FilterDeleteError

func FilterDeleteError(msg string) string

FilterDeleteError returns a formatted error message with a link to 'filter delete' command usage page in addition to the error message

func FilterError

func FilterError(msg string) string

FilterError returns a formatted error message with a link to 'filter' command usage page in addition to the error message

func FilterImportError

func FilterImportError(msg string) string

FilterImportError returns a formatted error message with a link to 'filter import' command usage page in addition to the error message

func FilterListError

func FilterListError(msg string) string

FilterListError returns a formatted error message with a link to 'filter list' command usage page in addition to the error message

func FilterViewError

func FilterViewError(msg string) string

FilterViewError returns a formatted error message with a link to 'filter view' command usage page in addition to the error message

func FindClosestArg

func FindClosestArg(argPassed string, validArgs []string) string

func ForceCleanupCluster

func ForceCleanupCluster() error

func GenerateConfigGKE

func GenerateConfigGKE(configPath, SAName, namespc string) error

TODO@Aisuko this function is so hard to read and maintain, please refactor it

func GetBasePath

func GetBasePath(t *testing.T) string

Path to the current file

func GetChannelAndVersion

func GetChannelAndVersion(currCtx *(config.Context)) (string, string, error)

returns the Channel and Version given a context

func GetCleanPodName

func GetCleanPodName(name string) string

GetCleanPodName cleans the pod names in the MeshplayNamespace to make it more readable

func GetCurrentAuthToken

func GetCurrentAuthToken() (string, error)

GetCurrentAuthToken returns location of current context token

func GetDeploymentVersion

func GetDeploymentVersion(filePath string) (string, error)

func GetEphemeralPort

func GetEphemeralPort() (int, error)

GetEphemeralPort selects a port for the port-forwarding. It binds to a free ephemeral port and returns the port number.

func GetID

func GetID(meshplayServerUrl, configuration string) ([]string, error)

GetID returns a array of IDs from meshplay server endpoint /api/{configurations}

func GetK8sVersionInfo

func GetK8sVersionInfo() (*version.Info, error)

GetK8sVersionInfo returns version.Info for the Kubernetes cluster.

func GetManifestTreeURL

func GetManifestTreeURL(version string) (string, error)

GetManifestTreeURL returns the manifest tree url based on version

func GetManifestURL

func GetManifestURL(manifest Manifest, rawManifestsURL string) string

GetManifestURL returns the URLs for the manifest files

func GetName

func GetName(meshplayServerUrl, configuration string) (map[string]string, error)

GetName returns a of name:id from meshplay server endpoint /api/{configurations}

func GetPodList

func GetPodList(client *meshkitkube.Client, namespace string) (*v1core.PodList, error)

GetPods lists all the available pods in the MeshplayNamespace

func GetProviderInfo

func GetProviderInfo(mctCfg *config.MeshplayCtlConfig) (map[string]Provider, error)

GetProviderInfo queries meshplay API for the provider info

func GetRequiredPods

func GetRequiredPods(specifiedPods []string, availablePods []v1core.Pod) (map[string]string, error)

GetRequiredPodsMap checks if the pods specified by the user is valid returns a map of the required pods

func GetSessionData

func GetSessionData(mctlCfg *config.MeshplayCtlConfig) (*models.Preference, error)

Get Meshplay Session Data/Details (Adapters)

func GetTokenLocation

func GetTokenLocation(token config.Token) (string, error)

Function checks the location of token and returns appropriate location of the token

func InitiateLogin

func InitiateLogin(mctlCfg *config.MeshplayCtlConfig, option string) ([]byte, error)

InitiateLogin initates the login process

func InstallprereqDocker

func InstallprereqDocker() error

func IsAdapterValid

func IsAdapterValid(manifestArr []Manifest, componentManifest string) bool

IsAdapterValid checks if the component mentioned by the user is a valid component

func IsMeshplayRunning

func IsMeshplayRunning(currPlatform string) (bool, error)

IsMeshplayRunning checks if the meshplay server containers are up and running

func IsServerRunning

func IsServerRunning(serverAddr string) error

func IsValidSubcommand

func IsValidSubcommand(available []*cobra.Command, sub string) bool

IsValidSubcommand checks if the passed subcommand is supported by the parent command

func MakeRequest

func MakeRequest(req *http.Request) (*http.Response, error)

Function returns a new http response given a http request Function will test the response and return any errors associated with it

func MapGet

func MapGet(mp map[string]interface{}, key ...string) (interface{}, bool)

MapGet takes in the map keys - each key goes one level deeper in the map

func MapSet

func MapSet(mp map[string]interface{}, value interface{}, key ...string)

MapSet takes in the map that needs to be manipulated, the value that needs to be assgined to be assigned and the key - each key goes one level deeper in the map

func MeshError

func MeshError(msg string) string

MeshError returns a formatted error message with a link to 'mesh' command usage page in addition to the error message

func NavigateToBrowser(endpoint string) error

NavigateToBroswer naviagtes to the endpoint displaying Meshplay UI in the broswer.

func NewRequest

func NewRequest(method string, url string, body io.Reader) (*http.Request, error)

NewRequest creates *http.Request and handles adding authentication for Meshplay itself Function returns a http response generated by the new request

func ParseURLGithub

func ParseURLGithub(URL string) (string, string, error)

ParseURLGithub checks URL and returns raw repo, path, error

func PatternError

func PatternError(msg string) string

PatternError returns a formatted error message with a link to 'pattern' command usage page in addition to the error message

func PatternViewError

func PatternViewError(msg string) string

PatternViewError returns a formatted error message with a link to the 'pattern view' commad usage page in addition to the error message

func PerfError

func PerfError(msg string) string

PerfError returns a formatted error message with a link to 'perf' command usage page at in addition to the error message

func Populate

func Populate(src, dst string) error

func PrintToTable

func PrintToTable(header []string, data [][]string)

PrintToTable prints the given data into a table format

func PrintToTableInStringFormat

func PrintToTableInStringFormat(header []string, data [][]string) string

PrintToTableInStringFormat prints the given data into a table format but return as a string

func PrintToTableWithFooter

func PrintToTableWithFooter(header []string, data [][]string, footer []string)

PrintToTableWithFooter prints the given data into a table format but with a footer

func ReadToken

func ReadToken(filepath string) (map[string]string, error)

ReadToken returns a map of the token passed in

func RecursiveCastMapStringInterfaceToMapStringInterface

func RecursiveCastMapStringInterfaceToMapStringInterface(in map[string]interface{}) map[string]interface{}

RecursiveCastMapStringInterfaceToMapStringInterface will convert a map[string]interface{} recursively => map[string]interface{}

func RootError

func RootError(msg string) string

RootError returns a formatted error message with a link to 'root' command usage page at in addition to the error message

func SafeClose

func SafeClose(co io.Closer)

SafeClose is a helper function help to close the io

func SetFileLocation

func SetFileLocation() error

SetFileLocation to set absolute path

func SetFileLocationTesting

func SetFileLocationTesting(dir string)

Set file location for testing stuff

func SetKubeConfig

func SetKubeConfig()

Sets the path to user's kubeconfig file into global variables

func SetOverrideValues

func SetOverrideValues(ctx *config.Context, meshplayImageVersion string) map[string]interface{}

SetOverrideValues returns the value overrides based on current context to install/upgrade helm chart

func SetupContextEnv

func SetupContextEnv(t *testing.T)

use default context /pkg/utils/TestConfig.yaml

func SetupCustomContextEnv

func SetupCustomContextEnv(t *testing.T, pathToContext string)

setup custom context with SetupCustomContextEnv

func SetupLogrusFormatter

func SetupLogrusFormatter()

Call this function to setup logrus

func SetupLogrusGrabTesting

func SetupLogrusGrabTesting(_ *testing.T, _ bool) *bytes.Buffer

setup logrus formatter and return the buffer in which commands output is to be set.

func SetupMeshkitLogger

func SetupMeshkitLogger(debugLevel bool, output io.Writer)

Initialize Meshkit Logger instance

func SetupMeshkitLoggerTesting

func SetupMeshkitLoggerTesting(_ *testing.T, verbose bool) *bytes.Buffer

setup meshkit logger for testing and return the buffer in which commands output is to be set.

func StartMockMeshplayServer

func StartMockMeshplayServer(t *testing.T) error

func StartMockery

func StartMockery(t *testing.T)

Start mock HTTP client to mock requests

func Startdockerdaemon

func Startdockerdaemon(subcommand string) error

func StopMockery

func StopMockery(_ *testing.T)

stop HTTP mock client

func StringContainedInSlice

func StringContainedInSlice(str string, slice []string) int

StringContainedInSlice returns the index in which a string is a substring in a list of strings

func StringInSlice

func StringInSlice(str string, slice []string) bool

StringInSlice checks if a string is present in a slice

func StringWithCharset

func StringWithCharset(length int) string

StringWithCharset generates a random string with a given length

func SystemChannelSubError

func SystemChannelSubError(msg string, cmd string) string

SystemChannelSubError returns a formatted error message with a link to `channel` command usage page in addition to the error message

func SystemContextSubError

func SystemContextSubError(msg string, cmd string) string

SystemContextSubError returns a formatted error message with a link to `context` command usage page in addition to the error message

func SystemError

func SystemError(msg string) string

SystemError returns a formatted error message with a link to 'system' command usage page in addition to the error message

func SystemLifeCycleError

func SystemLifeCycleError(msg string, cmd string) string

func SystemModelSubError

func SystemModelSubError(msg string, cmd string) string

SystemProviderSubError returns a formatted error message with a link to `provider` command usage page in addition to the error message

func SystemProviderSubError

func SystemProviderSubError(msg string, cmd string) string

SystemProviderSubError returns a formatted error message with a link to `provider` command usage page in addition to the error message

func SystemTokenError

func SystemTokenError(msg string) string

SystemTokenError returns a formatted error message with a link to 'token' command usage page in addition to the error message

func TransformYAML

func TransformYAML(yamlByt []byte, transform func(interface{}) (interface{}, error), keys ...string) ([]byte, error)

TransformYAML takes in:

yamlByt - YAML Byte slice that needs to be modified
transform - function that will be executed on that value, the returned value will replace the current value
keys - takes in a series of keys which are supposed to be nested, numbers can also be passed to access an array

func TruncateID

func TruncateID(id string) string

TruncateID shortens an id to 8 characters

func UpdateAuthDetails

func UpdateAuthDetails(filepath string) error

UpdateAuthDetails checks gets the token (old/refreshed) from meshplay server and writes it back to the config file

func UpdateMeshplayContainers

func UpdateMeshplayContainers() error

UpdateMeshplayContainers runs the update command for meshplay client

func UploadFileWithParams

func UploadFileWithParams(uri string, params map[string]string, paramName, path string) (*http.Request, error)

UploadFileWithParams returns a request configured to upload files with other values

func ValidId

func ValidId(meshplayServerUrl, args string, configuration string) (string, bool, error)

ValidId - Check if args is a valid ID or a valid ID prefix and returns the full ID

func ValidName

func ValidName(meshplayServerUrl, args string, configuration string) (string, string, bool, error)

ValidId - Check if args is a valid name or a valid name prefix and returns the full name and ID

func ValidateURL

func ValidateURL(URL string) error

ValidateURL validates url provided for meshplay backend to meshplayctl context

func WaitForNamespaceDeleted

func WaitForNamespaceDeleted(c *meshkitkube.Client, namespace string, timeout int) error

Wait up to timeout seconds for `namespace` to be deleted.

func WaitForPodRunning

func WaitForPodRunning(c *meshkitkube.Client, desiredPod, namespace string, timeout int) error

Wait up to timeout seconds for pod in 'namespace' to enter running state. Returns an error if no pods are found or not all discovered pods enter running state.

Types

type CmdTestInput

type CmdTestInput struct {
	Name                 string
	Args                 []string
	ExpectedResponse     string
	ExpectedResponseYaml string
	ExpectError          bool
	ErrorStringContains  []string
}

type Containers

type Containers struct {
	Env             interface{}      `yaml:"env,omitempty"`
	Image           string           `yaml:"image,omitempty"`
	ImagePullPolicy string           `yaml:"imagePullPolicy"`
	Name            string           `yaml:"name,omitempty"`
	Ports           []map[string]int `yaml:"ports,omitempty"`
	Resources       interface{}      `yaml:"resources,omitempty"`
}

type DockerCompose

type DockerCompose struct {
	Version  string             `yaml:"version,omitempty"`
	Services map[string]Service `yaml:"services,omitempty"`
	Volumes  Volumes            `yaml:"volumes,omitempty"`
}

type Event

type Event struct {
	Name string
	ID   string
	Data EventData
}

Event represents a Server-Sent Event

type EventData

type EventData struct {
	Details     string `json:"details"`
	OperationID string `json:"operation_id"`
	Summary     string `json:"summary"`
}

type GoldenFile

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

func NewGoldenFile

func NewGoldenFile(t *testing.T, name string, directory string) *GoldenFile

func (*GoldenFile) Load

func (tf *GoldenFile) Load() string

Load a Golden file

func (*GoldenFile) LoadByte

func (tf *GoldenFile) LoadByte() []byte

Load a Golden file

func (*GoldenFile) Write

func (tf *GoldenFile) Write(content string)

write a Golden file

func (*GoldenFile) WriteInByte

func (tf *GoldenFile) WriteInByte(content []byte)

write a Golden file

type K8sCompose

type K8sCompose struct {
	APIVersion interface{} `yaml:"apiVersion,omitempty"`
	Kind       string      `yaml:"kind,omitempty"`
	Metadata   interface{} `yaml:"metadata,omitempty"`
	Spec       Spec        `yaml:"spec,omitempty"`
	Status     interface{} `yaml:"status,omitempty"`
}

type Manifest

type Manifest struct {
	Path string      `json:"path,omitempty"`
	Mode string      `json:"mode,omitempty"`
	Typ  string      `json:"type,omitempty"`
	SHA  string      `json:"sha,omitempty"`
	Size json.Number `json:"size,omitempty"`
	URL  string      `json:"url,omitempty"`
}

func FetchManifests

func FetchManifests(currCtx *(config.Context)) ([]Manifest, error)

FetchManifests is a wrapper function that identifies the required manifest files as downloads them

func ListManifests

func ListManifests(url string) ([]Manifest, error)

ListManifests lists the manifest files stored in GitHub

type ManifestList

type ManifestList struct {
	SHA       string     `json:"sha,omitempty"`
	URL       string     `json:"url,omitempty"`
	Tree      []Manifest `json:"tree,omitempty"`
	Truncated bool       `json:"truncated,omitempty"`
}

type MockURL

type MockURL struct {
	// method such as GET or POST
	Method string
	// url to mock the request
	URL string
	// response for the request
	Response string
	// response code
	ResponseCode int
}

type PortForward

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

PortForward provides a port-forward connection into a Kubernetes cluster.

func NewPortForward

func NewPortForward(
	ctx context.Context,
	client *meshkitkube.Client,
	namespace, deployName string,
	host string, localPort, remotePort int,
	emitLogs bool,
) (*PortForward, error)

NewPortForward returns an instance of the PortForward struct that can be used to establish a port-forward connection to a pod in the deployment that's specified by namespace and deployName. If localPort is 0, it will use a random ephemeral port. Note that the connection remains open for the life of the process, as this function is typically called by the CLI.

func (*PortForward) AddressAndPort

func (pf *PortForward) AddressAndPort() string

AddressAndPort returns the address and port for the port-forward connection.

func (*PortForward) GetStop

func (pf *PortForward) GetStop() <-chan struct{}

GetStop returns the stopCh. Receiving on stopCh will block until the port forwarding stops.

func (*PortForward) Init

func (pf *PortForward) Init() error

Init creates and runs a port-forward connection. This function blocks until the connection is established, in which case it returns nil. It's the caller's responsibility to call Stop() to finish the connection.

func (*PortForward) Stop

func (pf *PortForward) Stop()

Stop terminates the port-forward connection. It is the caller's responsibility to call Stop even in case of errors

func (*PortForward) URLFor

func (pf *PortForward) URLFor(path string) string

URLFor returns the URL for the port-forward connection.

type Provider

type Provider struct {
	ProviderURL  string `json:"provider_url,omitempty"`
	ProviderName string `json:"provider_name,omitempty"`
}

type Service

type Service struct {
	Image       string   `yaml:"image,omitempty"`
	Labels      []string `yaml:"labels,omitempty"`
	Environment []string `yaml:"environment,omitempty"`
	Volumes     []string `yaml:"volumes,omitempty"`
	Ports       []string `yaml:"ports,omitempty"`
}

type Spec

type Spec struct {
	Replicas int         `yaml:"replicas,omitempty"`
	Selector interface{} `yaml:"selector,omitempty"`
	Strategy interface{} `yaml:"strategy,omitempty"`
	Template Template    `yaml:"template,omitempty"`
}

type Template

type Template struct {
	Metadata interface{}  `yaml:"metadata,omitempty"`
	Spec     TemplateSpec `yaml:"spec,omitempty"`
}

type TemplateSpec

type TemplateSpec struct {
	ServiceAccount     string       `yaml:"serviceAccount,omitempty"`
	ServiceAccountName string       `yaml:"serviceAccountName,omitempty"`
	Containers         []Containers `yaml:"containers,omitempty"`
	RestartPolicy      string       `yaml:"restartPolicy,omitempty"`
}

type TerminalFormatter

type TerminalFormatter struct{}

TerminalFormatter is exported

func (*TerminalFormatter) Format

func (f *TerminalFormatter) Format(entry *log.Entry) ([]byte, error)

Format defined the format of output for Logrus logs Format is exported

type TestHelper

type TestHelper struct {
	Version string
	BaseURL string
}

func NewTestHelper

func NewTestHelper(_ *testing.T) *TestHelper

type Volumes

type Volumes struct {
	MeshplayConfig interface{} `yaml:"meshplay-config,omitempty"`
}

Jump to

Keyboard shortcuts

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