diff --git a/.drone/drone.yml b/.drone/drone.yml index 8151954458b0..5f294b0e0eb3 100644 --- a/.drone/drone.yml +++ b/.drone/drone.yml @@ -16,7 +16,7 @@ trigger: steps: - name: lint - image: golangci/golangci-lint:v1.43 + image: golangci/golangci-lint:v1.44 commands: - apt-get update -y && apt-get install -y libsystemd-dev - make lint @@ -271,6 +271,6 @@ get: name: pat --- kind: signature -hmac: 3da266cfeead0295f439b0ec44ba62b6b9c53f2774aef54fe58585e4d51d8990 +hmac: 76ba44a90ab332caf4cd3bc11529e7ea674d4706ab8b4928b17b8c7dcda8abea ... diff --git a/.golangci.yml b/.golangci.yml index 565377a1ae63..994a45adccb6 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,74 +1,83 @@ -# This file contains all available configuration options -# with their default values. +# Full list of configuration options: https://golangci-lint.run/usage/configuration/ -# options for analysis running run: - # default concurrency is a available CPU number - concurrency: 16 - - # timeout for analysis, e.g. 30s, 5m, default is 1m timeout: 5m - # exit code when at least one issue was found, default is 1 - issues-exit-code: 1 - - # include test files or not, default is true - tests: true - - # list of build2 tags, all linters use it. Default is empty list. - build-tags: - - # which dirs to skip: they won't be analyzed; - # can use regexp here: generated.*, regexp is applied on full path; - # default value is empty list, but next dirs are always skipped independently - # from this option's value: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs: - # which files to skip: they will be analyzed, but issues from them - # won't be reported. Default value is empty list, but there is - # no need to include all autogenerated files, we confidently recognize - # autogenerated files. If it's not please let us know. - skip-files: -# output configuration options output: - # colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number" - format: colored-line-number - - # print lines of code with issue, default is true - print-issued-lines: true - - # print linter name in the end of issue text, default is true - print-linter-name: true + sort-results: true linters: enable: - - deadcode - - errcheck - - goconst - - gofmt - - goimports - - golint - - gosimple - - ineffassign - - megacheck - - misspell - - structcheck - - unconvert - - unparam - - varcheck - - govet - - unused # new from here. - - interfacer - - typecheck + - deadcode # Report on unused code + - errcheck # Report unchecked errors + - goconst # Find repeated strings that could be replaced by constant + - gofmt # Check whether code was gofmt-ed + - goimports # Check imports were formatted with gofmt + - revive # Broad set of rules; replaces deprecated golint + - gosimple # Check whether code can be simplified + - ineffassign # Detect when assignment to variable is never used + - misspell # Report on commonly misspelled English words + - structcheck # Report on unused struct fields + - unconvert # Remove unnecessary type conversions + - unparam # Detect unused function parameters + - varcheck # Find unused global variables/constants + - govet # `go vet` + - unused # Detect unused constants/variables/functions/types + - typecheck # Ensure code typechecks + - depguard # Allow/denylist specific imports + - makezero # Detect misuse of make with non-zero length and append + - tenv # Use testing.(*T).Setenv instead of os.Setenv + - whitespace # Report unnecessary blank lines issues: - # golangci-lint excludes some stuff we want by default (i.e., proper go-style comments). - # We exclude the defaults and then manually exclude the subset of defaults we truly don't - # care about. + # We want to use our own exclusion rules and ignore all the defaults. exclude-use-default: false + exclude-rules: + # It's fine if tests ignore errors. + - path: _test.go + linters: + - errcheck + exclude: - # EXC0001 errcheck: Almost all programs ignore errors on these functions - # and in most cases it's ok. This is copied from the golangci-lint defaults - # mut modified to include go-kit logging. - - Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv|.*\.Log). is not checked + # Ignoring errors on Close, Log, and removing files is OK in most cases. + - "Error return value of `(.*\\.Close|.*\\.Log|os.Remove)` is not checked" + # Packages for integrations are named matching their upstream counterpart, + # which almost always have underscores. + - "var-naming: don't use an underscore in package name" + +# Linter settings options: https://golangci-lint.run/usage/linters/ +linters-settings: + depguard: + # We want to report errors on stdlib packages, not just third party modules + include-go-root: true + + packages-with-error-message: + - sync/atomic: "Use go.uber.org/atomic instead of sync/atomic" + - github.com/pkg/errors: "Use errors instead of github.com/pkg/errors" + - github.com/go-kit/kit/log: "Use github.com/go-kit/log instead of github.com/go-kit/kit/log" + - golang.org/x/sync/errgroup: "Use github.com/oklog/run instead of golang.org/x/sync/errgroup" + + whitespace: + # While there normally shouldn't be extra redundant leading/trailing + # whitespace, if statement conditions and function headers that cross + # multiple lines are an exception. + # + # if true || + # false { + # + # // ... ^ must have empty line above + # } + # + # func foo( + # a int, + # ) { + # + # // ... ^ must have empty line above + # } + # + # This helps readers easily separate where the multi-line if/function ends + # at a glance. + multi-if: true + multi-func: true + diff --git a/pkg/config/config.go b/pkg/config/config.go index eccc1bab054c..0e9ade95ba8f 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -20,7 +20,6 @@ import ( "github.com/grafana/agent/pkg/util" "github.com/grafana/dskit/kv/consul" "github.com/grafana/dskit/kv/etcd" - "github.com/pkg/errors" "github.com/prometheus/common/config" "github.com/prometheus/common/version" "github.com/stretchr/testify/require" @@ -219,7 +218,7 @@ func (c *Config) RegisterFlags(f *flag.FlagSet) { func LoadFile(filename string, expandEnvVars bool, c *Config) error { buf, err := ioutil.ReadFile(filename) if err != nil { - return errors.Wrap(err, "error reading config file") + return fmt.Errorf("error reading config file: %w", err) } return LoadBytes(buf, expandEnvVars, c) } diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index c2d4697ebfb6..85ba384779c6 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -3,7 +3,6 @@ package config import ( "flag" "net/url" - "os" "strings" "testing" "time" @@ -99,7 +98,7 @@ metrics: EvaluationInterval: model.Duration(1 * time.Minute), }, } - _ = os.Setenv("SCRAPE_TIMEOUT", "33s") + t.Setenv("SCRAPE_TIMEOUT", "33s") fs := flag.NewFlagSet("test", flag.ExitOnError) c, err := load(fs, []string{"-config.file", "test"}, func(_ string, _ bool, c *Config) error { diff --git a/pkg/integrations/cadvisor/common.go b/pkg/integrations/cadvisor/common.go index 6d5d0b5eb70a..efd5df363860 100644 --- a/pkg/integrations/cadvisor/common.go +++ b/pkg/integrations/cadvisor/common.go @@ -9,7 +9,7 @@ import ( const name = "cadvisor" // DefaultConfig holds the default settings for the cadvisor integration -var DefaultConfig Config = Config{ +var DefaultConfig = Config{ // Common cadvisor config defaults StoreContainerLabels: true, ResctrlInterval: 0, diff --git a/pkg/integrations/dnsmasq_exporter/dnsmasq_exporter.go b/pkg/integrations/dnsmasq_exporter/dnsmasq_exporter.go index 93dd2ee1f837..3f89ec2d842a 100644 --- a/pkg/integrations/dnsmasq_exporter/dnsmasq_exporter.go +++ b/pkg/integrations/dnsmasq_exporter/dnsmasq_exporter.go @@ -11,7 +11,7 @@ import ( ) // DefaultConfig is the default config for dnsmasq_exporter. -var DefaultConfig Config = Config{ +var DefaultConfig = Config{ DnsmasqAddress: "localhost:53", LeasesPath: "/var/lib/misc/dnsmasq.leases", } diff --git a/pkg/integrations/github_exporter/github_exporter.go b/pkg/integrations/github_exporter/github_exporter.go index b9997eb4ee07..268c451a1d55 100644 --- a/pkg/integrations/github_exporter/github_exporter.go +++ b/pkg/integrations/github_exporter/github_exporter.go @@ -15,7 +15,7 @@ import ( ) // DefaultConfig holds the default settings for the github_exporter integration -var DefaultConfig Config = Config{ +var DefaultConfig = Config{ APIURL: "https://api.github.com", } @@ -74,7 +74,6 @@ func init() { // New creates a new github_exporter integration. func New(logger log.Logger, c *Config) (integrations.Integration, error) { - conf := gh_config.Config{} err := conf.SetAPIURL(c.APIURL) if err != nil { diff --git a/pkg/integrations/manager_test.go b/pkg/integrations/manager_test.go index 88325dfb874f..ffd44dbb8100 100644 --- a/pkg/integrations/manager_test.go +++ b/pkg/integrations/manager_test.go @@ -36,8 +36,8 @@ use_hostname_label: true ` var ( cfg ManagerConfig - listenPort int = 12345 - listenHost string = "127.0.0.1" + listenPort = 12345 + listenHost = "127.0.0.1" ) require.NoError(t, yaml.Unmarshal([]byte(cfgText), &cfg)) @@ -66,8 +66,8 @@ test: ` var ( cfg ManagerConfig - listenPort int = 12345 - listenHost string = "127.0.0.1" + listenPort = 12345 + listenHost = "127.0.0.1" ) require.NoError(t, yaml.Unmarshal([]byte(cfgText), &cfg)) @@ -89,8 +89,8 @@ agent: var ( cfg ManagerConfig - listenPort int = 12345 - listenHost string = "127.0.0.1" + listenPort = 12345 + listenHost = "127.0.0.1" ) require.NoError(t, yaml.Unmarshal([]byte(cfgText), &cfg)) diff --git a/pkg/integrations/memcached_exporter/memcached_exporter.go b/pkg/integrations/memcached_exporter/memcached_exporter.go index c117528450bf..93d79871dc09 100644 --- a/pkg/integrations/memcached_exporter/memcached_exporter.go +++ b/pkg/integrations/memcached_exporter/memcached_exporter.go @@ -12,7 +12,7 @@ import ( ) // DefaultConfig is the default config for memcached_exporter. -var DefaultConfig Config = Config{ +var DefaultConfig = Config{ MemcachedAddress: "localhost:11211", Timeout: time.Second, } diff --git a/pkg/integrations/mongodb_exporter/mongodb_exporter.go b/pkg/integrations/mongodb_exporter/mongodb_exporter.go index e666d54c2b34..905ffcef58cc 100644 --- a/pkg/integrations/mongodb_exporter/mongodb_exporter.go +++ b/pkg/integrations/mongodb_exporter/mongodb_exporter.go @@ -20,7 +20,6 @@ type Config struct { // UnmarshalYAML implements yaml.Unmarshaler for Config func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { - type plain Config return unmarshal((*plain)(c)) } diff --git a/pkg/integrations/postgres_exporter/postgres_test.go b/pkg/integrations/postgres_exporter/postgres_test.go index 0b6bbe8963b1..e3a74f7bbc57 100644 --- a/pkg/integrations/postgres_exporter/postgres_test.go +++ b/pkg/integrations/postgres_exporter/postgres_test.go @@ -17,5 +17,4 @@ integrations: ` config.CheckSecret(t, stringCfg, "secret_password_in_uri") config.CheckSecret(t, stringCfg, "secret_password_in_uri_2") - } diff --git a/pkg/integrations/redis_exporter/redis_exporter.go b/pkg/integrations/redis_exporter/redis_exporter.go index 2a71d35c1e44..1661ee5a86ca 100644 --- a/pkg/integrations/redis_exporter/redis_exporter.go +++ b/pkg/integrations/redis_exporter/redis_exporter.go @@ -144,9 +144,7 @@ func New(log log.Logger, c *Config) (integrations.Integration, error) { if (c.TLSClientKeyFile != "") != (c.TLSClientCertFile != "") { return nil, errors.New("TLS client key file and cert file should both be present") - } - if c.TLSClientKeyFile != "" && c.TLSClientCertFile != "" { - + } else if c.TLSClientKeyFile != "" && c.TLSClientCertFile != "" { exporterConfig.ClientKeyFile = c.TLSClientKeyFile exporterConfig.ClientCertFile = c.TLSClientCertFile } diff --git a/pkg/integrations/redis_exporter/redis_exporter_test.go b/pkg/integrations/redis_exporter/redis_exporter_test.go index 49391bae0cbc..2830c0657f40 100644 --- a/pkg/integrations/redis_exporter/redis_exporter_test.go +++ b/pkg/integrations/redis_exporter/redis_exporter_test.go @@ -104,7 +104,6 @@ func TestRedisCases(t *testing.T) { logger := log.NewNopLogger() for _, test := range tt { - t.Run(test.name, func(t *testing.T) { integration, err := New(logger, &test.cfg) @@ -151,7 +150,6 @@ func TestRedisCases(t *testing.T) { require.True(t, exists, "could not find metric %s", metric) } }) - } } diff --git a/pkg/integrations/v2/autoscrape/autoscrape.go b/pkg/integrations/v2/autoscrape/autoscrape.go index a5d986273bd4..70b7fbd89cbd 100644 --- a/pkg/integrations/v2/autoscrape/autoscrape.go +++ b/pkg/integrations/v2/autoscrape/autoscrape.go @@ -19,7 +19,7 @@ import ( ) // DefaultGlobal holds default values for Global. -var DefaultGlobal Global = Global{ +var DefaultGlobal = Global{ Enable: true, MetricsInstance: "default", } @@ -197,8 +197,8 @@ func newInstanceScraper( s InstanceStore, instanceName string, ) *instanceScraper { - ctx, cancel := context.WithCancel(ctx) + ctx, cancel := context.WithCancel(ctx) l = log.With(l, "target_instance", instanceName) sd := discovery.NewManager(ctx, l, discovery.Name("autoscraper/"+instanceName)) diff --git a/pkg/integrations/v2/autoscrape/autoscrape_test.go b/pkg/integrations/v2/autoscrape/autoscrape_test.go index 2abee73295b2..2e9a5e9e73eb 100644 --- a/pkg/integrations/v2/autoscrape/autoscrape_test.go +++ b/pkg/integrations/v2/autoscrape/autoscrape_test.go @@ -3,7 +3,6 @@ package autoscrape import ( "context" "net/http/httptest" - "sync/atomic" "testing" "time" @@ -18,6 +17,7 @@ import ( "github.com/prometheus/prometheus/storage" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/atomic" ) // TestAutoscrape is a basic end-to-end test of the autoscraper. @@ -68,15 +68,15 @@ func TestAutoscrape(t *testing.T) { require.NoError(t, wt.Wait(5*time.Second), "timed out waiting for scrape") } -var globalRef uint64 +var globalRef atomic.Uint64 var noOpAppender = mockAppender{ AppendFunc: func(ref uint64, l labels.Labels, t int64, v float64) (uint64, error) { - return atomic.AddUint64(&globalRef, 1), nil + return globalRef.Inc(), nil }, CommitFunc: func() error { return nil }, RollbackFunc: func() error { return nil }, AppendExemplarFunc: func(ref uint64, l labels.Labels, e exemplar.Exemplar) (uint64, error) { - return atomic.AddUint64(&globalRef, 1), nil + return globalRef.Inc(), nil }, } diff --git a/pkg/integrations/v2/metricsutils/metricshandler_integration.go b/pkg/integrations/v2/metricsutils/metricshandler_integration.go index 38470cfcd341..5edd9c6ac1c2 100644 --- a/pkg/integrations/v2/metricsutils/metricshandler_integration.go +++ b/pkg/integrations/v2/metricsutils/metricshandler_integration.go @@ -26,6 +26,7 @@ func NewMetricsHandlerIntegration( globals integrations.Globals, h http.Handler, ) (integrations.MetricsIntegration, error) { + id, err := c.Identifier(globals) if err != nil { return nil, err diff --git a/pkg/integrations/v2/subsystem_test.go b/pkg/integrations/v2/subsystem_test.go index 1d9e8cfbd920..71427b15e1f1 100644 --- a/pkg/integrations/v2/subsystem_test.go +++ b/pkg/integrations/v2/subsystem_test.go @@ -52,7 +52,6 @@ func TestSubsystemOptions_Unmarshal(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { - var so SubsystemOptions err := yaml.UnmarshalStrict([]byte(tc.in), &so) diff --git a/pkg/metrics/cluster/cluster.go b/pkg/metrics/cluster/cluster.go index 5c94a4a01628..7ca80360fcd1 100644 --- a/pkg/metrics/cluster/cluster.go +++ b/pkg/metrics/cluster/cluster.go @@ -52,6 +52,7 @@ func New( im instance.Manager, validate ValidationFunc, ) (*Cluster, error) { + l = log.With(l, "component", "cluster") var ( @@ -116,9 +117,7 @@ func (c *Cluster) Reshard(ctx context.Context, _ *agentproto.ReshardRequest) (*e } // ApplyConfig applies configuration changes to Cluster. -func (c *Cluster) ApplyConfig( - cfg Config, -) error { +func (c *Cluster) ApplyConfig(cfg Config) error { c.mut.Lock() defer c.mut.Unlock() diff --git a/pkg/metrics/cluster/config_watcher_test.go b/pkg/metrics/cluster/config_watcher_test.go index 5bd02c72aa87..e365cb2f5f3a 100644 --- a/pkg/metrics/cluster/config_watcher_test.go +++ b/pkg/metrics/cluster/config_watcher_test.go @@ -227,7 +227,6 @@ func Test_configWatcher_nextReshard(t *testing.T) { require.FailNow(t, "nextReshard took too long to return") } }) - } type mockConfigManager struct { diff --git a/pkg/metrics/instance/configstore/remote.go b/pkg/metrics/instance/configstore/remote.go index 712cdf583ce9..9bf01732e9a7 100644 --- a/pkg/metrics/instance/configstore/remote.go +++ b/pkg/metrics/instance/configstore/remote.go @@ -120,8 +120,8 @@ func (r *Remote) ApplyConfig(cfg kv.Config, enable bool) error { if err != nil { return err } - } + if err != nil { return fmt.Errorf("failed to create kv client: %w", err) } @@ -354,8 +354,8 @@ func (r *Remote) all(ctx context.Context, keep func(key string) bool) (<-chan in if r.kv.consul != nil { return r.allConsul(ctx, keep) } - return r.allOther(ctx, keep) + return r.allOther(ctx, keep) } // allConsul is ONLY usable when consul is the keystore. This is a performance improvement in using the client directly diff --git a/pkg/metrics/instance/host_filter.go b/pkg/metrics/instance/host_filter.go index 01099bde45ad..aca92e1c6cac 100644 --- a/pkg/metrics/instance/host_filter.go +++ b/pkg/metrics/instance/host_filter.go @@ -88,7 +88,6 @@ func (f *HostFilter) PatchSD(scrapes []*config.ScrapeConfig) { } } } - } // SetRelabels updates the relabeling rules used by the HostFilter. diff --git a/pkg/metrics/instance/instance_integration_test.go b/pkg/metrics/instance/instance_integration_test.go index 67776026dcde..c15be5a55d04 100644 --- a/pkg/metrics/instance/instance_integration_test.go +++ b/pkg/metrics/instance/instance_integration_test.go @@ -244,7 +244,6 @@ remote_write: [] require.EqualError(t, err, tc.expect) }) } - } func loadConfig(t *testing.T, s string) Config { diff --git a/pkg/metrics/instance/instance_test.go b/pkg/metrics/instance/instance_test.go index 0f79bd073c58..4e3815df6728 100644 --- a/pkg/metrics/instance/instance_test.go +++ b/pkg/metrics/instance/instance_test.go @@ -139,7 +139,6 @@ func TestConfig_ApplyDefaults_Validations(t *testing.T) { for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { - // Copy the input and all of its slices input := cfg diff --git a/pkg/metrics/wal/wal.go b/pkg/metrics/wal/wal.go index 15814d070739..91bc79fb6418 100644 --- a/pkg/metrics/wal/wal.go +++ b/pkg/metrics/wal/wal.go @@ -10,7 +10,6 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/prometheus/pkg/exemplar" "github.com/prometheus/prometheus/pkg/labels" @@ -164,7 +163,7 @@ func NewStorage(logger log.Logger, registerer prometheus.Registerer, path string if err := storage.replayWAL(); err != nil { level.Warn(storage.logger).Log("msg", "encountered WAL read error, attempting repair", "err", err) if err := w.Repair(err); err != nil { - return nil, errors.Wrap(err, "repair corrupted WAL") + return nil, fmt.Errorf("repair corrupted WAL: %w", err) } } @@ -182,13 +181,13 @@ func (w *Storage) replayWAL() error { level.Info(w.logger).Log("msg", "replaying WAL, this may take a while", "dir", w.wal.Dir()) dir, startFrom, err := wal.LastCheckpoint(w.wal.Dir()) if err != nil && err != record.ErrNotFound { - return errors.Wrap(err, "find last checkpoint") + return fmt.Errorf("find last checkpoint: %w", err) } if err == nil { sr, err := wal.NewSegmentsReader(dir) if err != nil { - return errors.Wrap(err, "open checkpoint") + return fmt.Errorf("open checkpoint: %w", err) } defer func() { if err := sr.Close(); err != nil { @@ -199,7 +198,7 @@ func (w *Storage) replayWAL() error { // A corrupted checkpoint is a hard error for now and requires user // intervention. There's likely little data that can be recovered anyway. if err := w.loadWAL(wal.NewReader(sr)); err != nil { - return errors.Wrap(err, "backfill checkpoint") + return fmt.Errorf("backfill checkpoint: %w", err) } startFrom++ level.Info(w.logger).Log("msg", "WAL checkpoint loaded") @@ -208,14 +207,14 @@ func (w *Storage) replayWAL() error { // Find the last segment. _, last, err := wal.Segments(w.wal.Dir()) if err != nil { - return errors.Wrap(err, "finding WAL segments") + return fmt.Errorf("finding WAL segments: %w", err) } // Backfill segments from the most recent checkpoint onwards. for i := startFrom; i <= last; i++ { s, err := wal.OpenReadSegment(wal.SegmentName(w.wal.Dir(), i)) if err != nil { - return errors.Wrap(err, fmt.Sprintf("open WAL segment: %d", i)) + return fmt.Errorf("open WAL segment %d: %w", i, err) } sr := wal.NewSegmentBufReader(s) @@ -262,7 +261,7 @@ func (w *Storage) loadWAL(r *wal.Reader) (err error) { series, err = dec.Series(rec, series) if err != nil { errCh <- &wal.CorruptionErr{ - Err: errors.Wrap(err, "decode series"), + Err: fmt.Errorf("decode series: %w", err), Segment: r.Segment(), Offset: r.Offset(), } @@ -274,7 +273,7 @@ func (w *Storage) loadWAL(r *wal.Reader) (err error) { samples, err = dec.Samples(rec, samples) if err != nil { errCh <- &wal.CorruptionErr{ - Err: errors.Wrap(err, "decode samples"), + Err: fmt.Errorf("decode samples: %w", err), Segment: r.Segment(), Offset: r.Offset(), } @@ -287,7 +286,7 @@ func (w *Storage) loadWAL(r *wal.Reader) (err error) { continue default: errCh <- &wal.CorruptionErr{ - Err: errors.Errorf("invalid record type %v", dec.Type(rec)), + Err: fmt.Errorf("invalid record type %v", dec.Type(rec)), Segment: r.Segment(), Offset: r.Offset(), } @@ -353,7 +352,7 @@ func (w *Storage) loadWAL(r *wal.Reader) (err error) { } if r.Err() != nil { - return errors.Wrap(r.Err(), "read records") + return fmt.Errorf("read records: %w", r.Err()) } return nil @@ -393,14 +392,14 @@ func (w *Storage) Truncate(mint int64) error { first, last, err := wal.Segments(w.wal.Dir()) if err != nil { - return errors.Wrap(err, "get segment range") + return fmt.Errorf("get segment range: %w", err) } // Start a new segment, so low ingestion volume instance don't have more WAL // than needed. err = w.wal.NextSegment() if err != nil { - return errors.Wrap(err, "next segment") + return fmt.Errorf("next segment: %w", err) } last-- // Never consider last segment for checkpoint. @@ -426,7 +425,7 @@ func (w *Storage) Truncate(mint int64) error { return ok } if _, err = wal.Checkpoint(w.logger, w.wal, first, last, keep, mint); err != nil { - return errors.Wrap(err, "create checkpoint") + return fmt.Errorf("create checkpoint: %w", err) } if err := w.wal.Truncate(last + 1); err != nil { // If truncating fails, we'll just try again at the next checkpoint. @@ -573,11 +572,11 @@ func (a *appender) Append(ref uint64, l labels.Labels, t int64, v float64) (uint // equivalent validation code in the TSDB's headAppender. l = l.WithoutEmpty() if len(l) == 0 { - return 0, errors.Wrap(tsdb.ErrInvalidSample, "empty labelset") + return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample) } if lbl, dup := l.HasDuplicateLabelNames(); dup { - return 0, errors.Wrap(tsdb.ErrInvalidSample, fmt.Sprintf(`label name "%s" is not unique`, lbl)) + return 0, fmt.Errorf("label name %q is not unique: %w", lbl, tsdb.ErrInvalidSample) } var created bool @@ -633,7 +632,7 @@ func (a *appender) AppendExemplar(ref uint64, _ labels.Labels, e exemplar.Exempl e.Labels = e.Labels.WithoutEmpty() if lbl, dup := e.Labels.HasDuplicateLabelNames(); dup { - return 0, errors.Wrap(tsdb.ErrInvalidExemplar, fmt.Sprintf(`label name "%s" is not unique`, lbl)) + return 0, fmt.Errorf("label name %q is not unique: %w", lbl, tsdb.ErrInvalidExemplar) } // Exemplar label length does not include chars involved in text rendering such as quotes diff --git a/pkg/operator/clientutil/merge.go b/pkg/operator/clientutil/merge.go index a5aae204876e..5e43e951a898 100644 --- a/pkg/operator/clientutil/merge.go +++ b/pkg/operator/clientutil/merge.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" - "github.com/pkg/errors" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/strategicpatch" ) @@ -28,21 +27,21 @@ func MergePatchContainers(base, patches []v1.Container) ([]v1.Container, error) // Get the json for the container and the patch containerBytes, err := json.Marshal(container) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("failed to marshal json for container %s", container.Name)) + return nil, fmt.Errorf("failed to marshal json for container %s: %w", container.Name, err) } patchBytes, err := json.Marshal(patchContainer) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("failed to marshal json for patch container %s", container.Name)) + return nil, fmt.Errorf("failed to marshal json for patch container %s: %w", container.Name, err) } // Calculate the patch result jsonResult, err := strategicpatch.StrategicMergePatch(containerBytes, patchBytes, v1.Container{}) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("failed to generate merge patch for %s", container.Name)) + return nil, fmt.Errorf("failed to generate merge patch for %s: %w", container.Name, err) } var patchResult v1.Container if err := json.Unmarshal(jsonResult, &patchResult); err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("failed to unmarshal merged container %s", container.Name)) + return nil, fmt.Errorf("failed to unmarshal merged container %s: %w", container.Name, err) } // Add the patch result and remove the corresponding key from the to do list diff --git a/pkg/operator/config/fs_importer.go b/pkg/operator/config/fs_importer.go index 60b73120ced6..2a8044c0c986 100644 --- a/pkg/operator/config/fs_importer.go +++ b/pkg/operator/config/fs_importer.go @@ -30,7 +30,6 @@ func NewFSImporter(f fs.FS, paths []string) *FSImporter { // Import implements jsonnet.Importer. func (i *FSImporter) Import(importedFrom, importedPath string) (contents jsonnet.Contents, foundAt string, err error) { - tryPaths := append([]string{importedFrom}, i.paths...) for _, p := range tryPaths { cleanedPath := path.Clean( diff --git a/pkg/operator/reconciler_logs.go b/pkg/operator/reconciler_logs.go index a12e752a5db8..05c973253b99 100644 --- a/pkg/operator/reconciler_logs.go +++ b/pkg/operator/reconciler_logs.go @@ -21,6 +21,7 @@ func (r *reconciler) createLogsConfigurationSecret( d config.Deployment, s assets.SecretStore, ) error { + return r.createTelemetryConfigurationSecret(ctx, l, d, s, config.LogsType) } @@ -31,6 +32,7 @@ func (r *reconciler) createLogsDaemonSet( d config.Deployment, s assets.SecretStore, ) error { + name := fmt.Sprintf("%s-logs", d.Agent.Name) ds, err := generateLogsDaemonSet(r.config, name, d) if err != nil { diff --git a/pkg/operator/reconciler_metrics.go b/pkg/operator/reconciler_metrics.go index 6a52948133b5..1a1ac6fb0da6 100644 --- a/pkg/operator/reconciler_metrics.go +++ b/pkg/operator/reconciler_metrics.go @@ -29,6 +29,7 @@ func (r *reconciler) createMetricsConfigurationSecret( d config.Deployment, s assets.SecretStore, ) error { + return r.createTelemetryConfigurationSecret(ctx, l, d, s, config.MetricsType) } @@ -104,6 +105,7 @@ func (r *reconciler) createMetricsGoverningService( d config.Deployment, s assets.SecretStore, ) error { + svc := generateMetricsStatefulSetService(r.config, d) // Delete the old Secret if one exists and we have no prometheus instances. diff --git a/pkg/operator/resources_logs.go b/pkg/operator/resources_logs.go index 85dc07b6cce9..27617517cd7f 100644 --- a/pkg/operator/resources_logs.go +++ b/pkg/operator/resources_logs.go @@ -19,6 +19,7 @@ func generateLogsDaemonSet( name string, d config.Deployment, ) (*apps_v1.DaemonSet, error) { + d = *d.DeepCopy() if d.Agent.Spec.PortName == "" { diff --git a/pkg/operator/resources_metrics.go b/pkg/operator/resources_metrics.go index ea2cd5dc2456..cd282b464969 100644 --- a/pkg/operator/resources_metrics.go +++ b/pkg/operator/resources_metrics.go @@ -109,6 +109,7 @@ func generateMetricsStatefulSet( d config.Deployment, shard int32, ) (*apps_v1.StatefulSet, error) { + d = *d.DeepCopy() // diff --git a/pkg/traces/automaticloggingprocessor/factory.go b/pkg/traces/automaticloggingprocessor/factory.go index ac1af7e39c82..c942ba7e6f7d 100644 --- a/pkg/traces/automaticloggingprocessor/factory.go +++ b/pkg/traces/automaticloggingprocessor/factory.go @@ -127,7 +127,7 @@ func createTraceProcessor( cfg config.Processor, nextConsumer consumer.Traces, ) (component.TracesProcessor, error) { - oCfg := cfg.(*Config) + oCfg := cfg.(*Config) return newTraceProcessor(nextConsumer, oCfg.LoggingConfig) } diff --git a/pkg/traces/config.go b/pkg/traces/config.go index 87848eeb366f..177c46c80aba 100644 --- a/pkg/traces/config.go +++ b/pkg/traces/config.go @@ -813,6 +813,7 @@ func orderProcessors(processors []string, splitPipelines bool) [][]string { processor == "tail_sampling" || processor == "automatic_logging" || processor == "service_graphs" { + foundAt = i break } diff --git a/pkg/traces/internal/traceutils/server.go b/pkg/traces/internal/traceutils/server.go index 4f2bf2a3f541..d8a9c9a98ae2 100644 --- a/pkg/traces/internal/traceutils/server.go +++ b/pkg/traces/internal/traceutils/server.go @@ -214,6 +214,7 @@ func newFuncProcessorFactory(callback func(pdata.Traces)) component.ProcessorFac _ config.Processor, next consumer.Traces, ) (component.TracesProcessor, error) { + return &funcProcessor{ Callback: callback, Next: next, @@ -254,6 +255,7 @@ func newNoopExporterFactory() component.ExporterFactory { config.Exporter) ( component.TracesExporter, error) { + return &noopExporter{}, nil }), ) diff --git a/pkg/traces/noopreceiver/factory.go b/pkg/traces/noopreceiver/factory.go index 05d50c7a8cef..1963f525b791 100644 --- a/pkg/traces/noopreceiver/factory.go +++ b/pkg/traces/noopreceiver/factory.go @@ -41,5 +41,6 @@ func createMetricsReceiver( _ config.Receiver, _ consumer.Metrics, ) (component.MetricsReceiver, error) { + return newNoopReceiver(nil, nil, nil), nil } diff --git a/pkg/traces/promsdprocessor/factory.go b/pkg/traces/promsdprocessor/factory.go index 006cf2c4de82..7ae4c80d4ec0 100644 --- a/pkg/traces/promsdprocessor/factory.go +++ b/pkg/traces/promsdprocessor/factory.go @@ -59,8 +59,8 @@ func createTraceProcessor( cfg config.Processor, nextConsumer consumer.Traces, ) (component.TracesProcessor, error) { - oCfg := cfg.(*Config) + oCfg := cfg.(*Config) out, err := yaml.Marshal(oCfg.ScrapeConfigs) if err != nil { return nil, fmt.Errorf("unable to marshal scrapeConfigs interface{} to yaml: %w", err) diff --git a/pkg/traces/remotewriteexporter/exporter.go b/pkg/traces/remotewriteexporter/exporter.go index 1f0cab384fb4..371516314bc1 100644 --- a/pkg/traces/remotewriteexporter/exporter.go +++ b/pkg/traces/remotewriteexporter/exporter.go @@ -157,8 +157,8 @@ func (e *remoteWriteExporter) handleHistogramIntDataPoints(app storage.Appender, if err := e.appendDataPointWithLabels(app, name, bucketSuffix, dataPoint, float64(cumulativeCount), ls); err != nil { return err } - } + return nil } diff --git a/pkg/traces/remotewriteexporter/factory.go b/pkg/traces/remotewriteexporter/factory.go index 226df1fc8891..790828a368c8 100644 --- a/pkg/traces/remotewriteexporter/factory.go +++ b/pkg/traces/remotewriteexporter/factory.go @@ -49,7 +49,7 @@ func createMetricsExporter( _ component.ExporterCreateSettings, cfg config.Exporter, ) (component.MetricsExporter, error) { - eCfg := cfg.(*Config) + eCfg := cfg.(*Config) return newRemoteWriteExporter(eCfg) } diff --git a/pkg/traces/servicegraphprocessor/factory.go b/pkg/traces/servicegraphprocessor/factory.go index e31dfa7ff85e..8fcdcb6757cf 100644 --- a/pkg/traces/servicegraphprocessor/factory.go +++ b/pkg/traces/servicegraphprocessor/factory.go @@ -60,7 +60,7 @@ func createTracesProcessor( cfg config.Processor, nextConsumer consumer.Traces, ) (component.TracesProcessor, error) { - eCfg := cfg.(*Config) + eCfg := cfg.(*Config) return newProcessor(nextConsumer, eCfg), nil } diff --git a/pkg/traces/servicegraphprocessor/processor.go b/pkg/traces/servicegraphprocessor/processor.go index 5d59044981d0..39ac5197836d 100644 --- a/pkg/traces/servicegraphprocessor/processor.go +++ b/pkg/traces/servicegraphprocessor/processor.go @@ -279,7 +279,6 @@ func (p *processor) consume(trace pdata.Traces) error { ils := ilsSlice.At(j) for k := 0; k < ils.Spans().Len(); k++ { - span := ils.Spans().At(k) switch span.Kind() { diff --git a/pkg/traces/servicegraphprocessor/processor_test.go b/pkg/traces/servicegraphprocessor/processor_test.go index 48119cb533eb..8f70ae0a4625 100644 --- a/pkg/traces/servicegraphprocessor/processor_test.go +++ b/pkg/traces/servicegraphprocessor/processor_test.go @@ -95,7 +95,6 @@ func TestConsumeMetrics(t *testing.T) { require.NoError(t, err) }) } - } func traceSamples(t *testing.T, path string) pdata.Traces { diff --git a/pkg/util/trigger_test.go b/pkg/util/trigger_test.go index 2959ba974d0f..5e8d4f70702a 100644 --- a/pkg/util/trigger_test.go +++ b/pkg/util/trigger_test.go @@ -26,5 +26,4 @@ func TestWaitTrigger(t *testing.T) { err := wt.Wait(time.Second) require.NoError(t, err) }) - }