2024-02-21 08:41:49 +00:00
|
|
|
package k6
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-02-21 13:09:22 +00:00
|
|
|
"log/slog"
|
2024-02-21 08:41:49 +00:00
|
|
|
"net/url"
|
2024-02-21 13:09:22 +00:00
|
|
|
"os"
|
2024-02-21 08:41:49 +00:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"go.k6.io/k6/event"
|
|
|
|
"go.k6.io/k6/execution"
|
|
|
|
"go.k6.io/k6/execution/local"
|
|
|
|
"go.k6.io/k6/js/common"
|
|
|
|
"go.k6.io/k6/lib"
|
|
|
|
"go.k6.io/k6/lib/fsext"
|
|
|
|
"go.k6.io/k6/lib/trace"
|
|
|
|
"go.k6.io/k6/loader"
|
|
|
|
"go.k6.io/k6/metrics"
|
|
|
|
"go.k6.io/k6/metrics/engine"
|
|
|
|
"go.k6.io/k6/output"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// We use an excessively high timeout to wait for event processing to complete,
|
|
|
|
// since prematurely proceeding before it is done could create bigger problems.
|
|
|
|
// In practice, this effectively acts as no timeout, and the user will have to
|
|
|
|
// kill k6 if a hang happens, which is the behavior without events anyway.
|
|
|
|
waitEventDoneTimeout = 30 * time.Minute
|
|
|
|
|
|
|
|
// This timeout should be long enough to flush all remaining traces, but still
|
|
|
|
// provides a safeguard to not block indefinitely.
|
|
|
|
waitForTracerProviderStopTimeout = 3 * time.Minute
|
|
|
|
)
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
type ExecutionResult struct {
|
|
|
|
Note string
|
|
|
|
Success bool
|
|
|
|
}
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
type Execution struct {
|
|
|
|
FS fsext.Fs
|
|
|
|
Env map[string]string
|
|
|
|
Events *event.System
|
|
|
|
|
|
|
|
LoggerCompat *logrus.Logger
|
|
|
|
|
|
|
|
Script string
|
|
|
|
|
|
|
|
Logger *slog.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewExecution(logger *slog.Logger, script string) *Execution {
|
|
|
|
loggerCompat := logrus.StandardLogger()
|
2024-02-21 22:15:21 +00:00
|
|
|
loggerCompat.SetLevel(logrus.DebugLevel)
|
2024-02-21 13:09:22 +00:00
|
|
|
|
|
|
|
return &Execution{
|
|
|
|
FS: fsext.NewOsFs(),
|
|
|
|
Env: BuildEnvMap(os.Environ()),
|
|
|
|
Events: event.NewEventSystem(100, loggerCompat),
|
|
|
|
LoggerCompat: loggerCompat,
|
|
|
|
Logger: logger,
|
|
|
|
Script: script,
|
|
|
|
}
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
func (e *Execution) loadLocalTest() (*loadedAndConfiguredTest, *local.Controller, error) {
|
|
|
|
data := []byte(e.Script)
|
|
|
|
|
|
|
|
fileSystems := loader.CreateFilesystems(e.FS)
|
|
|
|
|
|
|
|
err := fsext.WriteFile(fileSystems["file"].(fsext.CacheLayerGetter).GetCachingFs(), "/-", data, 0o644)
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 13:09:22 +00:00
|
|
|
return nil, nil, fmt.Errorf("caching data read from -: %w", err)
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
2024-02-21 13:09:22 +00:00
|
|
|
|
|
|
|
src := &loader.SourceData{URL: &url.URL{Path: "/-", Scheme: "file"}, Data: data}
|
|
|
|
e.Logger.Debug(
|
|
|
|
"successfully loaded bytes!",
|
|
|
|
"bytes", len(src.Data),
|
2024-02-21 08:41:49 +00:00
|
|
|
)
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
e.Logger.Debug("Gathering k6 runtime options...")
|
2024-02-21 08:41:49 +00:00
|
|
|
runtimeOptions := lib.RuntimeOptions{}
|
|
|
|
|
|
|
|
registry := metrics.NewRegistry()
|
|
|
|
state := &lib.TestPreInitState{
|
2024-02-21 13:09:22 +00:00
|
|
|
Logger: e.LoggerCompat,
|
2024-02-21 08:41:49 +00:00
|
|
|
RuntimeOptions: runtimeOptions,
|
|
|
|
Registry: registry,
|
|
|
|
BuiltinMetrics: metrics.RegisterBuiltinMetrics(registry),
|
2024-02-21 13:09:22 +00:00
|
|
|
Events: e.Events,
|
2024-02-21 08:41:49 +00:00
|
|
|
LookupEnv: func(key string) (string, bool) {
|
2024-02-21 13:09:22 +00:00
|
|
|
val, ok := e.Env[key]
|
2024-02-21 08:41:49 +00:00
|
|
|
return val, ok
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
test := &loadedTest{
|
2024-02-21 13:09:22 +00:00
|
|
|
source: src,
|
|
|
|
fs: e.FS,
|
|
|
|
fileSystems: fileSystems,
|
|
|
|
preInitState: state,
|
|
|
|
logger: e.Logger,
|
|
|
|
loggerCompat: e.LoggerCompat,
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
e.Logger.Debug("Initializing k6 runner...")
|
|
|
|
if err := test.initializeFirstRunner(); err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("could not initialize: %w", err)
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
2024-02-21 13:09:22 +00:00
|
|
|
e.Logger.Debug("Runner successfully initialized!")
|
2024-02-21 08:41:49 +00:00
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
configuredTest, err := test.consolidateDeriveAndValidateConfig()
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 13:09:22 +00:00
|
|
|
return nil, nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
controller := local.NewController()
|
|
|
|
return configuredTest, controller, nil
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Execution) setupTracerProvider(ctx context.Context, test *loadedAndConfiguredTest) error {
|
|
|
|
ro := test.preInitState.RuntimeOptions
|
|
|
|
if ro.TracesOutput.String == "" {
|
|
|
|
test.preInitState.TracerProvider = trace.NewNoopTracerProvider()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
tp, err := trace.TracerProviderFromConfigLine(ctx, ro.TracesOutput.String)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
test.preInitState.TracerProvider = tp
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
func (e *Execution) Run(ctx context.Context) (result *ExecutionResult, err error) {
|
2024-02-21 08:41:49 +00:00
|
|
|
globalCtx, globalCancel := context.WithCancel(ctx)
|
|
|
|
defer globalCancel()
|
|
|
|
|
|
|
|
// lingerCtx is cancelled by Ctrl+C, and is used to wait for that event when
|
|
|
|
// k6 was started with the --linger option.
|
|
|
|
lingerCtx, lingerCancel := context.WithCancel(globalCtx)
|
|
|
|
defer lingerCancel()
|
|
|
|
|
|
|
|
// runCtx is used for the test run execution and is created with the special
|
|
|
|
// execution.NewTestRunContext() function so that it can be aborted even
|
|
|
|
// from sub-contexts while also attaching a reason for the abort.
|
2024-02-21 22:15:21 +00:00
|
|
|
runCtx, runAbort := execution.NewTestRunContext(lingerCtx, e.LoggerCompat)
|
2024-02-21 08:41:49 +00:00
|
|
|
|
|
|
|
emitEvent := func(evt *event.Event) func() {
|
2024-02-21 13:09:22 +00:00
|
|
|
waitDone := e.Events.Emit(evt)
|
2024-02-21 08:41:49 +00:00
|
|
|
return func() {
|
|
|
|
waitCtx, waitCancel := context.WithTimeout(globalCtx, waitEventDoneTimeout)
|
|
|
|
defer waitCancel()
|
|
|
|
if werr := waitDone(waitCtx); werr != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.With(werr).Warn("")
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
waitExitDone := emitEvent(&event.Event{
|
|
|
|
Type: event.Exit,
|
|
|
|
Data: &event.ExitData{Error: err},
|
|
|
|
})
|
|
|
|
waitExitDone()
|
2024-02-21 13:09:22 +00:00
|
|
|
e.Events.UnsubscribeAll()
|
2024-02-21 08:41:49 +00:00
|
|
|
}()
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
configuredTest, controller, err := e.loadLocalTest()
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-21 13:09:22 +00:00
|
|
|
if err = e.setupTracerProvider(globalCtx, configuredTest); err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
waitTracesFlushed := func() {
|
|
|
|
ctx, cancel := context.WithTimeout(globalCtx, waitForTracerProviderStopTimeout)
|
|
|
|
defer cancel()
|
2024-02-21 13:09:22 +00:00
|
|
|
if tpErr := configuredTest.preInitState.TracerProvider.Shutdown(ctx); tpErr != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Error("The tracer provider didn't stop gracefully", tpErr)
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the full consolidated *and derived* options back to the Runner.
|
2024-02-21 13:09:22 +00:00
|
|
|
conf := configuredTest.config
|
|
|
|
testRunState, err := configuredTest.buildTestRunState(conf)
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create a local execution scheduler wrapping the runner.
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Initializing the execution scheduler...")
|
2024-02-21 08:41:49 +00:00
|
|
|
execScheduler, err := execution.NewScheduler(testRunState, controller)
|
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
backgroundProcesses := &sync.WaitGroup{}
|
|
|
|
defer backgroundProcesses.Wait()
|
|
|
|
|
|
|
|
// Create all outputs.
|
|
|
|
// executionPlan := execScheduler.GetExecutionPlan()
|
|
|
|
outputs := []output.Output{}
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
metricsEngine, err := engine.NewMetricsEngine(testRunState.Registry, e.LoggerCompat)
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We'll need to pipe metrics to the MetricsEngine and process them if any
|
|
|
|
// of these are enabled: thresholds, end-of-test summary
|
|
|
|
shouldProcessMetrics := (!testRunState.RuntimeOptions.NoSummary.Bool ||
|
|
|
|
!testRunState.RuntimeOptions.NoThresholds.Bool)
|
|
|
|
var metricsIngester *engine.OutputIngester
|
|
|
|
if shouldProcessMetrics {
|
|
|
|
err = metricsEngine.InitSubMetricsAndThresholds(conf, testRunState.RuntimeOptions.NoThresholds.Bool)
|
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
// We'll need to pipe metrics to the MetricsEngine if either the
|
|
|
|
// thresholds or the end-of-test summary are enabled.
|
|
|
|
metricsIngester = metricsEngine.CreateIngester()
|
|
|
|
outputs = append(outputs, metricsIngester)
|
|
|
|
}
|
|
|
|
|
|
|
|
executionState := execScheduler.GetState()
|
|
|
|
if !testRunState.RuntimeOptions.NoSummary.Bool {
|
|
|
|
defer func() {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Generating the end-of-test summary...")
|
2024-02-21 13:09:22 +00:00
|
|
|
summaryResult, hsErr := configuredTest.initRunner.HandleSummary(globalCtx, &lib.Summary{
|
2024-02-21 08:41:49 +00:00
|
|
|
Metrics: metricsEngine.ObservedMetrics,
|
|
|
|
RootGroup: testRunState.Runner.GetDefaultGroup(),
|
|
|
|
TestRunDuration: executionState.GetCurrentTestRunDuration(),
|
2024-02-21 13:09:22 +00:00
|
|
|
NoColor: true,
|
2024-02-21 08:41:49 +00:00
|
|
|
UIState: lib.UIState{
|
2024-02-21 13:09:22 +00:00
|
|
|
IsStdOutTTY: false,
|
|
|
|
IsStdErrTTY: false,
|
2024-02-21 08:41:49 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
if hsErr == nil {
|
|
|
|
for _, o := range summaryResult {
|
2024-02-21 13:09:22 +00:00
|
|
|
_, err := io.Copy(os.Stdout, o)
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.With(err).Error("failed to write summary output")
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if hsErr != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.With(hsErr).Error("failed to handle the end-of-test summary")
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
waitInitDone := emitEvent(&event.Event{Type: event.Init})
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
outputManager := output.NewManager(outputs, e.LoggerCompat, func(err error) {
|
2024-02-21 08:41:49 +00:00
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.With(err).Error("Received error to stop from output")
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
// TODO: attach run status and exit code?
|
|
|
|
runAbort(err)
|
|
|
|
})
|
2024-02-21 13:09:22 +00:00
|
|
|
samples := make(chan metrics.SampleContainer, configuredTest.config.MetricSamplesBufferSize.Int64)
|
2024-02-21 08:41:49 +00:00
|
|
|
waitOutputsFlushed, stopOutputs, err := outputManager.Start(samples)
|
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
defer func() {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Stopping outputs...")
|
2024-02-21 08:41:49 +00:00
|
|
|
// We call waitOutputsFlushed() below because the threshold calculations
|
|
|
|
// need all of the metrics to be sent to the MetricsEngine before we can
|
|
|
|
// calculate them one last time. We need the threshold calculated here,
|
|
|
|
// since they may change the run status for the outputs.
|
|
|
|
stopOutputs(err)
|
|
|
|
}()
|
|
|
|
|
|
|
|
if !testRunState.RuntimeOptions.NoThresholds.Bool {
|
|
|
|
finalizeThresholds := metricsEngine.StartThresholdCalculations(
|
|
|
|
metricsIngester, runAbort, executionState.GetCurrentTestRunDuration,
|
|
|
|
)
|
|
|
|
if finalizeThresholds != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
defer func() {
|
|
|
|
// This gets called after the Samples channel has been closed and
|
|
|
|
// the OutputManager has flushed all of the cached samples to
|
|
|
|
// outputs (including MetricsEngine's ingester). So we are sure
|
|
|
|
// there won't be any more metrics being sent.
|
|
|
|
e.Logger.Debug("Finalizing thresholds...")
|
|
|
|
breachedThresholds := finalizeThresholds()
|
|
|
|
if len(breachedThresholds) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err == nil {
|
|
|
|
result = &ExecutionResult{
|
|
|
|
Success: false,
|
|
|
|
Note: fmt.Sprintf("thresholds on metrics '%s' have been crossed", strings.Join(breachedThresholds, ", ")),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Waiting for metrics and traces processing to finish...")
|
2024-02-21 08:41:49 +00:00
|
|
|
close(samples)
|
|
|
|
|
|
|
|
ww := [...]func(){
|
|
|
|
waitOutputsFlushed,
|
|
|
|
waitTracesFlushed,
|
|
|
|
}
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(len(ww))
|
|
|
|
for _, w := range ww {
|
|
|
|
w := w
|
|
|
|
go func() {
|
|
|
|
w()
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Metrics and traces processing finished!")
|
2024-02-21 08:41:49 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
// Initialize the VUs and executors
|
|
|
|
stopVUEmission, err := execScheduler.Init(runCtx, samples)
|
|
|
|
if err != nil {
|
2024-02-21 22:15:21 +00:00
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
defer stopVUEmission()
|
|
|
|
|
|
|
|
waitInitDone()
|
|
|
|
|
|
|
|
waitTestStartDone := emitEvent(&event.Event{Type: event.TestStart})
|
|
|
|
waitTestStartDone()
|
|
|
|
|
|
|
|
// Start the test! However, we won't immediately return if there was an
|
|
|
|
// error, we still have things to do.
|
|
|
|
err = execScheduler.Run(globalCtx, runCtx, samples)
|
|
|
|
|
|
|
|
waitTestEndDone := emitEvent(&event.Event{Type: event.TestEnd})
|
|
|
|
defer waitTestEndDone()
|
|
|
|
|
|
|
|
// Check what the execScheduler.Run() error is.
|
|
|
|
if err != nil {
|
|
|
|
err = common.UnwrapGojaInterruptedError(err)
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.With(err).Debug("Test finished with an error")
|
|
|
|
return nil, err
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Warn if no iterations could be completed.
|
|
|
|
if executionState.GetFullIterationCount() == 0 {
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Warn("No script iterations fully finished, consider making the test duration longer")
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
e.Logger.Debug("Test finished cleanly")
|
2024-02-21 08:41:49 +00:00
|
|
|
|
2024-02-21 22:15:21 +00:00
|
|
|
return &ExecutionResult{Success: true, Note: ""}, nil
|
2024-02-21 08:41:49 +00:00
|
|
|
}
|