diff --git a/.golangci.yml b/.golangci.yml index ee0866e5e14..e44900d7a58 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -143,7 +143,7 @@ linters: - errcheck - errorlint - gocritic - - gofmt + - gofumpt - goimports - gosec - govet diff --git a/client/doc_test.go b/client/doc_test.go index b55eb72862f..6b01ac8777c 100644 --- a/client/doc_test.go +++ b/client/doc_test.go @@ -77,6 +77,7 @@ func (e *exampleAuthData) GetAttribute(key string) any { } return nil } + func (e *exampleAuthData) GetAttributeNames() []string { return []string{"username"} } diff --git a/cmd/builder/internal/builder/config.go b/cmd/builder/internal/builder/config.go index d0549e0d6ea..902d13500f4 100644 --- a/cmd/builder/internal/builder/config.go +++ b/cmd/builder/internal/builder/config.go @@ -17,14 +17,14 @@ import ( "go.uber.org/zap" ) -const defaultBetaOtelColVersion = "v0.113.0" -const defaultStableOtelColVersion = "v1.17.0" - -var ( - // errMissingGoMod indicates an empty gomod field - errMissingGoMod = errors.New("missing gomod specification for module") +const ( + defaultBetaOtelColVersion = "v0.113.0" + defaultStableOtelColVersion = "v1.17.0" ) +// errMissingGoMod indicates an empty gomod field +var errMissingGoMod = errors.New("missing gomod specification for module") + // Config holds the builder's configuration type Config struct { Logger *zap.Logger diff --git a/cmd/builder/internal/builder/main.go b/cmd/builder/internal/builder/main.go index 8b564532d6a..197d1038613 100644 --- a/cmd/builder/internal/builder/main.go +++ b/cmd/builder/internal/builder/main.go @@ -77,7 +77,7 @@ func Generate(cfg *Config) error { // if the file does not exist, try to create it if _, err := os.Stat(cfg.Distribution.OutputPath); os.IsNotExist(err) { - if err = os.Mkdir(cfg.Distribution.OutputPath, 0750); err != nil { + if err = os.Mkdir(cfg.Distribution.OutputPath, 0o750); err != nil { return fmt.Errorf("failed to create output path: %w", err) } } else if err != nil { @@ -109,7 +109,7 @@ func Compile(cfg *Config) error { cfg.Logger.Info("Compiling") - var ldflags = "-s -w" + ldflags := "-s -w" args := []string{"build", "-trimpath", "-o", cfg.Distribution.Name} if cfg.Distribution.DebugCompilation { diff --git a/cmd/builder/internal/builder/main_test.go b/cmd/builder/internal/builder/main_test.go index e1b43a99210..c491978b534 100644 --- a/cmd/builder/internal/builder/main_test.go +++ b/cmd/builder/internal/builder/main_test.go @@ -37,75 +37,73 @@ require ( modulePrefix = "go.opentelemetry.io/collector" ) -var ( - replaceModules = []string{ - "", - "/component", - "/component/componenttest", - "/component/componentstatus", - "/client", - "/config/configauth", - "/config/configcompression", - "/config/configgrpc", - "/config/confighttp", - "/config/confignet", - "/config/configopaque", - "/config/configretry", - "/config/configtelemetry", - "/config/configtls", - "/config/internal", - "/confmap", - "/confmap/provider/envprovider", - "/confmap/provider/fileprovider", - "/confmap/provider/httpprovider", - "/confmap/provider/httpsprovider", - "/confmap/provider/yamlprovider", - "/consumer", - "/consumer/consumererror", - "/consumer/consumererror/consumererrorprofiles", - "/consumer/consumerprofiles", - "/consumer/consumertest", - "/connector", - "/connector/connectortest", - "/connector/connectorprofiles", - "/exporter", - "/exporter/debugexporter", - "/exporter/exporterprofiles", - "/exporter/exportertest", - "/exporter/exporterhelper/exporterhelperprofiles", - "/exporter/nopexporter", - "/exporter/otlpexporter", - "/exporter/otlphttpexporter", - "/extension", - "/extension/auth", - "/extension/experimental/storage", - "/extension/extensioncapabilities", +var replaceModules = []string{ + "", + "/component", + "/component/componenttest", + "/component/componentstatus", + "/client", + "/config/configauth", + "/config/configcompression", + "/config/configgrpc", + "/config/confighttp", + "/config/confignet", + "/config/configopaque", + "/config/configretry", + "/config/configtelemetry", + "/config/configtls", + "/config/internal", + "/confmap", + "/confmap/provider/envprovider", + "/confmap/provider/fileprovider", + "/confmap/provider/httpprovider", + "/confmap/provider/httpsprovider", + "/confmap/provider/yamlprovider", + "/consumer", + "/consumer/consumererror", + "/consumer/consumererror/consumererrorprofiles", + "/consumer/consumerprofiles", + "/consumer/consumertest", + "/connector", + "/connector/connectortest", + "/connector/connectorprofiles", + "/exporter", + "/exporter/debugexporter", + "/exporter/exporterprofiles", + "/exporter/exportertest", + "/exporter/exporterhelper/exporterhelperprofiles", + "/exporter/nopexporter", + "/exporter/otlpexporter", + "/exporter/otlphttpexporter", + "/extension", + "/extension/auth", + "/extension/experimental/storage", + "/extension/extensioncapabilities", "/extension/extensiontest", - "/extension/zpagesextension", - "/featuregate", - "/internal/memorylimiter", - "/internal/fanoutconsumer", - "/internal/sharedcomponent", - "/otelcol", - "/pipeline", - "/pipeline/pipelineprofiles", - "/processor", - "/processor/processortest", - "/processor/batchprocessor", - "/processor/memorylimiterprocessor", - "/processor/processorprofiles", - "/receiver", - "/receiver/nopreceiver", - "/receiver/otlpreceiver", - "/receiver/receiverprofiles", - "/receiver/receivertest", - "/pdata", - "/pdata/testdata", - "/pdata/pprofile", - "/semconv", - "/service", - } -) + "/extension/zpagesextension", + "/featuregate", + "/internal/memorylimiter", + "/internal/fanoutconsumer", + "/internal/sharedcomponent", + "/otelcol", + "/pipeline", + "/pipeline/pipelineprofiles", + "/processor", + "/processor/processortest", + "/processor/batchprocessor", + "/processor/memorylimiterprocessor", + "/processor/processorprofiles", + "/receiver", + "/receiver/nopreceiver", + "/receiver/otlpreceiver", + "/receiver/receiverprofiles", + "/receiver/receivertest", + "/pdata", + "/pdata/testdata", + "/pdata/pprofile", + "/semconv", + "/service", +} func newTestConfig(t testing.TB) *Config { cfg, err := NewDefaultConfig() @@ -427,14 +425,14 @@ func verifyGoMod(t *testing.T, dir string, replaceMods map[string]bool) { func makeModule(dir string, fileContents []byte) error { // if the file does not exist, try to create it if _, err := os.Stat(dir); os.IsNotExist(err) { - if err = os.Mkdir(dir, 0750); err != nil { + if err = os.Mkdir(dir, 0o750); err != nil { return fmt.Errorf("failed to create output path: %w", err) } } else if err != nil { return fmt.Errorf("failed to create output path: %w", err) } - err := os.WriteFile(filepath.Clean(filepath.Join(dir, "go.mod")), fileContents, 0600) + err := os.WriteFile(filepath.Clean(filepath.Join(dir, "go.mod")), fileContents, 0o600) if err != nil { return fmt.Errorf("failed to write go.mod file: %w", err) } diff --git a/cmd/builder/internal/version.go b/cmd/builder/internal/version.go index 98481612df4..3ceec03e7b7 100644 --- a/cmd/builder/internal/version.go +++ b/cmd/builder/internal/version.go @@ -10,9 +10,7 @@ import ( "github.com/spf13/cobra" ) -var ( - version = "" -) +var version = "" func init() { // the second returned value is a boolean, which is true if the binaries are built with module support. diff --git a/cmd/mdatagen/internal/command.go b/cmd/mdatagen/internal/command.go index 9d64f4492af..706a2985411 100644 --- a/cmd/mdatagen/internal/command.go +++ b/cmd/mdatagen/internal/command.go @@ -75,7 +75,7 @@ func run(ymlPath string) error { tmplDir := "templates" codeDir := filepath.Join(ymlDir, "internal", md.GeneratedPackageName) - if err = os.MkdirAll(codeDir, 0700); err != nil { + if err = os.MkdirAll(codeDir, 0o700); err != nil { return fmt.Errorf("unable to create output directory %q: %w", codeDir, err) } if md.Status != nil { @@ -130,7 +130,7 @@ func run(ymlPath string) error { return nil } - if err = os.MkdirAll(filepath.Join(codeDir, "testdata"), 0700); err != nil { + if err = os.MkdirAll(filepath.Join(codeDir, "testdata"), 0o700); err != nil { return fmt.Errorf("unable to create output directory %q: %w", filepath.Join(codeDir, "testdata"), err) } @@ -376,7 +376,7 @@ func inlineReplace(tmplFile string, outputFile string, md Metadata, start string return err } - var re = regexp.MustCompile(fmt.Sprintf("%s[\\s\\S]*%s", start, end)) + re := regexp.MustCompile(fmt.Sprintf("%s[\\s\\S]*%s", start, end)) if !re.Match(readmeContents) { return nil } @@ -391,7 +391,7 @@ func inlineReplace(tmplFile string, outputFile string, md Metadata, start string } s := re.ReplaceAllString(string(readmeContents), string(buf)) - if err := os.WriteFile(outputFile, []byte(s), 0600); err != nil { + if err := os.WriteFile(outputFile, []byte(s), 0o600); err != nil { return fmt.Errorf("failed writing %q: %w", outputFile, err) } @@ -416,7 +416,7 @@ func generateFile(tmplFile string, outputFile string, md Metadata, goPackage str } } - if err := os.WriteFile(outputFile, result, 0600); err != nil { + if err := os.WriteFile(outputFile, result, 0o600); err != nil { return fmt.Errorf("failed writing %q: %w", outputFile, err) } diff --git a/cmd/mdatagen/internal/command_test.go b/cmd/mdatagen/internal/command_test.go index a143da7ec02..a8a60cd1181 100644 --- a/cmd/mdatagen/internal/command_test.go +++ b/cmd/mdatagen/internal/command_test.go @@ -137,16 +137,16 @@ func TestRunContents(t *testing.T) { for _, tt := range tests { t.Run(tt.yml, func(t *testing.T) { tmpdir := filepath.Join(t.TempDir(), "shortname") - err := os.MkdirAll(tmpdir, 0750) + err := os.MkdirAll(tmpdir, 0o750) require.NoError(t, err) ymlContent, err := os.ReadFile(filepath.Join("testdata", tt.yml)) require.NoError(t, err) metadataFile := filepath.Join(tmpdir, "metadata.yaml") - require.NoError(t, os.WriteFile(metadataFile, ymlContent, 0600)) + require.NoError(t, os.WriteFile(metadataFile, ymlContent, 0o600)) require.NoError(t, os.WriteFile(filepath.Join(tmpdir, "README.md"), []byte(` foo -`), 0600)) +`), 0o600)) err = run(metadataFile) if tt.wantErr { @@ -472,7 +472,7 @@ Some info about a component tmpdir := t.TempDir() readmeFile := filepath.Join(tmpdir, "README.md") - require.NoError(t, os.WriteFile(readmeFile, []byte(tt.markdown), 0600)) + require.NoError(t, os.WriteFile(readmeFile, []byte(tt.markdown), 0o600)) err := inlineReplace("templates/readme.md.tmpl", readmeFile, md, statusStart, statusEnd, "metadata") require.NoError(t, err) diff --git a/cmd/mdatagen/internal/lint_test.go b/cmd/mdatagen/internal/lint_test.go index 24789d1011b..feca8fac27b 100644 --- a/cmd/mdatagen/internal/lint_test.go +++ b/cmd/mdatagen/internal/lint_test.go @@ -10,7 +10,7 @@ import ( ) func TestFormatIdentifier(t *testing.T) { - var tests = []struct { + tests := []struct { input string want string exported bool diff --git a/cmd/mdatagen/internal/metric.go b/cmd/mdatagen/internal/metric.go index 0d36efa372f..a24f7ded9ee 100644 --- a/cmd/mdatagen/internal/metric.go +++ b/cmd/mdatagen/internal/metric.go @@ -113,6 +113,7 @@ func (m *Metric) Unmarshal(parser *confmap.Conf) error { } return parser.Unmarshal(m) } + func (m Metric) Data() MetricData { if m.Sum != nil { return m.Sum diff --git a/component/componentstatus/status_test.go b/component/componentstatus/status_test.go index 87efdd245a4..43789e58925 100644 --- a/component/componentstatus/status_test.go +++ b/component/componentstatus/status_test.go @@ -105,8 +105,10 @@ func Test_ReportStatus(t *testing.T) { }) } -var _ = (component.Host)(nil) -var _ = (Reporter)(nil) +var ( + _ = (component.Host)(nil) + _ = (Reporter)(nil) +) type reporter struct { reportStatusCalled bool diff --git a/component/config_test.go b/component/config_test.go index 9e6daa0f618..2ac8f0a4fc6 100644 --- a/component/config_test.go +++ b/component/config_test.go @@ -75,7 +75,7 @@ func newErrMapType() *errMapType { } func TestValidateConfig(t *testing.T) { - var tests = []struct { + tests := []struct { name string cfg any expected error diff --git a/component/identifiable_test.go b/component/identifiable_test.go index 883e3c891a8..9f0d203606c 100644 --- a/component/identifiable_test.go +++ b/component/identifiable_test.go @@ -20,7 +20,7 @@ func TestMarshalText(t *testing.T) { func TestUnmarshalText(t *testing.T) { validType := MustNewType("valid_type") - var testCases = []struct { + testCases := []struct { name string expectedErr bool expectedID ID diff --git a/config/configgrpc/configgrpc_benchmark_test.go b/config/configgrpc/configgrpc_benchmark_test.go index 21125bcba59..e087497c769 100644 --- a/config/configgrpc/configgrpc_benchmark_test.go +++ b/config/configgrpc/configgrpc_benchmark_test.go @@ -124,45 +124,54 @@ func setupTestPayloads() []testPayload { payloads = append(payloads, testPayload{ name: "sm_log_request", message: testdata.GenerateLogs(1), - marshaler: logMarshaler}) + marshaler: logMarshaler, + }) payloads = append(payloads, testPayload{ name: "md_log_request", message: testdata.GenerateLogs(2), - marshaler: logMarshaler}) + marshaler: logMarshaler, + }) payloads = append(payloads, testPayload{ name: "lg_log_request", message: testdata.GenerateLogs(50), - marshaler: logMarshaler}) + marshaler: logMarshaler, + }) // trace payloads tracesMarshaler := &traceMarshaler{Marshaler: &ptrace.ProtoMarshaler{}} payloads = append(payloads, testPayload{ name: "sm_trace_request", message: testdata.GenerateTraces(1), - marshaler: tracesMarshaler}) + marshaler: tracesMarshaler, + }) payloads = append(payloads, testPayload{ name: "md_trace_request", message: testdata.GenerateTraces(2), - marshaler: tracesMarshaler}) + marshaler: tracesMarshaler, + }) payloads = append(payloads, testPayload{ name: "lg_trace_request", message: testdata.GenerateTraces(50), - marshaler: tracesMarshaler}) + marshaler: tracesMarshaler, + }) // metric payloads metricsMarshaler := &metricsMarshaler{Marshaler: &pmetric.ProtoMarshaler{}} payloads = append(payloads, testPayload{ name: "sm_metric_request", message: testdata.GenerateMetrics(1), - marshaler: metricsMarshaler}) + marshaler: metricsMarshaler, + }) payloads = append(payloads, testPayload{ name: "md_metric_request", message: testdata.GenerateMetrics(2), - marshaler: metricsMarshaler}) + marshaler: metricsMarshaler, + }) payloads = append(payloads, testPayload{ name: "lg_metric_request", message: testdata.GenerateMetrics(50), - marshaler: metricsMarshaler}) + marshaler: metricsMarshaler, + }) return payloads } diff --git a/config/configgrpc/configgrpc_test.go b/config/configgrpc/configgrpc_test.go index 561df1f1dfe..29979609197 100644 --- a/config/configgrpc/configgrpc_test.go +++ b/config/configgrpc/configgrpc_test.go @@ -57,12 +57,14 @@ func TestNewDefaultClientConfig(t *testing.T) { assert.Equal(t, expected, result) } + func TestNewDefaultKeepaliveServerParameters(t *testing.T) { expectedParams := &KeepaliveServerParameters{} params := NewDefaultKeepaliveServerParameters() assert.Equal(t, expectedParams, params) } + func TestNewDefaultKeepaliveEnforcementPolicy(t *testing.T) { expectedPolicy := &KeepaliveEnforcementPolicy{} diff --git a/config/configgrpc/wrappedstream_test.go b/config/configgrpc/wrappedstream_test.go index e08ba64426b..36a0dbfd3fa 100644 --- a/config/configgrpc/wrappedstream_test.go +++ b/config/configgrpc/wrappedstream_test.go @@ -14,8 +14,10 @@ import ( type ctxKey struct{} -var oneCtxKey = ctxKey{} -var otherCtxKey = ctxKey{} +var ( + oneCtxKey = ctxKey{} + otherCtxKey = ctxKey{} +) func TestWrapServerStream(t *testing.T) { ctx := context.WithValue(context.TODO(), oneCtxKey, 1) diff --git a/config/confighttp/confighttp.go b/config/confighttp/confighttp.go index 69ac3900fe5..b4946a09a8a 100644 --- a/config/confighttp/confighttp.go +++ b/config/confighttp/confighttp.go @@ -33,8 +33,11 @@ import ( "go.opentelemetry.io/collector/extension/auth" ) -const headerContentEncoding = "Content-Encoding" -const defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB +const ( + headerContentEncoding = "Content-Encoding" + defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB +) + var defaultCompressionAlgorithms = []string{"", "gzip", "zstd", "zlib", "snappy", "deflate", "lz4"} // ClientConfig defines settings for creating an HTTP client. diff --git a/config/confighttp/confighttp_test.go b/config/confighttp/confighttp_test.go index f314fa96948..938c193ff17 100644 --- a/config/confighttp/confighttp_test.go +++ b/config/confighttp/confighttp_test.go @@ -37,8 +37,7 @@ import ( "go.opentelemetry.io/collector/extension/auth/authtest" ) -type customRoundTripper struct { -} +type customRoundTripper struct{} var _ http.RoundTripper = (*customRoundTripper)(nil) @@ -431,7 +430,8 @@ func TestHTTPClientSettingWithAuthConfig(t *testing.T) { host: &mockHost{ ext: map[component.ID]component.Component{ mockID: &authtest.MockClient{ - ResultRoundTripper: &customRoundTripper{}, MustError: true}, + ResultRoundTripper: &customRoundTripper{}, MustError: true, + }, }, }, }, diff --git a/config/configopaque/doc_test.go b/config/configopaque/doc_test.go index e8ce708155d..e62e62cddb1 100644 --- a/config/configopaque/doc_test.go +++ b/config/configopaque/doc_test.go @@ -31,7 +31,7 @@ func Example_opaqueString() { panic(err) } fmt.Printf("encoded cfg (YAML) is:\n%s\n\n", string(bytes)) - //Output: encoded cfg (YAML) is: + // Output: encoded cfg (YAML) is: // censored: '[REDACTED]' // uncensored: not sensitive } @@ -53,7 +53,7 @@ func Example_opaqueSlice() { panic(err) } fmt.Printf("encoded cfg (JSON) is\n%s\n\n", string(bytes)) - //Output: encoded cfg (JSON) is + // Output: encoded cfg (JSON) is // { // "Censored": [ // "[REDACTED]", @@ -91,10 +91,10 @@ func Example_opaqueMap() { panic(err) } fmt.Printf("encoded cfg (YAML) is:\n%s\n\n", string(bytes)) - //Output: encoded cfg (YAML) is: - //censored: + // Output: encoded cfg (YAML) is: + // censored: // token: '[REDACTED]' - //uncensored: + // uncensored: // key: cloud.zone // value: zone-1 } diff --git a/config/configtelemetry/configtelemetry_test.go b/config/configtelemetry/configtelemetry_test.go index 1832fc0e175..4404c453878 100644 --- a/config/configtelemetry/configtelemetry_test.go +++ b/config/configtelemetry/configtelemetry_test.go @@ -11,8 +11,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ encoding.TextMarshaler = (*Level)(nil) -var _ encoding.TextUnmarshaler = (*Level)(nil) +var ( + _ encoding.TextMarshaler = (*Level)(nil) + _ encoding.TextUnmarshaler = (*Level)(nil) +) func TestUnmarshalText(t *testing.T) { tests := []struct { diff --git a/config/configtls/clientcasfilereloader_test.go b/config/configtls/clientcasfilereloader_test.go index f5e7a1b0e39..273a887823e 100644 --- a/config/configtls/clientcasfilereloader_test.go +++ b/config/configtls/clientcasfilereloader_test.go @@ -60,7 +60,7 @@ func TestErrorRecordedIfFileDeleted(t *testing.T) { loader.returnErrorOnSubsequentCalls("test error on reload") - err = os.WriteFile(filePath, []byte("some_data"), 0600) + err = os.WriteFile(filePath, []byte("some_data"), 0o600) require.NoError(t, err) assert.Eventually(t, func() bool { diff --git a/config/configtls/configtls_test.go b/config/configtls/configtls_test.go index 4c2cd6a7c76..2f1f1fb3439 100644 --- a/config/configtls/configtls_test.go +++ b/config/configtls/configtls_test.go @@ -441,11 +441,11 @@ func TestLoadTLSServerConfigFailing(t *testing.T) { } func overwriteClientCA(t *testing.T, targetFilePath string, testdataFileName string) { - targetFile, err := os.OpenFile(filepath.Clean(targetFilePath), os.O_RDWR, 0600) + targetFile, err := os.OpenFile(filepath.Clean(targetFilePath), os.O_RDWR, 0o600) require.NoError(t, err) testdataFilePath := filepath.Join("testdata", testdataFileName) - testdataFile, err := os.OpenFile(filepath.Clean(testdataFilePath), os.O_RDONLY, 0200) + testdataFile, err := os.OpenFile(filepath.Clean(testdataFilePath), os.O_RDONLY, 0o200) require.NoError(t, err) _, err = io.Copy(targetFile, testdataFile) diff --git a/confmap/confmap.go b/confmap/confmap.go index a7a99d10352..c21bcc61fc1 100644 --- a/confmap/confmap.go +++ b/confmap/confmap.go @@ -287,7 +287,8 @@ func useExpandValue() mapstructure.DecodeHookFuncType { return func( _ reflect.Type, to reflect.Type, - data any) (any, error) { + data any, + ) (any, error) { if exp, ok := data.(expandedValue); ok { v := castTo(exp, to.Kind() == reflect.String) // See https://github.com/open-telemetry/opentelemetry-collector/issues/10949 diff --git a/confmap/confmap_test.go b/confmap/confmap_test.go index 7055b683fa7..72a64497d00 100644 --- a/confmap/confmap_test.go +++ b/confmap/confmap_test.go @@ -449,15 +449,13 @@ func (ec *EmbeddedConfig2) Unmarshal(component *Conf) error { return nil } -type EmbeddedConfigWithError struct { -} +type EmbeddedConfigWithError struct{} func (ecwe *EmbeddedConfigWithError) Unmarshal(_ *Conf) error { return errors.New("embedded error") } -type EmbeddedConfigWithMarshalError struct { -} +type EmbeddedConfigWithMarshalError struct{} func (ecwe EmbeddedConfigWithMarshalError) Marshal(_ *Conf) error { return errors.New("marshaling error") @@ -864,7 +862,8 @@ func TestExpandedValue(t *testing.T) { "key": expandedValue{ Value: 0xdeadbeef, Original: "original", - }}) + }, + }) assert.Equal(t, 0xdeadbeef, cm.Get("key")) assert.Equal(t, map[string]any{"key": 0xdeadbeef}, cm.ToStringMap()) diff --git a/confmap/doc_test.go b/confmap/doc_test.go index 35492d3cae0..ee84acb25d4 100644 --- a/confmap/doc_test.go +++ b/confmap/doc_test.go @@ -27,7 +27,7 @@ func Example_simpleUnmarshaling() { panic(err) } fmt.Printf("Configuration contains the following:\nDisk: %q\nScrape: %s\n", scrapeInfo.Disk, scrapeInfo.Scrape) - //Output: Configuration contains the following: + // Output: Configuration contains the following: // Disk: "c" // Scrape: 5s } @@ -53,7 +53,7 @@ func Example_embeddedUnmarshaling() { panic(err) } fmt.Printf("Configuration contains the following:\nDisk: %q\nScrape: %s\nEnabled: %v\n", scrapeInfo.Disk, scrapeInfo.Scrape, scrapeInfo.Enabled) - //Output: Configuration contains the following: + // Output: Configuration contains the following: // Disk: "c" // Scrape: 5s // Enabled: true @@ -105,7 +105,7 @@ func Example_embeddedManualUnmarshaling() { panic(err) } fmt.Printf("Configuration contains the following:\nNetworks: %q\nWifi: %v\nEnabled: %v\n", scrapeInfo.Networks, scrapeInfo.Wifi, scrapeInfo.Enabled) - //Output: Configuration contains the following: + // Output: Configuration contains the following: // Networks: ["eth0" "eth1" "wlan0"] // Wifi: true // Enabled: true @@ -121,7 +121,7 @@ func Example_manualUnmarshaling() { panic(err) } fmt.Printf("Configuration contains the following:\nDisk: %q\nScrape: %s\n", scrapeInfo.Disk, scrapeInfo.Scrape) - //Output: Configuration contains the following: + // Output: Configuration contains the following: // Disk: "Beatles" // Scrape: 10s } diff --git a/confmap/expand_test.go b/confmap/expand_test.go index d634564d5b6..9062ef7a087 100644 --- a/confmap/expand_test.go +++ b/confmap/expand_test.go @@ -14,7 +14,7 @@ import ( ) func TestResolverExpandEnvVars(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string // test case name (also file name containing config yaml) }{ {name: "expand-with-no-env.yaml"}, @@ -75,7 +75,8 @@ func TestResolverExpandMapAndSliceValues(t *testing.T) { provider := newFakeProvider("input", func(context.Context, string, WatcherFunc) (*Retrieved, error) { return NewRetrieved(map[string]any{ "test_map": map[string]any{"recv": "${test:MAP_VALUE}"}, - "test_slice": []any{"${test:MAP_VALUE}"}}) + "test_slice": []any{"${test:MAP_VALUE}"}, + }) }) const receiverExtraMapValue = "some map value" @@ -90,7 +91,8 @@ func TestResolverExpandMapAndSliceValues(t *testing.T) { require.NoError(t, err) expectedMap := map[string]any{ "test_map": map[string]any{"recv": receiverExtraMapValue}, - "test_slice": []any{receiverExtraMapValue}} + "test_slice": []any{receiverExtraMapValue}, + } assert.Equal(t, expectedMap, cfgMap.ToStringMap()) } diff --git a/confmap/internal/e2e/types_test.go b/confmap/internal/e2e/types_test.go index 384ec092727..a820d70608c 100644 --- a/confmap/internal/e2e/types_test.go +++ b/confmap/internal/e2e/types_test.go @@ -408,7 +408,8 @@ func TestRecursiveMaps(t *testing.T) { Env: ENV2{ Env2: Value{ Value: 123, - }}, + }, + }, Inline: "inline {env2: \"{value: 123}\"}", }}, cfg, diff --git a/confmap/internal/mapstructure/encoder.go b/confmap/internal/mapstructure/encoder.go index 994ad038fd3..ffc0bdc2985 100644 --- a/confmap/internal/mapstructure/encoder.go +++ b/confmap/internal/mapstructure/encoder.go @@ -23,9 +23,7 @@ const ( optionSkip = "-" ) -var ( - errNonStringEncodedKey = errors.New("non string-encoded key") -) +var errNonStringEncodedKey = errors.New("non string-encoded key") // tagInfo stores the mapstructure tag details. type tagInfo struct { diff --git a/confmap/provider/internal/configurablehttpprovider/provider.go b/confmap/provider/internal/configurablehttpprovider/provider.go index 87a37fbc907..d982d770f75 100644 --- a/confmap/provider/internal/configurablehttpprovider/provider.go +++ b/confmap/provider/internal/configurablehttpprovider/provider.go @@ -49,14 +49,12 @@ func (fmp *provider) createClient() (*http.Client, error) { return &http.Client{}, nil case HTTPSScheme: pool, err := x509.SystemCertPool() - if err != nil { return nil, fmt.Errorf("unable to create a cert pool: %w", err) } if fmp.caCertPath != "" { cert, err := os.ReadFile(filepath.Clean(fmp.caCertPath)) - if err != nil { return nil, fmt.Errorf("unable to read CA from %q URI: %w", fmp.caCertPath, err) } @@ -89,7 +87,6 @@ func (fmp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFu } client, err := fmp.createClient() - if err != nil { return nil, fmt.Errorf("unable to configure http transport layer: %w", err) } diff --git a/confmap/provider/internal/configurablehttpprovider/provider_test.go b/confmap/provider/internal/configurablehttpprovider/provider_test.go index 0011cd2674d..fab77910eaf 100644 --- a/confmap/provider/internal/configurablehttpprovider/provider_test.go +++ b/confmap/provider/internal/configurablehttpprovider/provider_test.go @@ -52,7 +52,6 @@ func answerGet(w http.ResponseWriter, _ *http.Request) { // https://go.dev/src/crypto/tls/generate_cert.go func generateCertificate(hostname string) (cert string, key string, err error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { return "", "", fmt.Errorf("Failed to generate private key: %w", err) } @@ -62,7 +61,6 @@ func generateCertificate(hostname string) (cert string, key string, err error) { notAfter := notBefore.Add(time.Hour * 12) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { return "", "", fmt.Errorf("Failed to generate serial number: %w", err) } @@ -81,7 +79,6 @@ func generateCertificate(hostname string) (cert string, key string, err error) { DNSNames: []string{hostname}, } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) - if err != nil { return "", "", fmt.Errorf("Failed to create certificate: %w", err) } @@ -100,13 +97,11 @@ func generateCertificate(hostname string) (cert string, key string, err error) { } keyOut, err := os.CreateTemp("", "key*.pem") - if err != nil { return "", "", fmt.Errorf("Failed to open key.pem for writing: %w", err) } privBytes, err := x509.MarshalPKCS8PrivateKey(priv) - if err != nil { return "", "", fmt.Errorf("Unable to marshal private key: %w", err) } diff --git a/confmap/resolver_test.go b/confmap/resolver_test.go index 4c9691ca7b8..b9b96dec0fb 100644 --- a/confmap/resolver_test.go +++ b/confmap/resolver_test.go @@ -302,7 +302,8 @@ func TestBackwardsCompatibilityForFilePath(t *testing.T) { return nil, errors.New(uri) }), }, - ConverterFactories: nil}) + ConverterFactories: nil, + }) if tt.expectBuildErr { assert.Error(t, err) return @@ -324,7 +325,8 @@ func TestResolver(t *testing.T) { return nil }}), }, - ConverterFactories: nil}) + ConverterFactories: nil, + }) require.NoError(t, err) _, errN := resolver.Resolve(context.Background()) require.NoError(t, errN) @@ -355,7 +357,8 @@ func TestResolverNewLinesInOpaqueValue(t *testing.T) { _, err := NewResolver(ResolverSettings{ URIs: []string{"mock:receivers:\n nop:\n"}, ProviderFactories: []ProviderFactory{newMockProvider(&mockProvider{retM: map[string]any{}})}, - ConverterFactories: nil}) + ConverterFactories: nil, + }) assert.NoError(t, err) } @@ -363,7 +366,8 @@ func TestResolverNoLocations(t *testing.T) { _, err := NewResolver(ResolverSettings{ URIs: []string{}, ProviderFactories: []ProviderFactory{newMockProvider(&mockProvider{})}, - ConverterFactories: nil}) + ConverterFactories: nil, + }) assert.Error(t, err) } @@ -371,7 +375,8 @@ func TestResolverNoProviders(t *testing.T) { _, err := NewResolver(ResolverSettings{ URIs: []string{filepath.Join("testdata", "config.yaml")}, ProviderFactories: nil, - ConverterFactories: nil}) + ConverterFactories: nil, + }) assert.Error(t, err) } @@ -379,7 +384,8 @@ func TestResolverShutdownClosesWatch(t *testing.T) { resolver, err := NewResolver(ResolverSettings{ URIs: []string{filepath.Join("testdata", "config.yaml")}, ProviderFactories: []ProviderFactory{newFileProvider(t)}, - ConverterFactories: nil}) + ConverterFactories: nil, + }) require.NoError(t, err) _, errN := resolver.Resolve(context.Background()) require.NoError(t, errN) diff --git a/connector/connector_test.go b/connector/connector_test.go index 6dcff6d6a97..e190f5a4c31 100644 --- a/connector/connector_test.go +++ b/connector/connector_test.go @@ -228,9 +228,11 @@ type nopConnector struct { func createTracesToTraces(context.Context, Settings, component.Config, consumer.Traces) (Traces, error) { return nopInstance, nil } + func createTracesToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Traces, error) { return nopInstance, nil } + func createTracesToLogs(context.Context, Settings, component.Config, consumer.Logs) (Traces, error) { return nopInstance, nil } @@ -238,9 +240,11 @@ func createTracesToLogs(context.Context, Settings, component.Config, consumer.Lo func createMetricsToTraces(context.Context, Settings, component.Config, consumer.Traces) (Metrics, error) { return nopInstance, nil } + func createMetricsToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error) { return nopInstance, nil } + func createMetricsToLogs(context.Context, Settings, component.Config, consumer.Logs) (Metrics, error) { return nopInstance, nil } @@ -248,9 +252,11 @@ func createMetricsToLogs(context.Context, Settings, component.Config, consumer.L func createLogsToTraces(context.Context, Settings, component.Config, consumer.Traces) (Logs, error) { return nopInstance, nil } + func createLogsToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Logs, error) { return nopInstance, nil } + func createLogsToLogs(context.Context, Settings, component.Config, consumer.Logs) (Logs, error) { return nopInstance, nil } diff --git a/connector/connectorprofiles/connector_test.go b/connector/connectorprofiles/connector_test.go index 9e351b7f468..0a1a9851d95 100644 --- a/connector/connectorprofiles/connector_test.go +++ b/connector/connectorprofiles/connector_test.go @@ -138,9 +138,11 @@ func createProfilesToProfiles(context.Context, connector.Settings, component.Con func createProfilesToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (Profiles, error) { return nopInstance, nil } + func createProfilesToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (Profiles, error) { return nopInstance, nil } + func createProfilesToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (Profiles, error) { return nopInstance, nil } diff --git a/connector/connectorprofiles/profiles_router_test.go b/connector/connectorprofiles/profiles_router_test.go index e3d76499460..68b8aa27957 100644 --- a/connector/connectorprofiles/profiles_router_test.go +++ b/connector/connectorprofiles/profiles_router_test.go @@ -30,7 +30,7 @@ func (mts *mutatingProfilesSink) Capabilities() consumer.Capabilities { } func TestProfilesRouterMultiplexing(t *testing.T) { - var num = 20 + num := 20 for numIDs := 1; numIDs < num; numIDs++ { for numCons := 1; numCons < num; numCons++ { for numProfiles := 1; numProfiles < num; numProfiles++ { diff --git a/connector/connectortest/connector.go b/connector/connectortest/connector.go index 2905ce80f75..bbedb7e2623 100644 --- a/connector/connectortest/connector.go +++ b/connector/connectortest/connector.go @@ -83,6 +83,7 @@ func createMetricsToMetricsConnector(context.Context, connector.Settings, compon func createMetricsToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Metrics, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } + func createMetricsToProfilesConnector(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connector.Metrics, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } @@ -98,6 +99,7 @@ func createLogsToMetricsConnector(context.Context, connector.Settings, component func createLogsToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Logs, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } + func createLogsToProfilesConnector(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connector.Logs, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } @@ -113,6 +115,7 @@ func createProfilesToMetricsConnector(context.Context, connector.Settings, compo func createProfilesToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connectorprofiles.Profiles, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } + func createProfilesToProfilesConnector(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connectorprofiles.Profiles, error) { return &nopConnector{Consumer: consumertest.NewNop()}, nil } diff --git a/connector/logs_router_test.go b/connector/logs_router_test.go index dd59ce5a55d..4b9c0c53e5f 100644 --- a/connector/logs_router_test.go +++ b/connector/logs_router_test.go @@ -28,7 +28,7 @@ func (mts *mutatingLogsSink) Capabilities() consumer.Capabilities { } func TestLogsRouterMultiplexing(t *testing.T) { - var num = 20 + num := 20 for numIDs := 1; numIDs < num; numIDs++ { for numCons := 1; numCons < num; numCons++ { for numLogs := 1; numLogs < num; numLogs++ { diff --git a/connector/metrics_router_test.go b/connector/metrics_router_test.go index c0bf7eb0df0..942e27d4995 100644 --- a/connector/metrics_router_test.go +++ b/connector/metrics_router_test.go @@ -28,7 +28,7 @@ func (mts *mutatingMetricsSink) Capabilities() consumer.Capabilities { } func TestMetricsRouterMultiplexing(t *testing.T) { - var num = 20 + num := 20 for numIDs := 1; numIDs < num; numIDs++ { for numCons := 1; numCons < num; numCons++ { for numMetrics := 1; numMetrics < num; numMetrics++ { diff --git a/connector/traces_router_test.go b/connector/traces_router_test.go index 70b798c2266..7438d4aa9ab 100644 --- a/connector/traces_router_test.go +++ b/connector/traces_router_test.go @@ -28,7 +28,7 @@ func (mts *mutatingTracesSink) Capabilities() consumer.Capabilities { } func TestTracesRouterMultiplexing(t *testing.T) { - var num = 20 + num := 20 for numIDs := 1; numIDs < num; numIDs++ { for numCons := 1; numCons < num; numCons++ { for numTraces := 1; numTraces < num; numTraces++ { diff --git a/consumer/consumertest/consumer.go b/consumer/consumertest/consumer.go index 4b699b9449a..1d9d4051af1 100644 --- a/consumer/consumertest/consumer.go +++ b/consumer/consumertest/consumer.go @@ -37,10 +37,12 @@ type Consumer interface { unexported() } -var _ consumer.Logs = (Consumer)(nil) -var _ consumer.Metrics = (Consumer)(nil) -var _ consumer.Traces = (Consumer)(nil) -var _ consumerprofiles.Profiles = (Consumer)(nil) +var ( + _ consumer.Logs = (Consumer)(nil) + _ consumer.Metrics = (Consumer)(nil) + _ consumer.Traces = (Consumer)(nil) + _ consumerprofiles.Profiles = (Consumer)(nil) +) type nonMutatingConsumer struct{} diff --git a/exporter/debugexporter/config.go b/exporter/debugexporter/config.go index 3ddf8434dfa..e9407eafd5a 100644 --- a/exporter/debugexporter/config.go +++ b/exporter/debugexporter/config.go @@ -10,15 +10,13 @@ import ( "go.opentelemetry.io/collector/config/configtelemetry" ) -var ( - // supportedLevels in this exporter's configuration. - // configtelemetry.LevelNone and other future values are not supported. - supportedLevels map[configtelemetry.Level]struct{} = map[configtelemetry.Level]struct{}{ - configtelemetry.LevelBasic: {}, - configtelemetry.LevelNormal: {}, - configtelemetry.LevelDetailed: {}, - } -) +// supportedLevels in this exporter's configuration. +// configtelemetry.LevelNone and other future values are not supported. +var supportedLevels map[configtelemetry.Level]struct{} = map[configtelemetry.Level]struct{}{ + configtelemetry.LevelBasic: {}, + configtelemetry.LevelNormal: {}, + configtelemetry.LevelDetailed: {}, +} // Config defines configuration for debug exporter. type Config struct { diff --git a/exporter/exporter_test.go b/exporter/exporter_test.go index 21f5479479c..d363e2af665 100644 --- a/exporter/exporter_test.go +++ b/exporter/exporter_test.go @@ -16,7 +16,7 @@ import ( ) func TestNewFactory(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, @@ -32,7 +32,7 @@ func TestNewFactory(t *testing.T) { } func TestNewFactoryWithOptions(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, diff --git a/exporter/exporterhelper/exporterhelperprofiles/profiles.go b/exporter/exporterhelper/exporterhelperprofiles/profiles.go index 069613dbed3..bb6aa00de5c 100644 --- a/exporter/exporterhelper/exporterhelperprofiles/profiles.go +++ b/exporter/exporterhelper/exporterhelperprofiles/profiles.go @@ -22,8 +22,10 @@ import ( "go.opentelemetry.io/collector/pipeline/pipelineprofiles" ) -var profilesMarshaler = &pprofile.ProtoMarshaler{} -var profilesUnmarshaler = &pprofile.ProtoUnmarshaler{} +var ( + profilesMarshaler = &pprofile.ProtoMarshaler{} + profilesUnmarshaler = &pprofile.ProtoUnmarshaler{} +) type profilesRequest struct { pd pprofile.Profiles diff --git a/exporter/exporterhelper/exporterhelperprofiles/profiles_batch_test.go b/exporter/exporterhelper/exporterhelperprofiles/profiles_batch_test.go index 288b4c35790..96531becbea 100644 --- a/exporter/exporterhelper/exporterhelperprofiles/profiles_batch_test.go +++ b/exporter/exporterhelper/exporterhelperprofiles/profiles_batch_test.go @@ -144,8 +144,7 @@ func TestExtractProfiles(t *testing.T) { } // dummyRequest implements Request. It is for checking that merging two request types would fail -type dummyRequest struct { -} +type dummyRequest struct{} func (req *dummyRequest) Export(_ context.Context) error { return nil @@ -160,6 +159,7 @@ func (req *dummyRequest) Merge(_ context.Context, _ exporterhelper.Request) (exp } func (req *dummyRequest) MergeSplit(_ context.Context, _ exporterbatcher.MaxSizeConfig, _ exporterhelper.Request) ( - []exporterhelper.Request, error) { + []exporterhelper.Request, error, +) { return nil, nil } diff --git a/exporter/exporterhelper/exporterhelperprofiles/profiles_test.go b/exporter/exporterhelper/exporterhelperprofiles/profiles_test.go index 3c7d74efab2..b5ce4230b73 100644 --- a/exporter/exporterhelper/exporterhelperprofiles/profiles_test.go +++ b/exporter/exporterhelper/exporterhelperprofiles/profiles_test.go @@ -40,9 +40,7 @@ const ( fakeProfilesParentSpanName = "fake_profiles_parent_span_name" ) -var ( - fakeProfilesExporterConfig = struct{}{} -) +var fakeProfilesExporterConfig = struct{}{} func TestProfilesRequest(t *testing.T) { lr := newProfilesRequest(testdata.GenerateProfiles(1), nil) @@ -301,8 +299,7 @@ func generateProfilesTraffic(t *testing.T, tracer trace.Tracer, le exporterprofi } } -func checkWrapSpanForProfilesExporter(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le exporterprofiles.Profiles, - wantError error, numSampleRecords int64) { // nolint: unparam +func checkWrapSpanForProfilesExporter(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le exporterprofiles.Profiles, wantError error, numSampleRecords int64) { // nolint: unparam const numRequests = 5 generateProfilesTraffic(t, tracer, le, numRequests, wantError) diff --git a/exporter/exporterhelper/internal/batch_sender_test.go b/exporter/exporterhelper/internal/batch_sender_test.go index f75febca205..bf36f3ea774 100644 --- a/exporter/exporterhelper/internal/batch_sender_test.go +++ b/exporter/exporterhelper/internal/batch_sender_test.go @@ -72,8 +72,10 @@ func TestBatchSender_Merge(t *testing.T) { time.Sleep(50 * time.Millisecond) // should be ignored because of the merge error. - require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 3, sink: sink, - mergeErr: errors.New("merge error")})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{ + items: 3, sink: sink, + mergeErr: errors.New("merge error"), + })) assert.Equal(t, int64(1), sink.requestsCount.Load()) assert.Eventually(t, func() bool { @@ -175,8 +177,10 @@ func TestBatchSender_MergeOrSplit(t *testing.T) { }, 50*time.Millisecond, 10*time.Millisecond) // request that cannot be split should be dropped. - require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 11, sink: sink, - mergeErr: errors.New("split error")})) + require.NoError(t, be.Send(context.Background(), &fakeRequest{ + items: 11, sink: sink, + mergeErr: errors.New("split error"), + })) // big request should be broken down into two requests, both are sent right away. require.NoError(t, be.Send(context.Background(), &fakeRequest{items: 13, sink: sink})) diff --git a/exporter/exporterhelper/internal/queue_sender.go b/exporter/exporterhelper/internal/queue_sender.go index 9b53a340146..243662658eb 100644 --- a/exporter/exporterhelper/internal/queue_sender.go +++ b/exporter/exporterhelper/internal/queue_sender.go @@ -78,7 +78,8 @@ type QueueSender struct { } func NewQueueSender(q exporterqueue.Queue[internal.Request], set exporter.Settings, numConsumers int, - exportFailureMessage string, obsrep *ObsReport) *QueueSender { + exportFailureMessage string, obsrep *ObsReport, +) *QueueSender { qs := &QueueSender{ queue: q, numConsumers: numConsumers, diff --git a/exporter/exporterhelper/internal/queue_sender_test.go b/exporter/exporterhelper/internal/queue_sender_test.go index 2c89d9c2c00..8f25e0fb9be 100644 --- a/exporter/exporterhelper/internal/queue_sender_test.go +++ b/exporter/exporterhelper/internal/queue_sender_test.go @@ -350,7 +350,7 @@ func TestQueuedRetryPersistenceEnabled(t *testing.T) { WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - var extensions = map[component.ID]component.Component{ + extensions := map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), } host := &MockHost{Ext: extensions} @@ -375,7 +375,7 @@ func TestQueuedRetryPersistenceEnabledStorageError(t *testing.T) { WithUnmarshaler(mockRequestUnmarshaler(&mockRequest{})), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - var extensions = map[component.ID]component.Component{ + extensions := map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(storageError), } host := &MockHost{Ext: extensions} @@ -399,7 +399,7 @@ func TestQueuedRetryPersistentEnabled_NoDataLossOnShutdown(t *testing.T) { WithUnmarshaler(mockRequestUnmarshaler(mockReq)), WithRetry(rCfg), WithQueue(qCfg)) require.NoError(t, err) - var extensions = map[component.ID]component.Component{ + extensions := map[component.ID]component.Component{ storageID: queue.NewMockStorageExtension(nil), } host := &MockHost{Ext: extensions} diff --git a/exporter/exporterhelper/internal/request.go b/exporter/exporterhelper/internal/request.go index 87952c1e8f3..85bbf3311b1 100644 --- a/exporter/exporterhelper/internal/request.go +++ b/exporter/exporterhelper/internal/request.go @@ -57,7 +57,8 @@ func (r *fakeRequest) ItemsCount() int { } func (r *fakeRequest) Merge(_ context.Context, - r2 internal.Request) (internal.Request, error) { + r2 internal.Request, +) (internal.Request, error) { if r == nil { return r2, nil } @@ -74,7 +75,8 @@ func (r *fakeRequest) Merge(_ context.Context, } func (r *fakeRequest) MergeSplit(ctx context.Context, cfg exporterbatcher.MaxSizeConfig, - r2 internal.Request) ([]internal.Request, error) { + r2 internal.Request, +) ([]internal.Request, error) { if r.mergeErr != nil { return nil, r.mergeErr } diff --git a/exporter/exporterhelper/logs.go b/exporter/exporterhelper/logs.go index fc04e6d7380..55652dd7b4a 100644 --- a/exporter/exporterhelper/logs.go +++ b/exporter/exporterhelper/logs.go @@ -20,8 +20,10 @@ import ( "go.opentelemetry.io/collector/pipeline" ) -var logsMarshaler = &plog.ProtoMarshaler{} -var logsUnmarshaler = &plog.ProtoUnmarshaler{} +var ( + logsMarshaler = &plog.ProtoMarshaler{} + logsUnmarshaler = &plog.ProtoUnmarshaler{} +) type logsRequest struct { ld plog.Logs diff --git a/exporter/exporterhelper/logs_test.go b/exporter/exporterhelper/logs_test.go index 6b565fafbd8..85d5f5a3978 100644 --- a/exporter/exporterhelper/logs_test.go +++ b/exporter/exporterhelper/logs_test.go @@ -413,8 +413,7 @@ func generateLogsTraffic(t *testing.T, tracer trace.Tracer, le exporter.Logs, nu } } -func checkWrapSpanForLogs(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le exporter.Logs, - wantError error, numLogRecords int64) { // nolint: unparam +func checkWrapSpanForLogs(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le exporter.Logs, wantError error, numLogRecords int64) { // nolint: unparam const numRequests = 5 generateLogsTraffic(t, tracer, le, numRequests, wantError) diff --git a/exporter/exporterhelper/metrics.go b/exporter/exporterhelper/metrics.go index 9fc1ed38363..f84ed8c226e 100644 --- a/exporter/exporterhelper/metrics.go +++ b/exporter/exporterhelper/metrics.go @@ -20,8 +20,10 @@ import ( "go.opentelemetry.io/collector/pipeline" ) -var metricsMarshaler = &pmetric.ProtoMarshaler{} -var metricsUnmarshaler = &pmetric.ProtoUnmarshaler{} +var ( + metricsMarshaler = &pmetric.ProtoMarshaler{} + metricsUnmarshaler = &pmetric.ProtoUnmarshaler{} +) type metricsRequest struct { md pmetric.Metrics diff --git a/exporter/exporterhelper/metrics_test.go b/exporter/exporterhelper/metrics_test.go index 5d89c3bee63..17db002e348 100644 --- a/exporter/exporterhelper/metrics_test.go +++ b/exporter/exporterhelper/metrics_test.go @@ -387,6 +387,7 @@ func newPushMetricsData(retError error) consumer.ConsumeMetricsFunc { return retError } } + func newPushMetricsDataModifiedDownstream(retError error) consumer.ConsumeMetricsFunc { return func(_ context.Context, metric pmetric.Metrics) error { metric.ResourceMetrics().MoveAndAppendTo(pmetric.NewResourceMetricsSlice()) @@ -419,8 +420,7 @@ func generateMetricsTraffic(t *testing.T, tracer trace.Tracer, me exporter.Metri } } -func checkWrapSpanForMetrics(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, - me exporter.Metrics, wantError error, numMetricPoints int64) { // nolint: unparam +func checkWrapSpanForMetrics(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, me exporter.Metrics, wantError error, numMetricPoints int64) { // nolint: unparam const numRequests = 5 generateMetricsTraffic(t, tracer, me, numRequests, wantError) diff --git a/exporter/exporterhelper/traces.go b/exporter/exporterhelper/traces.go index ee05a547d82..2924eea1115 100644 --- a/exporter/exporterhelper/traces.go +++ b/exporter/exporterhelper/traces.go @@ -20,8 +20,10 @@ import ( "go.opentelemetry.io/collector/pipeline" ) -var tracesMarshaler = &ptrace.ProtoMarshaler{} -var tracesUnmarshaler = &ptrace.ProtoUnmarshaler{} +var ( + tracesMarshaler = &ptrace.ProtoMarshaler{} + tracesUnmarshaler = &ptrace.ProtoUnmarshaler{} +) type tracesRequest struct { td ptrace.Traces diff --git a/exporter/exporterhelper/traces_test.go b/exporter/exporterhelper/traces_test.go index 7b22e8dbbf3..d3433e577f6 100644 --- a/exporter/exporterhelper/traces_test.go +++ b/exporter/exporterhelper/traces_test.go @@ -421,8 +421,7 @@ func generateTraceTraffic(t *testing.T, tracer trace.Tracer, te exporter.Traces, } } -func checkWrapSpanForTraces(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, - te exporter.Traces, wantError error, numSpans int64) { // nolint: unparam +func checkWrapSpanForTraces(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, te exporter.Traces, wantError error, numSpans int64) { // nolint: unparam const numRequests = 5 generateTraceTraffic(t, tracer, te, numRequests, wantError) diff --git a/exporter/exporterprofiles/exporter_test.go b/exporter/exporterprofiles/exporter_test.go index 06b18f527de..ab30682e3ab 100644 --- a/exporter/exporterprofiles/exporter_test.go +++ b/exporter/exporterprofiles/exporter_test.go @@ -15,7 +15,7 @@ import ( ) func TestNewFactoryWithProfiles(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} factory := NewFactory( testType, diff --git a/exporter/exportertest/contract_checker.go b/exporter/exportertest/contract_checker.go index ac44eedc716..d708c097a68 100644 --- a/exporter/exportertest/contract_checker.go +++ b/exporter/exportertest/contract_checker.go @@ -106,7 +106,8 @@ func checkConsumeContractScenario(t *testing.T, params CheckConsumeContractParam } func checkMetrics(t *testing.T, params CheckConsumeContractParams, mockReceiver component.Component, - mockConsumer *mockConsumer, checkIfTestPassed func(*testing.T, int, requestCounter)) { + mockConsumer *mockConsumer, checkIfTestPassed func(*testing.T, int, requestCounter), +) { ctx := context.Background() var exp exporter.Metrics var err error diff --git a/exporter/exportertest/mock_consumer.go b/exporter/exportertest/mock_consumer.go index 6781f68e788..0290ed69510 100644 --- a/exporter/exportertest/mock_consumer.go +++ b/exporter/exportertest/mock_consumer.go @@ -19,8 +19,10 @@ import ( "go.opentelemetry.io/collector/pdata/ptrace" ) -var errNonPermanent = status.Error(codes.DeadlineExceeded, "non Permanent error") -var errPermanent = status.Error(codes.Internal, "Permanent error") +var ( + errNonPermanent = status.Error(codes.DeadlineExceeded, "non Permanent error") + errPermanent = status.Error(codes.Internal, "Permanent error") +) // // randomNonPermanentErrorConsumeDecision is a decision function that succeeds approximately // // half of the time and fails with a non-permanent error the rest of the time. diff --git a/exporter/exportertest/mock_consumer_test.go b/exporter/exportertest/mock_consumer_test.go index a5e297abf48..830813c61a9 100644 --- a/exporter/exportertest/mock_consumer_test.go +++ b/exporter/exportertest/mock_consumer_test.go @@ -195,6 +195,7 @@ func TestConsumeTracesSuccess(t *testing.T) { assert.Equal(t, 1, mc.reqCounter.success) assert.Equal(t, 1, mc.reqCounter.total) } + func TestConsumeMetricsNonPermanent(t *testing.T) { mc := newMockConsumer(returnNonPermanentError) validData := createMetric("metricId") diff --git a/exporter/internal/queue/batcher.go b/exporter/internal/queue/batcher.go index 08d51aa83d9..2250b27d1b1 100644 --- a/exporter/internal/queue/batcher.go +++ b/exporter/internal/queue/batcher.go @@ -35,7 +35,8 @@ type BaseBatcher struct { func NewBatcher(batchCfg exporterbatcher.Config, queue Queue[internal.Request], exportFunc func(ctx context.Context, req internal.Request) error, - maxWorkers int) (Batcher, error) { + maxWorkers int, +) (Batcher, error) { if !batchCfg.Enabled { return &DisabledBatcher{ BaseBatcher{ diff --git a/exporter/internal/queue/default_batcher.go b/exporter/internal/queue/default_batcher.go index a815a83bba9..a9a44c35e5e 100644 --- a/exporter/internal/queue/default_batcher.go +++ b/exporter/internal/queue/default_batcher.go @@ -67,7 +67,8 @@ func (qb *DefaultBatcher) startReadingFlushingGoroutine() { qb.flushAsync(batch{ req: reqList[i], ctx: ctx, - idxList: []uint64{idx}}) + idxList: []uint64{idx}, + }) // TODO: handle partial failure } qb.resetTimer() @@ -75,7 +76,8 @@ func (qb *DefaultBatcher) startReadingFlushingGoroutine() { qb.currentBatch = &batch{ req: reqList[0], ctx: ctx, - idxList: []uint64{idx}} + idxList: []uint64{idx}, + } qb.currentBatchMu.Unlock() } } else { @@ -84,7 +86,8 @@ func (qb *DefaultBatcher) startReadingFlushingGoroutine() { qb.currentBatch = &batch{ req: req, ctx: ctx, - idxList: []uint64{idx}} + idxList: []uint64{idx}, + } } else { mergedReq, mergeErr := qb.currentBatch.req.Merge(qb.currentBatch.ctx, req) if mergeErr != nil { @@ -95,7 +98,8 @@ func (qb *DefaultBatcher) startReadingFlushingGoroutine() { qb.currentBatch = &batch{ req: mergedReq, ctx: qb.currentBatch.ctx, - idxList: append(qb.currentBatch.idxList, idx)} + idxList: append(qb.currentBatch.idxList, idx), + } } if qb.currentBatch.req.ItemsCount() >= qb.batchCfg.MinSizeItems { diff --git a/exporter/internal/queue/disabled_batcher.go b/exporter/internal/queue/disabled_batcher.go index 97a3fd32510..efda8fc07d8 100644 --- a/exporter/internal/queue/disabled_batcher.go +++ b/exporter/internal/queue/disabled_batcher.go @@ -33,7 +33,8 @@ func (qb *DisabledBatcher) Start(_ context.Context, _ component.Host) error { qb.flushAsync(batch{ req: req, ctx: context.Background(), - idxList: []uint64{idx}}) + idxList: []uint64{idx}, + }) } }() return nil diff --git a/exporter/internal/queue/fake_request_test.go b/exporter/internal/queue/fake_request_test.go index 189268cf910..65ee3a289a3 100644 --- a/exporter/internal/queue/fake_request_test.go +++ b/exporter/internal/queue/fake_request_test.go @@ -54,7 +54,8 @@ func (r *fakeRequest) ItemsCount() int { } func (r *fakeRequest) Merge(_ context.Context, - r2 internal.Request) (internal.Request, error) { + r2 internal.Request, +) (internal.Request, error) { fr2 := r2.(*fakeRequest) if fr2.mergeErr != nil { return nil, fr2.mergeErr @@ -68,7 +69,8 @@ func (r *fakeRequest) Merge(_ context.Context, } func (r *fakeRequest) MergeSplit(ctx context.Context, cfg exporterbatcher.MaxSizeConfig, - r2 internal.Request) ([]internal.Request, error) { + r2 internal.Request, +) ([]internal.Request, error) { if r.mergeErr != nil { return nil, r.mergeErr } diff --git a/exporter/internal/queue/persistent_queue_test.go b/exporter/internal/queue/persistent_queue_test.go index fbabd0b83a4..5ee93c5b4d5 100644 --- a/exporter/internal/queue/persistent_queue_test.go +++ b/exporter/internal/queue/persistent_queue_test.go @@ -226,7 +226,8 @@ func (m *fakeStorageClientWithErrors) Reset() { // createAndStartTestPersistentQueue creates and starts a fake queue with the given capacity and number of consumers. func createAndStartTestPersistentQueue(t *testing.T, sizer Sizer[tracesRequest], capacity int64, numConsumers int, - consumeFunc func(_ context.Context, item tracesRequest) error) Queue[tracesRequest] { + consumeFunc func(_ context.Context, item tracesRequest) error, +) Queue[tracesRequest] { pq := NewPersistentQueue[tracesRequest](PersistentQueueSettings[tracesRequest]{ Sizer: sizer, Capacity: capacity, @@ -272,7 +273,8 @@ func createTestPersistentQueueWithItemsCapacity(t testing.TB, ext storage.Extens } func createTestPersistentQueueWithCapacityLimiter(t testing.TB, ext storage.Extension, sizer Sizer[tracesRequest], - capacity int64) *persistentQueue[tracesRequest] { + capacity int64, +) *persistentQueue[tracesRequest] { pq := NewPersistentQueue[tracesRequest](PersistentQueueSettings[tracesRequest]{ Sizer: sizer, Capacity: capacity, @@ -340,7 +342,8 @@ func TestPersistentQueue_FullCapacity(t *testing.T) { func TestPersistentQueue_Shutdown(t *testing.T) { pq := createAndStartTestPersistentQueue(t, &RequestSizer[tracesRequest]{}, 1001, 100, func(context.Context, - tracesRequest) error { + tracesRequest, + ) error { return nil }) req := newTracesRequest(1, 10) @@ -384,7 +387,8 @@ func TestPersistentQueue_ConsumersProducers(t *testing.T) { numMessagesConsumed := &atomic.Int32{} pq := createAndStartTestPersistentQueue(t, &RequestSizer[tracesRequest]{}, 1000, c.numConsumers, func(context.Context, - tracesRequest) error { + tracesRequest, + ) error { numMessagesConsumed.Add(int32(1)) return nil }) @@ -468,7 +472,7 @@ func TestToStorageClient(t *testing.T) { t.Run(tt.name, func(t *testing.T) { storageID := component.MustNewIDWithName("file_storage", strconv.Itoa(tt.storageIndex)) - var extensions = map[component.ID]component.Component{} + extensions := map[component.ID]component.Component{} for i := 0; i < tt.numStorages; i++ { extensions[component.MustNewIDWithName("file_storage", strconv.Itoa(i))] = NewMockStorageExtension(tt.getClientError) } @@ -499,7 +503,7 @@ func TestInvalidStorageExtensionType(t *testing.T) { settings := extensiontest.NewNopSettings() extension, err := factory.Create(context.Background(), settings, extConfig) require.NoError(t, err) - var extensions = map[component.ID]component.Component{ + extensions := map[component.ID]component.Component{ storageID: extension, } host := &mockHost{ext: extensions} diff --git a/exporter/internal/queue/queue.go b/exporter/internal/queue/queue.go index cae36b5c1c4..77cac737f7e 100644 --- a/exporter/internal/queue/queue.go +++ b/exporter/internal/queue/queue.go @@ -12,10 +12,8 @@ import ( "go.opentelemetry.io/collector/component" ) -var ( - // ErrQueueIsFull is the error returned when an item is offered to the Queue and the queue is full. - ErrQueueIsFull = errors.New("sending queue is full") -) +// ErrQueueIsFull is the error returned when an item is offered to the Queue and the queue is full. +var ErrQueueIsFull = errors.New("sending queue is full") // Queue defines a producer-consumer exchange which can be backed by e.g. the memory-based ring buffer queue // (boundedMemoryQueue) or via a disk-based queue (persistentQueue) diff --git a/exporter/otlphttpexporter/otlp_test.go b/exporter/otlphttpexporter/otlp_test.go index 65a2e5bacc7..3bf79687980 100644 --- a/exporter/otlphttpexporter/otlp_test.go +++ b/exporter/otlphttpexporter/otlp_test.go @@ -39,10 +39,12 @@ import ( "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp" ) -const tracesTelemetryType = "traces" -const metricsTelemetryType = "metrics" -const logsTelemetryType = "logs" -const profilesTelemetryType = "profiles" +const ( + tracesTelemetryType = "traces" + metricsTelemetryType = "metrics" + logsTelemetryType = "logs" + profilesTelemetryType = "profiles" +) type responseSerializer interface { MarshalJSON() ([]byte, error) diff --git a/extension/experimental/storage/storage.go b/extension/experimental/storage/storage.go index 184787db0f7..901b6fdd83f 100644 --- a/extension/experimental/storage/storage.go +++ b/extension/experimental/storage/storage.go @@ -35,7 +35,6 @@ type Extension interface { // // [overwrite | not-found | no-op] from "real" problems type Client interface { - // Get will retrieve data from storage that corresponds to the // specified key. It should return (nil, nil) if not found Get(ctx context.Context, key string) ([]byte, error) diff --git a/extension/extension.go b/extension/extension.go index 04a8bbbc42a..5bc630a9e4d 100644 --- a/extension/extension.go +++ b/extension/extension.go @@ -80,7 +80,8 @@ func NewFactory( cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, createServiceExtension CreateFunc, - sl component.StabilityLevel) Factory { + sl component.StabilityLevel, +) Factory { return &factory{ cfgType: cfgType, CreateDefaultConfigFunc: createDefaultConfig, diff --git a/extension/extension_test.go b/extension/extension_test.go index f86bf648b4d..1d85292b2b0 100644 --- a/extension/extension_test.go +++ b/extension/extension_test.go @@ -20,7 +20,7 @@ type nopExtension struct { } func TestNewFactory(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} nopExtensionInstance := new(nopExtension) diff --git a/extension/zpagesextension/zpagesextension_test.go b/extension/zpagesextension/zpagesextension_test.go index 39ca9fd4d99..21b8df5f8ca 100644 --- a/extension/zpagesextension/zpagesextension_test.go +++ b/extension/zpagesextension/zpagesextension_test.go @@ -31,8 +31,10 @@ func newZPagesHost() *zpagesHost { func (*zpagesHost) RegisterZPages(*http.ServeMux, string) {} -var _ registerableTracerProvider = (*registerableProvider)(nil) -var _ registerableTracerProvider = sdktrace.NewTracerProvider() +var ( + _ registerableTracerProvider = (*registerableProvider)(nil) + _ registerableTracerProvider = sdktrace.NewTracerProvider() +) type registerableProvider struct { trace.TracerProvider diff --git a/featuregate/registry.go b/featuregate/registry.go index a72e51a610d..9309024c38b 100644 --- a/featuregate/registry.go +++ b/featuregate/registry.go @@ -23,10 +23,8 @@ var ( idRegexp = regexp.MustCompile(`^[0-9a-zA-Z\.]*$`) ) -var ( - // ErrAlreadyRegistered is returned when adding a Gate that is already registered. - ErrAlreadyRegistered = errors.New("gate is already registered") -) +// ErrAlreadyRegistered is returned when adding a Gate that is already registered. +var ErrAlreadyRegistered = errors.New("gate is already registered") // GlobalRegistry returns the global Registry. func GlobalRegistry() *Registry { diff --git a/internal/memorylimiter/cgroups/mountpoint.go b/internal/memorylimiter/cgroups/mountpoint.go index 28da20fdbcb..03f2cfa3d55 100644 --- a/internal/memorylimiter/cgroups/mountpoint.go +++ b/internal/memorylimiter/cgroups/mountpoint.go @@ -131,7 +131,6 @@ func NewMountPointFromLine(line string) (*MountPoint, error) { // the host file system path in the mount namespace the *MountPoint belongs to. func (mp *MountPoint) Translate(absPath string) (string, error) { relPath, err := filepath.Rel(mp.Root, absPath) - if err != nil { return "", err } diff --git a/internal/sharedcomponent/sharedcomponent.go b/internal/sharedcomponent/sharedcomponent.go index 6c9a94bb6b5..147dec1ed3f 100644 --- a/internal/sharedcomponent/sharedcomponent.go +++ b/internal/sharedcomponent/sharedcomponent.go @@ -102,8 +102,10 @@ func (c *Component[V]) Start(ctx context.Context, host component.Host) error { return nil } -var _ component.Host = (*hostWrapper)(nil) -var _ componentstatus.Reporter = (*hostWrapper)(nil) +var ( + _ component.Host = (*hostWrapper)(nil) + _ componentstatus.Reporter = (*hostWrapper)(nil) +) type hostWrapper struct { host component.Host diff --git a/internal/sharedcomponent/sharedcomponent_test.go b/internal/sharedcomponent/sharedcomponent_test.go index c65e59918ed..bb4d1e88489 100644 --- a/internal/sharedcomponent/sharedcomponent_test.go +++ b/internal/sharedcomponent/sharedcomponent_test.go @@ -82,7 +82,8 @@ func TestSharedComponent(t *testing.T) { ShutdownFunc: func(context.Context) error { calledStop++ return wantErr - }} + }, + } comps := NewMap[component.ID, *baseComponent]() got, err := comps.LoadOrStore( @@ -198,8 +199,10 @@ func TestReportStatusOnStartShutdown(t *testing.T) { } } -var _ component.Host = (*testHost)(nil) -var _ componentstatus.Reporter = (*testHost)(nil) +var ( + _ component.Host = (*testHost)(nil) + _ componentstatus.Reporter = (*testHost)(nil) +) type testHost struct { component.Host diff --git a/otelcol/config_test.go b/otelcol/config_test.go index e0455330bda..adcf0eca4c1 100644 --- a/otelcol/config_test.go +++ b/otelcol/config_test.go @@ -37,7 +37,7 @@ func (c *errConfig) Validate() error { } func TestConfigValidate(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string // test case name (also file name containing config yaml) cfgFn func() *Config expected error diff --git a/otelcol/configprovider_test.go b/otelcol/configprovider_test.go index a1ea023b9ab..a2f93f8e4c4 100644 --- a/otelcol/configprovider_test.go +++ b/otelcol/configprovider_test.go @@ -17,9 +17,8 @@ import ( ) func newConfig(yamlBytes []byte, factories Factories) (*Config, error) { - var stringMap = map[string]interface{}{} + stringMap := map[string]interface{}{} err := yaml.Unmarshal(yamlBytes, stringMap) - if err != nil { return nil, err } diff --git a/otelcol/internal/configunmarshaler/configs_test.go b/otelcol/internal/configunmarshaler/configs_test.go index efbf97194b0..ce1dc843284 100644 --- a/otelcol/internal/configunmarshaler/configs_test.go +++ b/otelcol/internal/configunmarshaler/configs_test.go @@ -77,7 +77,7 @@ func TestUnmarshal(t *testing.T) { func TestUnmarshalError(t *testing.T) { for _, tk := range testKinds { t.Run(tk.kind, func(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string conf *confmap.Conf // string that the error must contain diff --git a/otelcol/unmarshaler_test.go b/otelcol/unmarshaler_test.go index 309e6e4c109..7e0e34ac5ba 100644 --- a/otelcol/unmarshaler_test.go +++ b/otelcol/unmarshaler_test.go @@ -71,7 +71,7 @@ func TestUnmarshalUnknownTopLevel(t *testing.T) { } func TestPipelineConfigUnmarshalError(t *testing.T) { - var testCases = []struct { + testCases := []struct { // test case name (also file name containing config yaml) name string conf *confmap.Conf @@ -141,7 +141,7 @@ func TestPipelineConfigUnmarshalError(t *testing.T) { } func TestServiceUnmarshalError(t *testing.T) { - var testCases = []struct { + testCases := []struct { // test case name (also file name containing config yaml) name string conf *confmap.Conf diff --git a/pdata/internal/cmd/pdatagen/internal/packages.go b/pdata/internal/cmd/pdatagen/internal/packages.go index 8b0e2bb47d4..952d630a5ab 100644 --- a/pdata/internal/cmd/pdatagen/internal/packages.go +++ b/pdata/internal/cmd/pdatagen/internal/packages.go @@ -46,7 +46,7 @@ type PackageInfo struct { func (p *Package) GenerateFiles() error { for _, s := range p.structs { path := filepath.Join(p.info.path, "generated_"+strings.ToLower(s.getName())+".go") - if err := os.WriteFile(path, s.generate(p.info), 0600); err != nil { + if err := os.WriteFile(path, s.generate(p.info), 0o600); err != nil { return err } } @@ -57,7 +57,7 @@ func (p *Package) GenerateFiles() error { func (p *Package) GenerateTestFiles() error { for _, s := range p.structs { path := filepath.Join(p.info.path, "generated_"+strings.ToLower(s.getName())+"_test.go") - if err := os.WriteFile(path, s.generateTests(p.info), 0600); err != nil { + if err := os.WriteFile(path, s.generateTests(p.info), 0o600); err != nil { return err } } @@ -72,7 +72,7 @@ func (p *Package) GenerateInternalFiles() error { for _, s := range p.structs { path := filepath.Join("internal", "generated_wrapper_"+strings.ToLower(s.getName())+".go") - if err := os.WriteFile(path, s.generateInternal(p.info), 0600); err != nil { + if err := os.WriteFile(path, s.generateInternal(p.info), 0o600); err != nil { return err } } diff --git a/pdata/internal/cmd/pdatagen/internal/pmetric_package.go b/pdata/internal/cmd/pdatagen/internal/pmetric_package.go index e6e8e3a1901..87cde55da84 100644 --- a/pdata/internal/cmd/pdatagen/internal/pmetric_package.go +++ b/pdata/internal/cmd/pdatagen/internal/pmetric_package.go @@ -517,6 +517,7 @@ var sumField = &optionalPrimitiveValue{ defaultVal: "float64(0.0)", testVal: "float64(17.13)", } + var minField = &optionalPrimitiveValue{ fieldName: "Min", returnType: "float64", diff --git a/pdata/internal/cmd/pdatagen/internal/pprofile_package.go b/pdata/internal/cmd/pdatagen/internal/pprofile_package.go index 7071021b27d..2ee38abe1f6 100644 --- a/pdata/internal/cmd/pdatagen/internal/pprofile_package.go +++ b/pdata/internal/cmd/pdatagen/internal/pprofile_package.go @@ -447,6 +447,7 @@ var locationSlice = &sliceOfPtrs{ structName: "LocationSlice", element: location, } + var location = &messageValueStruct{ structName: "Location", description: "// Location describes function and line table debug information.", diff --git a/pdata/pcommon/timestamp_test.go b/pdata/pcommon/timestamp_test.go index edd94596ec6..40187e37b8e 100644 --- a/pdata/pcommon/timestamp_test.go +++ b/pdata/pcommon/timestamp_test.go @@ -11,7 +11,7 @@ import ( ) func TestUnixNanosConverters(t *testing.T) { - t1 := time.Date(2020, 03, 24, 1, 13, 23, 789, time.UTC) + t1 := time.Date(2020, 0o3, 24, 1, 13, 23, 789, time.UTC) // nolint:gosec tun := Timestamp(t1.UnixNano()) diff --git a/pdata/plog/fuzz_test.go b/pdata/plog/fuzz_test.go index c47fed13fba..4654c164b39 100644 --- a/pdata/plog/fuzz_test.go +++ b/pdata/plog/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzUnmarshalJsonLogs(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/plog/json_test.go b/pdata/plog/json_test.go index 160e5b7909e..ccdf9d17393 100644 --- a/pdata/plog/json_test.go +++ b/pdata/plog/json_test.go @@ -14,8 +14,10 @@ import ( "go.opentelemetry.io/collector/pdata/pcommon" ) -var _ Marshaler = (*JSONMarshaler)(nil) -var _ Unmarshaler = (*JSONUnmarshaler)(nil) +var ( + _ Marshaler = (*JSONMarshaler)(nil) + _ Unmarshaler = (*JSONUnmarshaler)(nil) +) var logsOTLP = func() Logs { ld := NewLogs() diff --git a/pdata/plog/plogotlp/fuzz_test.go b/pdata/plog/plogotlp/fuzz_test.go index 3203ee8e344..4236d7f9a9e 100644 --- a/pdata/plog/plogotlp/fuzz_test.go +++ b/pdata/plog/plogotlp/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzRequestUnmarshalJSON(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/plog/plogotlp/request_test.go b/pdata/plog/plogotlp/request_test.go index 5520d1ef021..4bea3ac6523 100644 --- a/pdata/plog/plogotlp/request_test.go +++ b/pdata/plog/plogotlp/request_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportRequest{} -var _ json.Marshaler = ExportRequest{} +var ( + _ json.Unmarshaler = ExportRequest{} + _ json.Marshaler = ExportRequest{} +) var logsRequestJSON = []byte(` { diff --git a/pdata/plog/plogotlp/response_test.go b/pdata/plog/plogotlp/response_test.go index 9d26bf22192..ba9a79ab16b 100644 --- a/pdata/plog/plogotlp/response_test.go +++ b/pdata/plog/plogotlp/response_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportResponse{} -var _ json.Marshaler = ExportResponse{} +var ( + _ json.Unmarshaler = ExportResponse{} + _ json.Marshaler = ExportResponse{} +) func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedLogRecords":1, "errorMessage":"nothing"}}` diff --git a/pdata/pmetric/metrics_test.go b/pdata/pmetric/metrics_test.go index 6e4c5ff2c1d..cd11d139537 100644 --- a/pdata/pmetric/metrics_test.go +++ b/pdata/pmetric/metrics_test.go @@ -810,6 +810,7 @@ func generateTestProtoGaugeMetric() *otlpmetrics.Metric { }, } } + func generateTestProtoSumMetric() *otlpmetrics.Metric { return &otlpmetrics.Metric{ Name: "my_metric_double", diff --git a/pdata/pmetric/pmetricotlp/request_test.go b/pdata/pmetric/pmetricotlp/request_test.go index d6fe9dbaa2f..e6eaab48882 100644 --- a/pdata/pmetric/pmetricotlp/request_test.go +++ b/pdata/pmetric/pmetricotlp/request_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportRequest{} -var _ json.Marshaler = ExportRequest{} +var ( + _ json.Unmarshaler = ExportRequest{} + _ json.Marshaler = ExportRequest{} +) var metricsRequestJSON = []byte(` { diff --git a/pdata/pmetric/pmetricotlp/response_test.go b/pdata/pmetric/pmetricotlp/response_test.go index a8b689aacc9..bf1f70b4186 100644 --- a/pdata/pmetric/pmetricotlp/response_test.go +++ b/pdata/pmetric/pmetricotlp/response_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportResponse{} -var _ json.Marshaler = ExportResponse{} +var ( + _ json.Unmarshaler = ExportResponse{} + _ json.Marshaler = ExportResponse{} +) func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedDataPoints":1, "errorMessage":"nothing"}}` diff --git a/pdata/pprofile/fuzz_test.go b/pdata/pprofile/fuzz_test.go index 46b204a845e..1079d779718 100644 --- a/pdata/pprofile/fuzz_test.go +++ b/pdata/pprofile/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzUnmarshalProfiles(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/pprofile/json_test.go b/pdata/pprofile/json_test.go index 98bdd858e64..456355a4683 100644 --- a/pdata/pprofile/json_test.go +++ b/pdata/pprofile/json_test.go @@ -14,8 +14,10 @@ import ( "go.opentelemetry.io/collector/pdata/pcommon" ) -var _ Marshaler = (*JSONMarshaler)(nil) -var _ Unmarshaler = (*JSONUnmarshaler)(nil) +var ( + _ Marshaler = (*JSONMarshaler)(nil) + _ Unmarshaler = (*JSONUnmarshaler)(nil) +) var profilesOTLP = func() Profiles { startTimestamp := pcommon.Timestamp(1684617382541971000) diff --git a/pdata/pprofile/pprofileotlp/fuzz_test.go b/pdata/pprofile/pprofileotlp/fuzz_test.go index c3e8a1b9372..fb0067b5a63 100644 --- a/pdata/pprofile/pprofileotlp/fuzz_test.go +++ b/pdata/pprofile/pprofileotlp/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzRequestUnmarshalJSON(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/pprofile/pprofileotlp/request_test.go b/pdata/pprofile/pprofileotlp/request_test.go index 49c19106c9e..6dea990283b 100644 --- a/pdata/pprofile/pprofileotlp/request_test.go +++ b/pdata/pprofile/pprofileotlp/request_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportRequest{} -var _ json.Marshaler = ExportRequest{} +var ( + _ json.Unmarshaler = ExportRequest{} + _ json.Marshaler = ExportRequest{} +) var profilesRequestJSON = []byte(` { diff --git a/pdata/pprofile/pprofileotlp/response_test.go b/pdata/pprofile/pprofileotlp/response_test.go index a7cede8fe9d..4e675f4899c 100644 --- a/pdata/pprofile/pprofileotlp/response_test.go +++ b/pdata/pprofile/pprofileotlp/response_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportResponse{} -var _ json.Marshaler = ExportResponse{} +var ( + _ json.Unmarshaler = ExportResponse{} + _ json.Marshaler = ExportResponse{} +) func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedProfiles":1, "errorMessage":"nothing"}}` diff --git a/pdata/ptrace/fuzz_test.go b/pdata/ptrace/fuzz_test.go index d35a00c80b7..efccc8e01a4 100644 --- a/pdata/ptrace/fuzz_test.go +++ b/pdata/ptrace/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzUnmarshalJSONTraces(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/ptrace/json_test.go b/pdata/ptrace/json_test.go index 8e1b683fc1d..46e07a0405d 100644 --- a/pdata/ptrace/json_test.go +++ b/pdata/ptrace/json_test.go @@ -13,8 +13,10 @@ import ( "go.opentelemetry.io/collector/pdata/pcommon" ) -var _ Marshaler = (*JSONMarshaler)(nil) -var _ Unmarshaler = (*JSONUnmarshaler)(nil) +var ( + _ Marshaler = (*JSONMarshaler)(nil) + _ Unmarshaler = (*JSONUnmarshaler)(nil) +) var tracesOTLP = func() Traces { startTimestamp := pcommon.Timestamp(1684617382541971000) diff --git a/pdata/ptrace/ptraceotlp/fuzz_test.go b/pdata/ptrace/ptraceotlp/fuzz_test.go index d6d866e9de4..c40310f49af 100644 --- a/pdata/ptrace/ptraceotlp/fuzz_test.go +++ b/pdata/ptrace/ptraceotlp/fuzz_test.go @@ -8,9 +8,7 @@ import ( "testing" ) -var ( - unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." -) +var unexpectedBytes = "expected the same bytes from unmarshaling and marshaling." func FuzzRequestUnmarshalJSON(f *testing.F) { f.Fuzz(func(t *testing.T, data []byte) { diff --git a/pdata/ptrace/ptraceotlp/request_test.go b/pdata/ptrace/ptraceotlp/request_test.go index 444ae74b712..98880ed4b17 100644 --- a/pdata/ptrace/ptraceotlp/request_test.go +++ b/pdata/ptrace/ptraceotlp/request_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportRequest{} -var _ json.Marshaler = ExportRequest{} +var ( + _ json.Unmarshaler = ExportRequest{} + _ json.Marshaler = ExportRequest{} +) var tracesRequestJSON = []byte(` { diff --git a/pdata/ptrace/ptraceotlp/response_test.go b/pdata/ptrace/ptraceotlp/response_test.go index c893557a075..8c228504d54 100644 --- a/pdata/ptrace/ptraceotlp/response_test.go +++ b/pdata/ptrace/ptraceotlp/response_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/require" ) -var _ json.Unmarshaler = ExportResponse{} -var _ json.Marshaler = ExportResponse{} +var ( + _ json.Unmarshaler = ExportResponse{} + _ json.Marshaler = ExportResponse{} +) func TestExportResponseJSON(t *testing.T) { jsonStr := `{"partialSuccess": {"rejectedSpans":1, "errorMessage":"nothing"}}` diff --git a/pdata/testdata/log.go b/pdata/testdata/log.go index 5d2a0a194ff..be9c8b2bce6 100644 --- a/pdata/testdata/log.go +++ b/pdata/testdata/log.go @@ -10,9 +10,7 @@ import ( "go.opentelemetry.io/collector/pdata/plog" ) -var ( - logTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)) -) +var logTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)) func GenerateLogs(count int) plog.Logs { ld := plog.NewLogs() diff --git a/pipeline/pipeline_test.go b/pipeline/pipeline_test.go index 8f897260fb2..23bb5c836ab 100644 --- a/pipeline/pipeline_test.go +++ b/pipeline/pipeline_test.go @@ -42,7 +42,7 @@ func TestMarshalText(t *testing.T) { func TestUnmarshalText(t *testing.T) { validSignal := globalsignal.MustNewSignal("valid") - var testCases = []struct { + testCases := []struct { idStr string expectedErr bool expectedID ID diff --git a/pipeline/pipelineprofiles/config.go b/pipeline/pipelineprofiles/config.go index e1cd9136cfd..6802cf15c95 100644 --- a/pipeline/pipelineprofiles/config.go +++ b/pipeline/pipelineprofiles/config.go @@ -7,6 +7,4 @@ import ( "go.opentelemetry.io/collector/pipeline/internal/globalsignal" ) -var ( - SignalProfiles = globalsignal.MustNewSignal("profiles") -) +var SignalProfiles = globalsignal.MustNewSignal("profiles") diff --git a/processor/batchprocessor/batch_processor_test.go b/processor/batchprocessor/batch_processor_test.go index 5791ddbd694..c4fa2b91476 100644 --- a/processor/batchprocessor/batch_processor_test.go +++ b/processor/batchprocessor/batch_processor_test.go @@ -218,9 +218,11 @@ func TestBatchProcessorSentBySize(t *testing.T) { { Attributes: attribute.NewSet(attribute.String("processor", "batch")), Count: uint64(expectedBatchesNum), - Bounds: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, + Bounds: []float64{ + 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000, - 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000}, + 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000, + }, BucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Sum: int64(sizeSum), Min: metricdata.NewExtrema(int64(sizeSum / expectedBatchesNum)), @@ -343,9 +345,11 @@ func TestBatchProcessorSentBySizeWithMaxSize(t *testing.T) { { Attributes: attribute.NewSet(attribute.String("processor", "batch")), Count: uint64(expectedBatchesNum), - Bounds: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, + Bounds: []float64{ + 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000, - 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000}, + 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000, + }, BucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, uint64(expectedBatchesNum - 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Sum: int64(sizeSum), Min: metricdata.NewExtrema(int64(minSize)), @@ -601,9 +605,11 @@ func TestBatchMetricProcessorBatchSize(t *testing.T) { { Attributes: attribute.NewSet(attribute.String("processor", "batch")), Count: uint64(expectedBatchesNum), - Bounds: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, + Bounds: []float64{ + 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000, - 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000}, + 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000, + }, BucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Sum: int64(size), Min: metricdata.NewExtrema(int64(size / int(expectedBatchesNum))), @@ -975,9 +981,11 @@ func TestBatchLogProcessor_BatchSize(t *testing.T) { { Attributes: attribute.NewSet(attribute.String("processor", "batch")), Count: uint64(expectedBatchesNum), - Bounds: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, + Bounds: []float64{ + 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000, - 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000}, + 1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000, + }, BucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Sum: int64(size), Min: metricdata.NewExtrema(int64(size / int(expectedBatchesNum))), diff --git a/processor/batchprocessor/metrics.go b/processor/batchprocessor/metrics.go index 0e5ddafd8ed..01621ad86e6 100644 --- a/processor/batchprocessor/metrics.go +++ b/processor/batchprocessor/metrics.go @@ -38,7 +38,6 @@ func newBatchProcessorTelemetry(set processor.Settings, currentMetadataCardinali set.TelemetrySettings, metadata.WithProcessorBatchMetadataCardinalityCallback(func() int64 { return int64(currentMetadataCardinality()) }, attrs), ) - if err != nil { return nil, err } diff --git a/processor/processor_test.go b/processor/processor_test.go index d38b0b57581..03c821964bc 100644 --- a/processor/processor_test.go +++ b/processor/processor_test.go @@ -17,7 +17,7 @@ import ( ) func TestNewFactory(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, @@ -33,7 +33,7 @@ func TestNewFactory(t *testing.T) { } func TestNewFactoryWithOptions(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, diff --git a/processor/processorhelper/traces.go b/processor/processorhelper/traces.go index 941168985a2..f6389a2272a 100644 --- a/processor/processorhelper/traces.go +++ b/processor/processorhelper/traces.go @@ -65,7 +65,6 @@ func NewTraces( obs.recordInOut(ctx, spansIn, spansOut) return nextConsumer.ConsumeTraces(ctx, td) }, bs.consumerOptions...) - if err != nil { return nil, err } diff --git a/processor/processorprofiles/processor_test.go b/processor/processorprofiles/processor_test.go index 3e735a69261..1e743e67bfa 100644 --- a/processor/processorprofiles/processor_test.go +++ b/processor/processorprofiles/processor_test.go @@ -16,7 +16,7 @@ import ( ) func TestNewFactoryWithProfiles(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} factory := NewFactory( testType, diff --git a/receiver/otlpreceiver/config.go b/receiver/otlpreceiver/config.go index 8e512f5a278..b40a0476fed 100644 --- a/receiver/otlpreceiver/config.go +++ b/receiver/otlpreceiver/config.go @@ -46,8 +46,10 @@ type Config struct { Protocols `mapstructure:"protocols"` } -var _ component.Config = (*Config)(nil) -var _ confmap.Unmarshaler = (*Config)(nil) +var ( + _ component.Config = (*Config)(nil) + _ confmap.Unmarshaler = (*Config)(nil) +) // Validate checks the receiver configuration is valid func (cfg *Config) Validate() error { diff --git a/receiver/otlpreceiver/internal/profiles/otlp_test.go b/receiver/otlpreceiver/internal/profiles/otlp_test.go index cb4abc8ae39..7ad26ef4ce3 100644 --- a/receiver/otlpreceiver/internal/profiles/otlp_test.go +++ b/receiver/otlpreceiver/internal/profiles/otlp_test.go @@ -55,6 +55,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, pprofileotlp.ExportResponse{}, resp) } + func TestExport_PermanentErrorConsumer(t *testing.T) { ld := testdata.GenerateProfiles(1) req := pprofileotlp.NewExportRequestFromProfiles(ld) diff --git a/receiver/otlpreceiver/internal/trace/otlp_test.go b/receiver/otlpreceiver/internal/trace/otlp_test.go index 3df87c317f0..7e353dd27c5 100644 --- a/receiver/otlpreceiver/internal/trace/otlp_test.go +++ b/receiver/otlpreceiver/internal/trace/otlp_test.go @@ -58,6 +58,7 @@ func TestExport_NonPermanentErrorConsumer(t *testing.T) { assert.IsType(t, status.Error(codes.Unknown, ""), err) assert.Equal(t, ptraceotlp.ExportResponse{}, resp) } + func TestExport_PermanentErrorConsumer(t *testing.T) { ld := testdata.GenerateTraces(1) req := ptraceotlp.NewExportRequestFromTraces(ld) diff --git a/receiver/receiver_test.go b/receiver/receiver_test.go index 40d2ca1240e..eb8af181019 100644 --- a/receiver/receiver_test.go +++ b/receiver/receiver_test.go @@ -17,7 +17,7 @@ import ( ) func TestNewFactory(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, @@ -33,7 +33,7 @@ func TestNewFactory(t *testing.T) { } func TestNewFactoryWithOptions(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} f := NewFactory( testType, diff --git a/receiver/receiverprofiles/receiver_test.go b/receiver/receiverprofiles/receiver_test.go index 7f30fb4a05f..8182d650eed 100644 --- a/receiver/receiverprofiles/receiver_test.go +++ b/receiver/receiverprofiles/receiver_test.go @@ -16,7 +16,7 @@ import ( ) func TestNewFactoryWithProfiles(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} factory := NewFactory( testType, diff --git a/receiver/receivertest/contract_checker.go b/receiver/receivertest/contract_checker.go index 6cd92177192..148a025048c 100644 --- a/receiver/receivertest/contract_checker.go +++ b/receiver/receivertest/contract_checker.go @@ -271,8 +271,10 @@ func (ds idSet) union(other idSet) (union idSet, duplicates []UniqueIDAttrVal) { // between the receiver and it next consumer. type consumeDecisionFunc func(ids idSet) error -var errNonPermanent = errors.New("non permanent error") -var errPermanent = errors.New("permanent error") +var ( + errNonPermanent = errors.New("non permanent error") + errPermanent = errors.New("permanent error") +) // randomNonPermanentErrorConsumeDecision is a decision function that succeeds approximately // half of the time and fails with a non-permanent error the rest of the time. diff --git a/receiver/scraperhelper/config.go b/receiver/scraperhelper/config.go index 84b7cd2073e..31f181aa908 100644 --- a/receiver/scraperhelper/config.go +++ b/receiver/scraperhelper/config.go @@ -11,9 +11,7 @@ import ( "go.uber.org/multierr" ) -var ( - errNonPositiveInterval = errors.New("requires positive value") -) +var errNonPositiveInterval = errors.New("requires positive value") // ControllerConfig defines common settings for a scraper controller // configuration. Scraper controller receivers can embed this struct, instead diff --git a/receiver/scraperhelper/scrapercontroller.go b/receiver/scraperhelper/scrapercontroller.go index c8e37e393c1..788fdf889ad 100644 --- a/receiver/scraperhelper/scrapercontroller.go +++ b/receiver/scraperhelper/scrapercontroller.go @@ -201,7 +201,6 @@ func (sc *controller) scrapeMetricsAndReport() { scrp := sc.obsScrapers[i] ctx = scrp.StartMetricsOp(ctx) md, err := scraper.Scrape(ctx) - if err != nil { sc.logger.Error("Error scraping metrics", zap.Error(err), zap.Stringer("scraper", scraper.id)) if !scrapererror.IsPartialScrapeError(err) { diff --git a/semconv/semconv_test.go b/semconv/semconv_test.go index 2d528bd23b4..bb36e335ea3 100644 --- a/semconv/semconv_test.go +++ b/semconv/semconv_test.go @@ -15,7 +15,7 @@ import ( func TestAllSemConvFilesAreCrated(t *testing.T) { // Files that have to be present in each semconv package - var expectedFiles = []string{"generated_resource.go", "generated_trace.go", "schema.go", "nonstandard.go"} + expectedFiles := []string{"generated_resource.go", "generated_trace.go", "schema.go", "nonstandard.go"} files, err := os.ReadDir(".") require.NoError(t, err) diff --git a/service/config_test.go b/service/config_test.go index 09567436cfa..ab292a2665d 100644 --- a/service/config_test.go +++ b/service/config_test.go @@ -21,7 +21,7 @@ import ( ) func TestConfigValidate(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string // test case name (also file name containing config yaml) cfgFn func() *Config expected error @@ -98,11 +98,13 @@ func generateConfig() *Config { }, Metrics: telemetry.MetricsConfig{ Level: configtelemetry.LevelNormal, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: newPtr("localhost"), - Port: newPtr(8080), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: newPtr("localhost"), + Port: newPtr(8080), + }}}, + }, }, }, }, diff --git a/service/internal/builders/connector_test.go b/service/internal/builders/connector_test.go index d02f304d930..2dc1d7b108b 100644 --- a/service/internal/builders/connector_test.go +++ b/service/internal/builders/connector_test.go @@ -490,12 +490,15 @@ type nopConnector struct { func createConnectorTracesToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Traces, error) { return nopConnectorInstance, nil } + func createConnectorTracesToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Traces, error) { return nopConnectorInstance, nil } + func createConnectorTracesToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Traces, error) { return nopConnectorInstance, nil } + func createConnectorTracesToProfiles(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connector.Traces, error) { return nopConnectorInstance, nil } @@ -503,12 +506,15 @@ func createConnectorTracesToProfiles(context.Context, connector.Settings, compon func createConnectorMetricsToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Metrics, error) { return nopConnectorInstance, nil } + func createConnectorMetricsToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Metrics, error) { return nopConnectorInstance, nil } + func createConnectorMetricsToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Metrics, error) { return nopConnectorInstance, nil } + func createConnectorMetricsToProfiles(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connector.Metrics, error) { return nopConnectorInstance, nil } @@ -516,12 +522,15 @@ func createConnectorMetricsToProfiles(context.Context, connector.Settings, compo func createConnectorLogsToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Logs, error) { return nopConnectorInstance, nil } + func createConnectorLogsToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Logs, error) { return nopConnectorInstance, nil } + func createConnectorLogsToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Logs, error) { return nopConnectorInstance, nil } + func createConnectorLogsToProfiles(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connector.Logs, error) { return nopConnectorInstance, nil } @@ -529,12 +538,15 @@ func createConnectorLogsToProfiles(context.Context, connector.Settings, componen func createConnectorProfilesToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connectorprofiles.Profiles, error) { return nopConnectorInstance, nil } + func createConnectorProfilesToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connectorprofiles.Profiles, error) { return nopConnectorInstance, nil } + func createConnectorProfilesToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connectorprofiles.Profiles, error) { return nopConnectorInstance, nil } + func createConnectorProfilesToProfiles(context.Context, connector.Settings, component.Config, consumerprofiles.Profiles) (connectorprofiles.Profiles, error) { return nopConnectorInstance, nil } diff --git a/service/internal/builders/extension_test.go b/service/internal/builders/extension_test.go index 13c19d62aca..527a078a71d 100644 --- a/service/internal/builders/extension_test.go +++ b/service/internal/builders/extension_test.go @@ -17,7 +17,7 @@ import ( ) func TestExtensionBuilder(t *testing.T) { - var testType = component.MustNewType("test") + testType := component.MustNewType("test") defaultCfg := struct{}{} testID := component.NewID(testType) unknownID := component.MustNewID("unknown") diff --git a/service/internal/graph/graph.go b/service/internal/graph/graph.go index 26754e8fc34..76e4d862802 100644 --- a/service/internal/graph/graph.go +++ b/service/internal/graph/graph.go @@ -603,9 +603,11 @@ func connectorStability(f connector.Factory, expType, recType pipeline.Signal) c return component.StabilityLevelUndefined } -var _ getExporters = (*HostWrapper)(nil) -var _ component.Host = (*HostWrapper)(nil) -var _ componentstatus.Reporter = (*HostWrapper)(nil) +var ( + _ getExporters = (*HostWrapper)(nil) + _ component.Host = (*HostWrapper)(nil) + _ componentstatus.Reporter = (*HostWrapper)(nil) +) type HostWrapper struct { *Host diff --git a/service/internal/graph/host.go b/service/internal/graph/host.go index 6463eaad531..fd81f7dcca8 100644 --- a/service/internal/graph/host.go +++ b/service/internal/graph/host.go @@ -27,8 +27,10 @@ type getExporters interface { GetExporters() map[pipeline.Signal]map[component.ID]component.Component } -var _ getExporters = (*Host)(nil) -var _ component.Host = (*Host)(nil) +var ( + _ getExporters = (*Host)(nil) + _ component.Host = (*Host)(nil) +) type Host struct { AsyncErrorChannel chan error @@ -92,10 +94,8 @@ const ( zFeaturePath = "featurez" ) -var ( - // InfoVar is a singleton instance of the Info struct. - runtimeInfoVar [][2]string -) +// InfoVar is a singleton instance of the Info struct. +var runtimeInfoVar [][2]string func init() { runtimeInfoVar = [][2]string{ diff --git a/service/internal/testcomponents/example_connector.go b/service/internal/testcomponents/example_connector.go index a9005e5a2db..9ca751f32ee 100644 --- a/service/internal/testcomponents/example_connector.go +++ b/service/internal/testcomponents/example_connector.go @@ -187,6 +187,7 @@ func createExampleProfilesToLogs(_ context.Context, set connector.Settings, _ co mutatesData: set.ID.Name() == "mutate", }, nil } + func createExampleProfilesToProfiles(_ context.Context, set connector.Settings, _ component.Config, profiles consumerprofiles.Profiles) (connectorprofiles.Profiles, error) { return &ExampleConnector{ ConsumeProfilesFunc: profiles.ConsumeProfiles, diff --git a/service/internal/testcomponents/example_exporter.go b/service/internal/testcomponents/example_exporter.go index 6c33be0aecb..394a7f30762 100644 --- a/service/internal/testcomponents/example_exporter.go +++ b/service/internal/testcomponents/example_exporter.go @@ -45,6 +45,7 @@ func createMetricsExporter(context.Context, exporter.Settings, component.Config) func createLogsExporter(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) { return &ExampleExporter{}, nil } + func createProfilesExporter(context.Context, exporter.Settings, component.Config) (exporterprofiles.Profiles, error) { return &ExampleExporter{}, nil } diff --git a/service/pipelines/config_test.go b/service/pipelines/config_test.go index 74f129e725c..c42af8da603 100644 --- a/service/pipelines/config_test.go +++ b/service/pipelines/config_test.go @@ -18,7 +18,7 @@ import ( ) func TestConfigValidate(t *testing.T) { - var testCases = []struct { + testCases := []struct { name string // test case name (also file name containing config yaml) cfgFn func(*testing.T) Config expected error diff --git a/service/service.go b/service/service.go index b5e9f8e2384..39df6e5f5e0 100644 --- a/service/service.go +++ b/service/service.go @@ -140,7 +140,6 @@ func New(ctx context.Context, set Settings, cfg Config) (*Service, error) { }, ), ) - if err != nil { return nil, fmt.Errorf("failed to create SDK: %w", err) } diff --git a/service/service_test.go b/service/service_test.go index fb30d7a8fcb..fb095f8a4a9 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -58,10 +58,12 @@ type ownMetricsTestCase struct { expectedLabels map[string]labelValue } -var testResourceAttrValue = "resource_attr_test_value" // #nosec G101: Potential hardcoded credentials -var testInstanceID = "test_instance_id" -var testServiceVersion = "2022-05-20" -var testServiceName = "test name" +var ( + testResourceAttrValue = "resource_attr_test_value" // #nosec G101: Potential hardcoded credentials + testInstanceID = "test_instance_id" + testServiceVersion = "2022-05-20" + testServiceName = "test name" +) // prometheusToOtelConv is used to check that the expected resource labels exist as // part of the otel resource attributes. @@ -71,25 +73,28 @@ var prometheusToOtelConv = map[string]string{ "service_version": "service.version", } -const metricsVersion = "test version" -const otelCommand = "otelcoltest" +const ( + metricsVersion = "test version" + otelCommand = "otelcoltest" +) func ownMetricsTestCases() []ownMetricsTestCase { - return []ownMetricsTestCase{{ - name: "no resource", - userDefinedResource: nil, - // All labels added to all collector metrics by default are listed below. - // These labels are hard coded here in order to avoid inadvertent changes: - // at this point changing labels should be treated as a breaking changing - // and requires a good justification. The reason is that changes to metric - // names or labels can break alerting, dashboards, etc that are used to - // monitor the Collector in production deployments. - expectedLabels: map[string]labelValue{ - "service_instance_id": {state: labelAnyValue}, - "service_name": {label: otelCommand, state: labelSpecificValue}, - "service_version": {label: metricsVersion, state: labelSpecificValue}, + return []ownMetricsTestCase{ + { + name: "no resource", + userDefinedResource: nil, + // All labels added to all collector metrics by default are listed below. + // These labels are hard coded here in order to avoid inadvertent changes: + // at this point changing labels should be treated as a breaking changing + // and requires a good justification. The reason is that changes to metric + // names or labels can break alerting, dashboards, etc that are used to + // monitor the Collector in production deployments. + expectedLabels: map[string]labelValue{ + "service_instance_id": {state: labelAnyValue}, + "service_name": {label: otelCommand, state: labelSpecificValue}, + "service_version": {label: metricsVersion, state: labelSpecificValue}, + }, }, - }, { name: "resource with custom attr", userDefinedResource: map[string]*string{ @@ -167,7 +172,8 @@ func ownMetricsTestCases() []ownMetricsTestCase { "service_name": {label: otelCommand, state: labelSpecificValue}, "service_version": {state: labelNotPresent}, }, - }} + }, + } } var ( @@ -397,7 +403,7 @@ func TestExtensionNotificationFailure(t *testing.T) { set := newNopSettings() cfg := newNopConfig() - var extName = component.MustNewType("configWatcher") + extName := component.MustNewType("configWatcher") configWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName) set.ExtensionsConfigs = map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()} set.ExtensionsFactories = map[component.Type]extension.Factory{extName: configWatcherExtensionFactory} @@ -419,7 +425,7 @@ func TestNilCollectorEffectiveConfig(t *testing.T) { set.CollectorConf = nil cfg := newNopConfig() - var extName = component.MustNewType("configWatcher") + extName := component.MustNewType("configWatcher") configWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName) set.ExtensionsConfigs = map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()} set.ExtensionsFactories = map[component.Type]extension.Factory{extName: configWatcherExtensionFactory} @@ -683,11 +689,13 @@ func newNopConfigPipelineConfigs(pipelineCfgs pipelines.Config) Config { }, Metrics: telemetry.MetricsConfig{ Level: configtelemetry.LevelBasic, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: newPtr("localhost"), - Port: newPtr(8888), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: newPtr("localhost"), + Port: newPtr(8888), + }}}, + }, }, }, }, diff --git a/service/telemetry/config_test.go b/service/telemetry/config_test.go index 9f8f9da1efd..780f059aff6 100644 --- a/service/telemetry/config_test.go +++ b/service/telemetry/config_test.go @@ -117,11 +117,13 @@ func TestConfigValidate(t *testing.T) { cfg: &Config{ Metrics: MetricsConfig{ Level: configtelemetry.LevelBasic, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: newPtr("127.0.0.1"), - Port: newPtr(3333), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: newPtr("127.0.0.1"), + Port: newPtr(3333), + }}}, + }, }, }, }, diff --git a/service/telemetry/factory.go b/service/telemetry/factory.go index 6fbc155de79..af23cfcabae 100644 --- a/service/telemetry/factory.go +++ b/service/telemetry/factory.go @@ -115,11 +115,13 @@ func createDefaultConfig() component.Config { }, Metrics: MetricsConfig{ Level: configtelemetry.LevelNormal, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: &metricsHost, - Port: newPtr(8888), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: &metricsHost, + Port: newPtr(8888), + }}}, + }, }, }, } diff --git a/service/telemetry/factory_test.go b/service/telemetry/factory_test.go index 09cda6b7861..23fbcc4ad89 100644 --- a/service/telemetry/factory_test.go +++ b/service/telemetry/factory_test.go @@ -65,11 +65,13 @@ func TestTelemetryConfiguration(t *testing.T) { }, Metrics: MetricsConfig{ Level: configtelemetry.LevelBasic, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: newPtr("127.0.0.1"), - Port: newPtr(3333), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: newPtr("127.0.0.1"), + Port: newPtr(3333), + }}}, + }, }, }, }, @@ -83,11 +85,13 @@ func TestTelemetryConfiguration(t *testing.T) { }, Metrics: MetricsConfig{ Level: configtelemetry.LevelBasic, - Readers: []config.MetricReader{{ - Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ - Host: newPtr("127.0.0.1"), - Port: newPtr(3333), - }}}}, + Readers: []config.MetricReader{ + { + Pull: &config.PullMetricReader{Exporter: config.MetricExporter{Prometheus: &config.Prometheus{ + Host: newPtr("127.0.0.1"), + Port: newPtr(3333), + }}}, + }, }, }, }, diff --git a/service/telemetry/logger.go b/service/telemetry/logger.go index 6f8e662a990..02194538db8 100644 --- a/service/telemetry/logger.go +++ b/service/telemetry/logger.go @@ -31,7 +31,6 @@ func newLogger(set Settings, cfg Config) (*zap.Logger, log.LoggerProvider, error } logger, err := zapCfg.Build(set.ZapOptions...) - if err != nil { return nil, nil, err } diff --git a/service/telemetry/tracer.go b/service/telemetry/tracer.go index 9febba8e29f..f9ff92c1878 100644 --- a/service/telemetry/tracer.go +++ b/service/telemetry/tracer.go @@ -30,9 +30,7 @@ const ( b3Propagator = "b3" ) -var ( - errUnsupportedPropagator = errors.New("unsupported trace propagator") -) +var errUnsupportedPropagator = errors.New("unsupported trace propagator") type noopNoContextTracer struct { embedded.Tracer