From 791a5b9aa3eb2a03f4e2630430d42309373d7325 Mon Sep 17 00:00:00 2001 From: Bastrykov Evgeniy Date: Fri, 19 Jun 2026 22:27:24 +0400 Subject: [PATCH] chore(lint): enable golangci-lint for pp and pp-pkg Remove pp/pp-pkg from golangci-lint exclude-dirs so they are actually linted by `make lint` (and CI), and enable gosec and govet shadow. Resolve all resulting findings: - gofumpt/goimports formatting across pp/go and pp-pkg - errorlint: use errors.Is/As (sender, registerer) - testifylint: require-error for error assertions in tests - revive: var-naming Id->ID for non-cppbridge identifiers, exported doc comments, drop redundant `= 0`, comment spacings - govet shadow: rename shadowed ctx/err/interval/it variables - gosec: tighten file/dir permissions, justified nolint for md5 config fingerprinting and intentional file opens - depguard: use github.com/grafana/regexp - staticcheck SA5012: justified nolint in labelset test - unused: drop dead fields, delete orphaned relabeler/main_test.go, keep ABI-required fields with nolint cppbridge keeps C++-mirroring naming via exclude rules; the generated entrypoint.go is excluded from linting. Co-authored-by: Cursor --- .golangci.yml | 27 ++- pp-pkg/handler/adapter/remote_write.go | 2 +- pp-pkg/handler/otlp_handler.go | 4 +- pp-pkg/handler/pp_converter_test.go | 4 +- pp-pkg/handler/states_test.go | 3 +- pp-pkg/handler/storage/block/storage.go | 5 +- pp-pkg/remote/config.go | 5 +- pp-pkg/rules/alerting_stuck_test.go | 9 +- pp-pkg/rules/alerting_test.go | 8 +- pp-pkg/rules/control_plane_expr_test.go | 3 +- pp-pkg/rules/group.go | 23 ++- pp-pkg/rules/manager_test.go | 2 +- pp-pkg/scrape/pool.go | 1 + pp-pkg/scrape/scrape.go | 8 +- pp-pkg/scrape/target.go | 10 +- pp-pkg/storage/adapter_promql_test.go | 22 +-- pp-pkg/storage/batch_storage_test.go | 3 +- pp-pkg/storage/remote/noop.go | 1 + pp-pkg/storage/remote/remote_read.go | 2 + pp-pkg/tsdb/compactor.go | 2 + pp-pkg/tsdb/db.go | 1 + pp/go/cppbridge/common.go | 6 +- pp/go/cppbridge/data_storage.go | 2 +- pp/go/cppbridge/exception.go | 20 +-- pp/go/cppbridge/exception_test.go | 7 +- pp/go/cppbridge/head_status_test.go | 3 +- pp/go/cppbridge/head_test.go | 17 +- pp/go/cppbridge/head_wal.go | 4 +- pp/go/cppbridge/index_writer_test.go | 6 +- pp/go/cppbridge/labels.go | 2 +- pp/go/cppbridge/lss_snapshot.go | 4 +- pp/go/cppbridge/lss_snapshot_test.go | 3 +- pp/go/cppbridge/metrics_test.go | 2 +- pp/go/cppbridge/primitives_lss.go | 4 +- pp/go/cppbridge/primitives_lss_test.go | 8 +- pp/go/cppbridge/prometheus_relabeler.go | 10 +- pp/go/cppbridge/prometheus_relabeler_test.go | 10 +- pp/go/cppbridge/remote_write.go | 1 + pp/go/cppbridge/remote_write_test.go | 3 +- pp/go/cppbridge/wal_decoder.go | 5 +- pp/go/cppbridge/wal_decoder_test.go | 9 +- pp/go/cppbridge/wal_encode_decode_test.go | 7 +- pp/go/cppbridge/wal_encoder.go | 12 +- pp/go/cppbridge/wal_encoder_test.go | 13 +- pp/go/cppbridge/wal_hashdex.go | 6 +- pp/go/cppbridge/wal_hashdex_test.go | 17 +- .../wal_open_metrics_scraper_hashdex_test.go | 2 +- .../wal_prometheus_scraper_hashdex_test.go | 14 +- pp/go/frames/binary_body.go | 12 +- pp/go/frames/consts.go | 10 +- pp/go/frames/frames.go | 25 ++- pp/go/frames/frames_test.go | 131 ++++++-------- pp/go/frames/framestest/read_payload.go | 7 +- pp/go/frames/header.go | 4 +- pp/go/frames/header_test.go | 3 +- pp/go/frames/title.go | 6 +- pp/go/frames/title_test.go | 3 +- pp/go/frames/transport_frames.go | 8 +- pp/go/frames/transport_frames_test.go | 7 +- pp/go/frames/types.go | 2 +- pp/go/frames/write_frame.go | 4 +- pp/go/logger/logger.go | 2 +- pp/go/model/labelset.go | 54 +++--- pp/go/model/labelset_test.go | 1 + pp/go/relabeler/autosharder.go | 2 +- pp/go/relabeler/config/config.go | 1 + pp/go/relabeler/destination_group.go | 10 +- pp/go/relabeler/errors.go | 28 +-- pp/go/relabeler/exchange.go | 13 +- pp/go/relabeler/file_storage.go | 8 +- pp/go/relabeler/high_availability_tracker.go | 3 +- pp/go/relabeler/main_test.go | 162 ------------------ pp/go/relabeler/manager.go | 4 +- pp/go/relabeler/markup_file.go | 4 +- pp/go/relabeler/models.go | 19 +- pp/go/relabeler/refill.go | 3 +- pp/go/relabeler/refill_sender.go | 2 +- pp/go/relabeler/sender.go | 12 +- pp/go/relabeler/storage_manager.go | 21 +-- pp/go/relabeler/task.go | 2 +- pp/go/relabeler/transport.go | 21 +-- pp/go/server/transport.go | 3 +- pp/go/server/transport_test.go | 1 - pp/go/storage/appender/appender.go | 8 +- pp/go/storage/appender/appender_bench_test.go | 2 +- pp/go/storage/appender/appender_test.go | 25 +-- pp/go/storage/block/block.go | 4 +- pp/go/storage/block/block_writer.go | 1 - pp/go/storage/block/compactor.go | 2 + pp/go/storage/block/compactor_test.go | 3 +- pp/go/storage/block/manager_test.go | 3 +- pp/go/storage/block/writer.go | 13 +- pp/go/storage/block/writer_test.go | 8 +- pp/go/storage/builder.go | 1 + pp/go/storage/catalog/catalog.go | 2 +- pp/go/storage/catalog/gc.go | 1 + pp/go/storage/catalog/log_file_handler.go | 2 +- pp/go/storage/catalog/record.go | 1 + pp/go/storage/head/container/weighted_test.go | 2 +- pp/go/storage/head/head/head.go | 6 +- pp/go/storage/head/services/functions.go | 2 +- pp/go/storage/head/services/merger_test.go | 3 +- .../storage/head/services/persistener_test.go | 3 +- pp/go/storage/head/shard/data_storage.go | 12 +- pp/go/storage/head/shard/lss.go | 26 +-- pp/go/storage/head/shard/shard.go | 18 +- .../head/shard/wal/reader/byte_reader.go | 2 +- pp/go/storage/head/shard/wal/wal.go | 1 + .../storage/head/shard/wal/wal_reader_test.go | 3 +- .../head/shard/wal/writer/notifier_test.go | 3 +- pp/go/storage/head/task/task.go | 2 +- pp/go/storage/head/task/waiter_test.go | 3 +- pp/go/storage/head/transactionhead/head.go | 2 +- pp/go/storage/loader.go | 4 +- pp/go/storage/loader_test.go | 15 +- pp/go/storage/manager_test.go | 9 +- pp/go/storage/mediator/mediator_test.go | 7 +- pp/go/storage/querier/instant_series.go | 2 +- .../storage/querier/load_and_query_waiter.go | 2 +- .../storage/querier/merge_series_set_test.go | 3 +- pp/go/storage/querier/metrics.go | 1 + pp/go/storage/querier/querier.go | 1 + pp/go/storage/querier/querier_test.go | 3 +- pp/go/storage/querier/series.go | 5 +- pp/go/storage/querier/series_bench_test.go | 7 +- pp/go/storage/querier/series_test.go | 77 ++++----- pp/go/storage/querier/stalenan_series_set.go | 2 +- .../querier/stalenan_series_set_test.go | 3 +- pp/go/storage/remotewriter/datasourceV2.go | 7 +- pp/go/storage/remotewriter/destination.go | 11 +- pp/go/storage/remotewriter/iterator.go | 3 +- pp/go/storage/remotewriter/iterator_test.go | 4 +- pp/go/storage/remotewriter/remotewriter.go | 2 +- .../remotewriter/remotewritertest/fixtures.go | 3 +- pp/go/storage/remotewriter/walreader_test.go | 3 +- pp/go/storage/remotewriter/writeloop.go | 7 +- pp/go/storage/remotewriter/writer.go | 2 +- pp/go/storage/storagetest/fixtures.go | 3 +- pp/go/transport/transport.go | 5 +- pp/go/util/file_reader.go | 2 +- pp/go/util/fn_writer.go | 4 +- pp/go/util/locker/priweighted_test.go | 1 - pp/go/util/offset_reader.go | 6 +- pp/go/util/profile.go | 4 +- pp/go/util/registerer.go | 21 ++- pp/go/util/varint.go | 2 +- 146 files changed, 618 insertions(+), 717 deletions(-) delete mode 100644 pp/go/relabeler/main_test.go diff --git a/.golangci.yml b/.golangci.yml index ce3a1db475..b8207a00f8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,7 @@ linters: - gocritic - godot - gofumpt + - gosec - goimports - misspell - nolintlint @@ -39,12 +40,12 @@ issues: exclude-files: # Skip autogenerated files. - ^.*\.(pb|y)\.go$ + # cgo bridge to the C++ core: identifiers intentionally mirror the C++ ABI. + - ^pp/go/cppbridge/entrypoint\.go$ exclude-dirs: # Copied it from a different source. - storage/remote/otlptranslator/prometheusremotewrite - storage/remote/otlptranslator/prometheus - - pp - - pp-pkg exclude-rules: - linters: - errcheck @@ -74,7 +75,29 @@ issues: - linters: - perfsprint text: "fmt.Sprintf can be replaced with string concatenation" + # gosec is too noisy in tests (weak rand, file perms, unhandled errors in helpers). + - path: _test\.go + linters: + - gosec + # cppbridge identifiers intentionally mirror the C++ ABI (Id, snake_case fields). + - path: ^pp/go/cppbridge/ + linters: + - revive + text: "var-naming" + # fastcgo declares Go mirrors of runtime structs purely for memory layout. + - path: ^pp/go/cppbridge/fastcgo/ + linters: + - unused linters-settings: + govet: + enable: + - shadow + gosec: + excludes: + # G103: use of unsafe is intentional and pervasive in the C++ bridge. + - G103 + # G104: unhandled errors are already covered (with excludes) by errcheck. + - G104 depguard: rules: main: diff --git a/pp-pkg/handler/adapter/remote_write.go b/pp-pkg/handler/adapter/remote_write.go index 80950b5d2a..dc20bf2811 100644 --- a/pp-pkg/handler/adapter/remote_write.go +++ b/pp-pkg/handler/adapter/remote_write.go @@ -21,7 +21,7 @@ type RemoteWrite struct { contentLength int } -// NewRefill init new RemoteWrite. +// NewRemoteWrite initializes a new RemoteWrite. func NewRemoteWrite( reader io.ReadCloser, writer http.ResponseWriter, diff --git a/pp-pkg/handler/otlp_handler.go b/pp-pkg/handler/otlp_handler.go index c127f6c277..13df205a7c 100644 --- a/pp-pkg/handler/otlp_handler.go +++ b/pp-pkg/handler/otlp_handler.go @@ -85,8 +85,8 @@ func (h *OTLPWriteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } converter := NewPPConverter(h.logger, req.Metrics().MetricCount()) - if err := converter.FromMetrics(req.Metrics()); err != nil { - level.Warn(h.logger).Log("msg", "Error translating OTLP metrics to Prometheus write request", "err", err) + if convErr := converter.FromMetrics(req.Metrics()); convErr != nil { + level.Warn(h.logger).Log("msg", "Error translating OTLP metrics to Prometheus write request", "err", convErr) } stats, err := h.adapter.AppendTimeSeries( diff --git a/pp-pkg/handler/pp_converter_test.go b/pp-pkg/handler/pp_converter_test.go index c409d6a2dc..147dec4662 100644 --- a/pp-pkg/handler/pp_converter_test.go +++ b/pp-pkg/handler/pp_converter_test.go @@ -81,7 +81,7 @@ func (s *PPConverterSuite) TestEmptyLabelsName() { actual := ppconverter.TimeSeries().TimeSeries() - s.Require().Len(actual, 0) + s.Require().Empty(actual) } func (s *PPConverterSuite) TestEmptyLabelsValue() { @@ -92,7 +92,7 @@ func (s *PPConverterSuite) TestEmptyLabelsValue() { actual := ppconverter.TimeSeries().TimeSeries() - s.Require().Len(actual, 0) + s.Require().Empty(actual) } func createExportRequest( diff --git a/pp-pkg/handler/states_test.go b/pp-pkg/handler/states_test.go index 977355d202..b27ecb2f2e 100644 --- a/pp-pkg/handler/states_test.go +++ b/pp-pkg/handler/states_test.go @@ -3,12 +3,13 @@ package handler_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/config" pp_pkg_config "github.com/prometheus/prometheus/pp-pkg/config" "github.com/prometheus/prometheus/pp-pkg/handler" "github.com/prometheus/prometheus/pp/go/cppbridge" rconfig "github.com/prometheus/prometheus/pp/go/relabeler/config" - "github.com/stretchr/testify/suite" ) type StatesStorageSuite struct { diff --git a/pp-pkg/handler/storage/block/storage.go b/pp-pkg/handler/storage/block/storage.go index 83c17a421e..e7c2675c2d 100644 --- a/pp-pkg/handler/storage/block/storage.go +++ b/pp-pkg/handler/storage/block/storage.go @@ -37,10 +37,11 @@ func (s *Storage) Writer(blockID uuid.UUID, shardID uint16, shardLog, segmentEnc fileFn: func() (*os.File, error) { fileName := path.Join(s.dir, fmt.Sprintf("%s-%d", blockID.String(), shardID)) dir := filepath.Dir(fileName) - if err := os.MkdirAll(dir, 0o744); err != nil { + if err := os.MkdirAll(dir, 0o750); err != nil { return nil, err } - return os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644) + //nolint:gosec // fileName is derived from the configured storage dir and block/shard IDs + return os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o600) }, blockHeader: storage.BlockHeader{ FileVersion: FileVersion, diff --git a/pp-pkg/remote/config.go b/pp-pkg/remote/config.go index d569639548..de965e8c4a 100644 --- a/pp-pkg/remote/config.go +++ b/pp-pkg/remote/config.go @@ -1,13 +1,14 @@ package remote import ( - "crypto/md5" + "crypto/md5" //nolint:gosec // md5 is used only to fingerprint configs, not for security "encoding/hex" "time" "gopkg.in/yaml.v2" "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/pp/go/storage/remotewriter" ) @@ -53,6 +54,6 @@ func toHash(data interface{}) (string, error) { if err != nil { return "", err } - hash := md5.Sum(bytes) + hash := md5.Sum(bytes) //nolint:gosec // md5 is used only to fingerprint configs, not for security return hex.EncodeToString(hash[:]), nil } diff --git a/pp-pkg/rules/alerting_stuck_test.go b/pp-pkg/rules/alerting_stuck_test.go index 2e4b9143e1..c760ed6073 100644 --- a/pp-pkg/rules/alerting_stuck_test.go +++ b/pp-pkg/rules/alerting_stuck_test.go @@ -25,10 +25,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/promql" "github.com/prometheus/prometheus/promql/parser" - "github.com/stretchr/testify/require" ) // scriptedQuery returns a QueryFunc that hands out canned promql.Vector values @@ -85,9 +86,9 @@ func TestAlertingRule_OnePassEmpty_TransitionsToInactive(t *testing.T) { F: 0, }} q, _ := scriptedQuery([]promql.Vector{ - hot, // t=0 : pending starts (new entry in r.active) - hot, // t=1m : transitions to firing (holdDuration met) - nil, // t=2m : empty → must transition to Inactive + hot, // t=0 : pending starts (new entry in r.active) + hot, // t=1m : transitions to firing (holdDuration met) + nil, // t=2m : empty → must transition to Inactive }) t0 := time.Unix(0, 0).UTC() diff --git a/pp-pkg/rules/alerting_test.go b/pp-pkg/rules/alerting_test.go index 67d683c851..ab96b1fc44 100644 --- a/pp-pkg/rules/alerting_test.go +++ b/pp-pkg/rules/alerting_test.go @@ -235,8 +235,8 @@ func TestAlertingRuleLabelsUpdate(t *testing.T) { t.Logf("case %d", i) evalTime := baseTime.Add(time.Duration(i) * time.Minute) result[0].T = timestamp.FromTime(evalTime) - res, err := rule.Eval(context.TODO(), 0, evalTime, EngineQueryFunc(ng, storage), nil, 0) - require.NoError(t, err) + res, evalErr := rule.Eval(context.TODO(), 0, evalTime, EngineQueryFunc(ng, storage), nil, 0) + require.NoError(t, evalErr) var filteredRes promql.Vector // After removing 'ALERTS_FOR_STATE' samples. for _, smpl := range res { @@ -885,8 +885,8 @@ func TestKeepFiringFor(t *testing.T) { t.Logf("case %d", i) evalTime := baseTime.Add(time.Duration(i) * time.Minute) result[0].T = timestamp.FromTime(evalTime) - res, err := rule.Eval(context.TODO(), 0, evalTime, EngineQueryFunc(ng, storage), nil, 0) - require.NoError(t, err) + res, evalErr := rule.Eval(context.TODO(), 0, evalTime, EngineQueryFunc(ng, storage), nil, 0) + require.NoError(t, evalErr) var filteredRes promql.Vector // After removing 'ALERTS_FOR_STATE' samples. for _, smpl := range res { diff --git a/pp-pkg/rules/control_plane_expr_test.go b/pp-pkg/rules/control_plane_expr_test.go index 54d706f490..a726fe6394 100644 --- a/pp-pkg/rules/control_plane_expr_test.go +++ b/pp-pkg/rules/control_plane_expr_test.go @@ -22,8 +22,9 @@ import ( "testing" "time" - "github.com/prometheus/prometheus/promql/promqltest" "github.com/stretchr/testify/require" + + "github.com/prometheus/prometheus/promql/promqltest" ) const cpmExpr = `max by (node) (kube_node_role{role="master"} unless kube_node_role{role="master"}` + diff --git a/pp-pkg/rules/group.go b/pp-pkg/rules/group.go index 1074a62fb9..9648963b5c 100644 --- a/pp-pkg/rules/group.go +++ b/pp-pkg/rules/group.go @@ -252,7 +252,6 @@ func (g *Group) run(ctx context.Context) { level.Error(g.logger).Log("msg", "Failed to commit batch storage", "err", err) return } - } }(time.Now()) }() @@ -939,7 +938,7 @@ func (g *Group) concurrencyEval(ctx context.Context, ts time.Time, bs storage.Ba } logger := log.WithPrefix(g.logger, "name", rule.Name(), "index", i) - ctx, sp := otel.Tracer("").Start(ctx, "rule") + spanCtx, sp := otel.Tracer("").Start(ctx, "rule") sp.SetAttributes(attribute.String("name", rule.Name())) defer func(t time.Time) { sp.End() @@ -956,7 +955,7 @@ func (g *Group) concurrencyEval(ctx context.Context, ts time.Time, bs storage.Ba g.metrics.EvalTotal.WithLabelValues(GroupKey(g.File(), g.Name())).Inc() - vector, err := rule.Eval(ctx, ruleQueryOffset, ts, queryFunc, g.opts.ExternalURL, g.Limit()) + vector, err := rule.Eval(spanCtx, ruleQueryOffset, ts, queryFunc, g.opts.ExternalURL, g.Limit()) if err != nil { rule.SetHealth(HealthBad) rule.SetLastError(err) @@ -976,7 +975,7 @@ func (g *Group) concurrencyEval(ctx context.Context, ts time.Time, bs storage.Ba samplesTotal.Add(float64(len(vector))) if ar, ok := rule.(*AlertingRule); ok { - ar.sendAlerts(ctx, ts, g.opts.ResendDelay, g.interval, g.opts.NotifyFunc) + ar.sendAlerts(spanCtx, ts, g.opts.ResendDelay, g.interval, g.opts.NotifyFunc) } mtx.Lock() @@ -1073,7 +1072,7 @@ func (g *Group) sequentiallyEval( } logger := log.WithPrefix(g.logger, "name", rule.Name(), "index", i) - ctx, sp := otel.Tracer("").Start(ctx, "rule") + spanCtx, sp := otel.Tracer("").Start(ctx, "rule") sp.SetAttributes(attribute.String("name", rule.Name())) defer func(t time.Time) { sp.End() @@ -1090,7 +1089,7 @@ func (g *Group) sequentiallyEval( g.metrics.EvalTotal.WithLabelValues(GroupKey(g.File(), g.Name())).Inc() - vector, err := rule.Eval(ctx, ruleQueryOffset, ts, queryFunc, g.opts.ExternalURL, g.Limit()) + vector, err := rule.Eval(spanCtx, ruleQueryOffset, ts, queryFunc, g.opts.ExternalURL, g.Limit()) if err != nil { rule.SetHealth(HealthBad) rule.SetLastError(err) @@ -1110,18 +1109,18 @@ func (g *Group) sequentiallyEval( samplesTotal += float64(len(vector)) if ar, ok := rule.(*AlertingRule); ok { - ar.sendAlerts(ctx, ts, g.opts.ResendDelay, g.interval, g.opts.NotifyFunc) + ar.sendAlerts(spanCtx, ts, g.opts.ResendDelay, g.interval, g.opts.NotifyFunc) } - app := bs.Appender(ctx) + app := bs.Appender(spanCtx) defer func() { - if err := app.Commit(); err != nil { + if commitErr := app.Commit(); commitErr != nil { rule.SetHealth(HealthBad) - rule.SetLastError(err) - sp.SetStatus(codes.Error, err.Error()) + rule.SetLastError(commitErr) + sp.SetStatus(codes.Error, commitErr.Error()) g.metrics.EvalFailures.WithLabelValues(GroupKey(g.File(), g.Name())).Inc() - level.Warn(logger).Log("msg", "Rule sample appending failed", "err", err) + level.Warn(logger).Log("msg", "Rule sample appending failed", "err", commitErr) return } }() diff --git a/pp-pkg/rules/manager_test.go b/pp-pkg/rules/manager_test.go index 445706d57c..482fbf7e69 100644 --- a/pp-pkg/rules/manager_test.go +++ b/pp-pkg/rules/manager_test.go @@ -651,7 +651,7 @@ func readSeriesSet(ss storage.SeriesSet) (map[string][]promql.FPoint, error) { series := ss.At() points := []promql.FPoint{} - it := series.Iterator(it) + it = series.Iterator(it) for it.Next() == chunkenc.ValFloat { t, v := it.At() points = append(points, promql.FPoint{T: t, F: v}) diff --git a/pp-pkg/scrape/pool.go b/pp-pkg/scrape/pool.go index c13f3035b7..cf4f2ca878 100644 --- a/pp-pkg/scrape/pool.go +++ b/pp-pkg/scrape/pool.go @@ -8,6 +8,7 @@ import ( "time" "github.com/klauspost/compress/gzip" + "github.com/prometheus/prometheus/model/timestamp" "github.com/prometheus/prometheus/model/value" "github.com/prometheus/prometheus/storage" diff --git a/pp-pkg/scrape/scrape.go b/pp-pkg/scrape/scrape.go index 65863c2360..707b7ee95b 100644 --- a/pp-pkg/scrape/scrape.go +++ b/pp-pkg/scrape/scrape.go @@ -444,12 +444,12 @@ func (sp *scrapePool) restartLoops(reuseCache bool) { } t := sp.activeTargets[fp] - interval, timeout, err := t.intervalAndTimeout(interval, timeout) + iterInterval, iterTimeout, err := t.intervalAndTimeout(interval, timeout) var ( s = &targetScraper{ Target: t, client: sp.client, - timeout: timeout, + timeout: iterTimeout, bodySizeLimit: bodySizeLimit, acceptHeader: acceptHeader(sp.config.ScrapeProtocols, validationScheme), acceptEncodingHeader: acceptEncodingHeader(enableCompression), @@ -465,8 +465,8 @@ func (sp *scrapePool) restartLoops(reuseCache bool) { trackTimestampsStaleness: trackTimestampsStaleness, mrc: mrc, cache: cache, - interval: interval, - timeout: timeout, + interval: iterInterval, + timeout: iterTimeout, validationScheme: validationScheme, }) ) diff --git a/pp-pkg/scrape/target.go b/pp-pkg/scrape/target.go index fa957e064c..a41eaaf5a3 100644 --- a/pp-pkg/scrape/target.go +++ b/pp-pkg/scrape/target.go @@ -352,13 +352,13 @@ func PopulateLabels(lb *labels.Builder, cfg *config.ScrapeConfig, noDefaultPort // If the address is not valid, we don't append a port either. addPort := func(s string) (string, string, bool) { // If we can split, a port exists and we don't have to add one. - if host, port, err := net.SplitHostPort(s); err == nil { + if host, port, splitErr := net.SplitHostPort(s); splitErr == nil { return host, port, false } // If adding a port makes it valid, the previous error // was not due to an invalid address and we can append a port. - _, _, err := net.SplitHostPort(s + ":1234") - return "", "", err == nil + _, _, checkErr := net.SplitHostPort(s + ":1234") + return "", "", checkErr == nil } addr := lb.Get(model.AddressLabel) @@ -394,8 +394,8 @@ func PopulateLabels(lb *labels.Builder, cfg *config.ScrapeConfig, noDefaultPort } } - if err := config.CheckTargetAddress(model.LabelValue(addr)); err != nil { - return labels.EmptyLabels(), labels.EmptyLabels(), err + if addrErr := config.CheckTargetAddress(model.LabelValue(addr)); addrErr != nil { + return labels.EmptyLabels(), labels.EmptyLabels(), addrErr } interval := lb.Get(model.ScrapeIntervalLabel) diff --git a/pp-pkg/storage/adapter_promql_test.go b/pp-pkg/storage/adapter_promql_test.go index 0ec401ae6f..a48b981981 100644 --- a/pp-pkg/storage/adapter_promql_test.go +++ b/pp-pkg/storage/adapter_promql_test.go @@ -477,7 +477,7 @@ func (s *AdapterPromQLSuite) TestCPM_PodReplaced_AcrossRotation_PromppStorage() innerV := s.queryAt( `(kube_pod_status_ready{condition="true"} == 1) * on (pod, namespace) group_right () `+ `kube_controller_pod{controller_name="d8-control-plane-manager",controller_type="DaemonSet",namespace="kube-system"}`, t20m) - if !s.Equal(3, len(innerV), "INNER must yield exactly 3 series at t=20m — got %d:\n%v", len(innerV), innerV) { + if !s.Len(innerV, 3, "INNER must yield exactly 3 series at t=20m — got %d:\n%v", len(innerV), innerV) { for i, ss := range innerV { s.T().Logf(" inner[%d] = %s", i, ss.Metric.String()) } @@ -769,11 +769,11 @@ func (s *AdapterPromQLSuite) TestCPM_RecordingRuleMissedIterations_AlertStaysFir // cppbridge head ingest path needs more than 19 ms to make the new sample // visible to a querier. Result: // -// - alert eval @ T+6.329 sees the LATEST committed sample at T-60+6.308 -// (previous minute) → distance = 60.021 s > LookbackDelta (60 s) -// - INNER subexpression is empty → `unless` cancels nothing -// - `max by (node)` returns all three masters → alert FIRING -// - API queries (run later) see the new sample already committed → empty +// - alert eval @ T+6.329 sees the LATEST committed sample at T-60+6.308 +// (previous minute) → distance = 60.021 s > LookbackDelta (60 s) +// - INNER subexpression is empty → `unless` cancels nothing +// - `max by (node)` returns all three masters → alert FIRING +// - API queries (run later) see the new sample already committed → empty // // The fix is to add `query_offset` (per-group or global). An offset of 30 s // pushes alert eval to ask storage for time `T-23.671`; the previous-minute @@ -787,11 +787,11 @@ func (s *AdapterPromQLSuite) TestCPM_RecordingRuleMissedIterations_AlertStaysFir // behind the alert eval timestamp). func (s *AdapterPromQLSuite) TestCPM_OffsetCollisionRace_FixedByQueryOffset() { const ( - stepMs = int64(60_000) - offsetMs = int64(6_000) // shared offset of both groups inside the minute - alertJitterMs = int64(329) // alert eval starts 329 ms after minute+offset (matches prod 6.329) - nLastWritten = int64(29) // we write kube_controller_pod up to and including this step - alertStep = int64(30) // alert eval happens at this step's tick + stepMs = int64(60_000) + offsetMs = int64(6_000) // shared offset of both groups inside the minute + alertJitterMs = int64(329) // alert eval starts 329 ms after minute+offset (matches prod 6.329) + nLastWritten = int64(29) // we write kube_controller_pod up to and including this step + alertStep = int64(30) // alert eval happens at this step's tick ) var points []scrapePoint diff --git a/pp-pkg/storage/batch_storage_test.go b/pp-pkg/storage/batch_storage_test.go index 7574c892bf..e963c73321 100644 --- a/pp-pkg/storage/batch_storage_test.go +++ b/pp-pkg/storage/batch_storage_test.go @@ -9,9 +9,10 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/storage/storagetest" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" pp_model "github.com/prometheus/prometheus/pp/go/model" diff --git a/pp-pkg/storage/remote/noop.go b/pp-pkg/storage/remote/noop.go index 369ae44bab..07fee64977 100644 --- a/pp-pkg/storage/remote/noop.go +++ b/pp-pkg/storage/remote/noop.go @@ -4,6 +4,7 @@ import ( "context" "github.com/prometheus/common/model" + "github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/histogram" "github.com/prometheus/prometheus/model/labels" diff --git a/pp-pkg/storage/remote/remote_read.go b/pp-pkg/storage/remote/remote_read.go index fa812c6e2d..2ccbd3bf10 100644 --- a/pp-pkg/storage/remote/remote_read.go +++ b/pp-pkg/storage/remote/remote_read.go @@ -19,6 +19,8 @@ import ( ) // RemoteRead represents all the remote read endpoints. +// +//nolint:revive // RemoteRead mirrors the public NewRemoteRead constructor used across the codebase. type RemoteRead struct { logger *logging.Deduper mtx sync.Mutex diff --git a/pp-pkg/tsdb/compactor.go b/pp-pkg/tsdb/compactor.go index 15a41da445..d3b8ec1306 100644 --- a/pp-pkg/tsdb/compactor.go +++ b/pp-pkg/tsdb/compactor.go @@ -2,9 +2,11 @@ package tsdb import ( "context" + "github.com/go-kit/log" "github.com/oklog/ulid" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/tsdb" "github.com/prometheus/prometheus/tsdb/chunkenc" ) diff --git a/pp-pkg/tsdb/db.go b/pp-pkg/tsdb/db.go index c0a88f2674..b297eb012a 100644 --- a/pp-pkg/tsdb/db.go +++ b/pp-pkg/tsdb/db.go @@ -7,6 +7,7 @@ import ( "github.com/oklog/ulid" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/storage/catalog" "github.com/prometheus/prometheus/tsdb" "github.com/prometheus/prometheus/tsdb/fileutil" diff --git a/pp/go/cppbridge/common.go b/pp/go/cppbridge/common.go index fe2a761ea4..2ba8d18f5b 100644 --- a/pp/go/cppbridge/common.go +++ b/pp/go/cppbridge/common.go @@ -7,19 +7,19 @@ func GetFlavor() string { return getFlavor() } -// MemInfo stats from C++ allocator +// MemInfo stats from C++ allocator. type MemInfo struct { InUse uint64 Allocated uint64 Resident uint64 } -// GetMemInfo returns current C++ allocator stats +// GetMemInfo returns current C++ allocator stats. func GetMemInfo() MemInfo { return memInfo() } -// DumpMemoryProfile Dump C++ allocated memory profile to file +// DumpMemoryProfile Dump C++ allocated memory profile to file. func DumpMemoryProfile(filename string) bool { return dumpMemoryProfile(filename) == 0 } diff --git a/pp/go/cppbridge/data_storage.go b/pp/go/cppbridge/data_storage.go index 01d073c9f8..5b2974d39d 100644 --- a/pp/go/cppbridge/data_storage.go +++ b/pp/go/cppbridge/data_storage.go @@ -118,7 +118,7 @@ func (ds *DataStorage) InstantQuery(targetTimestamp int64, labelSetIDs []uint32, return seriesDataDataStorageInstantQuery(ds.dataStorage, labelSetIDs, targetTimestamp, samples) } -// QueryFirstTimestamps fills timestamps with the first sample timestamp (Prometheus ms) for each series in seriesIDs +// QueryFirstTimestamps fills timestamps with the first sample timestamp (Prometheus ms) for each series in seriesIDs. func (ds *DataStorage) QueryFirstTimestamps(seriesIDs []uint32, timestamps []int64) { seriesDataDataStorageQueryFirstTimestamps(ds.dataStorage, seriesIDs, timestamps) runtime.KeepAlive(ds) diff --git a/pp/go/cppbridge/exception.go b/pp/go/cppbridge/exception.go index a9b1d6f14c..fd08b01ffc 100644 --- a/pp/go/cppbridge/exception.go +++ b/pp/go/cppbridge/exception.go @@ -8,10 +8,10 @@ import ( "strings" ) -// UnknownExceptionCode is not handled error +// UnknownExceptionCode is not handled error. const UnknownExceptionCode uint64 = 0x0000000000000000 -// GetExceptionCodeFromError returns code from error chain if any exists +// GetExceptionCodeFromError returns code from error chain if any exists. func GetExceptionCodeFromError(err error) uint64 { var code interface { Code() uint64 @@ -22,7 +22,7 @@ func GetExceptionCodeFromError(err error) uint64 { return 0 } -// IsExceptionCodeFromErrorAnyOf returns true if error code equal any in list +// IsExceptionCodeFromErrorAnyOf returns true if error code equal any in list. func IsExceptionCodeFromErrorAnyOf(err error, codes ...uint64) bool { code := GetExceptionCodeFromError(err) for i := range codes { @@ -33,7 +33,7 @@ func IsExceptionCodeFromErrorAnyOf(err error, codes ...uint64) bool { return false } -// IsRemoteWriteParsingError returns true if error throwed on parsing invalid protobuf +// IsRemoteWriteParsingError returns true if error throwed on parsing invalid protobuf. func IsRemoteWriteParsingError(err error) bool { //revive:disable:add-constant this is already constants return IsExceptionCodeFromErrorAnyOf(err, @@ -47,7 +47,7 @@ func IsRemoteWriteParsingError(err error) bool { //revive:enable } -// IsRemoteWriteLimitsExceedsError returns true if limits exceeds +// IsRemoteWriteLimitsExceedsError returns true if limits exceeds. func IsRemoteWriteLimitsExceedsError(err error) bool { //revive:disable:add-constant this is already constants return IsExceptionCodeFromErrorAnyOf(err, @@ -60,7 +60,7 @@ func IsRemoteWriteLimitsExceedsError(err error) bool { //revive:enable } -// Exception container for errors from core +// Exception container for errors from core. type Exception struct { code uint64 msg string @@ -89,22 +89,22 @@ func handleException(b []byte) error { } } -// Error implements error +// Error implements error. func (err *Exception) Error() string { return err.msg } -// Code return uniq code to locate error +// Code return uniq code to locate error. func (err *Exception) Code() uint64 { return err.code } -// Stacktrace return stacktrace to throw instruction +// Stacktrace return stacktrace to throw instruction. func (err *Exception) Stacktrace() string { return err.st } -// Format implements fmt.Formatter interface +// Format implements fmt.Formatter interface. func (err *Exception) Format(s fmt.State, verb rune) { switch verb { case 'v': diff --git a/pp/go/cppbridge/exception_test.go b/pp/go/cppbridge/exception_test.go index a57a8c587f..d7d58a402b 100644 --- a/pp/go/cppbridge/exception_test.go +++ b/pp/go/cppbridge/exception_test.go @@ -4,10 +4,11 @@ import ( "testing" "github.com/golang/snappy" - "github.com/prometheus/prometheus/prompb" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/pp/go/cppbridge" ) @@ -30,9 +31,9 @@ func TestHashdex_error(t *testing.T) { hlimits := cppbridge.DefaultWALHashdexLimits() _, err = cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, b), hlimits) - assert.Error(t, err) + require.Error(t, err) var coreErr *cppbridge.Exception - assert.ErrorAs(t, err, &coreErr) + require.ErrorAs(t, err, &coreErr) assert.EqualValues(t, 0x68997b7d2e49de1e, coreErr.Code()) assert.Greater(t, len(coreErr.Stacktrace()), 1) } diff --git a/pp/go/cppbridge/head_status_test.go b/pp/go/cppbridge/head_status_test.go index b0ea93f681..c772ee2bfc 100644 --- a/pp/go/cppbridge/head_status_test.go +++ b/pp/go/cppbridge/head_status_test.go @@ -3,9 +3,10 @@ package cppbridge_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" - "github.com/stretchr/testify/suite" ) type HeadStatusSuite struct { diff --git a/pp/go/cppbridge/head_test.go b/pp/go/cppbridge/head_test.go index cf1b201884..8c161d69c4 100644 --- a/pp/go/cppbridge/head_test.go +++ b/pp/go/cppbridge/head_test.go @@ -5,11 +5,11 @@ import ( "unsafe" "github.com/prometheus/prometheus/pp/go/storage/querier" - "github.com/stretchr/testify/require" + + "github.com/stretchr/testify/suite" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" - "github.com/stretchr/testify/suite" ) type HeadSuite struct { @@ -123,7 +123,8 @@ func (s *HeadSuite) TestSerializedChunkRecoder() { result := s.dataStorage.Query(cppbridge.DataStorageQuery{ StartTimestampMs: timeInterval.MinT, EndTimestampMs: timeInterval.MaxT, - LabelSetIDs: []uint32{0, 1}}, + LabelSetIDs: []uint32{0, 1}, + }, ) recoder := cppbridge.NewSerializedChunkRecoder(result.SerializedData, timeInterval) @@ -181,7 +182,7 @@ func (s *HeadSuite) TestInstantQuery() { // Arrange dataStorage := cppbridge.NewDataStorage() encoder := cppbridge.NewHeadEncoderWithDataStorage(dataStorage) - var series = []struct { + series := []struct { SeriesID uint32 cppbridge.Sample }{ @@ -211,12 +212,12 @@ func (s *HeadSuite) TestInstantQuery() { result := dataStorage.InstantQuery(targetTimestamp, seriesIDs, uintptr(unsafe.Pointer(unsafe.SliceData(instantSeries)))) // Assert - require.Equal(s.T(), cppbridge.DataStorageQueryStatusSuccess, result.Status) + s.Require().Equal(cppbridge.DataStorageQueryStatusSuccess, result.Status) s.Equal(defaultTimestamp, instantSeries[0].Timestamp) - s.Equal(series[2].Sample, cppbridge.Sample{Timestamp: instantSeries[1].Timestamp, Value: instantSeries[1].Value}) - s.Equal(series[5].Sample, cppbridge.Sample{Timestamp: instantSeries[2].Timestamp, Value: instantSeries[2].Value}) - s.Equal(series[6].Sample, cppbridge.Sample{Timestamp: instantSeries[3].Timestamp, Value: instantSeries[3].Value}) + s.Equal(cppbridge.Sample{Timestamp: instantSeries[1].Timestamp, Value: instantSeries[1].Value}, series[2].Sample) + s.Equal(cppbridge.Sample{Timestamp: instantSeries[2].Timestamp, Value: instantSeries[2].Value}, series[5].Sample) + s.Equal(cppbridge.Sample{Timestamp: instantSeries[3].Timestamp, Value: instantSeries[3].Value}, series[6].Sample) } func (s *HeadSuite) TestQueryFirstTimestampsWithEmptySeriesIds() { diff --git a/pp/go/cppbridge/head_wal.go b/pp/go/cppbridge/head_wal.go index 522ea6c80d..f350b2208d 100644 --- a/pp/go/cppbridge/head_wal.go +++ b/pp/go/cppbridge/head_wal.go @@ -148,7 +148,7 @@ func (d *HeadWalDecoder) Decode(segment []byte, innerSeries *InnerSeries) error // DecodeToDataStorage decodes a segment into a data storage. // //revive:disable-next-line:confusing-results // returns createTimestamp, encodeTimestamp, error. -//nolint:gocritic // unnamedResult // returns createTimestamp, encodeTimestamp, error. + func (d *HeadWalDecoder) DecodeToDataStorage(segment []byte, headEncoder *HeadEncoder) (int64, int64, error) { createTimestamp, encodeTimestamp, err := headWalDecoderDecodeToDataStorage(d.decoder, segment, headEncoder.encoder) runtime.KeepAlive(d) @@ -164,7 +164,7 @@ func (d *HeadWalDecoder) CreateEncoder() (*HeadWalEncoder, error) { encoder, err := headWalDecoderCreateEncoder(d.decoder) // the only error for now is: invalid encoder version if err != nil { - return nil, fmt.Errorf("%w: %s", ErrInvalidEncoderVersion, err) + return nil, fmt.Errorf("%w: %w", ErrInvalidEncoderVersion, err) } e := &HeadWalEncoder{ diff --git a/pp/go/cppbridge/index_writer_test.go b/pp/go/cppbridge/index_writer_test.go index cbd9cd9091..0973c01a8e 100644 --- a/pp/go/cppbridge/index_writer_test.go +++ b/pp/go/cppbridge/index_writer_test.go @@ -3,9 +3,10 @@ package cppbridge_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" - "github.com/stretchr/testify/suite" ) type IndexWriterSuite struct { @@ -118,5 +119,6 @@ func (s *IndexWriterSuite) TestWriteFullIndex() { 0x6f, 0x73, 0x74, 0x9c, 0x03, 0x37, 0x5d, 0x58, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xdb, 0xe1, 0x3a, 0xf5, 0x9b}, index) + 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xdb, 0xe1, 0x3a, 0xf5, 0x9b, + }, index) } diff --git a/pp/go/cppbridge/labels.go b/pp/go/cppbridge/labels.go index 0aa1f3850a..e92b4b2d99 100644 --- a/pp/go/cppbridge/labels.go +++ b/pp/go/cppbridge/labels.go @@ -1,6 +1,6 @@ package cppbridge -// Labels used for data exchenge between Go and C++ +// Labels used for data exchenge between Go and C++. type Labels []Label // Label is a key/value pair of strings. diff --git a/pp/go/cppbridge/lss_snapshot.go b/pp/go/cppbridge/lss_snapshot.go index 70e85805a0..c1040b2c81 100644 --- a/pp/go/cppbridge/lss_snapshot.go +++ b/pp/go/cppbridge/lss_snapshot.go @@ -81,8 +81,8 @@ type SeriesGroups struct { Groups [][]uint32 } -// GroupSeriesByLabelNames group series by label names -func (lss *LabelSetSnapshot) GroupSeriesByLabelNames(seriesIDs []uint32, labelNameIDs []uint32) *SeriesGroups { +// GroupSeriesByLabelNames group series by label names. +func (lss *LabelSetSnapshot) GroupSeriesByLabelNames(seriesIDs, labelNameIDs []uint32) *SeriesGroups { result := &SeriesGroups{ Groups: primitivesGroupSeriesByLabelNames(lss.pointer, seriesIDs, labelNameIDs), } diff --git a/pp/go/cppbridge/lss_snapshot_test.go b/pp/go/cppbridge/lss_snapshot_test.go index 6aecd33563..8d33458797 100644 --- a/pp/go/cppbridge/lss_snapshot_test.go +++ b/pp/go/cppbridge/lss_snapshot_test.go @@ -4,9 +4,10 @@ import ( "math" "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" - "github.com/stretchr/testify/suite" ) type LabelSetSnapshotSuite struct { diff --git a/pp/go/cppbridge/metrics_test.go b/pp/go/cppbridge/metrics_test.go index e215a590c6..043c4a6565 100644 --- a/pp/go/cppbridge/metrics_test.go +++ b/pp/go/cppbridge/metrics_test.go @@ -39,7 +39,7 @@ func (s *CppMetricsSuite) TestNoMetricPages() { metrics := s.getMetrics() // Assert - s.Len(metrics, 0) + s.Empty(metrics) } func (s *CppMetricsSuite) TestOneMetricsPage() { diff --git a/pp/go/cppbridge/primitives_lss.go b/pp/go/cppbridge/primitives_lss.go index 51336b0de7..da49fbed9f 100644 --- a/pp/go/cppbridge/primitives_lss.go +++ b/pp/go/cppbridge/primitives_lss.go @@ -48,7 +48,7 @@ func newLabelSetStorage(lssType uint32) *LabelSetStorage { return newLabelSetStorageFromPointer(primitivesLSSCtor(lssType)) } -// newLabelSetStorageFromPointer init new LabelSetStorage with pointer to constructed lss +// newLabelSetStorageFromPointer init new LabelSetStorage with pointer to constructed lss. func newLabelSetStorageFromPointer(lssPointer uintptr) *LabelSetStorage { lss := &LabelSetStorage{pointer: lssPointer, gcDestroyDetector: &gcDestroyDetector} runtime.SetFinalizer(lss, func(lss *LabelSetStorage) { @@ -135,7 +135,7 @@ func (lss *LabelSetStorage) QueryLabelValues( return result } -// GetLabelNameIDs - returns label name ids +// GetLabelNameIDs - returns label name ids. func (lss *LabelSetStorage) GetLabelNameIDs(names []string) []uint32 { out := primitivesLSSGetLabelNameIDs(lss.pointer, names) runtime.KeepAlive(lss) diff --git a/pp/go/cppbridge/primitives_lss_test.go b/pp/go/cppbridge/primitives_lss_test.go index 9e50613334..535f0ba626 100644 --- a/pp/go/cppbridge/primitives_lss_test.go +++ b/pp/go/cppbridge/primitives_lss_test.go @@ -10,8 +10,9 @@ import ( "github.com/prometheus/prometheus/pp/go/model" - "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/stretchr/testify/suite" + + "github.com/prometheus/prometheus/pp/go/cppbridge" ) type LSSSuite struct { @@ -901,7 +902,7 @@ func (s *RotateLSSSuite) makeRotatedLSS(lName string) *rotatedLSS { var lsid uint32 for i, labelSet := range s.labelSets { - labelSet.Range(func(lname string, lvalue string) bool { + labelSet.Range(func(lname, lvalue string) bool { if !slices.Contains(rLSS.oldNames, lname) { rLSS.oldNames = append(rLSS.oldNames, lname) } @@ -920,7 +921,7 @@ func (s *RotateLSSSuite) makeRotatedLSS(lName string) *rotatedLSS { rLSS.oldLabelSetIDs = append(rLSS.oldLabelSetIDs, rLSS.oldLSS.FindOrEmplace(labelSet).LabelSetID) rLSS.expectedLSes = append(rLSS.expectedLSes, labelSet) rLSS.newLabelSetIDs = append(rLSS.newLabelSetIDs, lsid) - labelSet.Range(func(lname string, lvalue string) bool { + labelSet.Range(func(lname, lvalue string) bool { if !slices.Contains(rLSS.newNames, lname) { rLSS.newNames = append(rLSS.newNames, lname) } @@ -954,7 +955,6 @@ func (s *RotateLSSSuite) convertQueryResultToLabelSets( actualLabelSets := make([]cppbridge.Labels, 0, len(res.IDs())) for _, lsid := range res.IDs() { - ls := cppbridge.Labels{} snapshot.RangeLabelSet(lsid, func(l cppbridge.Label) error { ls = append(ls, cppbridge.Label{ diff --git a/pp/go/cppbridge/prometheus_relabeler.go b/pp/go/cppbridge/prometheus_relabeler.go index 20514f36cc..936a8f8e93 100644 --- a/pp/go/cppbridge/prometheus_relabeler.go +++ b/pp/go/cppbridge/prometheus_relabeler.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "math" - "regexp" "runtime" "slices" "strconv" @@ -14,13 +13,14 @@ import ( "time" "github.com/cespare/xxhash/v2" + "github.com/grafana/regexp" "github.com/prometheus/common/model" ) // NullTimestamp the timestamp that is used as the nil value. const NullTimestamp = math.MinInt64 -// ErrLSSNullPointer - error when lss is null pointer +// ErrLSSNullPointer - error when lss is null pointer. var ErrLSSNullPointer = errors.New("lss is null pointer") // @@ -405,7 +405,7 @@ type RelabeledSeries struct { trackStaleNans CppRoaringBitset } -// IsEmpty - true if empty +// IsEmpty - true if empty. func (rss *RelabeledSeries) IsEmpty() bool { return rss.size == 0 } @@ -492,7 +492,7 @@ func NewShardedRelabeledSeries(numberOfShards uint16) *ShardedRelabeledSeries { return series } -// IsEmpty return true if all elements are empty +// IsEmpty return true if all elements are empty. func (sd *ShardedRelabeledSeries) IsEmpty() bool { for i := range sd.series { if !sd.series[i].IsEmpty() { @@ -1110,7 +1110,7 @@ func (pgr *PerGoroutineRelabeler) inputTransitionRelabelingOnlyRead( return stats, ok, handleException(exception) } -// PerGoroutineRelabelerTrackStaleNans add stale nans samples if needed +// PerGoroutineRelabelerTrackStaleNans add stale nans samples if needed. func PerGoroutineRelabelerTrackStaleNans( innerSeries []InnerSeries, state *StateV2, diff --git a/pp/go/cppbridge/prometheus_relabeler_test.go b/pp/go/cppbridge/prometheus_relabeler_test.go index 84d1a9dd89..b6f92ada33 100644 --- a/pp/go/cppbridge/prometheus_relabeler_test.go +++ b/pp/go/cppbridge/prometheus_relabeler_test.go @@ -2,25 +2,25 @@ package cppbridge_test import ( "context" - "fmt" "runtime" + "strconv" "testing" "time" "unsafe" "github.com/cespare/xxhash/v2" "github.com/golang/snappy" + "github.com/stretchr/testify/suite" + "gopkg.in/yaml.v3" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" "github.com/prometheus/prometheus/prompb" - "github.com/stretchr/testify/suite" - "gopkg.in/yaml.v3" ) type RelabelerSuite struct { suite.Suite baseCtx context.Context - options cppbridge.RelabelerOptions } func TestRelabelerSuite(t *testing.T) { @@ -91,7 +91,7 @@ func (s *RelabelerSuite) TestRelabelConfigValidate() { }, } for i, test := range tests { - s.Run(fmt.Sprint(i), func() { + s.Run(strconv.Itoa(i), func() { err := test.config.Validate() if test.expected == "" { s.Require().NoError(err) diff --git a/pp/go/cppbridge/remote_write.go b/pp/go/cppbridge/remote_write.go index 8a30791b5e..4b4ed82463 100644 --- a/pp/go/cppbridge/remote_write.go +++ b/pp/go/cppbridge/remote_write.go @@ -3,6 +3,7 @@ package cppbridge import "runtime" type RWMessage struct { + //nolint:unused // populated by the C++ core; part of the RWMessage ABI layout samplesIterator CppSegmentSamplesStorageListIterator Buffer []byte MaxTimestamp int64 diff --git a/pp/go/cppbridge/remote_write_test.go b/pp/go/cppbridge/remote_write_test.go index 478db38774..72c5e4cb55 100644 --- a/pp/go/cppbridge/remote_write_test.go +++ b/pp/go/cppbridge/remote_write_test.go @@ -4,8 +4,9 @@ import ( "runtime" "testing" - "github.com/prometheus/prometheus/pp/go/model" "github.com/stretchr/testify/suite" + + "github.com/prometheus/prometheus/pp/go/model" ) type MessageEncodersSuite struct { diff --git a/pp/go/cppbridge/wal_decoder.go b/pp/go/cppbridge/wal_decoder.go index 7147d6d6de..fe81f52721 100644 --- a/pp/go/cppbridge/wal_decoder.go +++ b/pp/go/cppbridge/wal_decoder.go @@ -7,6 +7,7 @@ import ( "runtime" "github.com/gogo/protobuf/proto" + "github.com/prometheus/prometheus/pp/go/frames" ) @@ -72,7 +73,7 @@ func (s DecodedSegmentStats) LatestBlockSample() int64 { return s.latestBlockSample } -// ProtobufContent - decoded to RemoteWrite protobuf segment +// ProtobufContent - decoded to RemoteWrite protobuf segment. type ProtobufContent interface { frames.WritePayload CreatedAt() int64 @@ -292,7 +293,7 @@ func (s OutputDecoderStats) SampleCount() uint32 { return s.sampleCount } -// SegmentSamplesStorageList mirrors PromPP::WAL::SegmentSamplesStorageList +// SegmentSamplesStorageList mirrors PromPP::WAL::SegmentSamplesStorageList. type SegmentSamplesStorageList struct { storages []CppSegmentSamplesStorage } diff --git a/pp/go/cppbridge/wal_decoder_test.go b/pp/go/cppbridge/wal_decoder_test.go index 824dd1b986..9cb161d107 100644 --- a/pp/go/cppbridge/wal_decoder_test.go +++ b/pp/go/cppbridge/wal_decoder_test.go @@ -5,10 +5,11 @@ import ( "context" "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames/framestest" "github.com/prometheus/prometheus/prompb" - "github.com/stretchr/testify/suite" ) type DecoderSuite struct { @@ -51,7 +52,8 @@ func (s *DecoderSuite) TestDecodeV1() { // encoded_at 0, 0, 0, 0, 0, 0, 0, 0, // data - 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 16, 0, 0, 0, 3, 0, 0, 0, 19, 0, 0, 0, 3, 0, 0, 0, 22, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 26, 0, 0, 0, 95, 95, 110, 97, 109, 101, 95, 95, 105, 110, 115, 116, 97, 110, 99, 101, 106, 111, 98, 108, 111, 119, 122, 101, 114, 111, 5, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 1, 5, 0, 0, 0, 116, 101, 115, 116, 48, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 1, 1, 10, 0, 0, 0, 98, 108, 97, 98, 108, 97, 98, 108, 97, 48, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 1, 7, 0, 0, 0, 116, 101, 115, 116, 101, 114, 48, 3, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 1, 6, 0, 0, 0, 98, 97, 110, 97, 110, 48, 4, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 1, 1, 9, 0, 0, 0, 110, 111, 110, 95, 122, 101, 114, 111, 48, 1, 1, 1, 2, 0, 0, 0, 4, 2, 1, 255, 255, 255, 255, 160, 220, 88, 62, 129, 1, 0, 0, 1, 1, 37, 0, 0, 0, 0, 0, 0, 0, 4, 76, 29, 0, 0, 1, 18, 166, 48, 76, 1, 84, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 112, 197, 2, 109, 133, 151, 198, 15, 1, 114, 37, 16, 239} + 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 16, 0, 0, 0, 3, 0, 0, 0, 19, 0, 0, 0, 3, 0, 0, 0, 22, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 26, 0, 0, 0, 95, 95, 110, 97, 109, 101, 95, 95, 105, 110, 115, 116, 97, 110, 99, 101, 106, 111, 98, 108, 111, 119, 122, 101, 114, 111, 5, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 1, 5, 0, 0, 0, 116, 101, 115, 116, 48, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 1, 1, 10, 0, 0, 0, 98, 108, 97, 98, 108, 97, 98, 108, 97, 48, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 1, 7, 0, 0, 0, 116, 101, 115, 116, 101, 114, 48, 3, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 1, 6, 0, 0, 0, 98, 97, 110, 97, 110, 48, 4, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 1, 1, 9, 0, 0, 0, 110, 111, 110, 95, 122, 101, 114, 111, 48, 1, 1, 1, 2, 0, 0, 0, 4, 2, 1, 255, 255, 255, 255, 160, 220, 88, 62, 129, 1, 0, 0, 1, 1, 37, 0, 0, 0, 0, 0, 0, 0, 4, 76, 29, 0, 0, 1, 18, 166, 48, 76, 1, 84, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 112, 197, 2, 109, 133, 151, 198, 15, 1, 114, 37, 16, 239, + } expectedProtob := [...]byte{10, 147, 1, 10, 17, 10, 8, 95, 95, 110, 97, 109, 101, 95, 95, 18, 5, 116, 101, 115, 116, 48, 10, 22, 10, 8, 105, 110, 115, 116, 97, 110, 99, 101, 18, 10, 98, 108, 97, 98, 108, 97, 98, 108, 97, 48, 10, 14, 10, 3, 106, 111, 98, 18, 7, 116, 101, 115, 116, 101, 114, 48, 10, 13, 10, 3, 108, 111, 119, 18, 6, 98, 97, 110, 97, 110, 48, 10, 17, 10, 4, 122, 101, 114, 111, 18, 9, 110, 111, 110, 95, 122, 101, 114, 111, 48, 18, 16, 9, 0, 0, 0, 0, 0, 92, 177, 64, 16, 160, 185, 227, 242, 147, 48, 18, 16, 9, 0, 0, 0, 0, 0, 95, 177, 64, 16, 128, 142, 231, 242, 147, 48, 18, 16, 9, 0, 0, 0, 0, 0, 96, 177, 64, 16, 224, 226, 234, 242, 147, 48} expectedString := "timeseries: labels: labels: labels: labels: samples: samples: samples: > " @@ -146,7 +148,8 @@ func BenchmarkDecoderV1(b *testing.B) { // written_at 0, 0, 0, 0, 0, 0, 0, 0, // data - 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 16, 0, 0, 0, 3, 0, 0, 0, 19, 0, 0, 0, 3, 0, 0, 0, 22, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 26, 0, 0, 0, 95, 95, 110, 97, 109, 101, 95, 95, 105, 110, 115, 116, 97, 110, 99, 101, 106, 111, 98, 108, 111, 119, 122, 101, 114, 111, 5, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 1, 5, 0, 0, 0, 116, 101, 115, 116, 48, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 1, 1, 10, 0, 0, 0, 98, 108, 97, 98, 108, 97, 98, 108, 97, 48, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 1, 7, 0, 0, 0, 116, 101, 115, 116, 101, 114, 48, 3, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 1, 6, 0, 0, 0, 98, 97, 110, 97, 110, 48, 4, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 1, 1, 9, 0, 0, 0, 110, 111, 110, 95, 122, 101, 114, 111, 48, 1, 1, 1, 2, 0, 0, 0, 4, 2, 1, 255, 255, 255, 255, 160, 220, 88, 62, 129, 1, 0, 0, 1, 1, 37, 0, 0, 0, 0, 0, 0, 0, 4, 76, 29, 0, 0, 1, 18, 166, 48, 76, 1, 84, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 112, 197, 2, 109, 133, 151, 198, 15, 1, 114, 37, 16, 239} + 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 16, 0, 0, 0, 3, 0, 0, 0, 19, 0, 0, 0, 3, 0, 0, 0, 22, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 0, 0, 0, 26, 0, 0, 0, 95, 95, 110, 97, 109, 101, 95, 95, 105, 110, 115, 116, 97, 110, 99, 101, 106, 111, 98, 108, 111, 119, 122, 101, 114, 111, 5, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 1, 5, 0, 0, 0, 116, 101, 115, 116, 48, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 1, 1, 10, 0, 0, 0, 98, 108, 97, 98, 108, 97, 98, 108, 97, 48, 2, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 1, 7, 0, 0, 0, 116, 101, 115, 116, 101, 114, 48, 3, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 1, 6, 0, 0, 0, 98, 97, 110, 97, 110, 48, 4, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 1, 1, 9, 0, 0, 0, 110, 111, 110, 95, 122, 101, 114, 111, 48, 1, 1, 1, 2, 0, 0, 0, 4, 2, 1, 255, 255, 255, 255, 160, 220, 88, 62, 129, 1, 0, 0, 1, 1, 37, 0, 0, 0, 0, 0, 0, 0, 4, 76, 29, 0, 0, 1, 18, 166, 48, 76, 1, 84, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 112, 197, 2, 109, 133, 151, 198, 15, 1, 114, 37, 16, 239, + } for i := 0; i < b.N; i++ { dec := cppbridge.NewWALDecoder(defaultEncodersVersion) diff --git a/pp/go/cppbridge/wal_encode_decode_test.go b/pp/go/cppbridge/wal_encode_decode_test.go index a19603b38f..0106d6512b 100644 --- a/pp/go/cppbridge/wal_encode_decode_test.go +++ b/pp/go/cppbridge/wal_encode_decode_test.go @@ -11,9 +11,10 @@ import ( "time" "github.com/golang/snappy" - "github.com/prometheus/prometheus/prompb" "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/frames/framestest" @@ -227,7 +228,7 @@ func (s *EncoderDecoderSuite) TestRestoreFromStream() { s.Equal(uint32(count-1), retoreSID) } -// this test run for local benchmark test +// this test run for local benchmark test. func (s *EncoderDecoderSuite) EncodeDecodeBench(i int64) { expectedWr := s.makeData(100, i) data, err := expectedWr.Marshal() @@ -248,7 +249,7 @@ func (s *EncoderDecoderSuite) EncodeDecodeBench(i int64) { _ = protob } -// this test run for local benchmark test +// this test run for local benchmark test. func (s *EncoderDecoderSuite) TestEncodeDecodeBenchmark() { for i := 0; i < 10; i++ { s.EncodeDecodeBench(int64(i)) diff --git a/pp/go/cppbridge/wal_encoder.go b/pp/go/cppbridge/wal_encoder.go index b479ab2f38..6972101131 100644 --- a/pp/go/cppbridge/wal_encoder.go +++ b/pp/go/cppbridge/wal_encoder.go @@ -15,18 +15,18 @@ import ( // ErrMustImplementCptrable - error on sharded data must implement cptrable interface. var ErrMustImplementCptrable = errors.New("sharded data must implement cptrable interface") -// SegmentKey is a key to store segment data in Exchange and Refill +// SegmentKey is a key to store segment data in Exchange and Refill. type SegmentKey struct { ShardID uint16 Segment uint32 } -// IsFirst returns true if it is a first segment in shard +// IsFirst returns true if it is a first segment in shard. func (key SegmentKey) IsFirst() bool { return key.Segment == 0 } -// Prev returns key to previous segment in the same shard +// Prev returns key to previous segment in the same shard. func (key SegmentKey) Prev() SegmentKey { return SegmentKey{ ShardID: key.ShardID, @@ -34,7 +34,7 @@ func (key SegmentKey) Prev() SegmentKey { } } -// String implements fmt.Stringer interface +// String implements fmt.Stringer interface. func (key SegmentKey) String() string { return fmt.Sprintf("%d:%d", key.ShardID, key.Segment) } @@ -97,7 +97,7 @@ func (s WALEncoderStats) Series() uint32 { return s.series } -// Segment - encoded data segment +// Segment - encoded data segment. type Segment interface { // WritePayload - is a payload to write in frame. frames.WritePayload @@ -141,7 +141,7 @@ func (s *EncodedSegment) WriteTo(w io.Writer) (int64, error) { return int64(n), err } -// SourceState - pointer to source state (null on first call) +// SourceState - pointer to source state (null on first call). type SourceState struct { pointer uintptr } diff --git a/pp/go/cppbridge/wal_encoder_test.go b/pp/go/cppbridge/wal_encoder_test.go index 32a1251d10..78772d74fa 100644 --- a/pp/go/cppbridge/wal_encoder_test.go +++ b/pp/go/cppbridge/wal_encoder_test.go @@ -6,9 +6,10 @@ import ( "testing" "github.com/golang/snappy" - "github.com/prometheus/prometheus/prompb" "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/frames/framestest" @@ -101,7 +102,7 @@ func (s *EncoderSuite) TestEncode() { size := seg.Size() tbyte := s.transferringData(seg) - s.EqualValues(size, len(tbyte)) + s.Len(tbyte, int(size)) } } @@ -125,7 +126,7 @@ func (s *EncoderSuite) TestEncodeDuplicateTS() { size := seg.Size() tbyte := s.transferringData(seg) - s.EqualValues(size, len(tbyte)) + s.Len(tbyte, int(size)) } func (s *EncoderSuite) TestEncodeError() { @@ -248,12 +249,12 @@ func (s *EncoderSuite) TestEncodeRemainingSize() { var remainingTableSize uint32 = math.MaxUint32 hlimits := cppbridge.DefaultWALHashdexLimits() h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, s.makeData(1)), hlimits) - s.NoError(err) + s.Require().NoError(err) enc := cppbridge.NewWALEncoder(0, 0) seg, err := enc.Add(s.baseCtx, h) - s.NoError(err) + s.Require().NoError(err) - var prevRemainingTableSize = seg.RemainingTableSize() + prevRemainingTableSize := seg.RemainingTableSize() s.Less(prevRemainingTableSize, remainingTableSize) } diff --git a/pp/go/cppbridge/wal_hashdex.go b/pp/go/cppbridge/wal_hashdex.go index 668983d844..dc079e2969 100644 --- a/pp/go/cppbridge/wal_hashdex.go +++ b/pp/go/cppbridge/wal_hashdex.go @@ -11,7 +11,7 @@ import ( "github.com/prometheus/prometheus/pp/go/model" ) -// ShardedData - array of structures with (*LabelSet, timestamp, value, LSHash) +// ShardedData - array of structures with (*LabelSet, timestamp, value, LSHash). type ShardedData interface { Cluster() string Replica() string @@ -137,7 +137,7 @@ type WALGoModelHashdex struct { } func (h *WALGoModelHashdex) RangeMetadata(f func(metadata WALScraperHashdexMetadata) bool) { - //TODO implement me + // TODO implement me panic("implement me") } @@ -202,7 +202,7 @@ type WALBasicDecoderHashdex struct { } func (h *WALBasicDecoderHashdex) RangeMetadata(f func(metadata WALScraperHashdexMetadata) bool) { - //TODO implement me + // TODO implement me panic("implement me") } diff --git a/pp/go/cppbridge/wal_hashdex_test.go b/pp/go/cppbridge/wal_hashdex_test.go index 20a5ffd687..532eef8097 100644 --- a/pp/go/cppbridge/wal_hashdex_test.go +++ b/pp/go/cppbridge/wal_hashdex_test.go @@ -9,11 +9,12 @@ import ( "github.com/go-faker/faker/v4" "github.com/go-faker/faker/v4/pkg/options" "github.com/golang/snappy" - "github.com/prometheus/prometheus/prompb" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames/framestest" "github.com/prometheus/prometheus/pp/go/model" @@ -132,7 +133,7 @@ func (s *HashdexSuite) TestCppInvalidDataForHashdex() { invalidPbData := []byte("1111") hlimits := cppbridge.DefaultWALHashdexLimits() h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, invalidPbData), hlimits) - s.Error(err) + s.Require().Error(err) s.T().Logf("Got an error (it's OK): %s", err.Error()) _ = h } @@ -144,7 +145,7 @@ func (s *HashdexSuite) TestHashdexWithHardLimitsOnLabelNameLength() { data := s.makeData(1) h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, data), limits) - s.Error(err) + s.Require().Error(err) s.T().Logf("Got an error (it's OK): %s", err.Error()) _ = h } @@ -156,7 +157,7 @@ func (s *HashdexSuite) TestHashdexWithHardLimitsOnLabelValueLength() { data := s.makeData(1) h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, data), limits) - s.Error(err) + s.Require().Error(err) s.T().Logf("Got an error (it's OK): %s", err.Error()) _ = h } @@ -168,7 +169,7 @@ func (s *HashdexSuite) TestHashdexWithHardLimitsOnLabelsInTimeseries() { data := s.makeData(1) h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, data), limits) - s.Error(err) + s.Require().Error(err) s.T().Logf("Got an error (it's OK): %s", err.Error()) _ = h } @@ -180,7 +181,7 @@ func (s *HashdexSuite) TestHashdexWithVeryHardLimitsOnTimeseries() { data := s.makeDataWithTwoTimeseries() h, err := cppbridge.NewWALSnappyProtobufHashdex(snappy.Encode(nil, data), limits) - s.Error(err) + s.Require().Error(err) s.T().Logf("Got an error (it's OK): %s", err.Error()) _ = h } @@ -402,8 +403,8 @@ func (s *GoModelHashdexTestSuite) TestHashdexLabels() { hdx, err := cppbridge.NewWALGoModelHashdex(limits, []model.TimeSeries{ts}) s.Require().NoError(err) - require.Equal(s.T(), cluster, hdx.Cluster()) - require.Equal(s.T(), replica, hdx.Replica()) + s.Require().Equal(cluster, hdx.Cluster()) + s.Require().Equal(replica, hdx.Replica()) } // max label name size exceeded diff --git a/pp/go/cppbridge/wal_open_metrics_scraper_hashdex_test.go b/pp/go/cppbridge/wal_open_metrics_scraper_hashdex_test.go index e7babed6b8..3d96c6d797 100644 --- a/pp/go/cppbridge/wal_open_metrics_scraper_hashdex_test.go +++ b/pp/go/cppbridge/wal_open_metrics_scraper_hashdex_test.go @@ -97,7 +97,7 @@ foo_total 17.0 1520879607.789 # {id="counter-test"} 5` }) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(uint32(24), scraped) s.Equal(expectedMetadata, actualMetadata) } diff --git a/pp/go/cppbridge/wal_prometheus_scraper_hashdex_test.go b/pp/go/cppbridge/wal_prometheus_scraper_hashdex_test.go index d1551b6c69..74bc5bee8b 100644 --- a/pp/go/cppbridge/wal_prometheus_scraper_hashdex_test.go +++ b/pp/go/cppbridge/wal_prometheus_scraper_hashdex_test.go @@ -71,7 +71,7 @@ testmetric{label="\"bar\""} 1` }) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(uint32(18), scraped) s.Equal(expectedMetadata, actualMetadata) } @@ -84,7 +84,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseErrScraperParseUnexpectedToken( scraped, err := s.hasdex.Parse(input, -1) // Assert - s.ErrorIs(err, cppbridge.ErrScraperParseUnexpectedToken) + s.Require().ErrorIs(err, cppbridge.ErrScraperParseUnexpectedToken) s.Equal(uint32(0), scraped) } @@ -96,7 +96,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseErrScraperParseNoMetricName() { scraped, err := s.hasdex.Parse(input, -1) // Assert - s.ErrorIs(err, cppbridge.ErrScraperParseNoMetricName) + s.Require().ErrorIs(err, cppbridge.ErrScraperParseNoMetricName) s.Equal(uint32(0), scraped) } @@ -108,7 +108,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseErrScraperInvalidUtf8() { scraped, err := s.hasdex.Parse(input, -1) // Assert - s.ErrorIs(err, cppbridge.ErrScraperInvalidUtf8) + s.Require().ErrorIs(err, cppbridge.ErrScraperInvalidUtf8) s.Equal(uint32(0), scraped) } @@ -120,7 +120,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseErrScraperParseInvalidValue() { scraped, err := s.hasdex.Parse(input, -1) // Assert - s.ErrorIs(err, cppbridge.ErrScraperParseInvalidValue) + s.Require().ErrorIs(err, cppbridge.ErrScraperParseInvalidValue) s.Equal(uint32(0), scraped) } @@ -132,7 +132,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseErrScraperParseInvalidTimestamp scraped, err := s.hasdex.Parse(input, -1) // Assert - s.ErrorIs(err, cppbridge.ErrScraperParseInvalidTimestamp) + s.Require().ErrorIs(err, cppbridge.ErrScraperParseInvalidTimestamp) s.Equal(uint32(0), scraped) } @@ -149,7 +149,7 @@ func (s *PrometheusScraperHashdexSuite) TestParseEmptyInput() { }) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal([]cppbridge.WALScraperHashdexMetadata(nil), actualMetadata) s.Equal(uint32(0), scraped) } diff --git a/pp/go/frames/binary_body.go b/pp/go/frames/binary_body.go index 7627977bcf..6b972650ba 100644 --- a/pp/go/frames/binary_body.go +++ b/pp/go/frames/binary_body.go @@ -8,7 +8,7 @@ import ( "io" ) -// SegmentInfoSize = sum 2(ShardID=uint16)+4(SegmentID=uint32) +// SegmentInfoSize = sum 2(ShardID=uint16)+4(SegmentID=uint32). const SegmentInfoSize int = 6 // BinaryBody - unsent segment for save refill. @@ -77,7 +77,7 @@ func NewBinaryBodyV1Empty() *BinaryBodyV1 { return new(BinaryBodyV1) } -// Bytes returns data as is +// Bytes returns data as is. func (sb *BinaryBodyV1) Bytes() []byte { return sb.data } @@ -95,7 +95,7 @@ func (sb *BinaryBodyV1) ReadFrom(ctx context.Context, r io.Reader, size int) err return nil } -// Size - get size body +// Size - get size body. func (sb *BinaryBodyV1) Size() int64 { return int64(len(sb.data)) } @@ -116,8 +116,10 @@ type BinaryBodyV2 struct { body *BinaryBodyV1 } -var _ WritePayload = (*BinaryBodyV2)(nil) -var _ BinaryBody = (*BinaryBodyV2)(nil) +var ( + _ WritePayload = (*BinaryBodyV2)(nil) + _ BinaryBody = (*BinaryBodyV2)(nil) +) // ReadBinaryBodyV2 - read body to BinaryBodyV2 with Reader. func ReadBinaryBodyV2(ctx context.Context, r io.Reader, size int) (*BinaryBodyV2, error) { diff --git a/pp/go/frames/consts.go b/pp/go/frames/consts.go index bdfa4c99e8..b6c0972311 100644 --- a/pp/go/frames/consts.go +++ b/pp/go/frames/consts.go @@ -1,6 +1,6 @@ package frames -// Protocol versions +// Protocol versions. const ( UnknownProtocolVersion uint8 = iota ProtocolVersion1 @@ -10,7 +10,7 @@ const ( ) const ( - // constant size of type + // constant size of type. sizeOfTypeFrame = 1 sizeOfUint8 = 1 sizeOfUint16 = 2 @@ -18,13 +18,13 @@ const ( sizeOfUint64 = 8 sizeOfUUID = 16 - // default version + // default version. defaultVersion uint8 = ProtocolVersion4 - // magic byte for header + // magic byte for header. magicByte byte = 165 ) -// Content versions +// Content versions. const ( UnknownContentVersion uint8 = iota ContentVersion1 diff --git a/pp/go/frames/frames.go b/pp/go/frames/frames.go index 44c86530a0..a29e0bd0e8 100644 --- a/pp/go/frames/frames.go +++ b/pp/go/frames/frames.go @@ -157,7 +157,7 @@ func (fr *ReadFrame) Read(ctx context.Context, r io.Reader) error { return fr.Validate() } -// WriteTo implements io.WriterTo interface +// WriteTo implements io.WriterTo interface. func (fr *ReadFrame) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(fr.EncodeBinary()) @@ -561,7 +561,7 @@ func NewRefillMsgEmpty() *RefillMsg { return new(RefillMsg) } -// Size returns bytes length of message after encoding +// Size returns bytes length of message after encoding. func (rm *RefillMsg) Size() int64 { var n int64 n += util.VarintLen(uint64(len(rm.Messages))) @@ -573,7 +573,7 @@ func (rm *RefillMsg) Size() int64 { return n } -// WriteTo implements io.WriterTo interface +// WriteTo implements io.WriterTo interface. func (rm *RefillMsg) WriteTo(w io.Writer) (int64, error) { buf := make([]byte, 0, rm.Size()) @@ -732,8 +732,7 @@ func NewDestinationsNamesFrameWithMsg(version uint8, msg *DestinationsNames) (*R return NewFrame(version, ContentVersion1, DestinationNamesType, body) } -// stringViewSize -contant size. -// sum = 4(begin=int32)+4(length=int32) +// sum = 4(begin=int32)+4(length=int32). const stringViewSize = 8 // stringView - string view for compact storage. @@ -745,7 +744,7 @@ type stringView struct { // toString - serialize to string. func (sv stringView) toString(data []byte) string { b := data[sv.begin : sv.begin+sv.length] - return unsafe.String(unsafe.SliceData(b), len(b)) //nolint:gosec // this is memory optimisation + return unsafe.String(unsafe.SliceData(b), len(b)) } // NotFoundName - not found name. @@ -1002,7 +1001,7 @@ func (ss Statuses) Reset() { } } -// MarshalBinary implements encoding.BinaryMarshaler +// MarshalBinary implements encoding.BinaryMarshaler. func (ss Statuses) MarshalBinary() ([]byte, error) { // 4(length slice as.status) + 4(status(uint32))*(number of statuses) buf := make([]byte, 0, sizeOfUint32+sizeOfUint32*len(ss)) @@ -1017,7 +1016,7 @@ func (ss Statuses) MarshalBinary() ([]byte, error) { return buf, nil } -// UnmarshalBinary implements encoding.BinaryUnmarshaler +// UnmarshalBinary implements encoding.BinaryUnmarshaler. func (ss *Statuses) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) length, err := binary.ReadUvarint(r) @@ -1115,7 +1114,7 @@ type Reject struct { // RejectStatuses - RejectStatuses - slice with rejected segment struct. type RejectStatuses []Reject -// the number is chosen with a finger to the sky +// the number is chosen with a finger to the sky. const defaultCapacityRejectStatuses = 512 // NewRejectStatusesEmpty - init RejectStatuses. @@ -1123,7 +1122,7 @@ func NewRejectStatusesEmpty() RejectStatuses { return make([]Reject, 0, defaultCapacityRejectStatuses) } -// MarshalBinary implements encoding.MarshalBinary +// MarshalBinary implements encoding.MarshalBinary. func (rjss RejectStatuses) MarshalBinary() ([]byte, error) { // 4(length slice status) + (4(NameID(uint32))+4(Segment(uint32))+2(ShardID(uint16)))*(number of statuses) buf := make([]byte, 0, sizeOfUint32+((sizeOfUint32+sizeOfUint32+sizeOfUint16)*len(rjss))) @@ -1140,7 +1139,7 @@ func (rjss RejectStatuses) MarshalBinary() ([]byte, error) { return buf, nil } -// UnmarshalBinary implements encoding.BinaryUnmarshaler +// UnmarshalBinary implements encoding.BinaryUnmarshaler. func (rjss *RejectStatuses) UnmarshalBinary(data []byte) error { r := bytes.NewReader(data) length, err := binary.ReadUvarint(r) @@ -1393,7 +1392,7 @@ func (fm FinalMsg) HasRefill() bool { return fm.hasRefill == 1 } -// Size returns bytes length of message after encoding +// Size returns bytes length of message after encoding. func (fm *FinalMsg) Size() int64 { var n int64 n += util.VarintLen(uint64(fm.hasRefill)) @@ -1404,7 +1403,7 @@ func (fm *FinalMsg) CRC32() uint32 { return 0 } -// WriteTo implements io.WriterTo interface +// WriteTo implements io.WriterTo interface. func (fm *FinalMsg) WriteTo(w io.Writer) (int64, error) { // error always nil buf, _ := fm.MarshalBinary() diff --git a/pp/go/frames/frames_test.go b/pp/go/frames/frames_test.go index b20deacc42..ab4fb122fd 100644 --- a/pp/go/frames/frames_test.go +++ b/pp/go/frames/frames_test.go @@ -10,9 +10,10 @@ import ( "github.com/go-faker/faker/v4" "github.com/google/uuid" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) // FileBuffer - implement file. @@ -651,15 +652,13 @@ func (s *FrameSuite) TestRefillMsgQuick() { func (s *FrameSuite) TestRefillMsgFrameAt() { ctx := context.Background() - var ( - msgs = []frames.MessageData{ - {ID: 0, Size: 5, Typemsg: 2}, - {ID: 1, Size: 6, Typemsg: 3}, - {ID: 2, Size: 12, Typemsg: 4}, - {ID: 3, Size: 4, Typemsg: 5}, - {ID: 4294967294, Size: 4294967294, Typemsg: 5}, - } - ) + msgs := []frames.MessageData{ + {ID: 0, Size: 5, Typemsg: 2}, + {ID: 1, Size: 6, Typemsg: 3}, + {ID: 2, Size: 12, Typemsg: 4}, + {ID: 3, Size: 4, Typemsg: 5}, + {ID: 4294967294, Size: 4294967294, Typemsg: 5}, + } wm, err := frames.NewRefillFrame(s.version, msgs) s.Require().NoError(err) @@ -682,15 +681,13 @@ func (s *FrameSuite) TestRefillMsgFrameAt() { func (s *FrameSuite) TestRefillMsgFrame() { ctx := context.Background() - var ( - msgs = []frames.MessageData{ - {ID: 0, Size: 5, Typemsg: 2}, - {ID: 1, Size: 6, Typemsg: 3}, - {ID: 2, Size: 12, Typemsg: 4}, - {ID: 3, Size: 4, Typemsg: 5}, - {ID: 4294967294, Size: 4294967294, Typemsg: 5}, - } - ) + msgs := []frames.MessageData{ + {ID: 0, Size: 5, Typemsg: 2}, + {ID: 1, Size: 6, Typemsg: 3}, + {ID: 2, Size: 12, Typemsg: 4}, + {ID: 3, Size: 4, Typemsg: 5}, + {ID: 4294967294, Size: 4294967294, Typemsg: 5}, + } wm, err := frames.NewRefillFrame(s.version, msgs) s.Require().NoError(err) @@ -714,15 +711,13 @@ func (s *FrameSuite) TestRefillMsgFrame() { func (s *FrameSuite) TestRefillMsgFrameAtWithMsg() { ctx := context.Background() - var ( - msgs = []frames.MessageData{ - {ID: 0, Size: 5, Typemsg: 2}, - {ID: 1, Size: 6, Typemsg: 3}, - {ID: 2, Size: 12, Typemsg: 4}, - {ID: 3, Size: 4, Typemsg: 5}, - {ID: 4294967294, Size: 4294967294, Typemsg: 5}, - } - ) + msgs := []frames.MessageData{ + {ID: 0, Size: 5, Typemsg: 2}, + {ID: 1, Size: 6, Typemsg: 3}, + {ID: 2, Size: 12, Typemsg: 4}, + {ID: 3, Size: 4, Typemsg: 5}, + {ID: 4294967294, Size: 4294967294, Typemsg: 5}, + } msg := frames.NewRefillMsg(msgs) wm, err := frames.NewRefillFrameWithMsg(s.version, msg) s.Require().NoError(err) @@ -745,15 +740,13 @@ func (s *FrameSuite) TestRefillMsgFrameAtWithMsg() { func (s *FrameSuite) TestRefillMsgFrameWithMsg() { ctx := context.Background() - var ( - msgs = []frames.MessageData{ - {ID: 0, Size: 5, Typemsg: 2}, - {ID: 1, Size: 6, Typemsg: 3}, - {ID: 2, Size: 12, Typemsg: 4}, - {ID: 3, Size: 4, Typemsg: 5}, - {ID: 4294967294, Size: 4294967294, Typemsg: 5}, - } - ) + msgs := []frames.MessageData{ + {ID: 0, Size: 5, Typemsg: 2}, + {ID: 1, Size: 6, Typemsg: 3}, + {ID: 2, Size: 12, Typemsg: 4}, + {ID: 3, Size: 4, Typemsg: 5}, + {ID: 4294967294, Size: 4294967294, Typemsg: 5}, + } msg := frames.NewRefillMsg(msgs) wm, err := frames.NewRefillFrameWithMsg(s.version, msg) s.Require().NoError(err) @@ -823,9 +816,7 @@ func (s *FrameSuite) TestDestinationsNamesQuick() { func (s *FrameSuite) TestDestinationsNamesFrameAt() { ctx := context.Background() - var ( - names = []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} - ) + names := []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} wm, err := frames.NewDestinationsNamesFrame(s.version, names...) s.Require().NoError(err) b := wm.EncodeBinary() @@ -847,9 +838,7 @@ func (s *FrameSuite) TestDestinationsNamesFrameAt() { func (s *FrameSuite) TestDestinationsNamesFrame() { ctx := context.Background() - var ( - names = []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} - ) + names := []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} wm, err := frames.NewDestinationsNamesFrame(s.version, names...) s.Require().NoError(err) b := wm.EncodeBinary() @@ -872,9 +861,7 @@ func (s *FrameSuite) TestDestinationsNamesFrame() { func (s *FrameSuite) TestDestinationsNamesFrameAtWithMsg() { ctx := context.Background() - var ( - names = []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} - ) + names := []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} msg := frames.NewDestinationsNames(names...) wm, err := frames.NewDestinationsNamesFrameWithMsg(s.version, msg) s.Require().NoError(err) @@ -897,9 +884,7 @@ func (s *FrameSuite) TestDestinationsNamesFrameAtWithMsg() { func (s *FrameSuite) TestDestinationsNamesFrameWithMsg() { ctx := context.Background() - var ( - names = []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} - ) + names := []string{uuid.NewString(), uuid.NewString(), uuid.NewString()} msg := frames.NewDestinationsNames(names...) wm, err := frames.NewDestinationsNamesFrameWithMsg(s.version, msg) s.Require().NoError(err) @@ -950,9 +935,7 @@ func (s *FrameSuite) TestStatusesQuick() { func (s *FrameSuite) TestStatusesFrameAt() { ctx := context.Background() - var ( - data frames.Statuses = []uint32{1, 2, 3, 4, 5} - ) + var data frames.Statuses = []uint32{1, 2, 3, 4, 5} wm, err := frames.NewStatusesFrame(data) s.Require().NoError(err) b := wm.EncodeBinary() @@ -974,9 +957,7 @@ func (s *FrameSuite) TestStatusesFrameAt() { func (s *FrameSuite) TestStatusesFrame() { ctx := context.Background() - var ( - data frames.Statuses = []uint32{1, 2, 3, 4, 5} - ) + var data frames.Statuses = []uint32{1, 2, 3, 4, 5} wm, err := frames.NewStatusesFrame(data) s.Require().NoError(err) b := wm.EncodeBinary() @@ -1038,15 +1019,13 @@ func (s *FrameSuite) TestRejectStatusesQuick() { func (s *FrameSuite) TestRejectStatusesFrameAt() { ctx := context.Background() - var ( - data = frames.RejectStatuses{ - frames.Reject{ - NameID: 10, - Segment: 15, - ShardID: 1, - }, - } - ) + data := frames.RejectStatuses{ + frames.Reject{ + NameID: 10, + Segment: 15, + ShardID: 1, + }, + } wm, err := frames.NewRejectStatusesFrame(data) s.Require().NoError(err) b := wm.EncodeBinary() @@ -1068,15 +1047,13 @@ func (s *FrameSuite) TestRejectStatusesFrameAt() { func (s *FrameSuite) TestRejectStatusesFrame() { ctx := context.Background() - var ( - data = frames.RejectStatuses{ - frames.Reject{ - NameID: 10, - Segment: 15, - ShardID: 1, - }, - } - ) + data := frames.RejectStatuses{ + frames.Reject{ + NameID: 10, + Segment: 15, + ShardID: 1, + }, + } wm, err := frames.NewRejectStatusesFrame(data) s.Require().NoError(err) b := wm.EncodeBinary() @@ -1206,9 +1183,7 @@ func (s *FrameSuite) TestFinalMsgQuick() { func (s *FrameSuite) TestFinalMsgFrameAt() { ctx := context.Background() - var ( - hasRefill = true - ) + hasRefill := true wm, err := frames.NewFinalMsgFrame(s.version, hasRefill) s.Require().NoError(err) @@ -1255,9 +1230,7 @@ func (s *FrameSuite) TestFinalMsgWriteFrameAt() { func (s *FrameSuite) TestFinalMsgFrame() { ctx := context.Background() - var ( - hasRefill = true - ) + hasRefill := true wm, err := frames.NewFinalMsgFrame(s.version, hasRefill) s.Require().NoError(err) diff --git a/pp/go/frames/framestest/read_payload.go b/pp/go/frames/framestest/read_payload.go index e1acb952df..51d79dc2cc 100644 --- a/pp/go/frames/framestest/read_payload.go +++ b/pp/go/frames/framestest/read_payload.go @@ -5,18 +5,19 @@ import ( "context" "io" - "github.com/prometheus/prometheus/pp/go/frames" "golang.org/x/sync/errgroup" + + "github.com/prometheus/prometheus/pp/go/frames" ) -// ReadPayload reads payload to bytes +// ReadPayload reads payload to bytes. func ReadPayload(p frames.WritePayload) ([]byte, error) { buf := bytes.NewBuffer(make([]byte, 0, p.Size())) _, err := p.WriteTo(buf) return buf.Bytes(), err } -// ReadFrame convert WriteFrame into ReadFrame +// ReadFrame convert WriteFrame into ReadFrame. func ReadFrame(ctx context.Context, f *frames.WriteFrame) (*frames.ReadFrame, error) { r, w := io.Pipe() g := new(errgroup.Group) diff --git a/pp/go/frames/header.go b/pp/go/frames/header.go index 605adb7a2b..16d79e4cc9 100644 --- a/pp/go/frames/header.go +++ b/pp/go/frames/header.go @@ -7,7 +7,7 @@ import ( "io" ) -// Header versions +// Header versions. const ( unknownHeaderVersion uint8 = iota headerVersion1 @@ -39,7 +39,7 @@ const ( maxheaderSize int = headerSizeMain + headerSizeV3 ) -// VersionedHeader - versioned header +// VersionedHeader - versioned header. type VersionedHeader interface { DecodeBinary(r io.Reader) error DecodeBuffer(buf []byte) diff --git a/pp/go/frames/header_test.go b/pp/go/frames/header_test.go index 907639dee2..f01997ebff 100644 --- a/pp/go/frames/header_test.go +++ b/pp/go/frames/header_test.go @@ -4,9 +4,10 @@ import ( "context" "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) type HeaderSuite struct { diff --git a/pp/go/frames/title.go b/pp/go/frames/title.go index c285f72913..5814dace2f 100644 --- a/pp/go/frames/title.go +++ b/pp/go/frames/title.go @@ -9,11 +9,9 @@ import ( ) const ( - // titleV1Size -contant size. - // sum = 1(logOfNumberOfShards=uint8)+16(blockID=uuid.UUID) + // sum = 1(logOfNumberOfShards=uint8)+16(blockID=uuid.UUID). titleV1Size int = 17 - // titleV2Size -contant size. - // sum = 1(logOfNumberOfShards=uint8)+16(blockID=uuid.UUID)+1(encodersVersion=uint8) + // sum = 1(logOfNumberOfShards=uint8)+16(blockID=uuid.UUID)+1(encodersVersion=uint8). titleV2Size int = 18 ) diff --git a/pp/go/frames/title_test.go b/pp/go/frames/title_test.go index 578f8cec3b..dfde45e999 100644 --- a/pp/go/frames/title_test.go +++ b/pp/go/frames/title_test.go @@ -8,9 +8,10 @@ import ( "time" "github.com/google/uuid" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) type TitleSuite struct { diff --git a/pp/go/frames/transport_frames.go b/pp/go/frames/transport_frames.go index 4e4fd79052..c452b3b1f1 100644 --- a/pp/go/frames/transport_frames.go +++ b/pp/go/frames/transport_frames.go @@ -69,7 +69,7 @@ func NewWriteSegmentV4(id uint32, payload WritePayload) *WriteSegmentV4 { return f } -// WriteTo implements io.WriterTo interface +// WriteTo implements io.WriterTo interface. func (f *WriteSegmentV4) WriteTo(w io.Writer) (int64, error) { buf := make([]byte, segmentSizeV4) var offset int @@ -191,8 +191,10 @@ type ResponseV4 struct { Text string } -var _ FrameReader = (*ResponseV4)(nil) -var _ FrameWriter = (*ResponseV4)(nil) +var ( + _ FrameReader = (*ResponseV4)(nil) + _ FrameWriter = (*ResponseV4)(nil) +) // NewResponseV4 - init new ResponseV4 via stream. func NewResponseV4(sentAt int64, segmentID uint32, code uint16, text string) *ResponseV4 { diff --git a/pp/go/frames/transport_frames_test.go b/pp/go/frames/transport_frames_test.go index 8dcc2c1ad6..3ceb627e5a 100644 --- a/pp/go/frames/transport_frames_test.go +++ b/pp/go/frames/transport_frames_test.go @@ -8,9 +8,10 @@ import ( "time" "github.com/google/uuid" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) // dataTest - test data. @@ -24,7 +25,7 @@ func newDataTest(data []byte) *dataTest { } } -// Size returns count of bytes in data +// Size returns count of bytes in data. func (dt *dataTest) Size() int64 { return int64(len(dt.data)) } @@ -33,7 +34,7 @@ func (dt *dataTest) CRC32() uint32 { return crc32.ChecksumIEEE(dt.data) } -// WriteTo implements io.WriterTo interface +// WriteTo implements io.WriterTo interface. func (dt *dataTest) WriteTo(w io.Writer) (int64, error) { n, err := w.Write(dt.data) return int64(n), err diff --git a/pp/go/frames/types.go b/pp/go/frames/types.go index 68c9c95f46..3b24792e5b 100644 --- a/pp/go/frames/types.go +++ b/pp/go/frames/types.go @@ -14,7 +14,7 @@ func (tf TypeFrame) Validate() error { return nil } -// Frame types +// Frame types. const ( UnknownType TypeFrame = iota AuthType diff --git a/pp/go/frames/write_frame.go b/pp/go/frames/write_frame.go index 47cacee9c2..9a903bf5d6 100644 --- a/pp/go/frames/write_frame.go +++ b/pp/go/frames/write_frame.go @@ -7,14 +7,14 @@ import ( "time" ) -// WritePayload is a payload to write in frame +// WritePayload is a payload to write in frame. type WritePayload interface { Size() int64 CRC32() uint32 io.WriterTo } -// WriteFrame - frame for write +// WriteFrame - frame for write. type WriteFrame struct { header *Header payload WritePayload diff --git a/pp/go/logger/logger.go b/pp/go/logger/logger.go index 548517806c..59707aff52 100644 --- a/pp/go/logger/logger.go +++ b/pp/go/logger/logger.go @@ -10,7 +10,7 @@ var ( Debugf = noop ) -// Unset logger funcs to NoOp +// Unset logger funcs to NoOp. func Unset() { Errorf = noop Warnf = noop diff --git a/pp/go/model/labelset.go b/pp/go/model/labelset.go index 1f498f8173..cb5bf8baf8 100644 --- a/pp/go/model/labelset.go +++ b/pp/go/model/labelset.go @@ -31,18 +31,18 @@ type delegatedStringView struct{ begin, len int32 } func (view delegatedStringView) reveal(data []byte) string { b := data[view.begin : view.begin+view.len] - return unsafe.String(unsafe.SliceData(b), len(b)) //nolint:gosec // this is memory optimisation + return unsafe.String(unsafe.SliceData(b), len(b)) } -// number of bytes addet to each key-value pair in LabelSet data +// number of bytes addet to each key-value pair in LabelSet data. const additionalSymbols = 2 // ':' between key and value and ';' at the end -// EmptyLabelSet is a constructor of empty LabelSet +// EmptyLabelSet is a constructor of empty LabelSet. func EmptyLabelSet() LabelSet { return LabelSet{} } -// LabelSetFromMap is a constructor for predefined LabelSet +// LabelSetFromMap is a constructor for predefined LabelSet. func LabelSetFromMap(m map[string]string) LabelSet { var size int keys := make([]string, 0, len(m)) @@ -89,7 +89,7 @@ func LabelSetFromSlice(s []SimpleLabel) LabelSet { return ls } -// LabelSetFromPairs is a short constructor for tests +// LabelSetFromPairs is a short constructor for tests. func LabelSetFromPairs(kv ...string) LabelSet { if len(kv)%additionalSymbols != 0 { panic("kv is not pairs") @@ -124,15 +124,15 @@ func LabelSetFromPairs(kv ...string) LabelSet { // // Implements fmt.Stringer. func (ls LabelSet) String() string { - return unsafe.String(unsafe.SliceData(ls.data), len(ls.data)) //nolint:gosec // memory and cpu optimization + return unsafe.String(unsafe.SliceData(ls.data), len(ls.data)) } -// IsEmpty returns true if label set is empty +// IsEmpty returns true if label set is empty. func (ls LabelSet) IsEmpty() bool { return ls.Len() == 0 } -// Get returns label value by key or default value if there is no key in label set +// Get returns label value by key or default value if there is no key in label set. func (ls LabelSet) Get(key, defaultValue string) string { if n, ok := ls.get(key); ok { return ls.Value(n) @@ -140,22 +140,22 @@ func (ls LabelSet) Get(key, defaultValue string) string { return defaultValue } -// Len returns number of label pairs +// Len returns number of label pairs. func (ls LabelSet) Len() int { return len(ls.pairs) } -// Key returns i-th key +// Key returns i-th key. func (ls LabelSet) Key(i int) string { return ls.pairs[i].key.reveal(ls.data) } -// Value returns i-th value +// Value returns i-th value. func (ls LabelSet) Value(i int) string { return ls.pairs[i].value.reveal(ls.data) } -// ToMap returns label pairs as map +// ToMap returns label pairs as map. func (ls LabelSet) ToMap() map[string]string { m := make(map[string]string, ls.Len()) for i := 0; i < ls.Len(); i++ { @@ -173,7 +173,7 @@ func (ls LabelSet) Range(f func(lname, lvalue string) bool) { } } -// With return LabelSet with label key-value +// With return LabelSet with label key-value. func (ls LabelSet) With(key, value string) LabelSet { i, ok := ls.get(key) if ok && ls.Value(i) == value { @@ -207,12 +207,12 @@ func (ls LabelSet) With(key, value string) LabelSet { return res } -// WithPairs returns result of merge label set with kv pairs +// WithPairs returns result of merge label set with kv pairs. func (ls LabelSet) WithPairs(kv ...string) LabelSet { return ls.Merge(LabelSetFromPairs(kv...)) } -// Merge returns result of merge ls with updates +// Merge returns result of merge ls with updates. func (ls LabelSet) Merge(updates LabelSet) LabelSet { if updates.IsEmpty() { return ls @@ -314,7 +314,7 @@ func (ls LabelSet) SplitBy(keys ...string) (extracted, rest LabelSet) { return extracted, rest } -// Without returns new label set without given keys +// Without returns new label set without given keys. func (ls LabelSet) Without(keys ...string) LabelSet { sortedKeys := make([]string, len(keys)) copy(sortedKeys, keys) @@ -340,7 +340,7 @@ func (ls LabelSet) Without(keys ...string) LabelSet { return res } -// MarshalJSON implements json.Marshaler +// MarshalJSON implements json.Marshaler. func (ls LabelSet) MarshalJSON() ([]byte, error) { w := &jwriter.Writer{} w.RawByte('{') @@ -358,7 +358,7 @@ func (ls LabelSet) MarshalJSON() ([]byte, error) { return w.BuildBytes() } -// UnmarshalJSON implements json.Unmarshaler +// UnmarshalJSON implements json.Unmarshaler. func (ls *LabelSet) UnmarshalJSON(data []byte) error { m := map[string]string{} if err := json.Unmarshal(data, &m); err != nil { @@ -368,12 +368,12 @@ func (ls *LabelSet) UnmarshalJSON(data []byte) error { return nil } -// MarshalYAML implements yaml.Marshaler +// MarshalYAML implements yaml.Marshaler. func (ls LabelSet) MarshalYAML() (interface{}, error) { return ls.ToMap(), nil } -// UnmarshalYAML implements yaml/v2.Unmarshaler (v3 compatible) +// UnmarshalYAML implements yaml/v2.Unmarshaler (v3 compatible). func (ls *LabelSet) UnmarshalYAML(unmarshal func(interface{}) error) error { m := map[string]string{} if err := unmarshal(&m); err != nil { @@ -400,7 +400,7 @@ func (ls *LabelSet) append(key, value string) { ls.pairs = append(ls.pairs, pair{dKey, dValue}) } -// appendFrom appends items from other in half-interval [a; b) +// appendFrom appends items from other in half-interval [a; b). func (ls *LabelSet) appendFrom(other LabelSet, a, b int) { if a >= b { return @@ -442,12 +442,12 @@ func (ls LabelSet) valueLen(i int) int { // LabelSetBuilder // -// LabelSetBuilder used for carry labels pairs +// LabelSetBuilder used for carry labels pairs. type LabelSetBuilder struct { pairs map[string]string } -// NewLabelSetBuilder is a constructor +// NewLabelSetBuilder is a constructor. func NewLabelSetBuilder() *LabelSetBuilder { return &LabelSetBuilder{ pairs: map[string]string{}, @@ -461,7 +461,7 @@ func NewLabelSetBuilderSize(size int) *LabelSetBuilder { } } -// Build label set +// Build label set. func (builder *LabelSetBuilder) Build() LabelSet { return LabelSetFromMap(builder.pairs) } @@ -471,13 +471,13 @@ func (builder *LabelSetBuilder) Add(key, value string) { builder.pairs[key] = value } -// Set key-value in label set +// Set key-value in label set. func (builder *LabelSetBuilder) Set(key, value string) *LabelSetBuilder { builder.pairs[key] = value return builder } -// Delete key-value pair from label set +// Delete key-value pair from label set. func (builder *LabelSetBuilder) Delete(keys ...string) *LabelSetBuilder { for _, key := range keys { delete(builder.pairs, key) @@ -485,7 +485,7 @@ func (builder *LabelSetBuilder) Delete(keys ...string) *LabelSetBuilder { return builder } -// NewWith clone builder and add given key-value +// NewWith clone builder and add given key-value. func (builder *LabelSetBuilder) NewWith(key, value string) *LabelSetBuilder { res := make(map[string]string, len(builder.pairs)+1) for k, v := range builder.pairs { diff --git a/pp/go/model/labelset_test.go b/pp/go/model/labelset_test.go index 374a2ad31a..cc7951de9e 100644 --- a/pp/go/model/labelset_test.go +++ b/pp/go/model/labelset_test.go @@ -54,6 +54,7 @@ func (s *LabelSetSuite) TestLabelSet_FromPairs() { func (s *LabelSetSuite) TestLabelSet_FromPairs_panic() { s.Panics(func() { + //nolint:staticcheck // odd number of elements is intentional to trigger the panic under test model.LabelSetFromPairs( "__name__", "example", "instance", "instance", diff --git a/pp/go/relabeler/autosharder.go b/pp/go/relabeler/autosharder.go index 67adc2f109..bfae265898 100644 --- a/pp/go/relabeler/autosharder.go +++ b/pp/go/relabeler/autosharder.go @@ -96,7 +96,7 @@ func (as *Autosharder) incShardsNumberPower(in uint8) uint8 { return as.currentShardsNumberPower + in } -// decShardsNumberPower - decrease the current ShardsNumberPower considering the minimum value +// decShardsNumberPower - decrease the current ShardsNumberPower considering the minimum value. func (as *Autosharder) decShardsNumberPower(in uint8) uint8 { if as.currentShardsNumberPower <= in { return 0 diff --git a/pp/go/relabeler/config/config.go b/pp/go/relabeler/config/config.go index ec6a3a0f49..f46d6171ca 100644 --- a/pp/go/relabeler/config/config.go +++ b/pp/go/relabeler/config/config.go @@ -2,6 +2,7 @@ package config import ( "errors" + "github.com/prometheus/prometheus/pp/go/cppbridge" ) diff --git a/pp/go/relabeler/destination_group.go b/pp/go/relabeler/destination_group.go index 7502a97924..979c6abff8 100644 --- a/pp/go/relabeler/destination_group.go +++ b/pp/go/relabeler/destination_group.go @@ -5,10 +5,12 @@ import ( "errors" "fmt" "path/filepath" + "strconv" "sync" "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/util" ) @@ -236,7 +238,7 @@ func (dg *DestinationGroup) ObserveEncodersMemory() { dg.memoryInUse.With( prometheus.Labels{ "allocator": fmt.Sprintf("encoder_%s", dg.cfg.Name), - "id": fmt.Sprintf("%d", id), + "id": strconv.Itoa(id), }, ).Set(val) }) @@ -348,7 +350,7 @@ func (dg *DestinationGroup) Shutdown(ctx context.Context) error { dg.memoryInUse.Delete( prometheus.Labels{ "allocator": fmt.Sprintf("output_relabeler_%s", dg.cfg.Name), - "id": fmt.Sprintf("%d", shardID), + "id": strconv.FormatUint(uint64(shardID), 10), }, ) @@ -356,7 +358,7 @@ func (dg *DestinationGroup) Shutdown(ctx context.Context) error { dg.memoryInUse.Delete( prometheus.Labels{ "allocator": fmt.Sprintf("encoder_%s", dg.cfg.Name), - "id": fmt.Sprintf("%d", id), + "id": strconv.Itoa(id), }, ) }) @@ -416,7 +418,7 @@ func (dg *DestinationGroup) reshardingOutputRelabelers( dg.memoryInUse.Delete( prometheus.Labels{ "allocator": fmt.Sprintf("output_relabeler_%s", dg.cfg.Name), - "id": fmt.Sprintf("%d", shardID), + "id": strconv.Itoa(shardID), }, ) continue diff --git a/pp/go/relabeler/errors.go b/pp/go/relabeler/errors.go index c159789211..c8faca95a9 100644 --- a/pp/go/relabeler/errors.go +++ b/pp/go/relabeler/errors.go @@ -8,33 +8,33 @@ import ( ) var ( - // exchange + // exchange. - // ErrPromiseCanceled - error for promise is canceled + // ErrPromiseCanceled - error for promise is canceled. ErrPromiseCanceled = errors.New("promise is canceled") - // ErrSegmentGone - error for segment gone from exchange + // ErrSegmentGone - error for segment gone from exchange. ErrSegmentGone = errors.New("segment gone from exchange") - // manager_keeper + // manager_keeper. // ErrShutdownTimeout - error when value ErrShutdownTimeout less UncommittedTimeWindow*2. ErrShutdownTimeout = errors.New("ShutdownTimeout must be greater than the UncommittedTimeWindow*2") - // manager + // manager. - // ErrDestinationsRequired - error no destinations found in config + // ErrDestinationsRequired - error no destinations found in config. ErrDestinationsRequired = errors.New("no destinations found in config") - // ErrShutdown - error shutdown + // ErrShutdown - error shutdown. ErrShutdown = errors.New("shutdown") - // models + // models. - // ErrAborted - error for promise is aborted + // ErrAborted - error for promise is aborted. ErrAborted = errors.New("promise is aborted") // ErrHADropped - error when metrics skip from High Availability. ErrHADropped = errors.New("dropped from HA") - // refill sender + // refill sender. // ErrCorruptedFile - error if the file is corrupted. ErrCorruptedFile = errors.New("corrupted file") @@ -43,7 +43,7 @@ var ( // errRefillLimitExceeded - error if refill limit exceeded. errRefillLimitExceeded = errors.New("refill limit exceeded") - // sender + // sender. // ErrBlockFinalization - signal if the current block is finalized. ErrBlockFinalization = errors.New("block finalization") @@ -65,12 +65,12 @@ type CorruptedEncoderError struct { err error } -// Error implements error interface +// Error implements error interface. func (err CorruptedEncoderError) Error() string { return err.err.Error() } -// Unwrap implements errors.Unwrapper interface +// Unwrap implements errors.Unwrapper interface. func (err CorruptedEncoderError) Unwrap() error { return err.err } @@ -91,7 +91,7 @@ type ErrSegmentNotFoundInRefill struct { key cppbridge.SegmentKey } -// SegmentNotFoundInRefill create ErrSegmentNotFoundInRefill error +// SegmentNotFoundInRefill create ErrSegmentNotFoundInRefill error. func SegmentNotFoundInRefill(key cppbridge.SegmentKey) ErrSegmentNotFoundInRefill { return ErrSegmentNotFoundInRefill{key} } diff --git a/pp/go/relabeler/exchange.go b/pp/go/relabeler/exchange.go index 152dd0e5b4..2454a0dc3d 100644 --- a/pp/go/relabeler/exchange.go +++ b/pp/go/relabeler/exchange.go @@ -8,12 +8,13 @@ import ( "sync/atomic" "time" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/util" - "github.com/prometheus/client_golang/prometheus" ) -// Exchange holds and coordinate segment-redundants flow +// Exchange holds and coordinate segment-redundants flow. type Exchange struct { records *sync.Map // map[common.SegmentKey]*exchangeRecord lastSegments []uint32 // max segment id per shard @@ -65,7 +66,7 @@ func NewExchange( } } -// Ack segment by key +// Ack segment by key. func (ex *Exchange) Ack(key cppbridge.SegmentKey) { record, ok := ex.records.Load(key) if !ok { @@ -125,7 +126,7 @@ func (ex *Exchange) Put( } } -// Reject segment by key +// Reject segment by key. func (ex *Exchange) Reject(key cppbridge.SegmentKey) bool { atomic.StoreUint32(&ex.rejects[key.ShardID], 1) record, ok := ex.records.Load(key) @@ -136,7 +137,7 @@ func (ex *Exchange) Reject(key cppbridge.SegmentKey) bool { return false } -// RejectedOrExpired returns slice of keys which was rejected +// RejectedOrExpired returns slice of keys which was rejected. func (ex *Exchange) RejectedOrExpired(now time.Time) (keys []cppbridge.SegmentKey, empty bool) { empty = true ex.records.Range(func(k, value any) bool { @@ -154,7 +155,7 @@ func (ex *Exchange) RejectedOrExpired(now time.Time) (keys []cppbridge.SegmentKe return keys, empty } -// Remove keys from exchange because them writted in refill +// Remove keys from exchange because them writted in refill. func (ex *Exchange) Remove(keys []cppbridge.SegmentKey) { if len(keys) == 0 { return diff --git a/pp/go/relabeler/file_storage.go b/pp/go/relabeler/file_storage.go index 209c7543e3..91fc16aa72 100644 --- a/pp/go/relabeler/file_storage.go +++ b/pp/go/relabeler/file_storage.go @@ -97,7 +97,7 @@ func (fs *FileStorage) ReadAt(b []byte, off int64) (int, error) { return fs.fileDescriptor.ReadAt(b, off) } -// Close - implements os.Close +// Close - implements os.Close. func (fs *FileStorage) Close() error { if fs.fileDescriptor == nil { return nil @@ -131,17 +131,17 @@ func (fs *FileStorage) GetPath() string { return filepath.Join(fs.dir, fs.fileName) } -// Rename file +// Rename file. func (fs *FileStorage) Rename(name string) error { return fs.renameFile(name + refillFileExtension) } -// IntermediateRename renames file with temporary extension +// IntermediateRename renames file with temporary extension. func (fs *FileStorage) IntermediateRename(name string) error { return fs.renameFile(name + refillIntermediateFileExtension) } -// GetIntermediateName returns true with name if file has temporary extension +// GetIntermediateName returns true with name if file has temporary extension. func (fs *FileStorage) GetIntermediateName() (string, bool) { if strings.HasSuffix(fs.fileName, refillIntermediateFileExtension) { return strings.TrimSuffix(fs.fileName, refillIntermediateFileExtension), true diff --git a/pp/go/relabeler/high_availability_tracker.go b/pp/go/relabeler/high_availability_tracker.go index 861b8fa2e8..dab8f385d0 100644 --- a/pp/go/relabeler/high_availability_tracker.go +++ b/pp/go/relabeler/high_availability_tracker.go @@ -6,8 +6,9 @@ import ( "time" "github.com/jonboulle/clockwork" - "github.com/prometheus/prometheus/pp/go/util" "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/pp/go/util" ) var ( diff --git a/pp/go/relabeler/main_test.go b/pp/go/relabeler/main_test.go deleted file mode 100644 index d5993265cf..0000000000 --- a/pp/go/relabeler/main_test.go +++ /dev/null @@ -1,162 +0,0 @@ -package relabeler_test - -import ( - "io" - - "github.com/prometheus/prometheus/pp/go/cppbridge" - "github.com/prometheus/prometheus/pp/go/model" -) - -const refillExt = ".refill" - -// dataTest - test data. -type dataTest struct { - data []byte -} - -func newDataTest(data []byte) *dataTest { - return &dataTest{ - data: data, - } -} - -// Add - sum incoming stats. -func (*dataTest) Add(_ cppbridge.SegmentStats) { -} - -// Size returns count of bytes in data -func (dt *dataTest) Size() int64 { - return int64(len(dt.data)) -} - -// WriteTo implements io.WriterTo interface -func (dt *dataTest) WriteTo(w io.Writer) (int64, error) { - n, err := w.Write(dt.data) - return int64(n), err -} - -func (dt *dataTest) Bytes() []byte { - return dt.data -} - -func (*dataTest) Samples() uint32 { - return 0 -} - -// Series returns count of series in segment -func (*dataTest) Series() uint32 { - return 0 -} - -// Earliest returns timestamp in ms of earliest sample in segment -func (*dataTest) EarliestTimestamp() int64 { - return 0 -} - -// Latest returns timestamp in ms of latest sample in segment -func (*dataTest) LatestTimestamp() int64 { - return 0 -} - -func (*dataTest) RemainingTableSize() uint32 { - return 0 -} - -// Destroy - clear memory, for implements. -func (dt *dataTest) Destroy() { - dt.data = nil -} - -type testHashdexFactory struct{} - -func (testHashdexFactory) Protobuf(data []byte, _ cppbridge.WALHashdexLimits) (cppbridge.ShardedData, error) { - return newShardedDataTest(string(data)), nil -} - -func (testHashdexFactory) GoModel(_ []model.TimeSeries, _ cppbridge.WALHashdexLimits) (cppbridge.ShardedData, error) { - return noOpShardedData{}, nil -} - -// dataTest - test data. -type shardedDataTest struct { - data string -} - -func (dt *shardedDataTest) RangeMetadata(f func(metadata cppbridge.WALScraperHashdexMetadata) bool) { - //TODO implement me - panic("implement me") -} - -func newByteShardedDataTest(data []byte, _ cppbridge.WALHashdexLimits) (cppbridge.ShardedData, error) { - return newShardedDataTest(string(data)), nil -} - -func newShardedDataTest(data string) *shardedDataTest { - return &shardedDataTest{ - data: data, - } -} - -// Bytes - return bytes, for implements. -func (dt *shardedDataTest) Bytes() []byte { - return []byte(dt.data) -} - -func (*shardedDataTest) Type() uint8 { - return 0 -} - -// Cluster - return cluster name, for implements. -func (*shardedDataTest) Cluster() string { - return "" -} - -// Replica - return replica name, for implements. -func (*shardedDataTest) Replica() string { - return "" -} - -// Destroy - clear memory, for implements. -func (dt *shardedDataTest) Destroy() { - dt.data = "" -} - -type noOpShardedData struct{} - -func (d noOpShardedData) RangeMetadata(f func(metadata cppbridge.WALScraperHashdexMetadata) bool) { - //TODO implement me - panic("implement me") -} - -func (noOpShardedData) Type() uint8 { - return 1 -} - -func (noOpShardedData) Cluster() string { - return "" -} - -func (noOpShardedData) Replica() string { - return "" -} - -// protoDataTest - test data. -type protoDataTest struct { - data []byte -} - -func newProtoDataTest(data []byte) *protoDataTest { - return &protoDataTest{ - data: data, - } -} - -// Bytes - return bytes, for implements. -func (pd *protoDataTest) Bytes() []byte { - return pd.data -} - -// Destroy - clear memory, for implements. -func (pd *protoDataTest) Destroy() { - pd.data = nil -} diff --git a/pp/go/relabeler/manager.go b/pp/go/relabeler/manager.go index de15c5b601..b4781a50d3 100644 --- a/pp/go/relabeler/manager.go +++ b/pp/go/relabeler/manager.go @@ -392,7 +392,7 @@ func (mgr *Manager) ObserveEncodersMemory(set func(id int, val float64)) { } } -// Open run senders and refill loops +// Open run senders and refill loops. func (mgr *Manager) Open(ctx context.Context) { mgr.senders = make([]*Sender, 0, len(mgr.dialers)*len(mgr.encoders)) for name, dialer := range mgr.dialers { @@ -676,7 +676,7 @@ func (mgr *Manager) writeSegmentToRefill(ctx context.Context, key cppbridge.Segm return mgr.refill.WriteSegment(ctx, key, segment) } -// DoNothingTicker - imitation of a ticker, but only one that does nothing +// DoNothingTicker - imitation of a ticker, but only one that does nothing. type DoNothingTicker struct { c chan time.Time } diff --git a/pp/go/relabeler/markup_file.go b/pp/go/relabeler/markup_file.go index b65cd9b82f..5aca309573 100644 --- a/pp/go/relabeler/markup_file.go +++ b/pp/go/relabeler/markup_file.go @@ -9,6 +9,7 @@ import ( "math" "github.com/google/uuid" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" ) @@ -276,8 +277,7 @@ func (mr *MarkupReader) readFull(ctx context.Context) error { } } -// checkRestoredServiceData - check restored service data(title, destinations names), -// these data are required to be restored, without them you cant read the rest +// these data are required to be restored, without them you cant read the rest. func (mr *MarkupReader) checkRestoredServiceData() bool { return mr.m.title != nil && mr.m.ackStatus != nil } diff --git a/pp/go/relabeler/models.go b/pp/go/relabeler/models.go index c1ceca2c52..13e72aa0f3 100644 --- a/pp/go/relabeler/models.go +++ b/pp/go/relabeler/models.go @@ -8,6 +8,7 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/model" @@ -28,7 +29,7 @@ const ( DefaultBlockSizePercentThresholdForDownscaling = 10 // DefaultDelayAfterNotify - default delay after notify reject. DefaultDelayAfterNotify = 300 * time.Second - // magic byte for header + // magic byte for header. magicByte byte = 189 // AlwaysToRefill - specific value for ManagerKeeperConfig.UncommittedTimeWindow parameter for scenario // when all data should always be written to the refill. @@ -75,7 +76,7 @@ func DefaultLimits() *Limits { } } -// OpenHeadLimits configure how long encoder should accumulate data for one segment +// OpenHeadLimits configure how long encoder should accumulate data for one segment. type OpenHeadLimits struct { MaxDuration time.Duration `validate:"required"` LastAddTimeout time.Duration `validate:"required"` @@ -178,7 +179,7 @@ func (l *BlockLimits) UnmarshalBinary(data []byte) error { return nil } -// Segment is an universal interface for blob segment data +// Segment is an universal interface for blob segment data. type Segment interface { frames.WritePayload } @@ -202,7 +203,7 @@ type SendPromise struct { var _ Promise = (*SendPromise)(nil) -// NewSendPromise is a constructor +// NewSendPromise is a constructor. func NewSendPromise(shardsNumber int) *SendPromise { return &SendPromise{ done: make(chan struct{}), @@ -211,14 +212,14 @@ func NewSendPromise(shardsNumber int) *SendPromise { } } -// Ack marks that one of shards has been ack +// Ack marks that one of shards has been ack. func (promise *SendPromise) Ack() { if atomic.AddInt32(&promise.counter, -1) == 0 { close(promise.done) } } -// Refill marks that one of shards has been refill +// Refill marks that one of shards has been refill. func (promise *SendPromise) Refill() { atomic.AddInt32(&promise.refills, 1) counter := atomic.AddInt32(&promise.counter, -1) @@ -275,7 +276,7 @@ var limitsCause = map[uint8]string{ timeoutLimit: "timeout_limit", } -// OpenHeadPromise is a SendPromise wrapper to combine several Sends in one segment +// OpenHeadPromise is a SendPromise wrapper to combine several Sends in one segment. type OpenHeadPromise struct { *SendPromise done chan struct{} @@ -289,7 +290,7 @@ type OpenHeadPromise struct { var _ Promise = (*OpenHeadPromise)(nil) -// NewOpenHeadPromise is a constructor +// NewOpenHeadPromise is a constructor. func NewOpenHeadPromise( shards int, limits OpenHeadLimits, @@ -365,7 +366,7 @@ func (promise *OpenHeadPromise) Add(segmentStats []cppbridge.SegmentStats) (limi return noLimit, func() {} } -// Finalized wait until Close method call +// Finalized wait until Close method call. func (promise *OpenHeadPromise) Finalized() <-chan struct{} { return promise.done } diff --git a/pp/go/relabeler/refill.go b/pp/go/relabeler/refill.go index 4f83211ef5..8e1a9f67e4 100644 --- a/pp/go/relabeler/refill.go +++ b/pp/go/relabeler/refill.go @@ -9,8 +9,9 @@ import ( "time" "github.com/google/uuid" - "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/prometheus/pp/go/cppbridge" ) const ( diff --git a/pp/go/relabeler/refill_sender.go b/pp/go/relabeler/refill_sender.go index c2b97902e8..6b4f0bd76b 100644 --- a/pp/go/relabeler/refill_sender.go +++ b/pp/go/relabeler/refill_sender.go @@ -661,7 +661,7 @@ func (sm *SendMap) Append(dname string, shardID uint16, segmentID uint32) { sm.m[dname][shardID] = append(list, segmentID) } -// Remove destination-shard data +// Remove destination-shard data. func (sm *SendMap) Remove(dname string, shardID uint16) { sm.m[dname][shardID] = nil } diff --git a/pp/go/relabeler/sender.go b/pp/go/relabeler/sender.go index 489eb48e75..fdaa64ef45 100644 --- a/pp/go/relabeler/sender.go +++ b/pp/go/relabeler/sender.go @@ -23,14 +23,14 @@ const ( defaultRTT = 120 * time.Second ) -// Source is a manager +// Source is a manager. type Source interface { Get(ctx context.Context, key cppbridge.SegmentKey) (Segment, error) Ack(key cppbridge.SegmentKey, dest string) Reject(key cppbridge.SegmentKey, dest string) } -// Sender is a transport adapter for manager +// Sender is a transport adapter for manager. type Sender struct { done chan struct{} dialer Dialer @@ -47,7 +47,7 @@ type Sender struct { responsedSegment *prometheus.GaugeVec } -// NewSender is a constructor +// NewSender is a constructor. func NewSender( ctx context.Context, blockID uuid.UUID, @@ -106,12 +106,12 @@ func NewSender( return sender } -// String implements fmt.Stringer interface +// String implements fmt.Stringer interface. func (sender *Sender) String() string { return sender.dialer.String() } -// Shutdown await while write receive ErrPromiseCanceled and then ack on last sent +// Shutdown await while write receive ErrPromiseCanceled and then ack on last sent. func (sender *Sender) Shutdown(ctx context.Context) error { sender.cancelCause(ErrShutdown) @@ -164,7 +164,7 @@ func (sender *Sender) getSegment(ctx context.Context, id uint32) (Segment, error } return segment, err }, bo) - if err != nil && err == ctx.Err() { + if err != nil && errors.Is(err, ctx.Err()) { err = context.Cause(ctx) } return segment, err diff --git a/pp/go/relabeler/storage_manager.go b/pp/go/relabeler/storage_manager.go index c6a6944dad..b8ed9b985c 100644 --- a/pp/go/relabeler/storage_manager.go +++ b/pp/go/relabeler/storage_manager.go @@ -11,6 +11,7 @@ import ( "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" @@ -430,7 +431,7 @@ func (sm *StorageManager) FileExist() (bool, error) { return sm.storage.FileExist() } -// Rename file +// Rename file. func (sm *StorageManager) Rename(name string) error { return sm.storage.Rename(name) } @@ -440,7 +441,7 @@ func (sm *StorageManager) IntermediateRename(name string) error { return sm.storage.IntermediateRename(name) } -// GetIntermediateName returns true with file name if file was intermediate renamed +// GetIntermediateName returns true with file name if file was intermediate renamed. func (sm *StorageManager) GetIntermediateName() (string, bool) { return sm.storage.GetIntermediateName() } @@ -532,7 +533,7 @@ func (rjs *Rejects) Add(nameID, segment uint32, shardID uint16) { ) } -// AckStatus keeps destinations list with last acked segments numbers per shard +// AckStatus keeps destinations list with last acked segments numbers per shard. type AckStatus struct { names *frames.DestinationsNames status frames.Statuses @@ -540,7 +541,7 @@ type AckStatus struct { rwmx *sync.RWMutex } -// NewAckStatus is a constructor +// NewAckStatus is a constructor. func NewAckStatus(destinations []string, shardsNumberPower uint8) *AckStatus { dn := frames.NewDestinationsNames(destinations...) shardsNumber := 1 << shardsNumberPower @@ -590,12 +591,12 @@ func NewAckStatusWithDNames(dnames *frames.DestinationsNames, shardsNumberPower } } -// Destinations returns number of destinations +// Destinations returns number of destinations. func (as *AckStatus) Destinations() int { return as.names.Len() } -// Shards returns number of shards +// Shards returns number of shards. func (as *AckStatus) Shards() int { if as.names.Len() == 0 { // The probability is extremely low. return 0 @@ -604,7 +605,7 @@ func (as *AckStatus) Shards() int { return len(as.status) / as.names.Len() } -// Ack increment status by destination and shard if segment is next for current value +// Ack increment status by destination and shard if segment is next for current value. func (as *AckStatus) Ack(key cppbridge.SegmentKey, dest string) { id := as.names.StringToID(dest) if id == frames.NotFoundName { @@ -644,7 +645,7 @@ func (as *AckStatus) Reject(segKey cppbridge.SegmentKey, dest string) { as.rwmx.RUnlock() } -// Index returns destination index by name +// Index returns destination index by name. func (as *AckStatus) Index(dest string) (int, bool) { id := as.names.StringToID(dest) if id == frames.NotFoundName { @@ -654,7 +655,7 @@ func (as *AckStatus) Index(dest string) (int, bool) { return int(id), true } -// Last return last ack segment by shard and destination +// Last return last ack segment by shard and destination. func (as *AckStatus) Last(shardID uint16, dest string) uint32 { id := as.names.StringToID(dest) if id == frames.NotFoundName { @@ -664,7 +665,7 @@ func (as *AckStatus) Last(shardID uint16, dest string) uint32 { return atomic.LoadUint32(&as.status[id*int32(as.Shards())+int32(shardID)]) } -// IsAck returns true if segment ack by all destinations +// IsAck returns true if segment ack by all destinations. func (as *AckStatus) IsAck(key cppbridge.SegmentKey) bool { for id := 0; id < as.Destinations(); id++ { if atomic.LoadUint32(&as.status[id*as.Shards()+int(key.ShardID)])+1 <= key.Segment { diff --git a/pp/go/relabeler/task.go b/pp/go/relabeler/task.go index dcca0a0410..285f4d0b36 100644 --- a/pp/go/relabeler/task.go +++ b/pp/go/relabeler/task.go @@ -67,7 +67,7 @@ func NewReadOnlyGenericTask(shardFn ShardFn) *GenericTask { return t } -// SetShardsNumber set shards number +// SetShardsNumber set shards number. func (t *GenericTask) SetShardsNumber(number uint16) { t.errs = make([]error, number) t.wg.Add(int(number)) diff --git a/pp/go/relabeler/transport.go b/pp/go/relabeler/transport.go index 8788b585d5..8c16a2eb96 100644 --- a/pp/go/relabeler/transport.go +++ b/pp/go/relabeler/transport.go @@ -17,10 +17,11 @@ import ( "github.com/google/uuid" "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "golang.org/x/net/websocket" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/transport" "github.com/prometheus/prometheus/pp/go/util" - "golang.org/x/net/websocket" ) // Dialer used for connect to backend @@ -39,11 +40,7 @@ type Dialer interface { ConnDialer() ConnDialer } -// Transport is a destination connection interface -// -// We suppose that Transport is full-initiated: -// - authorized -// - setted timeouts +// Transport sends frames to a remote endpoint using configured timeouts. type Transport interface { Send(context.Context, frames.FrameWriter) error Listen(ctx context.Context) @@ -158,7 +155,7 @@ type backoffWithLock struct { bo backoff.BackOff } -// BackoffWithLock wraps backoff with mutex to concurrent free use +// BackoffWithLock wraps backoff with mutex to concurrent free use. func BackoffWithLock(bo backoff.BackOff) backoff.BackOff { return backoffWithLock{ m: new(sync.Mutex), @@ -246,7 +243,7 @@ func (b *startWithBackOff) Reset() { b.delegate.Reset() } -// defaultTimer implements Timer interface using time.Timer +// defaultTimer implements Timer interface using time.Timer. type defaultTimer struct { timer *time.Timer } @@ -256,7 +253,7 @@ func (t *defaultTimer) C() <-chan time.Time { return t.timer.C } -// Start starts the timer to fire after the given duration +// Start starts the timer to fire after the given duration. func (t *defaultTimer) Start(duration time.Duration) { if t.timer == nil { t.timer = time.NewTimer(duration) @@ -373,7 +370,7 @@ func (d *WebSocketDialer) SendRefill(ctx context.Context, r io.Reader, shardMeta client := http.Client{ Transport: &http.Transport{ - DialTLSContext: func(dctx context.Context, _ string, _ string) (net.Conn, error) { + DialTLSContext: func(dctx context.Context, _, _ string) (net.Conn, error) { return d.connDialer.Dial(dctx) }, ForceAttemptHTTP2: true, @@ -440,7 +437,7 @@ func (*WebSocketDialer) makeHTTPError(res *http.Response) error { } } -// ResetBackoff resets next delay to zero +// ResetBackoff resets next delay to zero. func (d *WebSocketDialer) ResetBackoff() { d.backoff.Reset() } @@ -484,7 +481,7 @@ func NewWebSocketTransport( } } -// Send frame to server +// Send frame to server. func (tt *WebSocketTransport) Send(ctx context.Context, frame frames.FrameWriter) error { _, err := frame.WriteTo(tt.wt.Writer(ctx)) return err diff --git a/pp/go/server/transport.go b/pp/go/server/transport.go index c58dd04606..4e156882af 100644 --- a/pp/go/server/transport.go +++ b/pp/go/server/transport.go @@ -7,9 +7,10 @@ import ( "os" "path/filepath" - "github.com/prometheus/prometheus/prompb" "golang.org/x/net/websocket" + "github.com/prometheus/prometheus/prompb" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/transport" diff --git a/pp/go/server/transport_test.go b/pp/go/server/transport_test.go index 646d1c362c..164ea5e3be 100644 --- a/pp/go/server/transport_test.go +++ b/pp/go/server/transport_test.go @@ -87,7 +87,6 @@ func ExampleTCPReader() { } else { handleStream(ctx, msg, tcpReader) } - }(conn) } } diff --git a/pp/go/storage/appender/appender.go b/pp/go/storage/appender/appender.go index 1f435134c8..e822210220 100644 --- a/pp/go/storage/appender/appender.go +++ b/pp/go/storage/appender/appender.go @@ -61,8 +61,8 @@ type Shard interface { // WalWrite append the incoming inner series to wal encoder. WalWrite(innerSeriesSlice []cppbridge.InnerSeries) (bool, error) - // DstSrcLsIdsMapping return ids mapping after lss copying - DstSrcLsIdsMapping() *cppbridge.IdsMapping + // DstSrcLsIDsMapping return ids mapping after lss copying + DstSrcLsIDsMapping() *cppbridge.IdsMapping } // @@ -373,7 +373,7 @@ func (a *Appender[TTask, TShard, TGShard, THead]) updateRelabelerStateStage( return nil } -// trackStaleNans add stale nans samples if needed +// trackStaleNans add stale nans samples if needed. func (a *Appender[TTask, TShard, TGShard, THead]) trackStaleNans( shardInnerSeries *cppbridge.ShardedInnerSeries, state *cppbridge.StateV2, @@ -434,7 +434,7 @@ func (a *Appender[TTask, TShard, TGShard, THead]) resolveState(state *cppbridge. state.Reconfigure(a.head.Generation(), a.head.NumberOfShards(), func(maps []*cppbridge.IdsMapping) { for id, shard := range a.head.Shards() { - maps[id] = shard.DstSrcLsIdsMapping() + maps[id] = shard.DstSrcLsIDsMapping() } }) diff --git a/pp/go/storage/appender/appender_bench_test.go b/pp/go/storage/appender/appender_bench_test.go index a70fb6eda7..13746ec04e 100644 --- a/pp/go/storage/appender/appender_bench_test.go +++ b/pp/go/storage/appender/appender_bench_test.go @@ -114,7 +114,7 @@ func BenchmarkAppenderAppend(b *testing.B) { } } -// services.CFViaRange +// services.CFViaRange. func commitAndFlush(*benchHead) error { return nil } diff --git a/pp/go/storage/appender/appender_test.go b/pp/go/storage/appender/appender_test.go index fe1ace831f..534dd5c160 100644 --- a/pp/go/storage/appender/appender_test.go +++ b/pp/go/storage/appender/appender_test.go @@ -10,6 +10,8 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" "github.com/prometheus/prometheus/pp/go/storage" @@ -19,7 +21,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/shard" "github.com/prometheus/prometheus/pp/go/storage/head/task" "github.com/prometheus/prometheus/pp/go/storage/storagetest" - "github.com/stretchr/testify/suite" ) const ( @@ -153,7 +154,7 @@ func (s *AppenderSuite) TestDropInvalidSeries() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 0, SeriesAdded: 0, SeriesDrop: 1}, stats) } @@ -180,7 +181,7 @@ func (s *AppenderSuite) TestAppendMultipleSamplesInOneSeries() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 2, SeriesAdded: 1, SeriesDrop: 0}, stats) data := s.getHeadData([]uint32{0}) @@ -228,7 +229,7 @@ func (s *AppenderSuite) TestSeriesPerShardTransfer() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 2, SeriesAdded: 2, SeriesDrop: 0}, stats) data := s.getHeadData([]uint32{0}) @@ -286,7 +287,7 @@ func (s *AppenderSuite) TestShardedRelabeledSeriesFullNotEmpty() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 4, SeriesAdded: 4, SeriesDrop: 0}, stats) data := s.getHeadData([]uint32{0, 1, 2, 3}) @@ -345,7 +346,7 @@ func (s *AppenderSuite) TestTrackStaleness() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 2, SeriesAdded: 1, SeriesDrop: 0}, stats) data := s.getHeadData([]uint32{0}) @@ -392,7 +393,7 @@ func (s *AppenderSuite) TestTrackStalenessWithoutHonorTimestamps() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(cppbridge.RelabelerStats{SamplesAdded: 2, SeriesAdded: 1, SeriesDrop: 0}, stats) data := s.getHeadData([]uint32{0}) @@ -430,7 +431,7 @@ func (s *AppenderSuite) TestWithoutCommitToWal() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(0, s.walCommitCount) } @@ -452,7 +453,7 @@ func (s *AppenderSuite) TestWithCommitToWal() { true) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(1, s.walCommitCount) } @@ -484,11 +485,11 @@ func (s *AppenderSuite) TestWithCommitToWalByLimitExhausted() { false) // Assert - s.NoError(err) + s.Require().NoError(err) s.Equal(1, s.walCommitCount) } -/*func (s *AppenderSuite) TestUseRelabelerCache() { +/* func (s *AppenderSuite) TestUseRelabelerCache() { // Arrange state := s.createState([]*cppbridge.RelabelConfig{}) @@ -518,5 +519,5 @@ func (s *AppenderSuite) TestWithCommitToWalByLimitExhausted() { false) // Assert - s.NoError(err) + s.Require().NoError(err) }*/ diff --git a/pp/go/storage/block/block.go b/pp/go/storage/block/block.go index a5855bf5ee..caf73d2d4f 100644 --- a/pp/go/storage/block/block.go +++ b/pp/go/storage/block/block.go @@ -54,12 +54,12 @@ type ChunkIterator struct { // NewChunkIterator init new [ChunkIterator]. func NewChunkIterator( lss *cppbridge.LabelSetStorage, - lsIdBatchSize uint32, + lsIDBatchSize uint32, ds *cppbridge.DataStorage, minT, maxT int64, ) ChunkIterator { return ChunkIterator{ - r: cppbridge.NewChunkRecoder(lss, lsIdBatchSize, ds, cppbridge.TimeInterval{MinT: minT, MaxT: maxT}), + r: cppbridge.NewChunkRecoder(lss, lsIDBatchSize, ds, cppbridge.TimeInterval{MinT: minT, MaxT: maxT}), hasMoreData: true, } } diff --git a/pp/go/storage/block/block_writer.go b/pp/go/storage/block/block_writer.go index 4e41fcf256..412ec14574 100644 --- a/pp/go/storage/block/block_writer.go +++ b/pp/go/storage/block/block_writer.go @@ -191,7 +191,6 @@ type blockWriters []blockWriter // append appends a writer to the block writers. -//nolint:gocritic // hugeParam // we accumulate the writers func (bw *blockWriters) append(writer blockWriter) { *bw = append(*bw, writer) } diff --git a/pp/go/storage/block/compactor.go b/pp/go/storage/block/compactor.go index fae30ee015..cec768b1e1 100644 --- a/pp/go/storage/block/compactor.go +++ b/pp/go/storage/block/compactor.go @@ -32,6 +32,8 @@ type CompactorOptions struct { // BlockSource provides the compactor with the currently loaded blocks. // It is implemented by Manager. +// +//nolint:revive // BlockSource is intentionally descriptive despite the block package prefix. type BlockSource interface { // Blocks returns a snapshot of the currently loaded blocks (the open // argument for Compact). diff --git a/pp/go/storage/block/compactor_test.go b/pp/go/storage/block/compactor_test.go index abd939c9a0..3a3da10ad6 100644 --- a/pp/go/storage/block/compactor_test.go +++ b/pp/go/storage/block/compactor_test.go @@ -7,8 +7,9 @@ import ( "time" "github.com/oklog/ulid" - "github.com/prometheus/prometheus/tsdb" "github.com/stretchr/testify/require" + + "github.com/prometheus/prometheus/tsdb" ) func TestCompactorCompactBlocksUsesPlanAndSource(t *testing.T) { diff --git a/pp/go/storage/block/manager_test.go b/pp/go/storage/block/manager_test.go index e329f25a48..99faeedf71 100644 --- a/pp/go/storage/block/manager_test.go +++ b/pp/go/storage/block/manager_test.go @@ -7,11 +7,12 @@ import ( "github.com/go-kit/log" "github.com/oklog/ulid" + "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb" "github.com/prometheus/prometheus/tsdb/chunks" - "github.com/stretchr/testify/require" ) func TestManagerLoadsExistingBlocksOnStartup(t *testing.T) { diff --git a/pp/go/storage/block/writer.go b/pp/go/storage/block/writer.go index b0b08b5d7b..bf7d4bdfe7 100644 --- a/pp/go/storage/block/writer.go +++ b/pp/go/storage/block/writer.go @@ -5,6 +5,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/logger" "github.com/prometheus/prometheus/pp/go/storage/head/shard" @@ -18,8 +19,8 @@ const ( DefaultBlockDuration = 2 * time.Hour ) -// LsIdBatchSize is the batch size for label set ID. -var LsIdBatchSize uint32 = 100000 +// LsIDBatchSize is the batch size for label set ID. +var LsIDBatchSize uint32 = 100000 // Shard the minimum required head [Shard] implementation. type Shard interface { @@ -66,8 +67,8 @@ func (w *Writer[TShard]) Write(sd TShard) (writtenBlocks []WrittenBlock, err err return err } defer func() { - if err := writers.Close(); err != nil { - logger.Warnf("Failed to close block writers: %v", err) + if closeErr := writers.Close(); closeErr != nil { + logger.Warnf("Failed to close block writers: %v", closeErr) } }() @@ -101,7 +102,7 @@ func (w *Writer[TShard]) createWriters(sd TShard) (blockWriters, error) { var chunkIterator ChunkIterator _ = sd.DataStorage().WithRLock(func(*cppbridge.DataStorage) error { - chunkIterator = NewChunkIterator(sd.LSS().Target(), LsIdBatchSize, sd.DataStorage().Raw(), minT, maxT) + chunkIterator = NewChunkIterator(sd.LSS().Target(), LsIDBatchSize, sd.DataStorage().Raw(), minT, maxT) return nil }) @@ -125,7 +126,7 @@ func (w *Writer[TShard]) createWriters(sd TShard) (blockWriters, error) { func (*Writer[TShard]) recodeAndWriteChunks(sd TShard, writers blockWriters) error { var loader *cppbridge.UnloadedDataRevertableLoader _ = sd.DataStorage().WithRLock(func(*cppbridge.DataStorage) error { - loader = sd.DataStorage().CreateRevertableLoader(sd.LSS().Target(), LsIdBatchSize) + loader = sd.DataStorage().CreateRevertableLoader(sd.LSS().Target(), LsIDBatchSize) return nil }) diff --git a/pp/go/storage/block/writer_test.go b/pp/go/storage/block/writer_test.go index ce1a070921..a67aacbca8 100644 --- a/pp/go/storage/block/writer_test.go +++ b/pp/go/storage/block/writer_test.go @@ -236,7 +236,7 @@ func (s *WriterSuite) TestWrite() { s.fillHead() // Act - block.LsIdBatchSize = 2 + block.LsIDBatchSize = 2 blocks, err := s.blockWriter.Write(s.shard()) // Assert @@ -248,7 +248,7 @@ func (s *WriterSuite) TestWriteInBatches() { s.fillHead() // Act - block.LsIdBatchSize = 1 + block.LsIDBatchSize = 1 blocks, err := s.blockWriter.Write(s.shard()) // Assert @@ -261,7 +261,7 @@ func (s *WriterSuite) TestWriteWithDataUnloading() { s.Require().NoError(services.UnloadUnusedSeriesDataWithHead(s.head)) // Act - block.LsIdBatchSize = 2 + block.LsIDBatchSize = 2 blocks, err := s.blockWriter.Write(s.shard()) // Assert @@ -274,7 +274,7 @@ func (s *WriterSuite) TestWriteWithDataUnloadingInBatches() { s.Require().NoError(services.UnloadUnusedSeriesDataWithHead(s.head)) // Act - block.LsIdBatchSize = 1 + block.LsIDBatchSize = 1 blocks, err := s.blockWriter.Write(s.shard()) // Assert diff --git a/pp/go/storage/builder.go b/pp/go/storage/builder.go index e211c4a9e5..7e3227f6e8 100644 --- a/pp/go/storage/builder.go +++ b/pp/go/storage/builder.go @@ -8,6 +8,7 @@ import ( "time" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/logger" "github.com/prometheus/prometheus/pp/go/storage/catalog" diff --git a/pp/go/storage/catalog/catalog.go b/pp/go/storage/catalog/catalog.go index e5f5928036..3080aa6b7c 100644 --- a/pp/go/storage/catalog/catalog.go +++ b/pp/go/storage/catalog/catalog.go @@ -212,7 +212,7 @@ func (c *Catalog) List(filterFn func(record *Record) bool, sortLess func(lhs, rh return records } -// listWithFilter returns slice of filtered records +// listWithFilter returns slice of filtered records. func (c *Catalog) listWithFilter(filterFn func(record *Record) bool) []*Record { c.mtx.Lock() defer c.mtx.Unlock() diff --git a/pp/go/storage/catalog/gc.go b/pp/go/storage/catalog/gc.go index 0790ee86fd..ad979b25e0 100644 --- a/pp/go/storage/catalog/gc.go +++ b/pp/go/storage/catalog/gc.go @@ -7,6 +7,7 @@ import ( "time" "github.com/jonboulle/clockwork" + "github.com/prometheus/prometheus/pp/go/logger" ) diff --git a/pp/go/storage/catalog/log_file_handler.go b/pp/go/storage/catalog/log_file_handler.go index d111fb5130..81e1b9a08a 100644 --- a/pp/go/storage/catalog/log_file_handler.go +++ b/pp/go/storage/catalog/log_file_handler.go @@ -26,7 +26,7 @@ func NewFileHandler(filePath string) (*FileHandler, error) { // NewFileHandlerWithOpts init new [FileHandler] with opts. func NewFileHandlerWithOpts(filePath string, flag int, perm os.FileMode) (*FileHandler, error) { - file, err := os.OpenFile(filePath, flag, perm) //#nosec G304 // it's meant to be that way + file, err := os.OpenFile(filePath, flag, perm) //nolint:gosec // it's meant to be that way if err != nil { return nil, fmt.Errorf("open file: %w", err) } diff --git a/pp/go/storage/catalog/record.go b/pp/go/storage/catalog/record.go index 347a260899..6bcef6f10c 100644 --- a/pp/go/storage/catalog/record.go +++ b/pp/go/storage/catalog/record.go @@ -7,6 +7,7 @@ import ( "time" "github.com/google/uuid" + "github.com/prometheus/prometheus/pp/go/util/optional" ) diff --git a/pp/go/storage/head/container/weighted_test.go b/pp/go/storage/head/container/weighted_test.go index e216b856cd..ec98694f40 100644 --- a/pp/go/storage/head/container/weighted_test.go +++ b/pp/go/storage/head/container/weighted_test.go @@ -102,7 +102,7 @@ func (s *WeightedSuite) TestWithError() { cancel() synctest.Wait() - s.Error(err) + s.Require().Error(err) s.Require().ErrorIs(err, context.Canceled) }) } diff --git a/pp/go/storage/head/head/head.go b/pp/go/storage/head/head/head.go index dbadb80ce5..5f516a25bc 100644 --- a/pp/go/storage/head/head/head.go +++ b/pp/go/storage/head/head/head.go @@ -66,8 +66,6 @@ type Head[TShard Shard, TGShard Shard] struct { // for tasks metrics tasksCreated *prometheus.CounterVec tasksDone *prometheus.CounterVec - tasksLive *prometheus.CounterVec - tasksExecute *prometheus.CounterVec // pools for reusable objects headPool *poolprovider.HeadPool[TGShard] @@ -76,7 +74,7 @@ type Head[TShard Shard, TGShard Shard] struct { // NewHead init new [Head]. // //revive:disable-next-line:function-length long but readable. -func NewHead[TShard Shard, TGShard Shard]( +func NewHead[TShard, TGShard Shard]( id string, shards []TShard, gshardCtor func(TShard, uint16) TGShard, @@ -316,7 +314,7 @@ func calculateHeadConcurrency(numberOfShards int) int64 { // // CopyAddedSeries copy the label sets from the source lss to the destination lss that were added source lss. -func CopyAddedSeries[TShard Shard, TGShard Shard]( +func CopyAddedSeries[TShard, TGShard Shard]( shardCopier func(source, destination TShard), ) func(source, destination *Head[TShard, TGShard]) { return func(source, destination *Head[TShard, TGShard]) { diff --git a/pp/go/storage/head/services/functions.go b/pp/go/storage/head/services/functions.go index 70fa9800ea..7e4b53ebc0 100644 --- a/pp/go/storage/head/services/functions.go +++ b/pp/go/storage/head/services/functions.go @@ -9,7 +9,7 @@ const ( // dsMergeOutOfOrderChunks name of task. dsMergeOutOfOrderChunks = "data_storage_merge_out_of_order_chunks" - // dsUnloadUnusedSeriesData name of task + // dsUnloadUnusedSeriesData name of task. dsUnloadUnusedSeriesData = "data_storage_unload_unused_series_data" ) diff --git a/pp/go/storage/head/services/merger_test.go b/pp/go/storage/head/services/merger_test.go index 3c5131a52a..3204e9d255 100644 --- a/pp/go/storage/head/services/merger_test.go +++ b/pp/go/storage/head/services/merger_test.go @@ -4,6 +4,8 @@ import ( "context" "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" "github.com/prometheus/prometheus/pp/go/storage/head/container" @@ -12,7 +14,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/services/mock" "github.com/prometheus/prometheus/pp/go/storage/head/shard" "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal" - "github.com/stretchr/testify/suite" ) type MergerSuite struct { diff --git a/pp/go/storage/head/services/persistener_test.go b/pp/go/storage/head/services/persistener_test.go index a1fc2b1d1e..fbb4b46984 100644 --- a/pp/go/storage/head/services/persistener_test.go +++ b/pp/go/storage/head/services/persistener_test.go @@ -9,6 +9,8 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" @@ -21,7 +23,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/shard" "github.com/prometheus/prometheus/pp/go/storage/head/task" "github.com/prometheus/prometheus/pp/go/storage/storagetest" - "github.com/stretchr/testify/suite" ) const ( diff --git a/pp/go/storage/head/shard/data_storage.go b/pp/go/storage/head/shard/data_storage.go index 8941bf5ef1..db11e29bcc 100644 --- a/pp/go/storage/head/shard/data_storage.go +++ b/pp/go/storage/head/shard/data_storage.go @@ -43,7 +43,7 @@ func (ds *DataStorage) AppendInnerSeriesSlice(innerSeriesSlice []cppbridge.Inner // and add to encoder [cppbridge.HeadEncoder], returns createTs, encodeTs. // //revive:disable-next-line:confusing-results // returns createTs, encodeTs -//nolint:gocritic // returns createTs, encodeTs + func (ds *DataStorage) DecodeSegment(decoder *cppbridge.HeadWalDecoder, data []byte) (int64, int64, error) { return decoder.DecodeToDataStorage(data, ds.encoder) } @@ -133,22 +133,22 @@ func (ds *DataStorage) TimeInterval(invalidateCache bool) cppbridge.TimeInterval return result } -// CreateUnusedSeriesDataUnloader create unused series data unloader +// CreateUnusedSeriesDataUnloader create unused series data unloader. func (ds *DataStorage) CreateUnusedSeriesDataUnloader() *cppbridge.UnusedSeriesDataUnloader { return ds.dataStorage.CreateUnusedSeriesDataUnloader() } -// CreateLoader create series data unloader +// CreateLoader create series data unloader. func (ds *DataStorage) CreateLoader(queriers []uintptr) *cppbridge.UnloadedDataLoader { return ds.dataStorage.CreateLoader(queriers) } -// CreateRevertableLoader create series data revertable unloader +// CreateRevertableLoader create series data revertable unloader. func (ds *DataStorage) CreateRevertableLoader( lss *cppbridge.LabelSetStorage, - lsIdBatchSize uint32, + lsIDBatchSize uint32, ) *cppbridge.UnloadedDataRevertableLoader { - return ds.dataStorage.CreateRevertableLoader(lss, lsIdBatchSize) + return ds.dataStorage.CreateRevertableLoader(lss, lsIDBatchSize) } // GetQueriedSeriesBitset gets the queried series bitset memory. diff --git a/pp/go/storage/head/shard/lss.go b/pp/go/storage/head/shard/lss.go index 5b77375bc0..fde887254c 100644 --- a/pp/go/storage/head/shard/lss.go +++ b/pp/go/storage/head/shard/lss.go @@ -15,8 +15,8 @@ type LSS struct { target *cppbridge.LabelSetStorage snapshot *cppbridge.LabelSetSnapshot // writes are unlocked because these fields are read only after rotation completes (no concurrent readers). - dstSrcLsIdsMapping *cppbridge.IdsMapping - newToOldLsIdsMapping *cppbridge.IdsMapping + dstSrcLsIDsMapping *cppbridge.IdsMapping + newToOldLsIDsMapping *cppbridge.IdsMapping mappedSnapshot *cppbridge.LabelSetSnapshot locker sync.RWMutex once sync.Once @@ -46,19 +46,19 @@ func (l *LSS) CopyAddedSeriesTo(destination *LSS) { bitsetSeries := l.target.BitsetSeries() l.locker.RUnlock() - // The post-copy writes to destination.dstSrcLsIdsMapping, l.mappedSnapshot - // and l.newToOldLsIdsMapping are performed without holding any locker: it is + // The post-copy writes to destination.dstSrcLsIDsMapping, l.mappedSnapshot + // and l.newToOldLsIDsMapping are performed without holding any locker: it is // safe because these fields are read only after the rotation completes (by - // [LSS.FinalizeCopyAndShrink] and [Shard.DstSrcLsIdsMapping] from the + // [LSS.FinalizeCopyAndShrink] and [Shard.DstSrcLsIDsMapping] from the // post-rotation path). - destination.dstSrcLsIdsMapping = snapshot.CopyAddedSeries(bitsetSeries, destination.target) + destination.dstSrcLsIDsMapping = snapshot.CopyAddedSeries(bitsetSeries, destination.target) } // FinalizeCopyAndShrink finalize copy and shrink the lss. func (l *LSS) FinalizeCopyAndShrink() { l.locker.Lock() - l.target.FinalizeCopyAndShrink(l.mappedSnapshot, l.newToOldLsIdsMapping) - l.newToOldLsIdsMapping = nil + l.target.FinalizeCopyAndShrink(l.mappedSnapshot, l.newToOldLsIDsMapping) + l.newToOldLsIDsMapping = nil l.ResetSnapshot() l.locker.Unlock() } @@ -71,14 +71,14 @@ func (l *LSS) FreezeAndCopyAddedSeries(destination *LSS, shrinkBoundary uint32) l.target.SetPendingShrinkBoundary(shrinkBoundary) l.locker.Unlock() - // The post-copy writes to destination.dstSrcLsIdsMapping, l.mappedSnapshot - // and l.newToOldLsIdsMapping are performed without holding any locker: it is + // The post-copy writes to destination.dstSrcLsIDsMapping, l.mappedSnapshot + // and l.newToOldLsIDsMapping are performed without holding any locker: it is // safe because these fields are read only after the rotation completes (by - // [LSS.FinalizeCopyAndShrink] and [Shard.DstSrcLsIdsMapping] from the + // [LSS.FinalizeCopyAndShrink] and [Shard.DstSrcLsIDsMapping] from the // post-rotation path). - destination.dstSrcLsIdsMapping = snapshot.CopyAddedSeries(bitsetSeries, destination.target) + destination.dstSrcLsIDsMapping = snapshot.CopyAddedSeries(bitsetSeries, destination.target) l.mappedSnapshot = destination.target.CreateLabelSetSnapshot() - l.newToOldLsIdsMapping = destination.dstSrcLsIdsMapping + l.newToOldLsIDsMapping = destination.dstSrcLsIDsMapping } // Input returns input lss. diff --git a/pp/go/storage/head/shard/shard.go b/pp/go/storage/head/shard/shard.go index ac8cdf71ed..4a6123d437 100644 --- a/pp/go/storage/head/shard/shard.go +++ b/pp/go/storage/head/shard/shard.go @@ -186,22 +186,22 @@ func (s *Shard) TimeInterval(invalidateCache bool) cppbridge.TimeInterval { return s.dataStorage.TimeInterval(invalidateCache) } -// UnloadedDataStorage get unloaded data storage +// UnloadedDataStorage get unloaded data storage. func (s *Shard) UnloadedDataStorage() *UnloadedDataStorage { return s.unloadedDataStorage } -// QueriedSeriesStorage get queried series storage +// QueriedSeriesStorage get queried series storage. func (s *Shard) QueriedSeriesStorage() *QueriedSeriesStorage { return s.queriedSeriesStorage } -// LoadAndQuerySeriesDataTask get load and query series data task +// LoadAndQuerySeriesDataTask get load and query series data task. func (s *Shard) LoadAndQuerySeriesDataTask() *LoadAndQuerySeriesDataTask { return s.loadAndQueryTask } -// UnloadUnusedSeriesData unload unused series data +// UnloadUnusedSeriesData unload unused series data. func (s *Shard) UnloadUnusedSeriesData() error { if s.UnloadedDataStorage() == nil { return nil @@ -218,7 +218,7 @@ func (s *Shard) UnloadUnusedSeriesData() error { header, err := s.UnloadedDataStorage().WriteSnapshot(snapshot) if err != nil { - return fmt.Errorf("unable to write unloaded series data snapshot: %v", err) + return fmt.Errorf("unable to write unloaded series data snapshot: %w", err) } _ = s.DataStorage().WithLock(func(*cppbridge.DataStorage) error { @@ -228,7 +228,7 @@ func (s *Shard) UnloadUnusedSeriesData() error { }) if err = s.QueriedSeriesStorage().Write(queriedSeries, time.Now().UnixMilli()); err != nil { - return fmt.Errorf("unable to write queried series data: %v", err) + return fmt.Errorf("unable to write queried series data: %w", err) } return nil @@ -253,10 +253,10 @@ func (s *Shard) LoadAndQuerySeriesData() (err error) { return nil } -// DstSrcLsIdsMapping return ids mapping after lss copying. +// DstSrcLsIDsMapping return ids mapping after lss copying. // Note: writes are unlocked because these fields are read only after rotation completes (no concurrent readers). -func (s *Shard) DstSrcLsIdsMapping() *cppbridge.IdsMapping { - return s.lss.dstSrcLsIdsMapping +func (s *Shard) DstSrcLsIDsMapping() *cppbridge.IdsMapping { + return s.lss.dstSrcLsIDsMapping } // diff --git a/pp/go/storage/head/shard/wal/reader/byte_reader.go b/pp/go/storage/head/shard/wal/reader/byte_reader.go index 1b308bd29d..b9a80addc7 100644 --- a/pp/go/storage/head/shard/wal/reader/byte_reader.go +++ b/pp/go/storage/head/shard/wal/reader/byte_reader.go @@ -9,7 +9,7 @@ type ByteReader struct { readBytes int // bytes read via ReadByte } -// NewByteReader init new [byteReader] +// NewByteReader init new [byteReader]. func NewByteReader(r io.Reader) *ByteReader { return &ByteReader{ r: r, diff --git a/pp/go/storage/head/shard/wal/wal.go b/pp/go/storage/head/shard/wal/wal.go index 2f83708fbd..3c5f26bba7 100644 --- a/pp/go/storage/head/shard/wal/wal.go +++ b/pp/go/storage/head/shard/wal/wal.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/util" "github.com/prometheus/prometheus/pp/go/util/locker" diff --git a/pp/go/storage/head/shard/wal/wal_reader_test.go b/pp/go/storage/head/shard/wal/wal_reader_test.go index 25a9588f8a..fd41314e5d 100644 --- a/pp/go/storage/head/shard/wal/wal_reader_test.go +++ b/pp/go/storage/head/shard/wal/wal_reader_test.go @@ -7,8 +7,9 @@ import ( "testing" "github.com/go-faker/faker/v4" - "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal" "github.com/stretchr/testify/suite" + + "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal" ) type SegmentWalReaderSuite struct { diff --git a/pp/go/storage/head/shard/wal/writer/notifier_test.go b/pp/go/storage/head/shard/wal/writer/notifier_test.go index 844b174ea9..d4f881005a 100644 --- a/pp/go/storage/head/shard/wal/writer/notifier_test.go +++ b/pp/go/storage/head/shard/wal/writer/notifier_test.go @@ -4,8 +4,9 @@ import ( "math" "testing" - "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer" "github.com/stretchr/testify/suite" + + "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer" ) type SegmentWriteNotifierSuite struct { diff --git a/pp/go/storage/head/task/task.go b/pp/go/storage/head/task/task.go index ab4b5b4483..b76525d0e3 100644 --- a/pp/go/storage/head/task/task.go +++ b/pp/go/storage/head/task/task.go @@ -73,7 +73,7 @@ func NewTransactionGeneric[TShard Shard](shardFn func(shard TShard) error) *Gene return t } -// SetShardsNumber set shards number +// SetShardsNumber set shards number. func (t *Generic[TShard]) SetShardsNumber(number uint16) { t.wg.Add(int(number)) } diff --git a/pp/go/storage/head/task/waiter_test.go b/pp/go/storage/head/task/waiter_test.go index d352f6377e..2a3f8c0754 100644 --- a/pp/go/storage/head/task/waiter_test.go +++ b/pp/go/storage/head/task/waiter_test.go @@ -3,8 +3,9 @@ package task_test import ( "testing" - "github.com/prometheus/prometheus/pp/go/storage/head/task" "github.com/stretchr/testify/require" + + "github.com/prometheus/prometheus/pp/go/storage/head/task" ) func TestTaskWaiter(t *testing.T) { diff --git a/pp/go/storage/head/transactionhead/head.go b/pp/go/storage/head/transactionhead/head.go index e0d9f7aa87..172201a514 100644 --- a/pp/go/storage/head/transactionhead/head.go +++ b/pp/go/storage/head/transactionhead/head.go @@ -41,7 +41,7 @@ type Head[TShard Shard, TGShard Shard] struct { } // NewHead init new [Head]. -func NewHead[TShard Shard, TGShard Shard]( +func NewHead[TShard, TGShard Shard]( id string, shard TShard, gshard TGShard, diff --git a/pp/go/storage/loader.go b/pp/go/storage/loader.go index c59ab41021..d949dc5961 100644 --- a/pp/go/storage/loader.go +++ b/pp/go/storage/loader.go @@ -147,8 +147,8 @@ func (l *Loader) loadHead( return h, err } -// EnsureSameErrorTypes checks if err contains targetErr - we ensure that all errors in chain would be targetErr, -// otherwise return all errors in chain except targetErr +// EnsureSameErrorTypes returns targetErr if every error in errs matches it, +// otherwise returns all errors in the chain except targetErr. func EnsureSameErrorTypes(errs []error, targetErr error) error { if len(errs) == 0 { return nil diff --git a/pp/go/storage/loader_test.go b/pp/go/storage/loader_test.go index 713a47474b..8c6628d376 100644 --- a/pp/go/storage/loader_test.go +++ b/pp/go/storage/loader_test.go @@ -12,6 +12,8 @@ import ( "github.com/google/uuid" "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" @@ -22,14 +24,13 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer" "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) type idGeneratorStub struct { uuid uuid.UUID } -func newIdGeneratorStub() *idGeneratorStub { +func newIDGeneratorStub() *idGeneratorStub { return &idGeneratorStub{ uuid: uuid.New(), } @@ -47,7 +48,7 @@ type HeadLoadSuite struct { suite.Suite dataDir string clock clockwork.Clock - headIdGenerator *idGeneratorStub + headIDGenerator *idGeneratorStub catalog *catalog.Catalog } @@ -61,18 +62,18 @@ func (s *HeadLoadSuite) SetupTest() { s.dataDir = dataDir s.clock = clockwork.NewFakeClockAt(time.Now()) - s.headIdGenerator = newIdGeneratorStub() + s.headIDGenerator = newIDGeneratorStub() s.createCatalog() } func (s *HeadLoadSuite) createCatalog() { - ctlg, err := storagetest.CreateCatalog(s.clock, filepath.Join(s.dataDir, "catalog.log"), s.headIdGenerator) + ctlg, err := storagetest.CreateCatalog(s.clock, filepath.Join(s.dataDir, "catalog.log"), s.headIDGenerator) s.Require().NoError(err) s.catalog = ctlg } func (s *HeadLoadSuite) headDir() string { - return filepath.Join(s.dataDir, s.headIdGenerator.last()) + return filepath.Join(s.dataDir, s.headIDGenerator.last()) } func (s *HeadLoadSuite) createHead(unloadDataStorageInterval time.Duration) (*storage.Head, error) { @@ -112,7 +113,7 @@ func (s *HeadLoadSuite) mustCreateHead(unloadDataStorageInterval time.Duration) } func (s *HeadLoadSuite) loadHead(unloadDataStorageInterval time.Duration) (*storage.Head, error) { - record, err := s.catalog.Get(s.headIdGenerator.last()) + record, err := s.catalog.Get(s.headIDGenerator.last()) s.Require().NoError(err) return storage.NewLoader(s.dataDir, storagetest.MaxSegmentSize, prometheus.DefaultRegisterer, unloadDataStorageInterval).Load(record, 0) diff --git a/pp/go/storage/manager_test.go b/pp/go/storage/manager_test.go index 90d0cfe23a..921748faf2 100644 --- a/pp/go/storage/manager_test.go +++ b/pp/go/storage/manager_test.go @@ -9,6 +9,8 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" "github.com/prometheus/prometheus/pp/go/storage/block" @@ -16,7 +18,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal" "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer" "github.com/prometheus/prometheus/pp/go/storage/storagetest" - "github.com/stretchr/testify/suite" ) var defaultSortCatalogRecordsFunc = func(lhs, rhs *catalog.Record) bool { @@ -27,7 +28,7 @@ type UploadOrBuildHeadSuite struct { suite.Suite dataDir string clock *clockwork.FakeClock - headIdGenerator catalog.IDGenerator + headIDGenerator catalog.IDGenerator catalog *catalog.Catalog builder *storage.Builder loader *storage.Loader @@ -43,7 +44,7 @@ func (s *UploadOrBuildHeadSuite) SetupTest() { s.dataDir = dataDir s.clock = clockwork.NewFakeClockAt(time.Now()) - s.headIdGenerator = catalog.DefaultIDGenerator{} + s.headIDGenerator = catalog.DefaultIDGenerator{} s.createCatalog() s.createBuilder() s.createLoader() @@ -51,7 +52,7 @@ func (s *UploadOrBuildHeadSuite) SetupTest() { func (s *UploadOrBuildHeadSuite) createCatalog() { var err error - s.catalog, err = storagetest.CreateCatalog(s.clock, filepath.Join(s.dataDir, "catalog.log"), s.headIdGenerator) + s.catalog, err = storagetest.CreateCatalog(s.clock, filepath.Join(s.dataDir, "catalog.log"), s.headIDGenerator) s.Require().NoError(err) } diff --git a/pp/go/storage/mediator/mediator_test.go b/pp/go/storage/mediator/mediator_test.go index d94ce2112e..09fd38564d 100644 --- a/pp/go/storage/mediator/mediator_test.go +++ b/pp/go/storage/mediator/mediator_test.go @@ -1,13 +1,15 @@ package mediator_test import ( - "github.com/stretchr/testify/require" "testing" "testing/synctest" "time" - "github.com/prometheus/prometheus/pp/go/storage/mediator" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + + "github.com/prometheus/prometheus/pp/go/storage/mediator" ) type MediatorSuite struct { @@ -73,7 +75,6 @@ func (s *MediatorSuite) TestClose() { if ok { counter++ } - }() synctest.Wait() diff --git a/pp/go/storage/querier/instant_series.go b/pp/go/storage/querier/instant_series.go index 2f6413540c..526aa9dfe5 100644 --- a/pp/go/storage/querier/instant_series.go +++ b/pp/go/storage/querier/instant_series.go @@ -136,7 +136,7 @@ func NewInstantSeriesChunkIterator(t int64, v float64) *InstantSeriesChunkIterat // At returns the current timestamp/value pair if the value is a float. // -//nolint:gocritic // unnamedResult not need + func (i *InstantSeriesChunkIterator) At() (int64, float64) { return i.t, i.v } diff --git a/pp/go/storage/querier/load_and_query_waiter.go b/pp/go/storage/querier/load_and_query_waiter.go index 919cfc2fe6..b18943342d 100644 --- a/pp/go/storage/querier/load_and_query_waiter.go +++ b/pp/go/storage/querier/load_and_query_waiter.go @@ -8,7 +8,7 @@ import ( ) const ( - // dsLoadAndQuerySeriesData + // dsLoadAndQuerySeriesData. dsLoadAndQuerySeriesData = "data_storage_load_and_query_series_data" ) diff --git a/pp/go/storage/querier/merge_series_set_test.go b/pp/go/storage/querier/merge_series_set_test.go index 447de5e9b4..57b6447a71 100644 --- a/pp/go/storage/querier/merge_series_set_test.go +++ b/pp/go/storage/querier/merge_series_set_test.go @@ -4,6 +4,8 @@ import ( "fmt" "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" @@ -11,7 +13,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/querier" "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/prometheus/prometheus/storage" - "github.com/stretchr/testify/suite" ) // mergeSeriesSetMatrix is exercised for happy-path, empty-set, and across-shard order scenarios. diff --git a/pp/go/storage/querier/metrics.go b/pp/go/storage/querier/metrics.go index 71e968890a..0fc79d32eb 100644 --- a/pp/go/storage/querier/metrics.go +++ b/pp/go/storage/querier/metrics.go @@ -2,6 +2,7 @@ package querier import ( "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/pp/go/util" ) diff --git a/pp/go/storage/querier/querier.go b/pp/go/storage/querier/querier.go index aa8979d2eb..1c41656e5e 100644 --- a/pp/go/storage/querier/querier.go +++ b/pp/go/storage/querier/querier.go @@ -9,6 +9,7 @@ import ( "unsafe" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/logger" diff --git a/pp/go/storage/querier/querier_test.go b/pp/go/storage/querier/querier_test.go index b45da5872e..a8df20d814 100644 --- a/pp/go/storage/querier/querier_test.go +++ b/pp/go/storage/querier/querier_test.go @@ -9,6 +9,8 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" @@ -19,7 +21,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/querier" "github.com/prometheus/prometheus/pp/go/storage/storagetest" prom_storage "github.com/prometheus/prometheus/storage" - "github.com/stretchr/testify/suite" ) const ( diff --git a/pp/go/storage/querier/series.go b/pp/go/storage/querier/series.go index 33e7efd390..ca0af7b337 100644 --- a/pp/go/storage/querier/series.go +++ b/pp/go/storage/querier/series.go @@ -59,7 +59,7 @@ func (it *ChunkIterator) Reset(serializedData *cppbridge.DataStorageSerializedDa // At returns the current timestamp/value pair if the value is a float. // -//nolint:gocritic // unnamedResult not need + func (it *ChunkIterator) At() (int64, float64) { return it.chunkIterator.Timestamp, it.chunkIterator.Value } @@ -173,8 +173,7 @@ type SeriesSet struct { labelSetSnapshot *cppbridge.LabelSetSnapshot serializedData *cppbridge.DataStorageSerializedData - lastIndexFromLSSQueryResult int - series []Series + series []Series } func NewSeriesSet( diff --git a/pp/go/storage/querier/series_bench_test.go b/pp/go/storage/querier/series_bench_test.go index c2ac78aabb..0b81575dc4 100644 --- a/pp/go/storage/querier/series_bench_test.go +++ b/pp/go/storage/querier/series_bench_test.go @@ -5,6 +5,8 @@ import ( "runtime" "testing" + "github.com/stretchr/testify/require" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" @@ -13,7 +15,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" - "github.com/stretchr/testify/require" ) func iterateSeriesSet(seriesSet storage.SeriesSet) { @@ -59,8 +60,8 @@ func BenchmarkSeriesSetOpt(b *testing.B) { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 - var end = int64(size) + var start int64 + end := int64(size) lss := shard.NewLSS() ds := shard.NewDataStorage() prepareData(lss, ds, size) diff --git a/pp/go/storage/querier/series_test.go b/pp/go/storage/querier/series_test.go index b04851802b..75b36b683e 100644 --- a/pp/go/storage/querier/series_test.go +++ b/pp/go/storage/querier/series_test.go @@ -3,6 +3,8 @@ package querier_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" @@ -11,8 +13,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" ) type SeriesSetTestSuite struct { @@ -73,7 +73,7 @@ func (s *SeriesSetTestSuite) SetupTest() { func (s *SeriesSetTestSuite) query(lss *shard.LSS, ds *shard.DataStorage, start, end int64, matchers ...model.LabelMatcher) *querier.SeriesSet { selector, snapshot, err := lss.QuerySelector(0, matchers) - require.NoError(s.T(), err) + s.Require().NoError(err) if selector == 0 || snapshot == nil { return &querier.SeriesSet{} } @@ -89,7 +89,7 @@ func (s *SeriesSetTestSuite) query(lss *shard.LSS, ds *shard.DataStorage, start, LabelSetIDs: lssQueryResult.IDs(), }) - require.Equal(s.T(), cppbridge.DataStorageQueryStatusSuccess, dsQueryResult.Status) + s.Require().Equal(cppbridge.DataStorageQueryStatusSuccess, dsQueryResult.Status) return querier.NewSeriesSet(start, end, lssQueryResult, snapshot, dsQueryResult.SerializedData) } @@ -110,7 +110,7 @@ func (s *SeriesSetTestSuite) TestQueryAllValues() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 50 expected := s.timeSeries @@ -121,7 +121,7 @@ func (s *SeriesSetTestSuite) TestQueryAllValues() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryNoValues() { @@ -132,7 +132,7 @@ func (s *SeriesSetTestSuite) TestQueryNoValues() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 1 expected := []storagetest.TimeSeries{} @@ -142,7 +142,7 @@ func (s *SeriesSetTestSuite) TestQueryNoValues() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQuerySingleSeries() { @@ -153,7 +153,7 @@ func (s *SeriesSetTestSuite) TestQuerySingleSeries() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 50 expected := s.timeSeries[:4] @@ -163,7 +163,7 @@ func (s *SeriesSetTestSuite) TestQuerySingleSeries() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQuerySingleSample() { @@ -184,7 +184,7 @@ func (s *SeriesSetTestSuite) TestQuerySingleSample() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryCutByUpperLimit() { @@ -205,7 +205,7 @@ func (s *SeriesSetTestSuite) TestQueryCutByUpperLimit() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryCutByLowerLimit() { @@ -226,7 +226,7 @@ func (s *SeriesSetTestSuite) TestQueryCutByLowerLimit() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryLargeChunks() { @@ -237,7 +237,7 @@ func (s *SeriesSetTestSuite) TestQueryLargeChunks() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = cppbridge.MaxPointsInChunk + 1 var timeSeries []storagetest.TimeSeries @@ -256,7 +256,7 @@ func (s *SeriesSetTestSuite) TestQueryLargeChunks() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryEmptyStorage() { @@ -267,7 +267,7 @@ func (s *SeriesSetTestSuite) TestQueryEmptyStorage() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 1000 expected := []storagetest.TimeSeries{} @@ -275,7 +275,7 @@ func (s *SeriesSetTestSuite) TestQueryEmptyStorage() { seriesSet := s.query(s.lss, s.ds, start, end, matcher) // Assert - require.Equal(s.T(), expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) + s.Require().Equal(expected, storagetest.TimeSeriesFromSeriesSet(seriesSet, false)) } func (s *SeriesSetTestSuite) TestQueryMergedSeriesSets() { @@ -286,7 +286,7 @@ func (s *SeriesSetTestSuite) TestQueryMergedSeriesSets() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 1000 timeSeries1 := []storagetest.TimeSeries{ @@ -331,8 +331,7 @@ func (s *SeriesSetTestSuite) TestQueryMergedSeriesSets() { seriesSet2 := s.query(anotherLss, anotherDs, start, end, matcher) // Assert - require.Equal( - s.T(), + s.Require().Equal( expected, storagetest.TimeSeriesFromSeriesSet( storage.NewMergeSeriesSet([]storage.SeriesSet{seriesSet1, seriesSet2}, storage.ChainedSeriesMerge), false), @@ -347,15 +346,15 @@ func (s *SeriesSetTestSuite) TestSeriesSeek() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 1000 expected := s.timeSeries[:4] storagetest.MustAppendTimeSeriesToLSSAndDataStorage(s.lss, s.ds, s.timeSeries[:4]...) seriesSet := s.query(s.lss, s.ds, start, end, matcher) - require.True(s.T(), seriesSet.Next()) + s.Require().True(seriesSet.Next()) series := seriesSet.At() - require.Equal(s.T(), expected[0].Labels, series.Labels()) + s.Require().Equal(expected[0].Labels, series.Labels()) var iterator chunkenc.Iterator iterator = series.Iterator(iterator) index := 2 @@ -363,18 +362,18 @@ func (s *SeriesSetTestSuite) TestSeriesSeek() { result := iterator.Seek(expected[index].Samples[0].Timestamp) // Assert - require.Equal(s.T(), chunkenc.ValFloat, result) + s.Require().Equal(chunkenc.ValFloat, result) ts, v := iterator.At() - require.Equal(s.T(), ts, expected[index].Samples[0].Timestamp) - require.Equal(s.T(), v, expected[index].Samples[0].Value) + s.Require().Equal(ts, expected[index].Samples[0].Timestamp) + s.Require().Equal(v, expected[index].Samples[0].Value) index++ - require.Equal(s.T(), chunkenc.ValFloat, iterator.Next()) + s.Require().Equal(chunkenc.ValFloat, iterator.Next()) ts, v = iterator.At() - require.Equal(s.T(), ts, expected[index].Samples[0].Timestamp) - require.Equal(s.T(), v, expected[index].Samples[0].Value) + s.Require().Equal(ts, expected[index].Samples[0].Timestamp) + s.Require().Equal(v, expected[index].Samples[0].Value) - require.Equal(s.T(), chunkenc.ValNone, iterator.Next()) + s.Require().Equal(chunkenc.ValNone, iterator.Next()) } func (s *SeriesSetTestSuite) TestSeriesSeekOutOfRange() { @@ -385,12 +384,12 @@ func (s *SeriesSetTestSuite) TestSeriesSeekOutOfRange() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 1000 storagetest.MustAppendTimeSeriesToLSSAndDataStorage(s.lss, s.ds, s.timeSeries[:4]...) seriesSet := s.query(s.lss, s.ds, start, end, matcher) - require.True(s.T(), seriesSet.Next()) + s.Require().True(seriesSet.Next()) series := seriesSet.At() var iterator chunkenc.Iterator iterator = series.Iterator(iterator) @@ -399,7 +398,7 @@ func (s *SeriesSetTestSuite) TestSeriesSeekOutOfRange() { result := iterator.Seek(end) // Assert - require.Equal(s.T(), chunkenc.ValNone, result) + s.Require().Equal(chunkenc.ValNone, result) } func (s *SeriesSetTestSuite) TestSeriesParallelRead() { @@ -410,7 +409,7 @@ func (s *SeriesSetTestSuite) TestSeriesParallelRead() { MatcherType: model.MatcherTypeExactMatch, } - var start int64 = 0 + var start int64 var end int64 = 50 expected := s.timeSeries @@ -418,11 +417,11 @@ func (s *SeriesSetTestSuite) TestSeriesParallelRead() { storagetest.MustAppendTimeSeriesToLSSAndDataStorage(s.lss, s.ds, s.timeSeries...) seriesSet := s.query(s.lss, s.ds, start, end, matcher) seriesSlice := make([]storage.Series, 0, 2) - require.True(s.T(), seriesSet.Next()) + s.Require().True(seriesSet.Next()) seriesSlice = append(seriesSlice, seriesSet.At()) - require.True(s.T(), seriesSet.Next()) + s.Require().True(seriesSet.Next()) seriesSlice = append(seriesSlice, seriesSet.At()) - require.False(s.T(), seriesSet.Next()) + s.Require().False(seriesSet.Next()) var chunkIterator chunkenc.Iterator // Act @@ -430,14 +429,14 @@ func (s *SeriesSetTestSuite) TestSeriesParallelRead() { timeSeriesFromSeries2 := storagetest.TimeSeriesFromSeries(seriesSlice[1], chunkIterator, false) // Assert - require.Equal(s.T(), expected, append(timeSeriesFromSeries1, timeSeriesFromSeries2...)) + s.Require().Equal(expected, append(timeSeriesFromSeries1, timeSeriesFromSeries2...)) } func (s *SeriesSetTestSuite) TestSeriesResetIterator() { // Arrange storagetest.MustAppendTimeSeriesToLSSAndDataStorage(s.lss, s.ds, s.timeSeries...) - var start int64 = 0 + var start int64 var end int64 = 50 seriesSet := s.query(s.lss, s.ds, start, end, model.LabelMatcher{ Name: "__name__", diff --git a/pp/go/storage/querier/stalenan_series_set.go b/pp/go/storage/querier/stalenan_series_set.go index 19862ee8f2..89946448f1 100644 --- a/pp/go/storage/querier/stalenan_series_set.go +++ b/pp/go/storage/querier/stalenan_series_set.go @@ -160,7 +160,7 @@ func NewStaleNaNSeriesChunkIterator(t int64) *StaleNaNSeriesChunkIterator { // Always returns the staleNaN value for the specified timestamp. // [chunkenc.Iterator] interface implementation. // -//nolint:gocritic // unnamedResult not needed + func (i *StaleNaNSeriesChunkIterator) At() (int64, float64) { return i.t, floatStaleNaN } diff --git a/pp/go/storage/querier/stalenan_series_set_test.go b/pp/go/storage/querier/stalenan_series_set_test.go index 4e21575514..a54f0036b9 100644 --- a/pp/go/storage/querier/stalenan_series_set_test.go +++ b/pp/go/storage/querier/stalenan_series_set_test.go @@ -3,6 +3,8 @@ package querier_test import ( "testing" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/value" "github.com/prometheus/prometheus/pp/go/cppbridge" @@ -11,7 +13,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/querier" "github.com/prometheus/prometheus/pp/go/storage/storagetest" "github.com/prometheus/prometheus/tsdb/chunkenc" - "github.com/stretchr/testify/suite" ) type StaleNaNSeriesSetTestSuite struct { diff --git a/pp/go/storage/remotewriter/datasourceV2.go b/pp/go/storage/remotewriter/datasourceV2.go index f9961e86e5..7cc4857ba1 100644 --- a/pp/go/storage/remotewriter/datasourceV2.go +++ b/pp/go/storage/remotewriter/datasourceV2.go @@ -13,6 +13,7 @@ import ( "github.com/jonboulle/clockwork" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/prometheus/model/relabel" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/logger" @@ -40,7 +41,7 @@ type dataSourceActive struct { // newDataSourceActive creates a new [dataSourceActive]. func newDataSourceActive( dataDir string, - config DestinationConfig, //nolint:gocritic // hugeParam // config + config DestinationConfig, numberOfShards uint16, discardCache bool, clock clockwork.Clock, @@ -290,7 +291,7 @@ func (ds *dataSourceActive) readFromShards( return readShardResults } -// segmentIsReady checks if the segment is ready and returns the shard IDs in which the segment is located, +// segmentIsReady checks if the segment is ready and returns the shard IDs in which the segment is located,. func (ds *dataSourceActive) segmentIsReady(ctx context.Context) ([]uint16, error) { for { if ctx.Err() != nil { @@ -347,7 +348,7 @@ type dataSourceRotated struct { // newDataSourceRotated creates a new [dataSourceRotated]. func newDataSourceRotated( dataDir string, - config DestinationConfig, //nolint:gocritic // hugeParam // config + config DestinationConfig, numberOfShards uint16, discardCache bool, clock clockwork.Clock, diff --git a/pp/go/storage/remotewriter/destination.go b/pp/go/storage/remotewriter/destination.go index 80b49f36de..fa10a57195 100644 --- a/pp/go/storage/remotewriter/destination.go +++ b/pp/go/storage/remotewriter/destination.go @@ -8,9 +8,10 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" + "gopkg.in/yaml.v2" + "github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/model/labels" - "gopkg.in/yaml.v2" ) // String constants for instrumentation. @@ -36,7 +37,7 @@ type DestinationConfig struct { // EqualTo checks if the config is equal to the other config. // -//nolint:gocritic // hugeParam // equal configs + func (c *DestinationConfig) EqualTo(other DestinationConfig) bool { return c.ExternalLabels.Hash() == other.ExternalLabels.Hash() && c.ReadTimeout == other.ReadTimeout && @@ -66,7 +67,7 @@ func (d *Destination) Config() DestinationConfig { // ResetConfig resets current config to the new one. // -//nolint:gocritic // hugeParam // resets config + func (d *Destination) ResetConfig(cfg DestinationConfig) { d.config = cfg } @@ -74,7 +75,7 @@ func (d *Destination) ResetConfig(cfg DestinationConfig) { // NewDestination creates a new [Destination]. // //revive:disable-next-line:function-length // this is a constructor -//nolint:gocritic // hugeParam // this is a constructor + func NewDestination(cfg DestinationConfig) *Destination { return &Destination{ config: cfg, @@ -174,7 +175,7 @@ func (d *Destination) UnregisterMetrics(registerer prometheus.Registerer) { // remoteWriteConfigsAreEqual compares two remote write configs. // -//nolint:gocritic // this is a compares configs + func remoteWriteConfigsAreEqual(lrwc, rwrc config.RemoteWriteConfig) bool { ldata, _ := yaml.Marshal(lrwc) rdata, _ := yaml.Marshal(rwrc) diff --git a/pp/go/storage/remotewriter/iterator.go b/pp/go/storage/remotewriter/iterator.go index 5d7ab5287b..56d1f7f740 100644 --- a/pp/go/storage/remotewriter/iterator.go +++ b/pp/go/storage/remotewriter/iterator.go @@ -11,9 +11,10 @@ import ( "github.com/cenkalti/backoff/v4" "github.com/jonboulle/clockwork" - "github.com/prometheus/prometheus/storage/remote" "golang.org/x/sync/semaphore" + "github.com/prometheus/prometheus/storage/remote" + "github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/logger" diff --git a/pp/go/storage/remotewriter/iterator_test.go b/pp/go/storage/remotewriter/iterator_test.go index a027ea8212..e2fdbc2c63 100644 --- a/pp/go/storage/remotewriter/iterator_test.go +++ b/pp/go/storage/remotewriter/iterator_test.go @@ -274,7 +274,7 @@ func (*IteratorSuite) decodeToWriteRequest(wr *prompb.WriteRequest, data []byte) // Benchmark // -// go test -test.fullpath=true -benchmem -run=^$ -tags stringlabels -bench ^BenchmarkIteratorV1$ github.com/prometheus/prometheus/pp/go/storage/remotewriter -v -count=1 -benchtime=1000x +// go test -test.fullpath=true -benchmem -run=^$ -tags stringlabels -bench ^BenchmarkIteratorV1$ github.com/prometheus/prometheus/pp/go/storage/remotewriter -v -count=1 -benchtime=1000x. func BenchmarkIteratorV1(b *testing.B) { if b.N != 100 && b.N != 1000 { return @@ -359,7 +359,7 @@ func BenchmarkIteratorV1(b *testing.B) { } } -// go test -test.fullpath=true -benchmem -run=^$ -tags stringlabels -bench ^BenchmarkIteratorV2$ github.com/prometheus/prometheus/pp/go/storage/remotewriter -v -count=1 -benchtime=1000x +// go test -test.fullpath=true -benchmem -run=^$ -tags stringlabels -bench ^BenchmarkIteratorV2$ github.com/prometheus/prometheus/pp/go/storage/remotewriter -v -count=1 -benchtime=1000x. func BenchmarkIteratorV2(b *testing.B) { if b.N != 100 && b.N != 1000 { return diff --git a/pp/go/storage/remotewriter/remotewriter.go b/pp/go/storage/remotewriter/remotewriter.go index 1d88242db4..a05805fab7 100644 --- a/pp/go/storage/remotewriter/remotewriter.go +++ b/pp/go/storage/remotewriter/remotewriter.go @@ -102,7 +102,7 @@ func (rw *RemoteWriter) Run(ctx context.Context) error { } } - for _, config := range configs { //nolint:gocritic // hugeParam // constructor + for _, config := range configs { destination, ok := destinations[config.Name] if !ok { destination = NewDestination(config) diff --git a/pp/go/storage/remotewriter/remotewritertest/fixtures.go b/pp/go/storage/remotewriter/remotewritertest/fixtures.go index 77beb1ccd1..ae748103c8 100644 --- a/pp/go/storage/remotewriter/remotewritertest/fixtures.go +++ b/pp/go/storage/remotewriter/remotewritertest/fixtures.go @@ -8,6 +8,7 @@ import ( "time" "github.com/jonboulle/clockwork" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" "github.com/prometheus/prometheus/pp/go/storage/catalog" @@ -415,7 +416,7 @@ func (tss *TimeSeries) ToWriteRequest() *prompb.WriteRequest { for _, mtss := range tss.data { for _, ts := range mtss { labels := make([]prompb.Label, 0, ts.LabelSet.Len()) - ts.LabelSet.Range(func(lname string, lvalue string) bool { + ts.LabelSet.Range(func(lname, lvalue string) bool { labels = append(labels, prompb.Label{ Name: lname, Value: lvalue, diff --git a/pp/go/storage/remotewriter/walreader_test.go b/pp/go/storage/remotewriter/walreader_test.go index 48e000594e..7687ac8572 100644 --- a/pp/go/storage/remotewriter/walreader_test.go +++ b/pp/go/storage/remotewriter/walreader_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/go-faker/faker/v4" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/storage" "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal" @@ -13,7 +15,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer" "github.com/prometheus/prometheus/pp/go/storage/head/shard/wal/writer/mock" "github.com/prometheus/prometheus/pp/go/util" - "github.com/stretchr/testify/suite" ) type WalReaderSuite struct { diff --git a/pp/go/storage/remotewriter/writeloop.go b/pp/go/storage/remotewriter/writeloop.go index fc6b03fcdf..949bd2fd3c 100644 --- a/pp/go/storage/remotewriter/writeloop.go +++ b/pp/go/storage/remotewriter/writeloop.go @@ -10,6 +10,7 @@ import ( "time" "github.com/jonboulle/clockwork" + "github.com/prometheus/prometheus/storage/remote" "github.com/prometheus/prometheus/pp/go/cppbridge" @@ -276,7 +277,7 @@ func (wl *writeLoop) nextIterator(ctx context.Context, protobufWriter ProtobufWr func (wl *writeLoop) makeDataSource( ctx context.Context, headDir string, - dcfg DestinationConfig, //nolint:gocritic // hugeParam // config + dcfg DestinationConfig, headRecord *catalog.Record, targetSegmentID uint32, discardCache bool, @@ -335,7 +336,7 @@ func (wl *writeLoop) makeCorruptMarker() CorruptMarker { // createClient creates a new [remote.WriteClient]. // -//nolint:gocritic // hugeParam // this is a constructor for new client + func createClient(config DestinationConfig) (client remote.WriteClient, err error) { clientConfig := remote.ClientConfig{ URL: config.URL, @@ -365,7 +366,7 @@ func (fn CorruptMarkerFn) MarkCorrupted(headID string) error { // nextHead returns next head record from catalog. // -//nolint:gocritic // hugeParam // this is a extractor + //revive:disable-next-line:cyclomatic // this is a extractor func nextHead(ctx context.Context, dataDir string, headCatalog Catalog, headID string) (*catalog.Record, error) { if err := contextErr(ctx); err != nil { diff --git a/pp/go/storage/remotewriter/writer.go b/pp/go/storage/remotewriter/writer.go index 6d66285089..d3cf00d61f 100644 --- a/pp/go/storage/remotewriter/writer.go +++ b/pp/go/storage/remotewriter/writer.go @@ -23,7 +23,7 @@ func (*protobufWriter) Close() error { return nil } -// Write [cppbridge.SnappyProtobufEncodedData] to [remote.WriteClient] +// Write [cppbridge.SnappyProtobufEncodedData] to [remote.WriteClient]. func (w *protobufWriter) Write(ctx context.Context, protobuf []byte) error { if len(protobuf) == 0 { return nil diff --git a/pp/go/storage/storagetest/fixtures.go b/pp/go/storage/storagetest/fixtures.go index 831d377096..b79eceb24b 100644 --- a/pp/go/storage/storagetest/fixtures.go +++ b/pp/go/storage/storagetest/fixtures.go @@ -13,6 +13,8 @@ import ( "github.com/jonboulle/clockwork" "golang.org/x/sync/semaphore" + "github.com/stretchr/testify/suite" + "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/pp/go/cppbridge" "github.com/prometheus/prometheus/pp/go/model" @@ -28,7 +30,6 @@ import ( "github.com/prometheus/prometheus/pp/go/storage/querier" promstorage "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" - "github.com/stretchr/testify/suite" ) // TimeSeries test data. diff --git a/pp/go/transport/transport.go b/pp/go/transport/transport.go index 4b9992b047..c00da5da85 100644 --- a/pp/go/transport/transport.go +++ b/pp/go/transport/transport.go @@ -7,9 +7,10 @@ import ( "net" "time" + "golang.org/x/net/websocket" + "github.com/prometheus/prometheus/pp/go/frames" "github.com/prometheus/prometheus/pp/go/util" - "golang.org/x/net/websocket" ) const ( @@ -88,7 +89,7 @@ func (nt *NetTransport) Write(ctx context.Context, fe *frames.ReadFrame) error { return nil } -// Writer returns new io.Writer with given context canceling +// Writer returns new io.Writer with given context canceling. func (nt *NetTransport) Writer(ctx context.Context) io.Writer { return util.FnWriter(func(data []byte) (int, error) { if nt.conn == nil { diff --git a/pp/go/util/file_reader.go b/pp/go/util/file_reader.go index fa325abf61..231d6098ce 100644 --- a/pp/go/util/file_reader.go +++ b/pp/go/util/file_reader.go @@ -16,7 +16,7 @@ type FileReader struct { // // It uses default os.Open with all default flags. func OpenFileReader(path string) (*FileReader, error) { - f, err := os.Open(path) + f, err := os.Open(path) //nolint:gosec // sequential reader opens caller-provided paths by design if err != nil { return nil, err } diff --git a/pp/go/util/fn_writer.go b/pp/go/util/fn_writer.go index b21e3e43ea..6c6a6a93d3 100644 --- a/pp/go/util/fn_writer.go +++ b/pp/go/util/fn_writer.go @@ -1,9 +1,9 @@ package util -// FnWriter is a helper functional wrapper to create unusuall writers +// FnWriter is a helper functional wrapper to create unusuall writers. type FnWriter func([]byte) (int, error) -// Write implements io.Writer interface +// Write implements io.Writer interface. func (fn FnWriter) Write(p []byte) (int, error) { return fn(p) } diff --git a/pp/go/util/locker/priweighted_test.go b/pp/go/util/locker/priweighted_test.go index 9ae37b1bb1..077ffd21ed 100644 --- a/pp/go/util/locker/priweighted_test.go +++ b/pp/go/util/locker/priweighted_test.go @@ -343,7 +343,6 @@ func (s *WeightedSuite) TestRLockWakesToErrSemaphoreClosedAfterClose() { }) } - func (s *WeightedSuite) TestTwoRLockWithPriorityOrder() { synctest.Test(s.T(), func(t *testing.T) { ctx := context.Background() diff --git a/pp/go/util/offset_reader.go b/pp/go/util/offset_reader.go index 7243202ffd..a4fbef95b2 100644 --- a/pp/go/util/offset_reader.go +++ b/pp/go/util/offset_reader.go @@ -2,13 +2,13 @@ package util import "io" -// OffsetReader is a wrapper of io.ReaderAt to implement io.Reader interface +// OffsetReader is a wrapper of io.ReaderAt to implement io.Reader interface. type OffsetReader struct { r io.ReaderAt off int64 } -// NewOffsetReader wraps io.ReaderAt with offset +// NewOffsetReader wraps io.ReaderAt with offset. func NewOffsetReader(r io.ReaderAt, off int64) *OffsetReader { return &OffsetReader{ r: r, @@ -16,7 +16,7 @@ func NewOffsetReader(r io.ReaderAt, off int64) *OffsetReader { } } -// Read implements io.Reader interface +// Read implements io.Reader interface. func (or *OffsetReader) Read(p []byte) (int, error) { n, err := or.r.ReadAt(p, or.off) or.off += int64(n) diff --git a/pp/go/util/profile.go b/pp/go/util/profile.go index b6436bb692..12b726d1f0 100644 --- a/pp/go/util/profile.go +++ b/pp/go/util/profile.go @@ -23,7 +23,7 @@ func (w *HeapProfileWriter) WriteHeapProfile() error { if !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("failed to stat dir: %w", err) } - if err = os.MkdirAll(w.dir, 0777); err != nil { + if err = os.MkdirAll(w.dir, 0o750); err != nil { return fmt.Errorf("failed to create dir: %w", err) } dirStat, err = os.Stat(w.dir) @@ -37,7 +37,7 @@ func (w *HeapProfileWriter) WriteHeapProfile() error { } filePath := filepath.Join(w.dir, fmt.Sprintf("heap_profile_%d", time.Now().UnixMilli())) - file, err := os.Create(filePath) + file, err := os.Create(filePath) //nolint:gosec // filePath is derived from the configured profile dir if err != nil { return fmt.Errorf("failed to create heap profile file: %w", err) } diff --git a/pp/go/util/registerer.go b/pp/go/util/registerer.go index 82fb5f3b47..b26b3f5ba0 100644 --- a/pp/go/util/registerer.go +++ b/pp/go/util/registerer.go @@ -1,6 +1,10 @@ package util -import "github.com/prometheus/client_golang/prometheus" +import ( + "errors" + + "github.com/prometheus/client_golang/prometheus" +) // UnconflictRegisterer is a prometheus.UnconflictRegisterer wrap to avoid duplicates errors. type UnconflictRegisterer struct { @@ -22,7 +26,7 @@ func (cr UnconflictRegisterer) NewCounter(opts prometheus.CounterOpts) prometheu return c.With(constLabels) } -// NewCounterVec create new prometheus.CounterVec and register it in wrapped registerer +// NewCounterVec create new prometheus.CounterVec and register it in wrapped registerer. func (cr UnconflictRegisterer) NewCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec { constLabels := opts.ConstLabels opts.ConstLabels = nil @@ -32,7 +36,7 @@ func (cr UnconflictRegisterer) NewCounterVec(opts prometheus.CounterOpts, labelN return c.MustCurryWith(constLabels) } -// NewGauge create new prometheus.Gauge and register it in wrapped registerer +// NewGauge create new prometheus.Gauge and register it in wrapped registerer. func (cr UnconflictRegisterer) NewGauge(opts prometheus.GaugeOpts) prometheus.Gauge { constLabels := opts.ConstLabels opts.ConstLabels = nil @@ -42,7 +46,7 @@ func (cr UnconflictRegisterer) NewGauge(opts prometheus.GaugeOpts) prometheus.Ga return c.With(constLabels) } -// NewGaugeVec create new prometheus.GaugeVec and register it in wrapped registerer +// NewGaugeVec create new prometheus.GaugeVec and register it in wrapped registerer. func (cr UnconflictRegisterer) NewGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec { constLabels := opts.ConstLabels opts.ConstLabels = nil @@ -57,9 +61,8 @@ func (cr UnconflictRegisterer) NewGaugeFunc(opts prometheus.GaugeOpts, fn func() return mustRegisterOrGet(cr.Registerer, prometheus.NewGaugeFunc(opts, fn)) } -// NewHistogramVec create new prometheus.HistogramVec and register it in wrapped registerer +// NewHistogramVec create new prometheus.HistogramVec and register it in wrapped registerer. func (cr UnconflictRegisterer) NewHistogramVec( - //nolint:gocritic // should be compatible with prometheus.NewHistogramVec opts prometheus.HistogramOpts, labelNames []string, ) *prometheus.HistogramVec { constLabels := opts.ConstLabels @@ -70,9 +73,8 @@ func (cr UnconflictRegisterer) NewHistogramVec( return h.MustCurryWith(constLabels).(*prometheus.HistogramVec) } -// NewHistogram create new prometheus.Histogram and register it in wrapped registerer +// NewHistogram create new prometheus.Histogram and register it in wrapped registerer. func (cr UnconflictRegisterer) NewHistogram( - //nolint:gocritic // should be compatible with prometheus.NewHistogramVec opts prometheus.HistogramOpts, ) prometheus.Histogram { constLabels := opts.ConstLabels @@ -104,7 +106,8 @@ func mustRegisterOrGet[Collector prometheus.Collector](r prometheus.Registerer, if err == nil { return c } - if arErr, ok := err.(prometheus.AlreadyRegisteredError); ok { + var arErr prometheus.AlreadyRegisteredError + if errors.As(err, &arErr) { return arErr.ExistingCollector.(Collector) } panic(err) diff --git a/pp/go/util/varint.go b/pp/go/util/varint.go index e319fd5af7..6077af28c3 100644 --- a/pp/go/util/varint.go +++ b/pp/go/util/varint.go @@ -1,6 +1,6 @@ package util -// VarintLen returns how many bytes needed to store x as varint +// VarintLen returns how many bytes needed to store x as varint. func VarintLen(x uint64) (n int64) { for x >= 0x80 { x >>= 7