|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "path/filepath" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/sirupsen/logrus" |
| 13 | + "gopkg.in/guregu/null.v3" |
| 14 | + |
| 15 | + "go.k6.io/k6/cloudapi" |
| 16 | + "go.k6.io/k6/cmd/state" |
| 17 | + "go.k6.io/k6/lib" |
| 18 | + "go.k6.io/k6/lib/consts" |
| 19 | + "go.k6.io/k6/metrics" |
| 20 | +) |
| 21 | + |
| 22 | +const ( |
| 23 | + defaultTestName = "k6 test" |
| 24 | + testRunIDKey = "K6_CLOUDRUN_TEST_RUN_ID" |
| 25 | +) |
| 26 | + |
| 27 | +// createCloudTest performs some test and Cloud configuration validations and if everything |
| 28 | +// looks good, then it creates a test run in the k6 Cloud, using the Cloud API, meant to be used |
| 29 | +// for streaming test results. |
| 30 | +// |
| 31 | +// This method is also responsible for filling the test run id on the test environment, so it can be used later, |
| 32 | +// and to populate the Cloud configuration back in case the Cloud API returned some overrides, |
| 33 | +// as expected by the Cloud output. |
| 34 | +// |
| 35 | +//nolint:funlen |
| 36 | +func createCloudTest(gs *state.GlobalState, test *loadedAndConfiguredTest) error { |
| 37 | + // Otherwise, we continue normally with the creation of the test run in the k6 Cloud backend services. |
| 38 | + conf, warn, err := cloudapi.GetConsolidatedConfig( |
| 39 | + test.derivedConfig.Collectors[builtinOutputCloud.String()], |
| 40 | + gs.Env, |
| 41 | + "", // Historically used for -o cloud=..., no longer used (deprecated). |
| 42 | + test.derivedConfig.Options.Cloud, |
| 43 | + test.derivedConfig.Options.External, |
| 44 | + ) |
| 45 | + if err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + |
| 49 | + if warn != "" { |
| 50 | + gs.Logger.Warn(warn) |
| 51 | + } |
| 52 | + |
| 53 | + // If not, we continue with some validations and the creation of the test run. |
| 54 | + if err := validateRequiredSystemTags(test.derivedConfig.Options.SystemTags); err != nil { |
| 55 | + return err |
| 56 | + } |
| 57 | + |
| 58 | + if !conf.Name.Valid || conf.Name.String == "" { |
| 59 | + scriptPath := test.source.URL.String() |
| 60 | + if scriptPath == "" { |
| 61 | + // Script from stdin without a name, likely from stdin |
| 62 | + return errors.New("script name not set, please specify K6_CLOUD_NAME or options.cloud.name") |
| 63 | + } |
| 64 | + |
| 65 | + conf.Name = null.StringFrom(filepath.Base(scriptPath)) |
| 66 | + } |
| 67 | + if conf.Name.String == "-" { |
| 68 | + conf.Name = null.StringFrom(defaultTestName) |
| 69 | + } |
| 70 | + |
| 71 | + thresholds := make(map[string][]string) |
| 72 | + for name, t := range test.derivedConfig.Thresholds { |
| 73 | + for _, threshold := range t.Thresholds { |
| 74 | + thresholds[name] = append(thresholds[name], threshold.Source) |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + et, err := lib.NewExecutionTuple( |
| 79 | + test.derivedConfig.Options.ExecutionSegment, |
| 80 | + test.derivedConfig.Options.ExecutionSegmentSequence, |
| 81 | + ) |
| 82 | + if err != nil { |
| 83 | + return err |
| 84 | + } |
| 85 | + executionPlan := test.derivedConfig.Options.Scenarios.GetFullExecutionRequirements(et) |
| 86 | + |
| 87 | + duration, testEnds := lib.GetEndOffset(executionPlan) |
| 88 | + if !testEnds { |
| 89 | + return errors.New("tests with unspecified duration are not allowed when outputting data to k6 cloud") |
| 90 | + } |
| 91 | + |
| 92 | + if conf.MetricPushConcurrency.Int64 < 1 { |
| 93 | + return fmt.Errorf("metrics push concurrency must be a positive number but is %d", |
| 94 | + conf.MetricPushConcurrency.Int64) |
| 95 | + } |
| 96 | + |
| 97 | + if conf.MaxTimeSeriesInBatch.Int64 < 1 { |
| 98 | + return fmt.Errorf("max allowed number of time series in a single batch must be a positive number but is %d", |
| 99 | + conf.MaxTimeSeriesInBatch.Int64) |
| 100 | + } |
| 101 | + |
| 102 | + var testArchive *lib.Archive |
| 103 | + if !test.derivedConfig.NoArchiveUpload.Bool { |
| 104 | + testArchive = test.initRunner.MakeArchive() |
| 105 | + } |
| 106 | + |
| 107 | + testRun := &cloudapi.TestRun{ |
| 108 | + Name: conf.Name.String, |
| 109 | + ProjectID: conf.ProjectID.Int64, |
| 110 | + VUsMax: int64(lib.GetMaxPossibleVUs(executionPlan)), //nolint:gosec |
| 111 | + Thresholds: thresholds, |
| 112 | + Duration: int64(duration / time.Second), |
| 113 | + Archive: testArchive, |
| 114 | + } |
| 115 | + |
| 116 | + logger := gs.Logger.WithFields(logrus.Fields{"output": builtinOutputCloud.String()}) |
| 117 | + |
| 118 | + apiClient := cloudapi.NewClient( |
| 119 | + logger, conf.Token.String, conf.Host.String, consts.Version, conf.Timeout.TimeDuration()) |
| 120 | + |
| 121 | + response, err := apiClient.CreateTestRun(testRun) |
| 122 | + if err != nil { |
| 123 | + return err |
| 124 | + } |
| 125 | + |
| 126 | + // We store the test run id in the environment, so it can be used later. |
| 127 | + test.preInitState.RuntimeOptions.Env[testRunIDKey] = response.ReferenceID |
| 128 | + |
| 129 | + // If the Cloud API returned configuration overrides, we apply them to the current configuration. |
| 130 | + // Then, we serialize the overridden configuration back, so it can be used by the Cloud output. |
| 131 | + if response.ConfigOverride != nil { |
| 132 | + logger.WithFields(logrus.Fields{"override": response.ConfigOverride}).Debug("overriding config options") |
| 133 | + |
| 134 | + raw, err := cloudConfToRawMessage(conf.Apply(*response.ConfigOverride)) |
| 135 | + if err != nil { |
| 136 | + return fmt.Errorf("could not serialize overridden cloud configuration: %w", err) |
| 137 | + } |
| 138 | + |
| 139 | + if test.derivedConfig.Collectors == nil { |
| 140 | + test.derivedConfig.Collectors = make(map[string]json.RawMessage) |
| 141 | + } |
| 142 | + test.derivedConfig.Collectors[builtinOutputCloud.String()] = raw |
| 143 | + } |
| 144 | + |
| 145 | + return nil |
| 146 | +} |
| 147 | + |
| 148 | +// validateRequiredSystemTags checks if all required tags are present. |
| 149 | +func validateRequiredSystemTags(scriptTags *metrics.SystemTagSet) error { |
| 150 | + var missingRequiredTags []string |
| 151 | + requiredTags := metrics.SystemTagSet(metrics.TagName | |
| 152 | + metrics.TagMethod | |
| 153 | + metrics.TagStatus | |
| 154 | + metrics.TagError | |
| 155 | + metrics.TagCheck | |
| 156 | + metrics.TagGroup) |
| 157 | + for _, tag := range metrics.SystemTagValues() { |
| 158 | + if requiredTags.Has(tag) && !scriptTags.Has(tag) { |
| 159 | + missingRequiredTags = append(missingRequiredTags, tag.String()) |
| 160 | + } |
| 161 | + } |
| 162 | + if len(missingRequiredTags) > 0 { |
| 163 | + return fmt.Errorf( |
| 164 | + "the cloud output needs the following system tags enabled: %s", |
| 165 | + strings.Join(missingRequiredTags, ", "), |
| 166 | + ) |
| 167 | + } |
| 168 | + return nil |
| 169 | +} |
| 170 | + |
| 171 | +func cloudConfToRawMessage(conf cloudapi.Config) (json.RawMessage, error) { |
| 172 | + var buff bytes.Buffer |
| 173 | + enc := json.NewEncoder(&buff) |
| 174 | + if err := enc.Encode(conf); err != nil { |
| 175 | + return nil, err |
| 176 | + } |
| 177 | + return buff.Bytes(), nil |
| 178 | +} |
0 commit comments