diff --git a/.golangci.yml b/.golangci.yml index 468bc54eff1..15b979e43f6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,4 @@ -# v1.60.1 +# v1.62.2 # Please don't remove the first line. It uses in CI to determine the golangci version run: timeout: 5m diff --git a/cloudapi/logs.go b/cloudapi/logs.go index 129c6500d5c..b4b90378cd4 100644 --- a/cloudapi/logs.go +++ b/cloudapi/logs.go @@ -226,11 +226,11 @@ func (sfn sleeperFunc) Sleep(d time.Duration) { // between the latest iteration and the next retry. // Interval is used as the base to compute an exponential backoff, // if the computed interval overtakes the max interval then max will be used. -func retry(s sleeper, attempts uint, interval, maxDuration time.Duration, do func() error) (err error) { +func retry(s sleeper, attempts int, interval, maxDuration time.Duration, do func() error) (err error) { baseInterval := math.Abs(interval.Truncate(time.Second).Seconds()) r := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec - for i := 0; i < int(attempts); i++ { + for i := 0; i < attempts; i++ { if i > 0 { // wait = (interval ^ i) + random milliseconds wait := time.Duration(math.Pow(baseInterval, float64(i))) * time.Second diff --git a/cmd/report.go b/cmd/report.go index 0aec8dca52d..dbe92e8efda 100644 --- a/cmd/report.go +++ b/cmd/report.go @@ -21,7 +21,7 @@ func createReport(u *usage.Usage, execScheduler *execution.Scheduler) map[string m["duration"] = execState.GetCurrentTestRunDuration().String() m["goos"] = runtime.GOOS m["goarch"] = runtime.GOARCH - m["vus_max"] = uint64(execState.GetInitializedVUsCount()) + m["vus_max"] = uint64(execState.GetInitializedVUsCount()) //nolint:gosec m["iterations"] = execState.GetFullIterationCount() executors := make(map[string]int) for _, ec := range execScheduler.GetExecutorConfigs() { diff --git a/cmd/report_test.go b/cmd/report_test.go index 273fd157188..a1ee1e16b67 100644 --- a/cmd/report_test.go +++ b/cmd/report_test.go @@ -45,7 +45,7 @@ func TestCreateReport(t *testing.T) { require.NoError(t, err) s.GetState().ModInitializedVUsCount(6) - s.GetState().AddFullIterations(uint64(opts.Iterations.Int64)) + s.GetState().AddFullIterations(uint64(opts.Iterations.Int64)) //nolint:gosec s.GetState().MarkStarted() time.Sleep(10 * time.Millisecond) s.GetState().MarkEnded() diff --git a/errext/abort_reason.go b/errext/abort_reason.go index a4c6f0348c3..4299698662d 100644 --- a/errext/abort_reason.go +++ b/errext/abort_reason.go @@ -36,20 +36,20 @@ func WithAbortReasonIfNone(err error, abortReason AbortReason) error { // The given error already has an abort reason, do nothing return err } - return withAbortReason{err, abortReason} + return withAbortReasonError{err, abortReason} } -type withAbortReason struct { +type withAbortReasonError struct { error abortReason AbortReason } -func (ar withAbortReason) Unwrap() error { +func (ar withAbortReasonError) Unwrap() error { return ar.error } -func (ar withAbortReason) AbortReason() AbortReason { +func (ar withAbortReasonError) AbortReason() AbortReason { return ar.abortReason } -var _ HasAbortReason = withAbortReason{} +var _ HasAbortReason = withAbortReasonError{} diff --git a/errext/exit_code.go b/errext/exit_code.go index 95463fc8c62..0eca70a7f2c 100644 --- a/errext/exit_code.go +++ b/errext/exit_code.go @@ -30,20 +30,20 @@ func WithExitCodeIfNone(err error, exitCode exitcodes.ExitCode) error { // The given error already has an exit code, do nothing return err } - return withExitCode{err, exitCode} + return withExitCodeError{err, exitCode} } -type withExitCode struct { +type withExitCodeError struct { error exitCode exitcodes.ExitCode } -func (wh withExitCode) Unwrap() error { +func (wh withExitCodeError) Unwrap() error { return wh.error } -func (wh withExitCode) ExitCode() exitcodes.ExitCode { +func (wh withExitCodeError) ExitCode() exitcodes.ExitCode { return wh.exitCode } -var _ HasExitCode = withExitCode{} +var _ HasExitCode = withExitCodeError{} diff --git a/errext/format_test.go b/errext/format_test.go index c8a94f5a8e2..2e7a5d24a4f 100644 --- a/errext/format_test.go +++ b/errext/format_test.go @@ -28,7 +28,7 @@ func TestFormat(t *testing.T) { t.Run("Exception", func(t *testing.T) { t.Parallel() - err := fakeException{error: errors.New("simple error"), stack: "stack trace"} + err := fakeExceptionError{error: errors.New("simple error"), stack: "stack trace"} errorText, fields := errext.Format(err) assert.Equal(t, "stack trace", errorText) assert.Empty(t, fields) @@ -44,27 +44,27 @@ func TestFormat(t *testing.T) { t.Run("ExceptionWithHint", func(t *testing.T) { t.Parallel() - err := fakeException{error: errext.WithHint(errors.New("error with hint"), "hint message"), stack: "stack trace"} + err := fakeExceptionError{error: errext.WithHint(errors.New("error with hint"), "hint message"), stack: "stack trace"} errorText, fields := errext.Format(err) assert.Equal(t, "stack trace", errorText) assert.Equal(t, map[string]interface{}{"hint": "hint message"}, fields) }) } -type fakeException struct { +type fakeExceptionError struct { error stack string abort errext.AbortReason } -func (e fakeException) StackTrace() string { +func (e fakeExceptionError) StackTrace() string { return e.stack } -func (e fakeException) AbortReason() errext.AbortReason { +func (e fakeExceptionError) AbortReason() errext.AbortReason { return e.abort } -func (e fakeException) Unwrap() error { +func (e fakeExceptionError) Unwrap() error { return e.error } diff --git a/errext/hint.go b/errext/hint.go index c3b90251779..1b053b120fa 100644 --- a/errext/hint.go +++ b/errext/hint.go @@ -18,19 +18,19 @@ func WithHint(err error, hint string) error { if err == nil { return nil // No error, do nothing } - return withHint{err, hint} + return withHintError{err, hint} } -type withHint struct { +type withHintError struct { error hint string } -func (wh withHint) Unwrap() error { +func (wh withHintError) Unwrap() error { return wh.error } -func (wh withHint) Hint() string { +func (wh withHintError) Hint() string { hint := wh.hint var oldhint HasHint if errors.As(wh.error, &oldhint) { @@ -41,4 +41,4 @@ func (wh withHint) Hint() string { return hint } -var _ HasHint = withHint{} +var _ HasHint = withHintError{} diff --git a/execution/scheduler.go b/execution/scheduler.go index 0759332ab77..11832b7a81c 100644 --- a/execution/scheduler.go +++ b/execution/scheduler.go @@ -151,7 +151,7 @@ func (e *Scheduler) getRunStats() string { status = fmt.Sprintf("%s (%s)", status, pb.GetFixedLengthDuration(dur, e.maxDuration)) } - vusFmt := pb.GetFixedLengthIntFormat(int64(e.maxPossibleVUs)) + vusFmt := pb.GetFixedLengthIntFormat(int64(e.maxPossibleVUs)) //nolint:gosec return fmt.Sprintf( "%s, "+vusFmt+"/"+vusFmt+" VUs, %d complete and %d interrupted iterations", status, e.state.GetCurrentlyActiveVUsCount(), e.state.GetInitializedVUsCount(), @@ -268,7 +268,7 @@ func (e *Scheduler) initVUsAndExecutors(ctx context.Context, samplesOut chan<- m doneInits := e.initVUsConcurrently(subctx, samplesOut, vusToInitialize, runtime.GOMAXPROCS(0), logger) initializedVUs := new(uint64) - vusFmt := pb.GetFixedLengthIntFormat(int64(vusToInitialize)) + vusFmt := pb.GetFixedLengthIntFormat(int64(vusToInitialize)) //nolint:gosec e.initProgress.Modify( pb.WithProgress(func() (float64, []string) { doneVUs := atomic.LoadUint64(initializedVUs) diff --git a/js/bundle.go b/js/bundle.go index c6a5978119e..4894b3a0bc7 100644 --- a/js/bundle.go +++ b/js/bundle.go @@ -296,7 +296,7 @@ func (b *Bundle) newCompiler(logger logrus.FieldLogger) *compiler.Compiler { func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*BundleInstance, error) { rt := vuImpl.runtime - err := b.setupJSRuntime(rt, int64(vuID), b.preInitState.Logger) + err := b.setupJSRuntime(rt, vuID, b.preInitState.Logger) if err != nil { return nil, err } @@ -375,7 +375,7 @@ func (b *Bundle) instantiate(vuImpl *moduleVUImpl, vuID uint64) (*BundleInstance return bi, nil } -func (b *Bundle) setupJSRuntime(rt *sobek.Runtime, vuID int64, logger logrus.FieldLogger) error { +func (b *Bundle) setupJSRuntime(rt *sobek.Runtime, vuID uint64, logger logrus.FieldLogger) error { rt.SetFieldNameMapper(common.FieldNameMapper{}) rt.SetRandSource(common.NewRandSource()) diff --git a/js/bundle_test.go b/js/bundle_test.go index 0cbc4405101..0264ca31002 100644 --- a/js/bundle_test.go +++ b/js/bundle_test.go @@ -870,15 +870,15 @@ func TestBundleNotSharable(t *testing.T) { require.NoError(t, err) bundles := map[string]*Bundle{"Source": b1, "Archive": b2} - vus, iters := 10, 1000 + var vus, iters uint64 = 10, 1000 for name, b := range bundles { b := b t.Run(name, func(t *testing.T) { t.Parallel() - for i := 0; i < vus; i++ { - bi, err := b.Instantiate(context.Background(), uint64(i)) + for i := uint64(0); i < vus; i++ { + bi, err := b.Instantiate(context.Background(), i) require.NoError(t, err) - for j := 0; j < iters; j++ { + for j := uint64(0); j < iters; j++ { require.NoError(t, bi.Runtime.Set("__ITER", j)) _, err := bi.getCallableExport(consts.DefaultFn)(sobek.Undefined()) require.NoError(t, err) diff --git a/js/modules/k6/crypto/crypto.go b/js/modules/k6/crypto/crypto.go index 728a6648d6f..29ccd998cd7 100644 --- a/js/modules/k6/crypto/crypto.go +++ b/js/modules/k6/crypto/crypto.go @@ -14,8 +14,8 @@ import ( "fmt" "hash" - "golang.org/x/crypto/md4" //nolint:staticcheck // #nosec G501 // MD4 is weak, but we need it for compatibility - "golang.org/x/crypto/ripemd160" // no lint:staticcheck // #nosec G501 // RIPEMD160 is weak, but we need it for compatibility + "golang.org/x/crypto/md4" //nolint:staticcheck,gosec // MD4 is weak, but we need it for compatibility + "golang.org/x/crypto/ripemd160" //nolint:staticcheck,gosec // RIPEMD160 is weak, but we need it for compatibility "github.com/grafana/sobek" diff --git a/js/modules/k6/crypto/x509/x509.go b/js/modules/k6/crypto/x509/x509.go index 0162989ef40..8fad8af805e 100644 --- a/js/modules/k6/crypto/x509/x509.go +++ b/js/modules/k6/crypto/x509/x509.go @@ -2,7 +2,7 @@ package x509 import ( - "crypto/dsa" // #nosec G505 // DSA is weak, but we need it for compatibility + "crypto/dsa" //nolint:staticcheck // DSA is weak, but we need it for compatibility "crypto/ecdsa" "crypto/rsa" "crypto/sha1" // #nosec G505 diff --git a/js/modules/k6/execution/execution.go b/js/modules/k6/execution/execution.go index 236c177e73b..bede17fc75b 100644 --- a/js/modules/k6/execution/execution.go +++ b/js/modules/k6/execution/execution.go @@ -127,15 +127,15 @@ func (mi *ModuleInstance) newScenarioInfo() (*sobek.Object, error) { return newInfoObj(rt, si) } -//nolint:lll,gochecknoglobals -var instanceInfoInitContextErr = common.NewInitContextError("getting instance information in the init context is not supported") +//nolint:lll +var errInstanceInfoInitContext = common.NewInitContextError("getting instance information in the init context is not supported") // newInstanceInfo returns a sobek.Object with property accessors to retrieve // information about the local instance stats. func (mi *ModuleInstance) newInstanceInfo() (*sobek.Object, error) { es := lib.GetExecutionState(mi.vu.Context()) if es == nil { - return nil, instanceInfoInitContextErr + return nil, errInstanceInfoInitContext } rt := mi.vu.Runtime() @@ -160,8 +160,7 @@ func (mi *ModuleInstance) newInstanceInfo() (*sobek.Object, error) { return newInfoObj(rt, ti) } -//nolint:gochecknoglobals -var testInfoInitContextErr = common.NewInitContextError("getting test options in the init context is not supported") +var errTestInfoInitContext = common.NewInitContextError("getting test options in the init context is not supported") // newTestInfo returns a sobek.Object with property accessors to retrieve // information and control execution of the overall test run. @@ -184,7 +183,7 @@ func (mi *ModuleInstance) newTestInfo() (*sobek.Object, error) { "options": func() interface{} { vuState := mi.vu.State() if vuState == nil { - common.Throw(rt, testInfoInitContextErr) + common.Throw(rt, errTestInfoInitContext) } if optionsObject == nil { opts, err := optionsAsObject(rt, vuState.Options) @@ -200,15 +199,14 @@ func (mi *ModuleInstance) newTestInfo() (*sobek.Object, error) { return newInfoObj(rt, ti) } -//nolint:gochecknoglobals -var vuInfoInitContextErr = common.NewInitContextError("getting VU information in the init context is not supported") +var errVUInfoInitContex = common.NewInitContextError("getting VU information in the init context is not supported") // newVUInfo returns a sobek.Object with property accessors to retrieve // information about the currently executing VU. func (mi *ModuleInstance) newVUInfo() (*sobek.Object, error) { vuState := mi.vu.State() if vuState == nil { - return nil, vuInfoInitContextErr + return nil, errVUInfoInitContex } rt := mi.vu.Runtime() diff --git a/js/modules/k6/grpc/client.go b/js/modules/k6/grpc/client.go index ff4836a379e..f58ae394e78 100644 --- a/js/modules/k6/grpc/client.go +++ b/js/modules/k6/grpc/client.go @@ -125,7 +125,7 @@ func decryptPrivateKey(key, password []byte) ([]byte, error) { being used here because it is deprecated due to it not supporting *good* cryptography ultimately though we want to support something so we will be using it for now. */ - decryptedKey, err := x509.DecryptPEMBlock(block, password) + decryptedKey, err := x509.DecryptPEMBlock(block, password) //nolint:staticcheck if err != nil { return nil, err } diff --git a/js/modules/k6/timers/timers_test.go b/js/modules/k6/timers/timers_test.go index 446a8cb229e..3cd1ad1c334 100644 --- a/js/modules/k6/timers/timers_test.go +++ b/js/modules/k6/timers/timers_test.go @@ -173,7 +173,7 @@ func TestSetTimeoutContextCancel(t *testing.T) { for i := 0; i < 2000; i++ { ctx, cancel := context.WithCancel(context.Background()) runtime.CancelContext = cancel - runtime.VU.CtxField = ctx + runtime.VU.CtxField = ctx //nolint:fatcontext runtime.VU.RuntimeField.ClearInterrupt() const interruptMsg = "definitely an interrupt" go func() { diff --git a/js/runner.go b/js/runner.go index 976f09e214f..c7187cb3e78 100644 --- a/js/runner.go +++ b/js/runner.go @@ -172,8 +172,8 @@ func (r *Runner) newVU( tlsConfig := &tls.Config{ InsecureSkipVerify: r.Bundle.Options.InsecureSkipTLSVerify.Bool, //nolint:gosec CipherSuites: cipherSuites, - MinVersion: uint16(tlsVersions.Min), - MaxVersion: uint16(tlsVersions.Max), + MinVersion: uint16(tlsVersions.Min), //nolint:gosec + MaxVersion: uint16(tlsVersions.Max), //nolint:gosec Certificates: certs, Renegotiation: tls.RenegotiateFreelyAsClient, KeyLogWriter: r.preInitState.KeyLogger, @@ -188,7 +188,7 @@ func (r *Runner) newVU( "deprecation - https://pkg.go.dev/crypto/tls@go1.17#Config.", ) }) - tlsConfig.NameToCertificate = nameToCert + tlsConfig.NameToCertificate = nameToCert //nolint:staticcheck } transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, diff --git a/js/runner_test.go b/js/runner_test.go index f9c0316987d..d82bbd57333 100644 --- a/js/runner_test.go +++ b/js/runner_test.go @@ -1204,7 +1204,7 @@ func TestVUIntegrationTLSConfig(t *testing.T) { "", }, "UnsupportedVersion": { - lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}}, + lib.Options{TLSVersion: &lib.TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionSSL30}}, //nolint:staticcheck unsupportedVersionErrorMsg, }, } @@ -2070,7 +2070,7 @@ func TestSystemTags(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - vu, err := r.NewVU(ctx, uint64(num), 0, samples) + vu, err := r.NewVU(ctx, uint64(num), 0, samples) //nolint:gosec require.NoError(t, err) activeVU := vu.Activate(&lib.VUActivationParams{ RunContext: ctx, diff --git a/lib/archive.go b/lib/archive.go index d84936d0487..0ca6ff47825 100644 --- a/lib/archive.go +++ b/lib/archive.go @@ -125,7 +125,7 @@ func ReadArchive(in io.Reader) (*Archive, error) { } return nil, err } - if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { + if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { //nolint:staticcheck continue } @@ -166,7 +166,7 @@ func ReadArchive(in io.Reader) (*Archive, error) { case "https", "file": fileSystem := arc.getFs(pfx) name = filepath.FromSlash(name) - if err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode)); err != nil { + if err = fsext.WriteFile(fileSystem, name, data, fs.FileMode(hdr.Mode)); err != nil { //nolint:gosec return nil, err } if err = fileSystem.Chtimes(name, hdr.AccessTime, hdr.ModTime); err != nil { diff --git a/lib/execution.go b/lib/execution.go index 239041e660d..b42a70e5f8f 100644 --- a/lib/execution.go +++ b/lib/execution.go @@ -207,7 +207,7 @@ func NewExecutionState( resumeNotify := make(chan struct{}) close(resumeNotify) // By default the ExecutionState starts unpaused - maxUnplannedUninitializedVUs := int64(maxPossibleVUs - maxPlannedVUs) + maxUnplannedUninitializedVUs := int64(maxPossibleVUs - maxPlannedVUs) //nolint:gosec segIdx := NewSegmentedIndex(et) return &ExecutionState{ @@ -240,7 +240,7 @@ func (es *ExecutionState) GetUniqueVUIdentifiers() (uint64, uint64) { es.vuIDSegIndexMx.Lock() defer es.vuIDSegIndexMx.Unlock() scaled, unscaled := es.vuIDSegIndex.Next() - return uint64(scaled), uint64(unscaled) + return uint64(scaled), uint64(unscaled) //nolint:gosec } // GetInitializedVUsCount returns the total number of currently initialized VUs. diff --git a/lib/executor/base_executor.go b/lib/executor/base_executor.go index ee5ed0c343a..9f9ec21d85f 100644 --- a/lib/executor/base_executor.go +++ b/lib/executor/base_executor.go @@ -47,7 +47,7 @@ func (bs *BaseExecutor) nextIterationCounters() (uint64, uint64) { bs.iterSegIndexMx.Lock() defer bs.iterSegIndexMx.Unlock() scaled, unscaled := bs.iterSegIndex.Next() - return uint64(scaled - 1), uint64(unscaled - 1) + return uint64(scaled - 1), uint64(unscaled - 1) //nolint:gosec } // Init doesn't do anything for most executors, since initialization of all diff --git a/lib/executor/constant_arrival_rate.go b/lib/executor/constant_arrival_rate.go index c53339ab5bf..1675d6eaa2c 100644 --- a/lib/executor/constant_arrival_rate.go +++ b/lib/executor/constant_arrival_rate.go @@ -133,8 +133,8 @@ func (carc ConstantArrivalRateConfig) GetExecutionRequirements(et *lib.Execution return []lib.ExecutionStep{ { TimeOffset: 0, - PlannedVUs: uint64(et.ScaleInt64(carc.PreAllocatedVUs.Int64)), - MaxUnplannedVUs: uint64(et.ScaleInt64(carc.MaxVUs.Int64) - et.ScaleInt64(carc.PreAllocatedVUs.Int64)), + PlannedVUs: uint64(et.ScaleInt64(carc.PreAllocatedVUs.Int64)), //nolint:gosec + MaxUnplannedVUs: uint64(et.ScaleInt64(carc.MaxVUs.Int64) - et.ScaleInt64(carc.PreAllocatedVUs.Int64)), //nolint:gosec }, { TimeOffset: carc.Duration.TimeDuration() + carc.GracefulStop.TimeDuration(), PlannedVUs: 0, diff --git a/lib/executor/constant_vus.go b/lib/executor/constant_vus.go index 414ccfbdee5..b0a8ca690f4 100644 --- a/lib/executor/constant_vus.go +++ b/lib/executor/constant_vus.go @@ -88,7 +88,7 @@ func (clvc ConstantVUsConfig) GetExecutionRequirements(et *lib.ExecutionTuple) [ return []lib.ExecutionStep{ { TimeOffset: 0, - PlannedVUs: uint64(clvc.GetVUs(et)), + PlannedVUs: uint64(clvc.GetVUs(et)), //nolint:gosec }, { TimeOffset: clvc.Duration.TimeDuration() + clvc.GracefulStop.TimeDuration(), diff --git a/lib/executor/execution_test.go b/lib/executor/execution_test.go index 020ac7dc35c..7547ff43a78 100644 --- a/lib/executor/execution_test.go +++ b/lib/executor/execution_test.go @@ -44,19 +44,19 @@ func TestExecutionStateVUIDs(t *testing.T) { es := lib.NewExecutionState(nil, et, 0, 0) idl, idg := es.GetUniqueVUIdentifiers() - assert.Equal(t, uint64(1), idl) + assert.EqualValues(t, 1, idl) expGlobal := start + 1 - assert.Equal(t, uint64(expGlobal), idg) + assert.EqualValues(t, expGlobal, idg) idl, idg = es.GetUniqueVUIdentifiers() - assert.Equal(t, uint64(2), idl) + assert.EqualValues(t, 2, idl) expGlobal += offsets[0] - assert.Equal(t, uint64(expGlobal), idg) + assert.EqualValues(t, expGlobal, idg) idl, idg = es.GetUniqueVUIdentifiers() - assert.Equal(t, uint64(3), idl) + assert.EqualValues(t, 3, idl) expGlobal += offsets[0] - assert.Equal(t, uint64(expGlobal), idg) + assert.EqualValues(t, expGlobal, idg) seed := time.Now().UnixNano() r := rand.New(rand.NewSource(seed)) //nolint:gosec @@ -72,8 +72,8 @@ func TestExecutionStateVUIDs(t *testing.T) { } wg.Wait() idl, idg = es.GetUniqueVUIdentifiers() - assert.Equal(t, uint64(4+count), idl) - assert.Equal(t, uint64((3+count)*int(offsets[0])+int(start+1)), idg) + assert.EqualValues(t, 4+count, idl) + assert.EqualValues(t, (3+count)*int(offsets[0])+int(start+1), idg) }) } } diff --git a/lib/executor/externally_controlled.go b/lib/executor/externally_controlled.go index 229cb7dd960..7f0c876b89f 100644 --- a/lib/executor/externally_controlled.go +++ b/lib/executor/externally_controlled.go @@ -123,7 +123,7 @@ func (mec ExternallyControlledConfig) Validate() []error { func (mec ExternallyControlledConfig) GetExecutionRequirements(et *lib.ExecutionTuple) []lib.ExecutionStep { startVUs := lib.ExecutionStep{ TimeOffset: 0, - PlannedVUs: uint64(et.ScaleInt64(mec.MaxVUs.Int64)), // user-configured, VUs to be pre-initialized + PlannedVUs: uint64(et.ScaleInt64(mec.MaxVUs.Int64)), //nolint:gosec MaxUnplannedVUs: 0, // intentional, see function comment } diff --git a/lib/executor/externally_controlled_test.go b/lib/executor/externally_controlled_test.go index 4e90ddc4fd4..ac9a5fd4fbb 100644 --- a/lib/executor/externally_controlled_test.go +++ b/lib/executor/externally_controlled_test.go @@ -104,6 +104,6 @@ func TestExternallyControlledRun(t *testing.T) { wg.Wait() require.NoError(t, <-errCh) - assert.InDelta(t, 48, int(atomic.LoadUint64(doneIters)), 2) + assert.InDelta(t, 48, atomic.LoadUint64(doneIters), 2) assert.Equal(t, [][]int64{{2, 10}, {4, 10}, {8, 20}, {4, 10}, {0, 10}}, resultVUCount) } diff --git a/lib/executor/per_vu_iterations.go b/lib/executor/per_vu_iterations.go index e2567df7e94..94159bbfb88 100644 --- a/lib/executor/per_vu_iterations.go +++ b/lib/executor/per_vu_iterations.go @@ -96,7 +96,7 @@ func (pvic PerVUIterationsConfig) GetExecutionRequirements(et *lib.ExecutionTupl return []lib.ExecutionStep{ { TimeOffset: 0, - PlannedVUs: uint64(pvic.GetVUs(et)), + PlannedVUs: uint64(pvic.GetVUs(et)), //nolint:gosec }, { TimeOffset: pvic.MaxDuration.TimeDuration() + pvic.GracefulStop.TimeDuration(), @@ -150,11 +150,11 @@ func (pvi PerVUIterations) Run(parentCtx context.Context, out chan<- metrics.Sam "vus": numVUs, "iterations": iterations, "maxDuration": duration, "type": pvi.config.GetType(), }).Debug("Starting executor run...") - totalIters := uint64(numVUs * iterations) + totalIters := numVUs * iterations doneIters := new(uint64) vusFmt := pb.GetFixedLengthIntFormat(numVUs) - itersFmt := pb.GetFixedLengthIntFormat(int64(totalIters)) + itersFmt := pb.GetFixedLengthIntFormat(totalIters) progressFn := func() (float64, []string) { spent := time.Since(startTime) progVUs := fmt.Sprintf(vusFmt+" VUs", numVUs) diff --git a/lib/executor/ramping_arrival_rate.go b/lib/executor/ramping_arrival_rate.go index 17ba7038dcc..84fd89fb735 100644 --- a/lib/executor/ramping_arrival_rate.go +++ b/lib/executor/ramping_arrival_rate.go @@ -122,8 +122,8 @@ func (varc RampingArrivalRateConfig) GetExecutionRequirements(et *lib.ExecutionT return []lib.ExecutionStep{ { TimeOffset: 0, - PlannedVUs: uint64(et.ScaleInt64(varc.PreAllocatedVUs.Int64)), - MaxUnplannedVUs: uint64(et.ScaleInt64(varc.MaxVUs.Int64) - et.ScaleInt64(varc.PreAllocatedVUs.Int64)), + PlannedVUs: uint64(et.ScaleInt64(varc.PreAllocatedVUs.Int64)), //nolint:gosec + MaxUnplannedVUs: uint64(et.ScaleInt64(varc.MaxVUs.Int64) - et.ScaleInt64(varc.PreAllocatedVUs.Int64)), //nolint:gosec }, { TimeOffset: sumStagesDuration(varc.Stages) + varc.GracefulStop.TimeDuration(), diff --git a/lib/executor/ramping_arrival_rate_test.go b/lib/executor/ramping_arrival_rate_test.go index 8146320340e..b5bf7bb4138 100644 --- a/lib/executor/ramping_arrival_rate_test.go +++ b/lib/executor/ramping_arrival_rate_test.go @@ -281,7 +281,7 @@ func BenchmarkRampingArrivalRateRun(b *testing.B) { testRunState := getTestRunState(b, lib.Options{}, runner) es := lib.NewExecutionState( testRunState, mustNewExecutionTuple(nil, nil), - uint64(tc.prealloc.Int64), uint64(tc.prealloc.Int64), + uint64(tc.prealloc.Int64), uint64(tc.prealloc.Int64), //nolint:gosec ) // an high target to get the highest rate @@ -578,8 +578,8 @@ func sqrtRat(x *big.Rat) *big.Rat { var z, a, b big.Rat var ns, ds big.Int ni, di := x.Num(), x.Denom() - z.SetFrac(ns.Rsh(ni, uint(ni.BitLen())/2), ds.Rsh(di, uint(di.BitLen())/2)) - for i := 10; i > 0; i-- { // TODO: better termination + z.SetFrac(ns.Rsh(ni, uint(ni.BitLen())/2), ds.Rsh(di, uint(di.BitLen())/2)) //nolint:gosec + for i := 10; i > 0; i-- { // TODO: better termination a.Sub(a.Mul(&z, &z), x) f, _ := a.Float64() if f == 0 { diff --git a/lib/executor/ramping_vus.go b/lib/executor/ramping_vus.go index 9acdc4e1773..e95c79fff77 100644 --- a/lib/executor/ramping_vus.go +++ b/lib/executor/ramping_vus.go @@ -178,7 +178,7 @@ func (vlvc RampingVUsConfig) getRawExecutionSteps(et *lib.ExecutionTuple, zeroEn // Reserve the scaled StartVUs at the beginning scaled, unscaled := index.GoTo(fromVUs) - steps = append(steps, lib.ExecutionStep{TimeOffset: 0, PlannedVUs: uint64(scaled)}) + steps = append(steps, lib.ExecutionStep{TimeOffset: 0, PlannedVUs: uint64(scaled)}) //nolint:gosec addStep := func(timeOffset time.Duration, plannedVUs uint64) { if steps[len(steps)-1].PlannedVUs != plannedVUs { steps = append(steps, lib.ExecutionStep{TimeOffset: timeOffset, PlannedVUs: plannedVUs}) @@ -196,7 +196,7 @@ func (vlvc RampingVUsConfig) getRawExecutionSteps(et *lib.ExecutionTuple, zeroEn } if stageDuration == 0 { scaled, unscaled = index.GoTo(stageEndVUs) - addStep(timeTillEnd, uint64(scaled)) + addStep(timeTillEnd, uint64(scaled)) //nolint:gosec fromVUs = stageEndVUs continue } @@ -212,14 +212,14 @@ func (vlvc RampingVUsConfig) getRawExecutionSteps(et *lib.ExecutionTuple, zeroEn // but we are ramping down so we should go 1 down, but because we want to not // stop VUs immediately we stop it on the next unscaled VU's time timeTillEnd-time.Duration(int64(stageDuration)*(stageEndVUs-unscaled+1)/stageVUDiff), - uint64(scaled-1), + uint64(scaled-1), //nolint:gosec ) } } else { for ; unscaled <= stageEndVUs; scaled, unscaled = index.Next() { addStep( timeTillEnd-time.Duration(int64(stageDuration)*(stageEndVUs-unscaled)/stageVUDiff), - uint64(scaled), + uint64(scaled), //nolint:gosec ) } } @@ -574,7 +574,7 @@ type rampingVUsRunState struct { } func (rs *rampingVUsRunState) makeProgressFn(regular time.Duration) (progressFn func() (float64, []string)) { - vusFmt := pb.GetFixedLengthIntFormat(int64(rs.maxVUs)) + vusFmt := pb.GetFixedLengthIntFormat(int64(rs.maxVUs)) //nolint:gosec regularDuration := pb.GetFixedLengthDuration(regular, regular) return func() (float64, []string) { diff --git a/lib/executor/shared_iterations.go b/lib/executor/shared_iterations.go index b58a4442030..c1ec7910648 100644 --- a/lib/executor/shared_iterations.go +++ b/lib/executor/shared_iterations.go @@ -114,7 +114,7 @@ func (sic SharedIterationsConfig) GetExecutionRequirements(et *lib.ExecutionTupl return []lib.ExecutionStep{ { TimeOffset: 0, - PlannedVUs: uint64(vus), + PlannedVUs: uint64(vus), //nolint:gosec }, { TimeOffset: sic.MaxDuration.TimeDuration() + sic.GracefulStop.TimeDuration(), @@ -182,10 +182,10 @@ func (si SharedIterations) Run(parentCtx context.Context, out chan<- metrics.Sam "vus": numVUs, "iterations": iterations, "maxDuration": duration, "type": si.config.GetType(), }).Debug("Starting executor run...") - totalIters := uint64(iterations) + totalIters := uint64(iterations) //nolint:gosec doneIters := new(uint64) vusFmt := pb.GetFixedLengthIntFormat(numVUs) - itersFmt := pb.GetFixedLengthIntFormat(int64(totalIters)) + itersFmt := pb.GetFixedLengthIntFormat(iterations) progressFn := func() (float64, []string) { spent := time.Since(startTime) progVUs := fmt.Sprintf(vusFmt+" VUs", numVUs) diff --git a/lib/executor/vu_handle_test.go b/lib/executor/vu_handle_test.go index a4e251068ce..623e768cc88 100644 --- a/lib/executor/vu_handle_test.go +++ b/lib/executor/vu_handle_test.go @@ -39,14 +39,14 @@ func TestVUHandleRace(t *testing.T) { return nil } - var getVUCount int64 - var returnVUCount int64 + var getVUCount uint64 + var returnVUCount uint64 getVU := func() (lib.InitializedVU, error) { - return runner.NewVU(ctx, uint64(atomic.AddInt64(&getVUCount, 1)), 0, nil) + return runner.NewVU(ctx, atomic.AddUint64(&getVUCount, 1), 0, nil) } returnVU := func(_ lib.InitializedVU) { - atomic.AddInt64(&returnVUCount, 1) + atomic.AddUint64(&returnVUCount, 1) // do something } var interruptedIter int64 @@ -107,7 +107,7 @@ func TestVUHandleRace(t *testing.T) { "too big of a difference %d >= %d - 1", interruptedBefore, interruptedAfter) assert.True(t, fullBefore+1 <= fullAfter, "too small of a difference %d + 1 <= %d", fullBefore, fullAfter) - require.Equal(t, atomic.LoadInt64(&getVUCount), atomic.LoadInt64(&returnVUCount)) + require.Equal(t, atomic.LoadUint64(&getVUCount), atomic.LoadUint64(&returnVUCount)) } // this test is mostly interesting when -race is enabled diff --git a/lib/limiter_test.go b/lib/limiter_test.go index dfaf3659baa..a9d06c7e9a6 100644 --- a/lib/limiter_test.go +++ b/lib/limiter_test.go @@ -70,7 +70,7 @@ func TestSlotLimiters(t *testing.T) { }() } wg.Wait() - assert.Equal(t, uint32(tc.expMid), atomic.LoadUint32(&counter)) + assert.EqualValues(t, tc.expMid, atomic.LoadUint32(&counter)) if tc.limit != 0 && tc.limit < tc.launches { wg.Add(tc.launches - tc.limit) @@ -78,7 +78,7 @@ func TestSlotLimiters(t *testing.T) { l.End() } wg.Wait() - assert.Equal(t, uint32(tc.launches), atomic.LoadUint32(&counter)) + assert.EqualValues(t, tc.launches, atomic.LoadUint32(&counter)) } }) } diff --git a/lib/netext/httpext/batch.go b/lib/netext/httpext/batch.go index 60394e7ae13..389b932dd32 100644 --- a/lib/netext/httpext/batch.go +++ b/lib/netext/httpext/batch.go @@ -47,7 +47,7 @@ func MakeBatchRequests( result <- err } - counter, i32reqCount := int32(-1), int32(reqCount) + counter, i32reqCount := int32(-1), int32(reqCount) //nolint:gosec for i := 0; i < workers; i++ { go func() { for { diff --git a/lib/netext/httpext/transport.go b/lib/netext/httpext/transport.go index f9b49a556e8..d2f00a5829d 100644 --- a/lib/netext/httpext/transport.go +++ b/lib/netext/httpext/transport.go @@ -112,7 +112,7 @@ func (t *transport) measureAndEmitMetrics(unfReq *unfinishedRequest) *finishedRe } else { tagsAndMeta.SetSystemTagOrMetaIfEnabled(enabledTags, metrics.TagStatus, strconv.Itoa(unfReq.response.StatusCode)) if unfReq.response.StatusCode >= 400 { - result.errorCode = errCode(1000 + unfReq.response.StatusCode) + result.errorCode = errCode(1000 + unfReq.response.StatusCode) //nolint:gosec tagsAndMeta.SetSystemTagOrMetaIfEnabled(enabledTags, metrics.TagErrorCode, strconv.Itoa(int(result.errorCode))) } tagsAndMeta.SetSystemTagOrMetaIfEnabled(enabledTags, metrics.TagProto, unfReq.response.Proto) diff --git a/lib/options.go b/lib/options.go index e4f3a2d6929..5dce2dbc766 100644 --- a/lib/options.go +++ b/lib/options.go @@ -180,7 +180,7 @@ func decryptPrivateKey(privKey, password string) ([]byte, error) { being used here because it is deprecated due to it not supporting *good* crypography ultimately though we want to support something so we will be using it for now. */ - decryptedKey, err := x509.DecryptPEMBlock(block, []byte(password)) + decryptedKey, err := x509.DecryptPEMBlock(block, []byte(password)) //nolint:staticcheck if err != nil { return nil, err } diff --git a/lib/options_test.go b/lib/options_test.go index c7132c4e983..7a5471cf76a 100644 --- a/lib/options_test.go +++ b/lib/options_test.go @@ -160,11 +160,11 @@ func TestOptions(t *testing.T) { }) t.Run("TLSVersion", func(t *testing.T) { t.Parallel() - versions := TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionTLS12} + versions := TLSVersions{Min: tls.VersionSSL30, Max: tls.VersionTLS12} //nolint:staticcheck opts := Options{}.Apply(Options{TLSVersion: &versions}) assert.NotNil(t, opts.TLSVersion) - assert.Equal(t, opts.TLSVersion.Min, TLSVersion(tls.VersionSSL30)) + assert.Equal(t, opts.TLSVersion.Min, TLSVersion(tls.VersionSSL30)) //nolint:staticcheck assert.Equal(t, opts.TLSVersion.Max, TLSVersion(tls.VersionTLS12)) t.Run("JSON", func(t *testing.T) { diff --git a/lib/testutils/untar.go b/lib/testutils/untar.go index 5b9989a9c48..e1b89eee29e 100644 --- a/lib/testutils/untar.go +++ b/lib/testutils/untar.go @@ -55,7 +55,7 @@ func Untar(t *testing.T, fileSystem fsext.Fs, fileName string, destination strin return err } case tar.TypeReg: - f, err := fileSystem.OpenFile(target, syscall.O_CREAT|syscall.O_RDWR, fs.FileMode(header.Mode)) + f, err := fileSystem.OpenFile(target, syscall.O_CREAT|syscall.O_RDWR, fs.FileMode(header.Mode)) //nolint:gosec if err != nil { return err } diff --git a/lib/types/types.go b/lib/types/types.go index 9c5ca15b2d5..0e26dcb1ff1 100644 --- a/lib/types/types.go +++ b/lib/types/types.go @@ -173,7 +173,7 @@ func getInt64(v interface{}) (int64, error) { case int64: return n, nil case uint: - return int64(n), nil + return int64(n), nil //nolint:gosec case uint8: return int64(n), nil case uint16: diff --git a/metrics/engine/engine.go b/metrics/engine/engine.go index 18567c2712e..37195a8fb32 100644 --- a/metrics/engine/engine.go +++ b/metrics/engine/engine.go @@ -249,7 +249,7 @@ func (me *MetricsEngine) evaluateThresholds( sort.Strings(breachedThresholds) me.logger.Debugf("Thresholds on %d metrics crossed: %v", len(breachedThresholds), breachedThresholds) } - atomic.StoreUint32(&me.breachedThresholdsCount, uint32(len(breachedThresholds))) + atomic.StoreUint32(&me.breachedThresholdsCount, uint32(len(breachedThresholds))) //nolint:gosec return breachedThresholds, shouldAbort } diff --git a/output/cloud/expv2/flush.go b/output/cloud/expv2/flush.go index 1ce39fb12ca..09b37633015 100644 --- a/output/cloud/expv2/flush.go +++ b/output/cloud/expv2/flush.go @@ -162,7 +162,7 @@ type metricSetBuilder struct { // metrics[XYZ]..TimeSeries. // It supports the iterative process for appending // the aggregated measurements for each time series. - seriesIndex map[metrics.TimeSeries]uint + seriesIndex map[metrics.TimeSeries]int // discardedLabels tracks the labels that have been discarded // since they are reserved for internal usage by the Cloud service. @@ -175,7 +175,7 @@ func newMetricSetBuilder(testRunID string, aggrPeriodSec uint32) metricSetBuilde // TODO: evaluate if removing the pointer from pbcloud.Metric // is a better trade-off metrics: make(map[*metrics.Metric]*pbcloud.Metric), - seriesIndex: make(map[metrics.TimeSeries]uint), + seriesIndex: make(map[metrics.TimeSeries]int), discardedLabels: nil, } builder.MetricSet.TestRunId = testRunID @@ -203,7 +203,7 @@ func (msb *metricSetBuilder) addTimeSeries(timestamp int64, timeSeries metrics.T Labels: labels, } pbmetric.TimeSeries = append(pbmetric.TimeSeries, pbTimeSeries) - msb.seriesIndex[timeSeries] = uint(len(pbmetric.TimeSeries) - 1) + msb.seriesIndex[timeSeries] = len(pbmetric.TimeSeries) - 1 } else { pbTimeSeries = pbmetric.TimeSeries[ix] } diff --git a/output/cloud/expv2/flush_test.go b/output/cloud/expv2/flush_test.go index f95aae2511a..5ff236c9f54 100644 --- a/output/cloud/expv2/flush_test.go +++ b/output/cloud/expv2/flush_test.go @@ -35,7 +35,7 @@ func TestMetricSetBuilderAddTimeBucket(t *testing.T) { assert.Contains(t, msb.metrics, m1) require.Contains(t, msb.seriesIndex, timeSeries) - assert.Equal(t, uint(0), msb.seriesIndex[timeSeries]) // TODO: assert with another number + assert.Equal(t, 0, msb.seriesIndex[timeSeries]) // TODO: assert with another number require.Len(t, msb.MetricSet.Metrics, 1) assert.Len(t, msb.MetricSet.Metrics[0].TimeSeries, 1) diff --git a/output/cloud/expv2/hdr.go b/output/cloud/expv2/hdr.go index 8e2cc6fef92..4a72649d500 100644 --- a/output/cloud/expv2/hdr.go +++ b/output/cloud/expv2/hdr.go @@ -212,12 +212,12 @@ func resolveBucketIndex(val float64) uint32 { // = (n-k+1)<>(n-k) - (1<>(n-k) // - nkdiff := uint64(bits.Len64(upscaled>>k)) - 1 // msb index + nkdiff := uint64(bits.Len64(upscaled>>k)) - 1 //nolint:gosec // msb index // We cast safely downscaling because we don't expect we may hit the uint32 limit // with the bucket index. The bucket represented from the index as MaxUint32 // would be a very huge number bigger than the trackable limits. - return uint32((nkdiff << k) + (upscaled >> nkdiff)) + return uint32((nkdiff << k) + (upscaled >> nkdiff)) //nolint:gosec } // Add implements the metricValue interface. diff --git a/output/cloud/output.go b/output/cloud/output.go index c8532a65019..2c86be5d10a 100644 --- a/output/cloud/output.go +++ b/output/cloud/output.go @@ -192,7 +192,7 @@ func (out *Output) Start() error { testRun := &cloudapi.TestRun{ Name: out.config.Name.String, ProjectID: out.config.ProjectID.Int64, - VUsMax: int64(lib.GetMaxPossibleVUs(out.executionPlan)), + VUsMax: int64(lib.GetMaxPossibleVUs(out.executionPlan)), //nolint:gosec Thresholds: thresholds, Duration: out.duration, Archive: out.testArchive, diff --git a/ui/pb/helpers.go b/ui/pb/helpers.go index 6f595f1693f..fd32fb59349 100644 --- a/ui/pb/helpers.go +++ b/ui/pb/helpers.go @@ -30,18 +30,18 @@ func GetFixedLengthIntFormat(maxValue int64) (formatStr string) { // returned string corresponds to the number of digits in the supplied maxValue // and the desired precision. func GetFixedLengthFloatFormat(maxValue float64, precision uint) (formatStr string) { - resLen := 1 + resLen := uint(1) if maxValue < 0 { maxValue = -maxValue resLen++ } if maxValue >= 10 { - resLen += int(math.Log10(maxValue)) + resLen += uint(math.Log10(maxValue)) } if precision > 0 { - resLen += int(precision + 1) + resLen += precision + 1 } - return "%0" + strconv.Itoa(resLen) + "." + strconv.Itoa(int(precision)) + "f" + return "%0" + strconv.FormatUint(uint64(resLen), 10) + "." + strconv.Itoa(int(precision)) + "f" } // GetFixedLengthDuration takes a *positive* duration and its max value and @@ -68,7 +68,7 @@ func GetFixedLengthDuration(d, maxDuration time.Duration) (result string) { // Positions: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 buf := [18]byte{'0', '0', '0', '0', '0', '0', 'd', '0', '0', 'h', '0', '0', 'm', '0', '0', '.', '0', 's'} - u := uint64(d.Round(rounding) / (rounding)) + u := d.Round(rounding) / (rounding) u, buf[16] = u/10, byte(u%10)+'0' u, buf[14] = u/10, byte(u%10)+'0' if maxDuration < 10*time.Second {