util

package
v1.0.0-beta2 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2020 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package util contains a set of common resources that are intended to be used in the ecctl project as a whole.

Index

Constants

View Source
const (
	// DefaultESPort is the default port on ES clusters running on cloud
	DefaultESPort = 9243

	// DefaultIndexPollerRate is the polling interval in seconds for tab-completion on index endpoints
	DefaultIndexPollerRate = 15
)
View Source
const (

	// ValidClusterID holds a valid cluster id value
	ValidClusterID = "320b7b540dfc967a7a649c18e2fce4ed"
	// InvalidClusterID holds an invalid valid cluster id value
	InvalidClusterID = "!23"
	// ValidDuration holds a valid duration value
	ValidDuration = "3 seconds"
)
View Source
const (
	// DefaultRetries retries for the plan.TrackParams which accounts
	// for the Pending plan not being present in the backend, it will retry
	// the request the times specified here. 2 is the default anectdotically
	// because it provides a maximum sleeping time of (PollFrequency * 2)^2
	// or math.Exp2(2). Increasing this value will cause the PlanTracker to
	// sleep for more time than it's required, thus making ecctl less efficient.
	DefaultRetries = 2

	// DefaultPollFrequency is frequency on which the API is polled for updates
	// on pending plans. This value is also used as the cooldown time when used
	// with MaxRetries > 0.
	DefaultPollFrequency = time.Second * 10
)
View Source
const (
	// DefaultClientTimeout client http timeout for console requests
	DefaultClientTimeout = 15
)

Variables

View Source
var (
	// ErrAPIReq is the message returned when API reference is required for a command
	ErrAPIReq = errors.New("api reference is required for command")
	// ErrClusterLength is the message returned when a provided cluster id is not of the expected length (32 chars)
	ErrClusterLength = errors.New("cluster id should have a length of 32 characters")
	// ErrDeploymentID is the message returned when a provided cluster id is not of the expected length (32 chars)
	ErrDeploymentID = errors.New("deployment id should have a length of 32 characters")
	// ErrIDCannotBeEmpty is the message returned when an ID field is empty
	ErrIDCannotBeEmpty = errors.New("id field cannot be empty")

	// SkipMaintenanceHeaders tells the EC proxy layer to still send requests to the
	// underlying cluster instances even if they are in maintenance mode
	SkipMaintenanceHeaders = map[string]string{
		"X-Found-Bypass-Maintenance": "true",
	}
)
View Source
var (
	// PlanNotFound represents a mocked response resulting from a plan not found.
	PlanNotFound = mock.Response{Response: http.Response{
		StatusCode: 404,
		Body:       mock.NewStringBody(`{}`),
	}}
)
View Source
var (
	// ValidTypes exposes a list of the valid Elastic Cloud workload Types.
	ValidTypes = []string{
		"elasticsearch",
		"kibana",
		"apm",
		"appsearch",
	}
)

Functions

func AppendTrackResponses

func AppendTrackResponses(res ...mock.Response) []mock.Response

AppendTrackResponses is aimed to be used while testing to add the tracking responses as a successful plan, it assumes that there's 1 retry performed by the client.

func AskForConfirmation

func AskForConfirmation(reader io.Reader, out *output.Device) bool

AskForConfirmation scans the stdin for "y" or "yes" (case insensitive)

func CheckErrType

func CheckErrType(got, want error) error

CheckErrType receives two errors, if either one is not nil, it triggers a comparison between the two, returning an error if the errors are not equal This function is useful for testing to ensure specific error types.

func CompareStructs

func CompareStructs(a, b interface{}) (equals bool, diff string, err error)

CompareStructs two structs and return the differences

func DashesToUnderscore

func DashesToUnderscore(s string) string

DashesToUnderscore returns an underscore separated string converted from dash separated form.

func FieldsOfStruct

func FieldsOfStruct(p interface{}) map[string]string

FieldsOfStruct returns a list of the kebabcased struct property names that have the tag `kebabcase:"description"` set. The map that will be returned will have the form of: "skip-data-migration": "description"

func GetTimeoutFromSize

func GetTimeoutFromSize(size int64) time.Duration

GetTimeoutFromSize computes a time.Duration from the size, if the computed value is smaller than the minimum timeout that is returned instead

func Min

func Min(a, b int8) int8

Min returns the minimum of two int8

func NewFailedPlanUnknown

func NewFailedPlanUnknown() mock.Response

NewFailedPlanUnknown returns a mocked response from a failed plan.

func NewSuccessfulPlan

func NewSuccessfulPlan() mock.Response

NewSuccessfulPlan returns a mocked response from a successful plan.

func ParseCUResponse

func ParseCUResponse(params ParseCUResponseParams) (*models.ClusterCrudResponse, error)

ParseCUResponse parses the create / update response

func ParseDate

func ParseDate(t *testing.T, date string) strfmt.DateTime

ParseDate parses a string to date and if parsing generates an error, it fails the given testing suite, otherwise it returns the strfmt.Datetime parsed value

func RandomString

func RandomString(n int) string

RandomString generates a random strings with a defined length.

func ReadMFAToken

func ReadMFAToken(reader io.Reader, out *output.Device) (string, error)

ReadMFAToken reads an MFA token

func ReturnErrOnly

func ReturnErrOnly(_ interface{}, e error) error

ReturnErrOnly is used to strip the first return argument of a function call

func Set

func Set(p interface{}, key string, value interface{})

Set will populate a property from its dashed version to the specified value i.e. passing `skip-snapshot` as a key will populate the `SkipSnapshot` prop.

func SetRawJSON

func SetRawJSON(c *client.Rest)

SetRawJSON prepares the API transport to send raw JSON

While setting the global JSONMime producer to runtime.TextProducer() looks scary, runtime.TextProducer() falls back on swag.WriteJSON(data) if the object we're marshalling is a struct or slice. So it actually works in most cases.

This is only necessary because the Cloud Swagger Spec lists some JSON blob data as strings. When those are changed to JSON Objects, this can go away.

func TrackCluster

func TrackCluster(params TrackClusterParams) error

TrackCluster tracks a cluster by its ID and kind to a specified output.

func UnderscoreToDashes

func UnderscoreToDashes(s string) string

UnderscoreToDashes returns a dash separated string converted from underscore or camelcase separated form.

func UnsetRawJSON

func UnsetRawJSON(c *client.Rest)

UnsetRawJSON un-does what SetRawJSON does :)

func ValidateEmail

func ValidateEmail(prefix, email string) error

ValidateEmail validates that a string is in a valid email format

func WrapError

func WrapError(text string, err error) error

WrapError takes the error that is passed and either wraps the error with the text or each of the multierror errors with it.

Types

type AuthenticationParams

type AuthenticationParams struct {
	User, Pass string
	Insecure   bool
}

AuthenticationParams is the generic parameter of most elasticsearch subcommands

type ClusterParams

type ClusterParams struct {
	*api.API
	ClusterID string
}

ClusterParams is the generic parameter of elasticsearch subcommands

func (*ClusterParams) Validate

func (cp *ClusterParams) Validate() error

Validate is the implementation for the ecctl.Validator interface

type ParseCUResponseParams

type ParseCUResponseParams struct {
	*api.API
	CreateResponse interface{}
	UpdateResponse interface{}
	Err            error
	TrackParams
}

ParseCUResponseParams is used by ParseCUResponse.

func (ParseCUResponseParams) Validate

func (params ParseCUResponseParams) Validate() error

Validate ensures that the parameters are usable by the consuming function.

type TrackClusterParams

type TrackClusterParams struct {
	plan.TrackParams
	Output *output.Device
}

TrackClusterParams is consumed by TrackCluster

func (TrackClusterParams) Validate

func (params TrackClusterParams) Validate() error

Validate ensures that the parameters are usable by the consuming function.

type TrackParams

type TrackParams struct {
	Output        *output.Device
	PollFrequency time.Duration
	Track         bool
	MaxRetries    uint8
}

TrackParams are intended to be used as a field in other params structs that aim to perform plan tracking.

func (TrackParams) Validate

func (params TrackParams) Validate() error

Validate ensures that the parameters are usable by the consuming function.

type Validator

type Validator interface {
	Validate() error
}

Validator interface is mostly used for parameter structures that need to check a set of conditions and act as a gate before running expensive external calls

Jump to

Keyboard shortcuts

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