cloudapi

package
v0.50.0 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: AGPL-3.0 Imports: 26 Imported by: 9

Documentation

Overview

Package cloudapi contains several things related to the k6 cloud - various data and config structures, a REST API client, log streaming logic, etc. They are all used in cloud tests (i.e. `k6 cloud`), and in local tests emitting their results to the k6 cloud output (i.e. `k6 run --out cloud`).

Index

Constants

View Source
const (
	// RetryInterval is the default cloud request retry interval
	RetryInterval = 500 * time.Millisecond
	// MaxRetries specifies max retry attempts
	MaxRetries = 3
)
View Source
const LegacyCloudConfigKey = "loadimpact"

LegacyCloudConfigKey is the key used in the JSON config for the cloud output.

Variables

This section is empty.

Functions

func CheckResponse added in v0.45.0

func CheckResponse(r *http.Response) error

CheckResponse checks the parsed response. It returns nil if the code is in the successful range, otherwise it tries to parse the body and return a parsed error.

func GetTemporaryCloudConfig added in v0.50.0

func GetTemporaryCloudConfig(
	cloudConfig json.RawMessage,
	external map[string]json.RawMessage,
) (map[string]interface{}, error)

GetTemporaryCloudConfig returns a temporary cloud config. Original comment TODO: Fix this We reuse cloud.Config for parsing options.cloud (or legacy loadimpact struct), but this probably shouldn't be done, as the idea of options.ext is that they are extensible without touching k6. But in order for this to happen, we shouldn't actually marshal cloud.Config on top of it, because it will be missing some fields that aren't actually mentioned in the struct. So in order for use to copy the fields that we need for k6 cloud's api we unmarshal in map[string]interface{} and copy what we need if it isn't set already

func URLForResults

func URLForResults(refID string, config Config) string

URLForResults returns the cloud URL with the test run results.

Types

type Client

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

Client handles communication with the k6 Cloud API.

func NewClient

func NewClient(logger logrus.FieldLogger, token, host, version string, timeout time.Duration) *Client

NewClient return a new client for the cloud API

func (*Client) BaseURL added in v0.45.0

func (c *Client) BaseURL() string

BaseURL returns configured host.

func (*Client) CreateTestRun

func (c *Client) CreateTestRun(testRun *TestRun) (*CreateTestRunResponse, error)

CreateTestRun is used when a test run is being executed locally, while the results are streamed to the cloud, i.e. `k6 run --out cloud script.js`.

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) error

Do is simpler to http.Do but also unmarshals the response in the provided v

func (*Client) GetTestProgress

func (c *Client) GetTestProgress(referenceID string) (*TestProgressResponse, error)

GetTestProgress for the provided referenceID.

func (*Client) Login

func (c *Client) Login(email string, password string) (*LoginResponse, error)

Login the user with the specified email and password.

func (*Client) NewRequest

func (c *Client) NewRequest(method, url string, data interface{}) (*http.Request, error)

NewRequest creates new HTTP request.

This is the same as http.NewRequest, except that data if not nil will be serialized in json format.

func (*Client) StartCloudTestRun

func (c *Client) StartCloudTestRun(name string, projectID int64, arc *lib.Archive) (*CreateTestRunResponse, error)

StartCloudTestRun starts a cloud test run, i.e. `k6 cloud script.js`.

func (*Client) StopCloudTestRun

func (c *Client) StopCloudTestRun(referenceID string) error

StopCloudTestRun tells the cloud to stop the test with the provided referenceID.

func (*Client) TestFinished

func (c *Client) TestFinished(referenceID string, thresholds ThresholdResult, tained bool, runStatus RunStatus) error

TestFinished sends the result and run status values to the cloud, along with information for the test thresholds, and marks the test run as finished.

func (*Client) UploadTestOnly added in v0.45.0

func (c *Client) UploadTestOnly(name string, projectID int64, arc *lib.Archive) (*CreateTestRunResponse, error)

UploadTestOnly uploads a test run to the cloud without actually starting it.

func (*Client) ValidateOptions

func (c *Client) ValidateOptions(options lib.Options) error

ValidateOptions sends the provided options to the cloud for validation.

type Config

type Config struct {
	// TODO: refactor common stuff between cloud execution and output
	Token     null.String `json:"token" envconfig:"K6_CLOUD_TOKEN"`
	ProjectID null.Int    `json:"projectID" envconfig:"K6_CLOUD_PROJECT_ID"`
	Name      null.String `json:"name" envconfig:"K6_CLOUD_NAME"`

	Host    null.String        `json:"host" envconfig:"K6_CLOUD_HOST"`
	Timeout types.NullDuration `json:"timeout" envconfig:"K6_CLOUD_TIMEOUT"`

	LogsTailURL    null.String `json:"-" envconfig:"K6_CLOUD_LOGS_TAIL_URL"`
	WebAppURL      null.String `json:"webAppURL" envconfig:"K6_CLOUD_WEB_APP_URL"`
	TestRunDetails null.String `json:"testRunDetails" envconfig:"K6_CLOUD_TEST_RUN_DETAILS"`
	NoCompress     null.Bool   `json:"noCompress" envconfig:"K6_CLOUD_NO_COMPRESS"`
	StopOnError    null.Bool   `json:"stopOnError" envconfig:"K6_CLOUD_STOP_ON_ERROR"`
	APIVersion     null.Int    `json:"apiVersion" envconfig:"K6_CLOUD_API_VERSION"`

	// PushRefID represents the test run id.
	// Note: It is a legacy name used by the backend, the code in k6 open-source
	// references it as test run id.
	// Currently, a renaming is not planned.
	PushRefID null.String `json:"pushRefID" envconfig:"K6_CLOUD_PUSH_REF_ID"`

	// Defines the max allowed number of time series in a single batch.
	MaxTimeSeriesInBatch null.Int `json:"maxTimeSeriesInBatch" envconfig:"K6_CLOUD_MAX_TIME_SERIES_IN_BATCH"`

	// The time interval between periodic API calls for sending samples to the cloud ingest service.
	MetricPushInterval types.NullDuration `json:"metricPushInterval" envconfig:"K6_CLOUD_METRIC_PUSH_INTERVAL"`

	// This is how many concurrent pushes will be done at the same time to the cloud
	MetricPushConcurrency null.Int `json:"metricPushConcurrency" envconfig:"K6_CLOUD_METRIC_PUSH_CONCURRENCY"`

	// If specified and is greater than 0, sample aggregation with that period is enabled
	AggregationPeriod types.NullDuration `json:"aggregationPeriod" envconfig:"K6_CLOUD_AGGREGATION_PERIOD"`

	// If aggregation is enabled, this specifies how long we'll wait for period samples to accumulate before trying to aggregate them.
	AggregationWaitPeriod types.NullDuration `json:"aggregationWaitPeriod" envconfig:"K6_CLOUD_AGGREGATION_WAIT_PERIOD"`

	// Indicates whether to send traces to the k6 Insights backend service.
	TracesEnabled null.Bool `json:"tracesEnabled" envconfig:"K6_CLOUD_TRACES_ENABLED"`

	// The host of the k6 Insights backend service.
	TracesHost null.String `json:"traceHost" envconfig:"K6_CLOUD_TRACES_HOST"`

	// This is how many concurrent pushes will be done at the same time to the cloud
	TracesPushConcurrency null.Int `json:"tracesPushConcurrency" envconfig:"K6_CLOUD_TRACES_PUSH_CONCURRENCY"`

	// The time interval between periodic API calls for sending samples to the cloud ingest service.
	TracesPushInterval types.NullDuration `json:"tracesPushInterval" envconfig:"K6_CLOUD_TRACES_PUSH_INTERVAL"`
}

Config holds all the necessary data and options for sending metrics to the k6 Cloud.

func GetConsolidatedConfig

func GetConsolidatedConfig(
	jsonRawConf json.RawMessage,
	env map[string]string,
	configArg string,
	cloudConfig json.RawMessage,
	external map[string]json.RawMessage,
) (Config, string, error)

GetConsolidatedConfig combines the default config values with the JSON config values and environment variables and returns the final result. it also returns a warning message that could be shown to the user. to bring some attention to the fact that the user.

func NewConfig

func NewConfig() Config

NewConfig creates a new Config instance with default values for some fields.

func (Config) Apply

func (c Config) Apply(cfg Config) Config

Apply saves config non-zero config values from the passed config in the receiver.

func (*Config) StreamLogsToLogger

func (c *Config) StreamLogsToLogger(
	ctx context.Context, logger logrus.FieldLogger, referenceID string, tailFrom time.Duration,
) error

StreamLogsToLogger streams the logs for the configured test to the provided logger until ctx is Done or an error occurs.

type CreateTestRunResponse

type CreateTestRunResponse struct {
	ReferenceID    string     `json:"reference_id"`
	ConfigOverride *Config    `json:"config"`
	Logs           []LogEntry `json:"logs"`
}

CreateTestRunResponse represents the response of successfully created test run in the cloud.

type LogEntry added in v0.43.0

type LogEntry struct {
	Level   string `json:"level"`
	Message string `json:"message"`
}

LogEntry can be used by the cloud to tell k6 to log something to the console, so the user can see it.

type LoginResponse

type LoginResponse struct {
	Token string `json:"token"`
}

LoginResponse includes the token after a successful login.

type ResponseError added in v0.50.0

type ResponseError struct {
	Response *http.Response `json:"-"`

	Code        int                 `json:"code"`
	Message     string              `json:"message"`
	Details     map[string][]string `json:"details"`
	FieldErrors map[string][]string `json:"field_errors"`
	Errors      []string            `json:"errors"`
}

ResponseError represents an error cause by talking to the API

func (ResponseError) Error added in v0.50.0

func (e ResponseError) Error() string

type ResultStatus

type ResultStatus int

ResultStatus represents the result status of a test.

const (
	// ResultStatusPassed means the test has passed
	ResultStatusPassed ResultStatus = 0
	// ResultStatusFailed means the test has failed
	ResultStatusFailed ResultStatus = 1
)

type RunStatus added in v0.43.0

type RunStatus int

RunStatus values are used to tell the cloud output how a local test run ended, and to get that information from the cloud for cloud tests.

const (
	RunStatusCreated            RunStatus = -2
	RunStatusValidated          RunStatus = -1
	RunStatusQueued             RunStatus = 0
	RunStatusInitializing       RunStatus = 1
	RunStatusRunning            RunStatus = 2
	RunStatusFinished           RunStatus = 3
	RunStatusTimedOut           RunStatus = 4
	RunStatusAbortedUser        RunStatus = 5
	RunStatusAbortedSystem      RunStatus = 6
	RunStatusAbortedScriptError RunStatus = 7
	RunStatusAbortedThreshold   RunStatus = 8
	RunStatusAbortedLimit       RunStatus = 9
	RunStatusArchived           RunStatus = 10
)

Possible run status values; iota isn't used intentionally

type TestProgressResponse

type TestProgressResponse struct {
	RunStatusText string       `json:"run_status_text"`
	RunStatus     RunStatus    `json:"run_status"`
	ResultStatus  ResultStatus `json:"result_status"`
	Progress      float64      `json:"progress"`
}

TestProgressResponse represents the progress of a cloud test.

type TestRun

type TestRun struct {
	Name       string              `json:"name"`
	ProjectID  int64               `json:"project_id,omitempty"`
	VUsMax     int64               `json:"vus"`
	Thresholds map[string][]string `json:"thresholds"`
	// Duration of test in seconds. -1 for unknown length, 0 for continuous running.
	Duration int64 `json:"duration"`
}

TestRun represents a test run.

type ThresholdResult

type ThresholdResult map[string]map[string]bool

ThresholdResult is a helper type to make sending the thresholds result to the cloud.

Directories

Path Synopsis
Package insights contains the domain data structures and client logic for the k6 cloud Insights API.
Package insights contains the domain data structures and client logic for the k6 cloud Insights API.
proto
Package proto contains the Protobuf definitions used by the k6 Insights.
Package proto contains the Protobuf definitions used by the k6 Insights.

Jump to

Keyboard shortcuts

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