diff --git a/receiver/activedirectorydsreceiver/factory_windows.go b/receiver/activedirectorydsreceiver/factory_windows.go index 24171d5e33db..4c883442fc07 100644 --- a/receiver/activedirectorydsreceiver/factory_windows.go +++ b/receiver/activedirectorydsreceiver/factory_windows.go @@ -37,7 +37,6 @@ func createMetricsReceiver( scraperhelper.WithStart(adds.start), scraperhelper.WithShutdown(adds.shutdown), ) - if err != nil { return nil, err } diff --git a/receiver/activedirectorydsreceiver/scraper_test.go b/receiver/activedirectorydsreceiver/scraper_test.go index 041ab3abd4ef..583efb5d0147 100644 --- a/receiver/activedirectorydsreceiver/scraper_test.go +++ b/receiver/activedirectorydsreceiver/scraper_test.go @@ -21,8 +21,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/activedirectorydsreceiver/internal/metadata" ) -var goldenScrapePath = filepath.Join("testdata", "golden_scrape.yaml") -var partialScrapePath = filepath.Join("testdata", "partial_scrape.yaml") +var ( + goldenScrapePath = filepath.Join("testdata", "golden_scrape.yaml") + partialScrapePath = filepath.Join("testdata", "partial_scrape.yaml") +) func TestScrape(t *testing.T) { t.Run("Fully successful scrape", func(t *testing.T) { diff --git a/receiver/aerospikereceiver/integration_test.go b/receiver/aerospikereceiver/integration_test.go index b77b4c6b1b36..567bd13a003a 100644 --- a/receiver/aerospikereceiver/integration_test.go +++ b/receiver/aerospikereceiver/integration_test.go @@ -120,8 +120,10 @@ type recordsCheckable interface { Results() <-chan *as.Result } -type aeroDoneFunc func() (doneCheckable, as.Error) -type aeroRecordsFunc func() (recordsCheckable, as.Error) +type ( + aeroDoneFunc func() (doneCheckable, as.Error) + aeroRecordsFunc func() (recordsCheckable, as.Error) +) func doneWaitAndCheck(f aeroDoneFunc) error { chk, err := f() diff --git a/receiver/apachesparkreceiver/config.go b/receiver/apachesparkreceiver/config.go index 7b89ef0724c8..78e5933e70b2 100644 --- a/receiver/apachesparkreceiver/config.go +++ b/receiver/apachesparkreceiver/config.go @@ -19,9 +19,7 @@ const ( defaultEndpoint = "http://localhost:4040" ) -var ( - errInvalidEndpoint = errors.New("'endpoint' must be in the form of ://:") -) +var errInvalidEndpoint = errors.New("'endpoint' must be in the form of ://:") // Config defines the configuration for the various elements of the receiver agent. type Config struct { diff --git a/receiver/apachesparkreceiver/scraper_test.go b/receiver/apachesparkreceiver/scraper_test.go index 8cdd323d692a..292abfb25d89 100644 --- a/receiver/apachesparkreceiver/scraper_test.go +++ b/receiver/apachesparkreceiver/scraper_test.go @@ -67,9 +67,10 @@ func TestScraper(t *testing.T) { expectedMetricGen: func(*testing.T) pmetric.Metrics { return pmetric.NewMetrics() }, - config: &Config{ControllerConfig: scraperhelper.ControllerConfig{ - CollectionInterval: defaultCollectionInterval, - }, + config: &Config{ + ControllerConfig: scraperhelper.ControllerConfig{ + CollectionInterval: defaultCollectionInterval, + }, ApplicationNames: []string{"local-123", "local-987"}, ClientConfig: clientConfig, MetricsBuilderConfig: metadata.DefaultMetricsBuilderConfig(), @@ -212,9 +213,10 @@ func TestScraper(t *testing.T) { require.NoError(t, err) return expectedMetrics }, - config: &Config{ControllerConfig: scraperhelper.ControllerConfig{ - CollectionInterval: defaultCollectionInterval, - }, + config: &Config{ + ControllerConfig: scraperhelper.ControllerConfig{ + CollectionInterval: defaultCollectionInterval, + }, ApplicationNames: []string{"streaming-example"}, ClientConfig: clientConfig, MetricsBuilderConfig: metadata.DefaultMetricsBuilderConfig(), diff --git a/receiver/awscloudwatchmetricsreceiver/config.go b/receiver/awscloudwatchmetricsreceiver/config.go index 67776872166b..46d88d49f47b 100644 --- a/receiver/awscloudwatchmetricsreceiver/config.go +++ b/receiver/awscloudwatchmetricsreceiver/config.go @@ -11,9 +11,7 @@ import ( "time" ) -var ( - defaultPollInterval = 5 * time.Minute -) +var defaultPollInterval = 5 * time.Minute // Config is the overall config structure for the awscloudwatchmetricsreceiver type Config struct { diff --git a/receiver/awscloudwatchmetricsreceiver/config_test.go b/receiver/awscloudwatchmetricsreceiver/config_test.go index 0adf05298d6f..4ab7ff8d3b83 100644 --- a/receiver/awscloudwatchmetricsreceiver/config_test.go +++ b/receiver/awscloudwatchmetricsreceiver/config_test.go @@ -133,17 +133,19 @@ func TestValidate(t *testing.T) { Region: "eu-west-1", PollInterval: time.Minute * 5, Metrics: &MetricsConfig{ - Names: []*NamedConfig{{ - Namespace: "AWS/EC2", - MetricName: "CPUUtilizaition", - Period: time.Second * 60, - AwsAggregation: "TS99", - }, + Names: []*NamedConfig{ + { + Namespace: "AWS/EC2", + MetricName: "CPUUtilizaition", + Period: time.Second * 60, + AwsAggregation: "TS99", + }, { Namespace: "AWS/EC2", MetricName: "CPUUtilizaition", Period: time.Second * 60, - AwsAggregation: "TS99"}, + AwsAggregation: "TS99", + }, }, }, }, diff --git a/receiver/awscloudwatchreceiver/config_test.go b/receiver/awscloudwatchreceiver/config_test.go index 2f85c8cd01b4..d5570575cd5f 100644 --- a/receiver/awscloudwatchreceiver/config_test.go +++ b/receiver/awscloudwatchreceiver/config_test.go @@ -87,7 +87,8 @@ func TestValidate(t *testing.T) { AutodiscoverConfig: &AutodiscoverConfig{ Limit: -10000, }, - }}, + }, + }, }, expectedErr: errInvalidAutodiscoverLimit, }, diff --git a/receiver/awscloudwatchreceiver/logs.go b/receiver/awscloudwatchreceiver/logs.go index 8bc78a6f2b97..05070b127ea0 100644 --- a/receiver/awscloudwatchreceiver/logs.go +++ b/receiver/awscloudwatchreceiver/logs.go @@ -295,7 +295,7 @@ func (l *logsReceiver) discoverGroups(ctx context.Context, auto *AutodiscoverCon } numGroups := 0 - var nextToken = aws.String("") + nextToken := aws.String("") for nextToken != nil { if numGroups >= auto.Limit { break diff --git a/receiver/awscontainerinsightreceiver/config.go b/receiver/awscontainerinsightreceiver/config.go index 24cca3dcf3f2..583a9b2a925e 100644 --- a/receiver/awscontainerinsightreceiver/config.go +++ b/receiver/awscontainerinsightreceiver/config.go @@ -9,7 +9,6 @@ import ( // Config defines configuration for aws ecs container metrics receiver. type Config struct { - // CollectionInterval is the interval at which metrics should be collected. The default is 60 second. CollectionInterval time.Duration `mapstructure:"collection_interval"` diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux.go index 2604ad8bb7e3..95a3b96c7c20 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux.go @@ -62,7 +62,8 @@ type createCadvisorManager func(*memory.InMemoryCache, sysfs.SysFs, manager.Hous // a better way to mock the cadvisor related part in the future. var defaultCreateManager = func(memoryCache *memory.InMemoryCache, sysfs sysfs.SysFs, housekeepingConfig manager.HousekeepingConfig, includedMetricsSet cadvisormetrics.MetricSet, collectorHTTPClient *http.Client, rawContainerCgroupPathPrefixWhiteList []string, - perfEventsFile string) (cadvisorManager, error) { + perfEventsFile string, +) (cadvisorManager, error) { return manager.New(memoryCache, sysfs, housekeepingConfig, includedMetricsSet, collectorHTTPClient, rawContainerCgroupPathPrefixWhiteList, []string{}, perfEventsFile, 0) } diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux_test.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux_test.go index ad56c66def28..9e16a5892b2c 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux_test.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_linux_test.go @@ -38,8 +38,7 @@ func (m *mockCadvisorManager) SubcontainersInfo(_ string, _ *info.ContainerInfoR return containerInfos, nil } -type mockCadvisorManager2 struct { -} +type mockCadvisorManager2 struct{} func (m *mockCadvisorManager2) Start() error { return errors.New("new error") @@ -52,25 +51,27 @@ func (m *mockCadvisorManager2) SubcontainersInfo(_ string, _ *info.ContainerInfo func newMockCreateManager(t *testing.T) createCadvisorManager { return func(_ *memory.InMemoryCache, _ sysfs.SysFs, _ manager.HousekeepingConfig, _ container.MetricSet, _ *http.Client, _ []string, - _ string) (cadvisorManager, error) { + _ string, + ) (cadvisorManager, error) { return &mockCadvisorManager{t: t}, nil } } var mockCreateManager2 = func(_ *memory.InMemoryCache, _ sysfs.SysFs, _ manager.HousekeepingConfig, _ container.MetricSet, _ *http.Client, _ []string, - _ string) (cadvisorManager, error) { + _ string, +) (cadvisorManager, error) { return &mockCadvisorManager2{}, nil } var mockCreateManagerWithError = func(_ *memory.InMemoryCache, _ sysfs.SysFs, _ manager.HousekeepingConfig, _ container.MetricSet, _ *http.Client, _ []string, - _ string) (cadvisorManager, error) { + _ string, +) (cadvisorManager, error) { return nil, errors.New("error") } -type MockK8sDecorator struct { -} +type MockK8sDecorator struct{} func (m *MockK8sDecorator) Decorate(metric *extractors.CAdvisorMetric) *extractors.CAdvisorMetric { return metric diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go index 6c12e9ee43c8..deedec3787e2 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/cadvisor_nolinux.go @@ -21,8 +21,7 @@ type HostInfo interface { } // Cadvisor is a dummy struct for windows -type Cadvisor struct { -} +type Cadvisor struct{} type Decorator interface { Decorate(*extractors.CAdvisorMetric) *extractors.CAdvisorMetric diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go index 398ad4805a59..5ea8d5580e24 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/extractors/extractor.go @@ -128,7 +128,8 @@ func newFloat64RateCalculator() awsmetrics.MetricCalculator { } func assignRateValueToField(rateCalculator *awsmetrics.MetricCalculator, fields map[string]any, metricName string, - cinfoName string, curVal any, curTime time.Time, multiplier float64) { + cinfoName string, curVal any, curTime time.Time, multiplier float64, +) { mKey := awsmetrics.NewKey(cinfoName+metricName, nil) if val, ok := rateCalculator.Calculate(mKey, curVal, curTime); ok { fields[metricName] = val.(float64) * multiplier diff --git a/receiver/awscontainerinsightreceiver/internal/cadvisor/testutils/helpers.go b/receiver/awscontainerinsightreceiver/internal/cadvisor/testutils/helpers.go index 7a48b6a73f0c..5ba6f415b74f 100644 --- a/receiver/awscontainerinsightreceiver/internal/cadvisor/testutils/helpers.go +++ b/receiver/awscontainerinsightreceiver/internal/cadvisor/testutils/helpers.go @@ -34,8 +34,7 @@ func LoadContainerInfo(t *testing.T, file string) []*cinfo.ContainerInfo { return result } -type MockCPUMemInfo struct { -} +type MockCPUMemInfo struct{} func (m MockCPUMemInfo) GetNumCores() int64 { return 2 diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go index cce6b10419f6..e3846616cd29 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup.go @@ -195,6 +195,7 @@ func readInt64(dirpath string, file string) (int64, error) { return val, nil } + func getCGroupMountPoint(mountConfigPath string) (string, error) { f, err := os.Open(mountConfigPath) if err != nil { diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup_test.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup_test.go index 0e62a7b772c4..7a5117ad5c2b 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup_test.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/cgroup_test.go @@ -159,7 +159,7 @@ func TestGetCGroupMountPoint(t *testing.T) { } func TestGetCPUReservedInTask(t *testing.T) { - var ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() taskinfo := &MockTaskInfo{ tasks: []ECSTask{}, @@ -215,7 +215,7 @@ func TestGetCPUReservedInTask(t *testing.T) { } func TestGetMEMReservedInTask(t *testing.T) { - var ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() taskinfo := &MockTaskInfo{ tasks: []ECSTask{}, @@ -269,7 +269,7 @@ func TestGetMEMReservedInTask(t *testing.T) { } func TestGetCPUReservedAndMemReserved(t *testing.T) { - var ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) var tasks []ECSTask var containers []ECSContainer diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info.go index 2aad38581eb9..ef2acb381979 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info.go @@ -41,7 +41,8 @@ type ContainerInstance struct { } func newECSInstanceInfo(ctx context.Context, ecsAgentEndpointProvider hostIPProvider, - refreshInterval time.Duration, logger *zap.Logger, httpClient doer, readyC chan bool) containerInstanceInfoProvider { + refreshInterval time.Duration, logger *zap.Logger, httpClient doer, readyC chan bool, +) containerInstanceInfoProvider { cii := &containerInstanceInfo{ logger: logger, httpClient: httpClient, @@ -76,7 +77,6 @@ func (cii *containerInstanceInfo) refresh(ctx context.Context) { cluster := containerInstance.Cluster instanceID, err := GetContainerInstanceIDFromArn(containerInstance.ContainerInstanceArn) - if err != nil { cii.logger.Warn("Failed to get instance id from arn, error: ", zap.Error(err)) } diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info_test.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info_test.go index b23b7ddbd0a2..a6bf60fa7d45 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info_test.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_instance_info_test.go @@ -22,13 +22,14 @@ type MockHostInfo struct{} func (mi *MockHostInfo) GetInstanceIP() string { return "0.0.0.0" } + func (mi *MockHostInfo) GetInstanceIPReadyC() chan bool { readyC := make(chan bool) return readyC } func TestECSInstanceInfo(t *testing.T) { - var ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() instanceReadyC := make(chan bool) hostIPProvider := &MockHostInfo{} diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_task_info.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_task_info.go index c998f11e1b42..026e5653a3ec 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_task_info.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecs_task_info.go @@ -45,7 +45,8 @@ type taskInfo struct { } func newECSTaskInfo(ctx context.Context, ecsTaskEndpointProvider hostIPProvider, - refreshInterval time.Duration, logger *zap.Logger, httpClient doer, readyC chan bool) ecsTaskInfoProvider { + refreshInterval time.Duration, logger *zap.Logger, httpClient doer, readyC chan bool, +) ecsTaskInfoProvider { ti := &taskInfo{ logger: logger, httpClient: httpClient, diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo.go index 6b66ce5163a6..0e5b911de441 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo.go @@ -86,7 +86,6 @@ func NewECSInfo(refreshInterval time.Duration, hostIPProvider hostIPProvider, ho ctx, cancel := context.WithCancel(context.Background()) client, err := setting.ToClient(ctx, host, settings) - if err != nil { settings.Logger.Warn("Failed to create a http client for ECS info!") cancel() diff --git a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo_test.go b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo_test.go index 5f5efcb442d5..f4120ee88f96 100644 --- a/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo_test.go +++ b/receiver/awscontainerinsightreceiver/internal/ecsInfo/ecsinfo_test.go @@ -18,9 +18,11 @@ type FakehostInfo struct{} func (hi *FakehostInfo) GetInstanceIP() string { return "host-ip-address" } + func (hi *FakehostInfo) GetClusterName() string { return "" } + func (hi *FakehostInfo) GetInstanceIPReadyC() chan bool { readyC := make(chan bool) close(readyC) @@ -35,6 +37,7 @@ type MockInstanceInfo struct { func (ii *MockInstanceInfo) GetClusterName() string { return ii.clusterName } + func (ii *MockInstanceInfo) GetContainerInstanceID() string { return ii.instanceID } @@ -47,6 +50,7 @@ type MockTaskInfo struct { func (ii *MockTaskInfo) getRunningTaskCount() int64 { return ii.runningTaskCount } + func (ii *MockTaskInfo) getRunningTasksInfo() []ECSTask { return ii.tasks } @@ -85,7 +89,8 @@ func TestNewECSInfo(t *testing.T) { taskinfoCreatorOpt := func(ei *EcsInfo) { ei.ecsTaskInfoCreator = func(context.Context, hostIPProvider, time.Duration, *zap.Logger, doer, - chan bool) ecsTaskInfoProvider { + chan bool, + ) ecsTaskInfoProvider { var tasks []ECSTask return &MockTaskInfo{ tasks: tasks, @@ -96,7 +101,8 @@ func TestNewECSInfo(t *testing.T) { cgroupScannerCreatorOpt := func(ei *EcsInfo) { ei.cgroupScannerCreator = func(context.Context, *zap.Logger, ecsTaskInfoProvider, containerInstanceInfoProvider, - time.Duration) cgroupScannerProvider { + time.Duration, + ) cgroupScannerProvider { return &MockCgroupScanner{ cpuReserved: int64(20), memReserved: int64(1024), diff --git a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume.go b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume.go index 23690675c287..e2e98a3e5ea4 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume.go @@ -53,7 +53,8 @@ type ebsVolume struct { type ebsVolumeOption func(*ebsVolume) func newEBSVolume(ctx context.Context, session *session.Session, instanceID string, region string, - refreshInterval time.Duration, logger *zap.Logger, options ...ebsVolumeOption) ebsVolumeProvider { + refreshInterval time.Duration, logger *zap.Logger, options ...ebsVolumeOption, +) ebsVolumeProvider { e := &ebsVolume{ dev2Vol: make(map[string]string), instanceID: instanceID, diff --git a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go index aa0b62b8bf17..dd37fc4a6c21 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ebsvolume_test.go @@ -27,7 +27,8 @@ type mockEBSVolumeClient struct { } func (m *mockEBSVolumeClient) DescribeVolumesWithContext(context.Context, *ec2.DescribeVolumesInput, - ...request.Option) (*ec2.DescribeVolumesOutput, error) { + ...request.Option, +) (*ec2.DescribeVolumesOutput, error) { m.mu.Lock() defer m.mu.Unlock() m.count++ @@ -99,8 +100,7 @@ func (m *mockEBSVolumeClient) DescribeVolumesWithContext(context.Context, *ec2.D }, nil } -type mockFileInfo struct { -} +type mockFileInfo struct{} func (m *mockFileInfo) Name() string { return "mockFileInfo" diff --git a/receiver/awscontainerinsightreceiver/internal/host/ec2metadata.go b/receiver/awscontainerinsightreceiver/internal/host/ec2metadata.go index 16efc64ee396..3dfb3d273f3e 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ec2metadata.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ec2metadata.go @@ -38,7 +38,8 @@ type ec2Metadata struct { type ec2MetadataOption func(*ec2Metadata) func newEC2Metadata(ctx context.Context, session *session.Session, refreshInterval time.Duration, - instanceIDReadyC chan bool, instanceIPReadyC chan bool, logger *zap.Logger, options ...ec2MetadataOption) ec2MetadataProvider { + instanceIDReadyC chan bool, instanceIPReadyC chan bool, logger *zap.Logger, options ...ec2MetadataOption, +) ec2MetadataProvider { emd := &ec2Metadata{ client: awsec2metadata.New(session), refreshInterval: refreshInterval, diff --git a/receiver/awscontainerinsightreceiver/internal/host/ec2tags.go b/receiver/awscontainerinsightreceiver/internal/host/ec2tags.go index 8e95fc763760..ca72b8af63ab 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ec2tags.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ec2tags.go @@ -48,7 +48,8 @@ type ec2Tags struct { type ec2TagsOption func(*ec2Tags) func newEC2Tags(ctx context.Context, session *session.Session, instanceID string, region string, containerOrchestrator string, - refreshInterval time.Duration, logger *zap.Logger, options ...ec2TagsOption) ec2TagsProvider { + refreshInterval time.Duration, logger *zap.Logger, options ...ec2TagsOption, +) ec2TagsProvider { et := &ec2Tags{ instanceID: instanceID, client: ec2.New(session, aws.NewConfig().WithRegion(region)), diff --git a/receiver/awscontainerinsightreceiver/internal/host/ec2tags_test.go b/receiver/awscontainerinsightreceiver/internal/host/ec2tags_test.go index 3dc65e766f62..479020ba817a 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/ec2tags_test.go +++ b/receiver/awscontainerinsightreceiver/internal/host/ec2tags_test.go @@ -29,7 +29,8 @@ type mockEC2TagsClient struct { } func (m *mockEC2TagsClient) DescribeTagsWithContext(_ context.Context, _ *ec2.DescribeTagsInput, - _ ...request.Option) (*ec2.DescribeTagsOutput, error) { + _ ...request.Option, +) (*ec2.DescribeTagsOutput, error) { m.count++ if m.count == 1 { return &ec2.DescribeTagsOutput{}, errors.New("error") diff --git a/receiver/awscontainerinsightreceiver/internal/host/hostinfo_test.go b/receiver/awscontainerinsightreceiver/internal/host/hostinfo_test.go index 379381fe8382..21da9ea2ce8c 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/hostinfo_test.go +++ b/receiver/awscontainerinsightreceiver/internal/host/hostinfo_test.go @@ -18,8 +18,7 @@ import ( ci "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/containerinsight" ) -type mockNodeCapacity struct { -} +type mockNodeCapacity struct{} func (m *mockNodeCapacity) getMemoryCapacity() int64 { return 1024 @@ -29,8 +28,7 @@ func (m *mockNodeCapacity) getNumCores() int64 { return 2 } -type mockEC2Metadata struct { -} +type mockEC2Metadata struct{} func (m *mockEC2Metadata) getInstanceID() string { return "instance-id" @@ -48,8 +46,7 @@ func (m *mockEC2Metadata) getRegion() string { return "region" } -type mockEBSVolume struct { -} +type mockEBSVolume struct{} func (m *mockEBSVolume) getEBSVolumeID(_ string) string { return "ebs-volume-id" @@ -59,8 +56,7 @@ func (m *mockEBSVolume) extractEbsIDsUsedByKubernetes() map[string]string { return map[string]string{} } -type mockEC2Tags struct { -} +type mockEC2Tags struct{} func (m *mockEC2Tags) getClusterName() string { return "cluster-name" @@ -104,19 +100,22 @@ func TestInfo(t *testing.T) { } ec2MetadataCreatorOpt := func(m *Info) { m.ec2MetadataCreator = func(context.Context, *session.Session, time.Duration, chan bool, chan bool, *zap.Logger, - ...ec2MetadataOption) ec2MetadataProvider { + ...ec2MetadataOption, + ) ec2MetadataProvider { return &mockEC2Metadata{} } } ebsVolumeCreatorOpt := func(m *Info) { m.ebsVolumeCreator = func(context.Context, *session.Session, string, string, time.Duration, *zap.Logger, - ...ebsVolumeOption) ebsVolumeProvider { + ...ebsVolumeOption, + ) ebsVolumeProvider { return &mockEBSVolume{} } } ec2TagsCreatorOpt := func(m *Info) { m.ec2TagsCreator = func(context.Context, *session.Session, string, string, string, time.Duration, *zap.Logger, - ...ec2TagsOption) ec2TagsProvider { + ...ec2TagsOption, + ) ec2TagsProvider { return &mockEC2Tags{} } } @@ -178,19 +177,22 @@ func TestInfoForECS(t *testing.T) { } ec2MetadataCreatorOpt := func(m *Info) { m.ec2MetadataCreator = func(context.Context, *session.Session, time.Duration, chan bool, chan bool, *zap.Logger, - ...ec2MetadataOption) ec2MetadataProvider { + ...ec2MetadataOption, + ) ec2MetadataProvider { return &mockEC2Metadata{} } } ebsVolumeCreatorOpt := func(m *Info) { m.ebsVolumeCreator = func(context.Context, *session.Session, string, string, time.Duration, *zap.Logger, - ...ebsVolumeOption) ebsVolumeProvider { + ...ebsVolumeOption, + ) ebsVolumeProvider { return &mockEBSVolume{} } } ec2TagsCreatorOpt := func(m *Info) { m.ec2TagsCreator = func(context.Context, *session.Session, string, string, string, time.Duration, *zap.Logger, - ...ec2TagsOption) ec2TagsProvider { + ...ec2TagsOption, + ) ec2TagsProvider { return &mockEC2Tags{} } } diff --git a/receiver/awscontainerinsightreceiver/internal/host/utils.go b/receiver/awscontainerinsightreceiver/internal/host/utils.go index edd4d00833cb..0d25ee458b1e 100644 --- a/receiver/awscontainerinsightreceiver/internal/host/utils.go +++ b/receiver/awscontainerinsightreceiver/internal/host/utils.go @@ -31,7 +31,8 @@ func hostJitter(max time.Duration) time.Duration { // execute the refresh() function periodically with the given refresh interval // until shouldRefresh() return false or the context is canceled func RefreshUntil(ctx context.Context, refresh func(context.Context), refreshInterval time.Duration, - shouldRefresh func() bool, maxJitterTime time.Duration) { + shouldRefresh func() bool, maxJitterTime time.Duration, +) { if maxJitterTime > 0 { // add some sleep jitter to prevent a large number of receivers calling the ec2 api at the same time time.Sleep(hostJitter(maxJitterTime)) diff --git a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go index a064d48723df..ac56d265107f 100644 --- a/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go +++ b/receiver/awscontainerinsightreceiver/internal/k8sapiserver/k8sapiserver_test.go @@ -31,8 +31,7 @@ func NewService(name, namespace string) k8sclient.Service { var mockClient = new(MockClient) -type mockK8sClient struct { -} +type mockK8sClient struct{} func (m *mockK8sClient) GetClientSet() kubernetes.Interface { return fake.NewSimpleClientset() @@ -51,11 +50,9 @@ func (m *mockK8sClient) GetPodClient() k8sclient.PodClient { } func (m *mockK8sClient) ShutdownNodeClient() { - } func (m *mockK8sClient) ShutdownPodClient() { - } type MockClient struct { @@ -89,8 +86,7 @@ func (client *MockClient) ServiceToPodNum() map[k8sclient.Service]int { return args.Get(0).(map[k8sclient.Service]int) } -type mockEventBroadcaster struct { -} +type mockEventBroadcaster struct{} func (m *mockEventBroadcaster) StartRecordingToSink(_ record.EventSink) watch.Interface { return watch.NewFake() @@ -144,8 +140,7 @@ func assertMetricValueEqual(t *testing.T, m pmetric.Metrics, metricName string, assert.Fail(t, msg) } -type MockClusterNameProvicer struct { -} +type MockClusterNameProvicer struct{} func (m MockClusterNameProvicer) GetClusterName() string { return "cluster-name" diff --git a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go index bf464069a349..d7dc7fcde649 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/podstore.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/podstore.go @@ -32,9 +32,7 @@ const ( kubeProxy = "kube-proxy" ) -var ( - re = regexp.MustCompile(splitRegexStr) -) +var re = regexp.MustCompile(splitRegexStr) type cachedEntry struct { pod corev1.Pod @@ -283,7 +281,8 @@ func (p *PodStore) refreshInternal(now time.Time, podList []corev1.Pod) { p.setCachedEntry(podKey, &cachedEntry{ pod: pod, - creation: now}) + creation: now, + }) } p.nodeInfo.setNodeStats(nodeStats{podCnt: podCount, containerCnt: containerCount, memReq: memRequest, cpuReq: cpuRequest}) diff --git a/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go b/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go index cefbe4f56c8a..3e278971fd97 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/podstore_test.go @@ -569,8 +569,7 @@ func TestPodStore_addPodOwnersAndPodName(t *testing.T) { assert.Empty(t, kubernetesBlob) } -type mockPodClient struct { -} +type mockPodClient struct{} func (m *mockPodClient) ListPods() ([]corev1.Pod, error) { pod := getBaseTestPodInfo() diff --git a/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go b/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go index a7e1604fe496..b1f7ec7a6574 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/servicestore_test.go @@ -14,8 +14,7 @@ import ( ci "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/containerinsight" ) -type mockEndpoint struct { -} +type mockEndpoint struct{} func (m *mockEndpoint) PodKeyToServiceNames() map[string][]string { return map[string][]string{ diff --git a/receiver/awscontainerinsightreceiver/internal/stores/store.go b/receiver/awscontainerinsightreceiver/internal/stores/store.go index da9be89624ae..a74c08597dd0 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/store.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/store.go @@ -55,7 +55,6 @@ func NewK8sDecorator(ctx context.Context, tagService bool, prefFullPodName bool, } podstore, err := NewPodStore(hostIP, prefFullPodName, addFullPodNameMetricLabel, logger) - if err != nil { return nil, err } diff --git a/receiver/awscontainerinsightreceiver/internal/stores/utils.go b/receiver/awscontainerinsightreceiver/internal/stores/utils.go index a0f187a388df..2790aeabaa2c 100644 --- a/receiver/awscontainerinsightreceiver/internal/stores/utils.go +++ b/receiver/awscontainerinsightreceiver/internal/stores/utils.go @@ -133,8 +133,10 @@ func TagMetricSource(metric CIMetric) { } func AddKubernetesInfo(metric CIMetric, kubernetesBlob map[string]any) { - needMoveToKubernetes := map[string]string{ci.ContainerNamekey: "container_name", ci.K8sPodNameKey: "pod_name", - ci.PodIDKey: "pod_id"} + needMoveToKubernetes := map[string]string{ + ci.ContainerNamekey: "container_name", ci.K8sPodNameKey: "pod_name", + ci.PodIDKey: "pod_id", + } needCopyToKubernetes := map[string]string{ci.K8sNamespace: "namespace_name", ci.TypeService: "service_name", ci.NodeNameKey: "host"} diff --git a/receiver/awscontainerinsightreceiver/receiver.go b/receiver/awscontainerinsightreceiver/receiver.go index d7c4293188b4..1df6a92ccdb1 100644 --- a/receiver/awscontainerinsightreceiver/receiver.go +++ b/receiver/awscontainerinsightreceiver/receiver.go @@ -43,7 +43,8 @@ type awsContainerInsightReceiver struct { func newAWSContainerInsightReceiver( settings component.TelemetrySettings, config *Config, - nextConsumer consumer.Metrics) (receiver.Metrics, error) { + nextConsumer consumer.Metrics, +) (receiver.Metrics, error) { r := &awsContainerInsightReceiver{ settings: settings, nextConsumer: nextConsumer, diff --git a/receiver/awscontainerinsightreceiver/receiver_test.go b/receiver/awscontainerinsightreceiver/receiver_test.go index f6b8ee900330..edcb931d7597 100644 --- a/receiver/awscontainerinsightreceiver/receiver_test.go +++ b/receiver/awscontainerinsightreceiver/receiver_test.go @@ -17,8 +17,7 @@ import ( ) // Mock cadvisor -type mockCadvisor struct { -} +type mockCadvisor struct{} func (c *mockCadvisor) GetMetrics() []pmetric.Metrics { md := pmetric.NewMetrics() @@ -30,8 +29,7 @@ func (c *mockCadvisor) Shutdown() error { } // Mock k8sapiserver -type mockK8sAPIServer struct { -} +type mockK8sAPIServer struct{} func (m *mockK8sAPIServer) Shutdown() error { return nil diff --git a/receiver/awsecscontainermetricsreceiver/config.go b/receiver/awsecscontainermetricsreceiver/config.go index 98f11e1f3981..c0b93e21c418 100644 --- a/receiver/awsecscontainermetricsreceiver/config.go +++ b/receiver/awsecscontainermetricsreceiver/config.go @@ -9,7 +9,6 @@ import ( // Config defines configuration for aws ecs container metrics receiver. type Config struct { - // CollectionInterval is the interval at which metrics should be collected CollectionInterval time.Duration `mapstructure:"collection_interval"` } diff --git a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator.go b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator.go index 898f77757d1e..11049b5cc341 100644 --- a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator.go +++ b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator.go @@ -39,7 +39,6 @@ func (acc *metricDataAccumulator) getMetricsData(containerStatsMap map[string]*C aggregateTaskMetrics(&taskMetrics, containerMetrics) } else if containerMetadata.FinishedAt != "" && containerMetadata.StartedAt != "" { duration, err := calculateDuration(containerMetadata.StartedAt, containerMetadata.FinishedAt) - if err != nil { logger.Warn("Error time format error found for this container:" + containerMetadata.ContainerName) } diff --git a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator_test.go b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator_test.go index f2f1d2182f10..d157ce5148a4 100644 --- a/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator_test.go +++ b/receiver/awsecscontainermetricsreceiver/internal/awsecscontainermetrics/accumulator_test.go @@ -216,6 +216,7 @@ func TestGetMetricsDataCpuReservedZero(t *testing.T) { acc.getMetricsData(cstats, tm, logger) require.NotEmpty(t, acc.mds) } + func TestIsEmptyStats(t *testing.T) { require.False(t, isEmptyStats(&containerStats)) require.True(t, isEmptyStats(cstats["002"])) diff --git a/receiver/awsecscontainermetricsreceiver/receiver.go b/receiver/awsecscontainermetricsreceiver/receiver.go index d4972aac39f0..41056b371ef2 100644 --- a/receiver/awsecscontainermetricsreceiver/receiver.go +++ b/receiver/awsecscontainermetricsreceiver/receiver.go @@ -33,7 +33,8 @@ func newAWSECSContainermetrics( logger *zap.Logger, config *Config, nextConsumer consumer.Metrics, - rest ecsutil.RestClient) (receiver.Metrics, error) { + rest ecsutil.RestClient, +) (receiver.Metrics, error) { r := &awsEcsContainerMetricsReceiver{ logger: logger, nextConsumer: nextConsumer, @@ -74,7 +75,6 @@ func (aecmr *awsEcsContainerMetricsReceiver) Shutdown(context.Context) error { func (aecmr *awsEcsContainerMetricsReceiver) collectDataFromEndpoint(ctx context.Context) error { aecmr.provider = awsecscontainermetrics.NewStatsProvider(aecmr.restClient, aecmr.logger) stats, metadata, err := aecmr.provider.GetStats() - if err != nil { aecmr.logger.Error("Failed to collect stats", zap.Error(err)) return err diff --git a/receiver/awsecscontainermetricsreceiver/receiver_test.go b/receiver/awsecscontainermetricsreceiver/receiver_test.go index ecfcf88cd218..d24822a92c27 100644 --- a/receiver/awsecscontainermetricsreceiver/receiver_test.go +++ b/receiver/awsecscontainermetricsreceiver/receiver_test.go @@ -92,8 +92,7 @@ func TestCollectDataFromEndpointWithConsumerError(t *testing.T) { require.EqualError(t, err, "Test Error for Metrics Consumer") } -type invalidFakeClient struct { -} +type invalidFakeClient struct{} func (f invalidFakeClient) GetResponse(_ string) ([]byte, error) { return nil, fmt.Errorf("intentional error") diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/cwlog/unmarshaler.go b/receiver/awsfirehosereceiver/internal/unmarshaler/cwlog/unmarshaler.go index a7afe38b292d..b3fa132166b5 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/cwlog/unmarshaler.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/cwlog/unmarshaler.go @@ -20,9 +20,7 @@ const ( recordDelimiter = "\n" ) -var ( - errInvalidRecords = errors.New("record format invalid") -) +var errInvalidRecords = errors.New("record format invalid") // Unmarshaler for the CloudWatch Log JSON record format. type Unmarshaler struct { diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/cwmetricstream/unmarshaler.go b/receiver/awsfirehosereceiver/internal/unmarshaler/cwmetricstream/unmarshaler.go index 8810b92e9384..110ef4afc0aa 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/cwmetricstream/unmarshaler.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/cwmetricstream/unmarshaler.go @@ -19,9 +19,7 @@ const ( recordDelimiter = "\n" ) -var ( - errInvalidRecords = errors.New("record format invalid") -) +var errInvalidRecords = errors.New("record format invalid") // Unmarshaler for the CloudWatch Metric Stream JSON record format. // diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler.go b/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler.go index af10aedc0c78..c3dde9699e90 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler.go @@ -19,9 +19,7 @@ const ( TypeStr = "otlp_v1" ) -var ( - errInvalidOTLPFormatStart = errors.New("unable to decode data length from message") -) +var errInvalidOTLPFormatStart = errors.New("unable to decode data length from message") // Unmarshaler for the CloudWatch Metric Stream OpenTelemetry record format. // @@ -42,7 +40,7 @@ func NewUnmarshaler(logger *zap.Logger) *Unmarshaler { func (u Unmarshaler) Unmarshal(records [][]byte) (pmetric.Metrics, error) { md := pmetric.NewMetrics() for recordIndex, record := range records { - var dataLen, pos = len(record), 0 + dataLen, pos := len(record), 0 for pos < dataLen { n, nLen := proto.DecodeVarint(record) if nLen == 0 && n == 0 { diff --git a/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler_test.go b/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler_test.go index 9fd61356c1b5..0f5a1ee3c905 100644 --- a/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler_test.go +++ b/receiver/awsfirehosereceiver/internal/unmarshaler/otlpmetricstream/unmarshaler_test.go @@ -20,11 +20,11 @@ func TestType(t *testing.T) { } func createMetricRecord() []byte { - var er = pmetricotlp.NewExportRequest() - var rsm = er.Metrics().ResourceMetrics().AppendEmpty() - var sm = rsm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty() + er := pmetricotlp.NewExportRequest() + rsm := er.Metrics().ResourceMetrics().AppendEmpty() + sm := rsm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty() sm.SetName("TestMetric") - var dp = sm.SetEmptySummary().DataPoints().AppendEmpty() + dp := sm.SetEmptySummary().DataPoints().AppendEmpty() dp.SetCount(1) dp.SetSum(1) qv := dp.QuantileValues() @@ -37,7 +37,7 @@ func createMetricRecord() []byte { dp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now())) temp, _ := er.MarshalProto() - var record = proto.EncodeVarint(uint64(len(temp))) + record := proto.EncodeVarint(uint64(len(temp))) record = append(record, temp...) return record } diff --git a/receiver/awsfirehosereceiver/receiver.go b/receiver/awsfirehosereceiver/receiver.go index 4d78eb2778d2..5e382720a714 100644 --- a/receiver/awsfirehosereceiver/receiver.go +++ b/receiver/awsfirehosereceiver/receiver.go @@ -101,8 +101,10 @@ type firehoseCommonAttributes struct { CommonAttributes map[string]string `json:"commonAttributes"` } -var _ receiver.Metrics = (*firehoseReceiver)(nil) -var _ http.Handler = (*firehoseReceiver)(nil) +var ( + _ receiver.Metrics = (*firehoseReceiver)(nil) + _ http.Handler = (*firehoseReceiver)(nil) +) // Start spins up the receiver's HTTP server and makes the receiver start // its processing. diff --git a/receiver/awss3receiver/receiver.go b/receiver/awss3receiver/receiver.go index 229dee0a88a8..89e67c4f525c 100644 --- a/receiver/awss3receiver/receiver.go +++ b/receiver/awss3receiver/receiver.go @@ -90,6 +90,7 @@ func (r *awss3Receiver) Start(ctx context.Context, host component.Host) error { }() return nil } + func (r *awss3Receiver) Shutdown(ctx context.Context) error { if r.notifier != nil { if err := r.notifier.Shutdown(ctx); err != nil { diff --git a/receiver/awss3receiver/s3reader_test.go b/receiver/awss3receiver/s3reader_test.go index 7dfe9ba4c92f..820b8f728ca8 100644 --- a/receiver/awss3receiver/s3reader_test.go +++ b/receiver/awss3receiver/s3reader_test.go @@ -19,7 +19,7 @@ import ( "go.uber.org/zap" ) -var testTime = time.Date(2021, 02, 01, 17, 32, 00, 00, time.UTC) +var testTime = time.Date(2021, 0o2, 0o1, 17, 32, 0o0, 0o0, time.UTC) func Test_getTimeKeyPartitionHour(t *testing.T) { result := getTimeKeyPartitionHour(testTime) @@ -324,9 +324,11 @@ type mockNotifier struct { func (m *mockNotifier) Start(_ context.Context, _ component.Host) error { return nil } + func (m *mockNotifier) Shutdown(_ context.Context) error { return nil } + func (m *mockNotifier) SendStatus(_ context.Context, notification statusNotification) { m.messages = append(m.messages, notification) } diff --git a/receiver/awsxrayreceiver/config_test.go b/receiver/awsxrayreceiver/config_test.go index b41b152b112a..b343a04c841c 100644 --- a/receiver/awsxrayreceiver/config_test.go +++ b/receiver/awsxrayreceiver/config_test.go @@ -77,7 +77,8 @@ func TestLoadConfig(t *testing.T) { LocalMode: true, ServiceName: "xray", }, - }}, + }, + }, } for _, tt := range tests { diff --git a/receiver/awsxrayreceiver/factory.go b/receiver/awsxrayreceiver/factory.go index 19e30dae8e40..e0c802fa4778 100644 --- a/receiver/awsxrayreceiver/factory.go +++ b/receiver/awsxrayreceiver/factory.go @@ -44,7 +44,8 @@ func createTracesReceiver( _ context.Context, params receiver.Settings, cfg component.Config, - consumer consumer.Traces) (receiver.Traces, error) { + consumer consumer.Traces, +) (receiver.Traces, error) { rcfg := cfg.(*Config) return newReceiver(rcfg, consumer, params) } diff --git a/receiver/awsxrayreceiver/internal/translator/sql_test.go b/receiver/awsxrayreceiver/internal/translator/sql_test.go index 1f0592c8e957..982e1f002c94 100644 --- a/receiver/awsxrayreceiver/internal/translator/sql_test.go +++ b/receiver/awsxrayreceiver/internal/translator/sql_test.go @@ -21,6 +21,7 @@ func TestSQLURL(t *testing.T) { "ebdb", dbName, "expected db name to be the same") } + func TestSQLURLQueryParameter(t *testing.T) { raw := "jdbc:postgresql://aawijb5u25wdoy.cpamxznpdoq8.us-west-2.rds.amazonaws.com:5432/ebdb?myInterceptor=foo" url, dbName, err := splitSQLURL(raw) diff --git a/receiver/awsxrayreceiver/internal/translator/translator_test.go b/receiver/awsxrayreceiver/internal/translator/translator_test.go index 68231cd57d8e..b387eb831e0f 100644 --- a/receiver/awsxrayreceiver/internal/translator/translator_test.go +++ b/receiver/awsxrayreceiver/internal/translator/translator_test.go @@ -47,7 +47,7 @@ type eventProps struct { } func TestTranslation(t *testing.T) { - var defaultServerSpanAttrs = func(seg *awsxray.Segment) pcommon.Map { + defaultServerSpanAttrs := func(seg *awsxray.Segment) pcommon.Map { m := pcommon.NewMap() assert.NoError(t, m.FromRaw(map[string]any{ conventions.AttributeHTTPMethod: *seg.HTTP.Request.Method, @@ -110,7 +110,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -495,7 +496,8 @@ func TestTranslation(t *testing.T) { attrs: pcommon.NewMap(), } - return []perSpanProperties{rootSpan, + return []perSpanProperties{ + rootSpan, childSpan7df6, childSpan7318, childSpan0239, @@ -517,7 +519,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), "one segment should translate to 1 ResourceSpans") @@ -557,7 +560,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -611,7 +615,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -651,7 +656,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -675,7 +681,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, actualSeg *awsxray.Segment, - _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { + _ ptrace.ResourceSpans, _ ptrace.Traces, err error, + ) { assert.EqualError(t, err, fmt.Sprintf("unexpected namespace: %s", *actualSeg.Subsegments[0].Subsegments[0].Namespace), @@ -721,7 +728,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -770,7 +778,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -819,7 +828,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -843,7 +853,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, actualSeg *awsxray.Segment, - _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { + _ ptrace.ResourceSpans, _ ptrace.Traces, err error, + ) { assert.EqualError(t, err, fmt.Sprintf( "failed to parse out the database name in the \"sql.url\" field, rawUrl: %s", @@ -888,7 +899,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error) { + expectedRs ptrace.ResourceSpans, actualTraces ptrace.Traces, err error, + ) { assert.NoError(t, err, testCase+": translation should've succeeded") assert.Equal(t, 1, actualTraces.ResourceSpans().Len(), testCase+": one segment should translate to 1 ResourceSpans") @@ -913,7 +925,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { + _ ptrace.ResourceSpans, _ ptrace.Traces, err error, + ) { assert.EqualError(t, err, fmt.Sprintf( "the value assigned to the `cause` field does not appear to be a string: %v", @@ -937,7 +950,8 @@ func TestTranslation(t *testing.T) { }, verification: func(testCase string, _ *awsxray.Segment, - _ ptrace.ResourceSpans, _ ptrace.Traces, err error) { + _ ptrace.ResourceSpans, _ ptrace.Traces, err error, + ) { assert.EqualError(t, err, `segment "start_time" can not be nil`, testCase+": translation should've failed") }, diff --git a/receiver/awsxrayreceiver/internal/udppoller/poller_test.go b/receiver/awsxrayreceiver/internal/udppoller/poller_test.go index 8b4d5e3e5d00..d5077e81f1f5 100644 --- a/receiver/awsxrayreceiver/internal/udppoller/poller_test.go +++ b/receiver/awsxrayreceiver/internal/udppoller/poller_test.go @@ -430,7 +430,8 @@ func (m *mockSocketConn) Close() error { return nil } func createAndOptionallyStartPoller( t *testing.T, start bool, - set receiver.Settings) (string, Poller, *observer.ObservedLogs) { + set receiver.Settings, +) (string, Poller, *observer.ObservedLogs) { addr, err := findAvailableAddress() assert.NoError(t, err, "there should be address available") diff --git a/receiver/awsxrayreceiver/receiver.go b/receiver/awsxrayreceiver/receiver.go index c45c3cb6cb90..7268e9d260ec 100644 --- a/receiver/awsxrayreceiver/receiver.go +++ b/receiver/awsxrayreceiver/receiver.go @@ -40,7 +40,8 @@ type xrayReceiver struct { func newReceiver(config *Config, consumer consumer.Traces, - set receiver.Settings) (receiver.Traces, error) { + set receiver.Settings, +) (receiver.Traces, error) { set.Logger.Info("Going to listen on endpoint for X-Ray segments", zap.String(udppoller.Transport, config.Endpoint)) poller, err := udppoller.New(&udppoller.Config{ diff --git a/receiver/awsxrayreceiver/receiver_test.go b/receiver/awsxrayreceiver/receiver_test.go index cbb2cf71d982..2114fc4b9f9e 100644 --- a/receiver/awsxrayreceiver/receiver_test.go +++ b/receiver/awsxrayreceiver/receiver_test.go @@ -263,7 +263,8 @@ func createAndOptionallyStartReceiver( t *testing.T, csu consumer.Traces, start bool, - set receiver.Settings) (string, receiver.Traces, *observer.ObservedLogs) { + set receiver.Settings, +) (string, receiver.Traces, *observer.ObservedLogs) { addr, err := findAvailableUDPAddress() assert.NoError(t, err, "there should be address available") tcpAddr := testutil.GetAvailableLocalAddress(t) diff --git a/receiver/azureblobreceiver/blobeventhandler.go b/receiver/azureblobreceiver/blobeventhandler.go index d096240db7dc..575238b93b1d 100644 --- a/receiver/azureblobreceiver/blobeventhandler.go +++ b/receiver/azureblobreceiver/blobeventhandler.go @@ -86,7 +86,6 @@ func (p *azureBlobEventHandler) newMessageHandler(ctx context.Context, event *ev if eventType == blobCreatedEventType { blobData, err := p.blobClient.readBlob(ctx, containerName, blobName) - if err != nil { return err } diff --git a/receiver/azureblobreceiver/factory.go b/receiver/azureblobreceiver/factory.go index 440bcf1ecb51..823f71e2a3df 100644 --- a/receiver/azureblobreceiver/factory.go +++ b/receiver/azureblobreceiver/factory.go @@ -24,9 +24,7 @@ const ( defaultCloud = AzureCloudType ) -var ( - errUnexpectedConfigurationType = errors.New("failed to cast configuration to Azure Blob Config") -) +var errUnexpectedConfigurationType = errors.New("failed to cast configuration to Azure Blob Config") type blobReceiverFactory struct { receivers *sharedcomponent.SharedComponents @@ -61,7 +59,6 @@ func (f *blobReceiverFactory) createLogsReceiver( nextConsumer consumer.Logs, ) (receiver.Logs, error) { receiver, err := f.getReceiver(set, cfg) - if err != nil { set.Logger.Error(err.Error()) return nil, err @@ -79,7 +76,6 @@ func (f *blobReceiverFactory) createTracesReceiver( nextConsumer consumer.Traces, ) (receiver.Traces, error) { receiver, err := f.getReceiver(set, cfg) - if err != nil { set.Logger.Error(err.Error()) return nil, err @@ -91,7 +87,8 @@ func (f *blobReceiverFactory) createTracesReceiver( func (f *blobReceiverFactory) getReceiver( set receiver.Settings, - cfg component.Config) (component.Component, error) { + cfg component.Config, +) (component.Component, error) { var err error r := f.receivers.GetOrAdd(cfg, func() component.Component { receiverConfig, ok := cfg.(*Config) diff --git a/receiver/azureeventhubreceiver/eventhubhandler_test.go b/receiver/azureeventhubreceiver/eventhubhandler_test.go index 438f71bddc5d..15382e127fc2 100644 --- a/receiver/azureeventhubreceiver/eventhubhandler_test.go +++ b/receiver/azureeventhubreceiver/eventhubhandler_test.go @@ -22,8 +22,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azureeventhubreceiver/internal/metadata" ) -type mockHubWrapper struct { -} +type mockHubWrapper struct{} func (m mockHubWrapper) GetRuntimeInformation(_ context.Context) (*eventhub.HubRuntimeInformation, error) { return &eventhub.HubRuntimeInformation{ diff --git a/receiver/azureeventhubreceiver/factory.go b/receiver/azureeventhubreceiver/factory.go index c0c5f624134f..2286cdb952e1 100644 --- a/receiver/azureeventhubreceiver/factory.go +++ b/receiver/azureeventhubreceiver/factory.go @@ -16,9 +16,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azureeventhubreceiver/internal/metadata" ) -var ( - errUnexpectedConfigurationType = errors.New("failed to cast configuration to azure event hub config") -) +var errUnexpectedConfigurationType = errors.New("failed to cast configuration to azure event hub config") type eventhubReceiverFactory struct { receivers *sharedcomponent.SharedComponents diff --git a/receiver/azuremonitorreceiver/scraper.go b/receiver/azuremonitorreceiver/scraper.go index 3e86b5608b88..99d24600faa5 100644 --- a/receiver/azuremonitorreceiver/scraper.go +++ b/receiver/azuremonitorreceiver/scraper.go @@ -298,7 +298,7 @@ func (s *azureScraper) getResources(ctx context.Context) { } func getResourceGroupFromID(id string) string { - var s = regexp.MustCompile(`\/resourcegroups/([^\/]+)\/`) + s := regexp.MustCompile(`\/resourcegroups/([^\/]+)\/`) match := s.FindStringSubmatch(strings.ToLower(id)) if len(match) == 2 { diff --git a/receiver/bigipreceiver/client_test.go b/receiver/bigipreceiver/client_test.go index 86e509a236e9..82c8118f6871 100644 --- a/receiver/bigipreceiver/client_test.go +++ b/receiver/bigipreceiver/client_test.go @@ -543,7 +543,8 @@ func TestGetPoolMembers(t *testing.T) { require.EqualError(t, err, errors.New("non 200 code returned 401").Error()) require.Equal(t, expected, poolMembers) }, - }, { + }, + { desc: "Successful call empty body for some", testFunc: func(t *testing.T) { // Setup test server diff --git a/receiver/carbonreceiver/internal/transport/server.go b/receiver/carbonreceiver/internal/transport/server.go index cf2f08afc490..321537f95ac4 100644 --- a/receiver/carbonreceiver/internal/transport/server.go +++ b/receiver/carbonreceiver/internal/transport/server.go @@ -12,10 +12,8 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/carbonreceiver/protocol" ) -var ( - errNilListenAndServeParameters = errors.New( - "no parameter of ListenAndServe can be nil") -) +var errNilListenAndServeParameters = errors.New( + "no parameter of ListenAndServe can be nil") // Server abstracts the type of transport being used and offer an // interface to handle serving clients over that transport. diff --git a/receiver/carbonreceiver/internal/transport/server_test.go b/receiver/carbonreceiver/internal/transport/server_test.go index 26b7c2ef8008..753e21cb56d3 100644 --- a/receiver/carbonreceiver/internal/transport/server_test.go +++ b/receiver/carbonreceiver/internal/transport/server_test.go @@ -71,7 +71,8 @@ func Test_Server_ListenAndServe(t *testing.T) { ts := time.Date(2020, 2, 20, 20, 20, 20, 20, time.UTC) err = gc.SendMetric(client.Metric{ - Name: "test.metric", Value: 1, Timestamp: ts}) + Name: "test.metric", Value: 1, Timestamp: ts, + }) assert.NoError(t, err) runtime.Gosched() diff --git a/receiver/carbonreceiver/protocol/config_test.go b/receiver/carbonreceiver/protocol/config_test.go index 587365b151d7..69d08793060f 100644 --- a/receiver/carbonreceiver/protocol/config_test.go +++ b/receiver/carbonreceiver/protocol/config_test.go @@ -38,7 +38,8 @@ func TestLoadParserConfig(t *testing.T) { Config: &RegexParserConfig{ Rules: []*RegexRule{ {Regexp: "(?.*test)"}, - }}, + }, + }, }, }, { diff --git a/receiver/carbonreceiver/receiver.go b/receiver/carbonreceiver/receiver.go index 8869550f572f..1f9199139f2f 100644 --- a/receiver/carbonreceiver/receiver.go +++ b/receiver/carbonreceiver/receiver.go @@ -19,9 +19,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/carbonreceiver/protocol" ) -var ( - errEmptyEndpoint = errors.New("empty endpoint") -) +var errEmptyEndpoint = errors.New("empty endpoint") // carbonreceiver implements a receiver.Metrics for Carbon plaintext, aka "line", protocol. // see https://graphite.readthedocs.io/en/latest/feeding-carbon.html#the-plaintext-protocol. diff --git a/receiver/chronyreceiver/factory.go b/receiver/chronyreceiver/factory.go index a8caee262243..a9a5c0ad8175 100644 --- a/receiver/chronyreceiver/factory.go +++ b/receiver/chronyreceiver/factory.go @@ -28,7 +28,8 @@ func newMetricsReceiver( ctx context.Context, set receiver.Settings, rCfg component.Config, - consumer consumer.Metrics) (receiver.Metrics, error) { + consumer consumer.Metrics, +) (receiver.Metrics, error) { cfg, ok := rCfg.(*Config) if !ok { return nil, fmt.Errorf("wrong config provided: %w", errInvalidValue) diff --git a/receiver/chronyreceiver/internal/chrony/client.go b/receiver/chronyreceiver/internal/chrony/client.go index 4ed1ae7486d9..63dde441a55e 100644 --- a/receiver/chronyreceiver/internal/chrony/client.go +++ b/receiver/chronyreceiver/internal/chrony/client.go @@ -14,9 +14,7 @@ import ( "github.com/jonboulle/clockwork" ) -var ( - errBadRequest = errors.New("bad request") -) +var errBadRequest = errors.New("bad request") type Client interface { // GetTrackingData will connection the configured chronyd endpoint diff --git a/receiver/chronyreceiver/internal/chrony/types.go b/receiver/chronyreceiver/internal/chrony/types.go index 209c3ae3e38d..0bfad527fe8d 100644 --- a/receiver/chronyreceiver/internal/chrony/types.go +++ b/receiver/chronyreceiver/internal/chrony/types.go @@ -61,8 +61,10 @@ const ( maxDataLen = 396 ) -type Tracking = chrony.Tracking -type ReplyHead = chrony.ReplyHead +type ( + Tracking = chrony.Tracking + ReplyHead = chrony.ReplyHead +) type ipAddr struct { IP [16]uint8 diff --git a/receiver/chronyreceiver/internal/chrony/util.go b/receiver/chronyreceiver/internal/chrony/util.go index 3e7db9ecbfb4..575be37c2e41 100644 --- a/receiver/chronyreceiver/internal/chrony/util.go +++ b/receiver/chronyreceiver/internal/chrony/util.go @@ -11,9 +11,7 @@ import ( "strings" ) -var ( - ErrInvalidNetwork = errors.New("invalid network format") -) +var ErrInvalidNetwork = errors.New("invalid network format") // SplitNetworkEndpoint takes in a URL like string of the format: [network type]://[network endpoint] // and then will return the network and the endpoint for the client to use for connection. diff --git a/receiver/cloudfoundryreceiver/receiver.go b/receiver/cloudfoundryreceiver/receiver.go index 1fb4bf93ce71..4084af4f5650 100644 --- a/receiver/cloudfoundryreceiver/receiver.go +++ b/receiver/cloudfoundryreceiver/receiver.go @@ -28,8 +28,10 @@ const ( dataFormat = "cloudfoundry" ) -var _ receiver.Metrics = (*cloudFoundryReceiver)(nil) -var _ receiver.Logs = (*cloudFoundryReceiver)(nil) +var ( + _ receiver.Metrics = (*cloudFoundryReceiver)(nil) + _ receiver.Logs = (*cloudFoundryReceiver)(nil) +) // newCloudFoundryReceiver implements the receiver.Metrics and receiver.Logs for the Cloud Foundry protocol. type cloudFoundryReceiver struct { @@ -47,7 +49,8 @@ type cloudFoundryReceiver struct { func newCloudFoundryMetricsReceiver( settings receiver.Settings, config Config, - nextConsumer consumer.Metrics) (*cloudFoundryReceiver, error) { + nextConsumer consumer.Metrics, +) (*cloudFoundryReceiver, error) { obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ ReceiverID: settings.ID, Transport: transport, @@ -70,7 +73,8 @@ func newCloudFoundryMetricsReceiver( func newCloudFoundryLogsReceiver( settings receiver.Settings, config Config, - nextConsumer consumer.Logs) (*cloudFoundryReceiver, error) { + nextConsumer consumer.Logs, +) (*cloudFoundryReceiver, error) { obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{ ReceiverID: settings.ID, Transport: transport, @@ -149,7 +153,8 @@ func (cfr *cloudFoundryReceiver) Shutdown(_ context.Context) error { func (cfr *cloudFoundryReceiver) streamMetrics( ctx context.Context, stream loggregator.EnvelopeStream, - host component.Host) { + host component.Host, +) { for { // Blocks until non-empty result or context is cancelled (returns nil in that case) envelopes := stream() @@ -188,7 +193,8 @@ func (cfr *cloudFoundryReceiver) streamMetrics( func (cfr *cloudFoundryReceiver) streamLogs( ctx context.Context, stream loggregator.EnvelopeStream, - host component.Host) { + host component.Host, +) { for { envelopes := stream() if envelopes == nil { diff --git a/receiver/cloudfoundryreceiver/stream.go b/receiver/cloudfoundryreceiver/stream.go index 338e28e081e1..c0b2e7b088ff 100644 --- a/receiver/cloudfoundryreceiver/stream.go +++ b/receiver/cloudfoundryreceiver/stream.go @@ -25,7 +25,8 @@ func newEnvelopeStreamFactory( settings component.TelemetrySettings, authTokenProvider *UAATokenProvider, httpConfig confighttp.ClientConfig, - host component.Host) (*EnvelopeStreamFactory, error) { + host component.Host, +) (*EnvelopeStreamFactory, error) { httpClient, err := httpConfig.ToClient(ctx, host, settings) if err != nil { return nil, fmt.Errorf("creating HTTP client for Cloud Foundry RLP Gateway: %w", err) diff --git a/receiver/collectdreceiver/factory.go b/receiver/collectdreceiver/factory.go index d95843fd474e..c56cdbd3d33e 100644 --- a/receiver/collectdreceiver/factory.go +++ b/receiver/collectdreceiver/factory.go @@ -29,6 +29,7 @@ func NewFactory() receiver.Factory { createDefaultConfig, receiver.WithMetrics(createMetricsReceiver, metadata.MetricsStability)) } + func createDefaultConfig() component.Config { return &Config{ ServerConfig: confighttp.ServerConfig{ diff --git a/receiver/collectdreceiver/receiver.go b/receiver/collectdreceiver/receiver.go index 5b8d282ca7b3..f0da99d73eef 100644 --- a/receiver/collectdreceiver/receiver.go +++ b/receiver/collectdreceiver/receiver.go @@ -41,7 +41,8 @@ func newCollectdReceiver( cfg *Config, defaultAttrsPrefix string, nextConsumer consumer.Metrics, - createSettings receiver.Settings) (receiver.Metrics, error) { + createSettings receiver.Settings, +) (receiver.Metrics, error) { r := &collectdReceiver{ logger: logger, nextConsumer: nextConsumer, diff --git a/receiver/datadogreceiver/internal/translator/series.go b/receiver/datadogreceiver/internal/translator/series.go index 9588839ebdb8..e400684809f3 100644 --- a/receiver/datadogreceiver/internal/translator/series.go +++ b/receiver/datadogreceiver/internal/translator/series.go @@ -124,7 +124,7 @@ func (mt *MetricsTranslator) TranslateSeriesV2(series []*gogen.MetricPayload_Met } dimensions.resourceAttrs.PutStr(k, v) } - dimensions.resourceAttrs.PutStr("source", serie.SourceTypeName) //TODO: check if this is correct handling of SourceTypeName field + dimensions.resourceAttrs.PutStr("source", serie.SourceTypeName) // TODO: check if this is correct handling of SourceTypeName field metric, metricID := bt.Lookup(dimensions) switch serie.Type { @@ -135,7 +135,7 @@ func (mt *MetricsTranslator) TranslateSeriesV2(series []*gogen.MetricPayload_Met case gogen.MetricPayload_GAUGE: dps = metric.Gauge().DataPoints() case gogen.MetricPayload_RATE: - metric.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) //TODO: verify that this is always the case + metric.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta) // TODO: verify that this is always the case dps = metric.Sum().DataPoints() case gogen.MetricPayload_UNSPECIFIED: // Type is unset/unspecified diff --git a/receiver/datadogreceiver/internal/translator/service_check_translator_test.go b/receiver/datadogreceiver/internal/translator/service_check_translator_test.go index 1f0dc69b3132..84f9fbda5291 100644 --- a/receiver/datadogreceiver/internal/translator/service_check_translator_test.go +++ b/receiver/datadogreceiver/internal/translator/service_check_translator_test.go @@ -15,9 +15,7 @@ import ( "go.opentelemetry.io/collector/pdata/pmetric" ) -var ( - testTimestamp = int64(1700000000) -) +var testTimestamp = int64(1700000000) func TestHandleStructureParsing(t *testing.T) { tests := []struct { diff --git a/receiver/datadogreceiver/internal/translator/sketches.go b/receiver/datadogreceiver/internal/translator/sketches.go index bb1283301906..6af96fc15596 100644 --- a/receiver/datadogreceiver/internal/translator/sketches.go +++ b/receiver/datadogreceiver/internal/translator/sketches.go @@ -140,8 +140,8 @@ func sketchToDatapoint(sketch gogen.SketchPayload_Sketch_Dogsketch, dp pmetric.E func mapSketchBucketsToHistogramBuckets(sketchKeys []int32, sketchCounts []uint32) (map[int]uint64, map[int]uint64, uint64, error) { var zeroCount uint64 - var positiveBuckets = make(map[int]uint64) - var negativeBuckets = make(map[int]uint64) + positiveBuckets := make(map[int]uint64) + negativeBuckets := make(map[int]uint64) // The data format for the sketch received from the sketch payload does not have separate positive and negative buckets, // and instead just uses a single list of sketch keys that are in order by increasing bucket index, starting with negative indices, @@ -173,7 +173,7 @@ func mapSketchBucketsToHistogramBuckets(sketchKeys []int32, sketchCounts []uint3 targetBucketCount := uint64(sketchCounts[i]) var currentAssignedCount uint64 - //TODO: look into better algorithms for applying fractional counts + // TODO: look into better algorithms for applying fractional counts for outIndex := histogramKey; histogramLowerBound(outIndex) < sketchUpperBound; outIndex++ { histogramLowerBound, histogramUpperBound := getHistogramBounds(outIndex) lowerIntersection := math.Max(histogramLowerBound, sketchLowerBound) diff --git a/receiver/datadogreceiver/receiver.go b/receiver/datadogreceiver/receiver.go index 17b2814ce007..de8a2fc6a383 100644 --- a/receiver/datadogreceiver/receiver.go +++ b/receiver/datadogreceiver/receiver.go @@ -207,7 +207,6 @@ func (ddr *datadogReceiver) buildInfoResponse(endpoints []Endpoint) ([]byte, err // handleInfo handles incoming /info payloads. func (ddr *datadogReceiver) handleInfo(w http.ResponseWriter, _ *http.Request, infoResponse []byte) { _, err := fmt.Fprintf(w, "%s", infoResponse) - if err != nil { ddr.params.Logger.Error("Error writing /info endpoint response", zap.Error(err)) http.Error(w, "Error writing /info endpoint response", http.StatusInternalServerError) @@ -446,7 +445,7 @@ func (ddr *datadogReceiver) handleDistributionPoints(w http.ResponseWriter, req func (ddr *datadogReceiver) handleStats(w http.ResponseWriter, req *http.Request) { obsCtx := ddr.tReceiver.StartMetricsOp(req.Context()) var err error - var metricsCount = 0 + metricsCount := 0 defer func(metricsCount *int) { ddr.tReceiver.EndMetricsOp(obsCtx, "datadog", *metricsCount, err) }(&metricsCount) @@ -462,7 +461,6 @@ func (ddr *datadogReceiver) handleStats(w http.ResponseWriter, req *http.Request } metrics, err := ddr.statsTranslator.TranslateStats(clientStats, req.Header.Get(header.Lang), req.Header.Get(header.TracerVersion)) - if err != nil { ddr.params.Logger.Error("Error translating stats", zap.Error(err)) http.Error(w, "Error translating stats", http.StatusBadRequest) diff --git a/receiver/elasticsearchreceiver/client.go b/receiver/elasticsearchreceiver/client.go index d70067cb0b86..a6304ebadd0d 100644 --- a/receiver/elasticsearchreceiver/client.go +++ b/receiver/elasticsearchreceiver/client.go @@ -78,12 +78,10 @@ func newElasticsearchClient(ctx context.Context, settings component.TelemetrySet return &esClient, nil } -var ( - es7_9 = func() *version.Version { - v, _ := version.NewVersion("7.9") - return v - }() -) +var es7_9 = func() *version.Version { + v, _ := version.NewVersion("7.9") + return v +}() const ( // A comma separated list of metrics that will be gathered from NodeStats. diff --git a/receiver/elasticsearchreceiver/scraper.go b/receiver/elasticsearchreceiver/scraper.go index ad1807498d28..13ef0f78b999 100644 --- a/receiver/elasticsearchreceiver/scraper.go +++ b/receiver/elasticsearchreceiver/scraper.go @@ -404,7 +404,6 @@ func (r *elasticsearchScraper) scrapeIndicesMetrics(ctx context.Context, now pco } indexStats, err := r.client.IndexStats(ctx, r.cfg.Indices) - if err != nil { errs.AddPartial(63, err) return diff --git a/receiver/elasticsearchreceiver/scraper_test.go b/receiver/elasticsearchreceiver/scraper_test.go index f5c592b6b867..63179a339b1d 100644 --- a/receiver/elasticsearchreceiver/scraper_test.go +++ b/receiver/elasticsearchreceiver/scraper_test.go @@ -23,10 +23,12 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/elasticsearchreceiver/internal/model" ) -const fullLinuxExpectedMetricsPath = "./testdata/expected_metrics/full_linux.yaml" -const fullOtherExpectedMetricsPath = "./testdata/expected_metrics/full_other.yaml" -const skipClusterExpectedMetricsPath = "./testdata/expected_metrics/clusterSkip.yaml" -const noNodesExpectedMetricsPath = "./testdata/expected_metrics/noNodes.yaml" +const ( + fullLinuxExpectedMetricsPath = "./testdata/expected_metrics/full_linux.yaml" + fullOtherExpectedMetricsPath = "./testdata/expected_metrics/full_other.yaml" + skipClusterExpectedMetricsPath = "./testdata/expected_metrics/clusterSkip.yaml" + noNodesExpectedMetricsPath = "./testdata/expected_metrics/noNodes.yaml" +) func TestScraper(t *testing.T) { t.Parallel() diff --git a/receiver/filelogreceiver/filelog.go b/receiver/filelogreceiver/filelog.go index d79fb31e8572..8889ab996093 100644 --- a/receiver/filelogreceiver/filelog.go +++ b/receiver/filelogreceiver/filelog.go @@ -32,6 +32,7 @@ func (f ReceiverType) Type() component.Type { func (f ReceiverType) CreateDefaultConfig() component.Config { return createDefaultConfig() } + func createDefaultConfig() *FileLogConfig { return &FileLogConfig{ BaseConfig: adapter.BaseConfig{ diff --git a/receiver/filelogreceiver/filelog_test.go b/receiver/filelogreceiver/filelog_test.go index 80931bbe87ee..03939fa11106 100644 --- a/receiver/filelogreceiver/filelog_test.go +++ b/receiver/filelogreceiver/filelog_test.go @@ -180,7 +180,7 @@ func (rt *rotationTest) Run(t *testing.T) { require.NoError(t, err, "failed to create receiver") require.NoError(t, rcvr.Start(context.Background(), componenttest.NewNopHost())) - file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0600) + file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0o600) defer func() { require.NoError(t, file.Close()) }() @@ -198,7 +198,7 @@ func (rt *rotationTest) Run(t *testing.T) { return errors.Is(removeErr, os.ErrNotExist) }, 5*time.Second, 100*time.Millisecond) - backupFile, openErr := os.OpenFile(backupFileName, os.O_CREATE|os.O_RDWR, 0600) + backupFile, openErr := os.OpenFile(backupFileName, os.O_CREATE|os.O_RDWR, 0o600) require.NoError(t, openErr) // Copy the current file to the backup file @@ -216,7 +216,7 @@ func (rt *rotationTest) Run(t *testing.T) { } else { require.NoError(t, file.Close()) require.NoError(t, os.Rename(fileName, backupFileName)) - file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0600) + file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0o600) require.NoError(t, err) } } diff --git a/receiver/filelogreceiver/storage_test.go b/receiver/filelogreceiver/storage_test.go index 906a2351502b..67d9fcc1a1a1 100644 --- a/receiver/filelogreceiver/storage_test.go +++ b/receiver/filelogreceiver/storage_test.go @@ -148,7 +148,7 @@ type recallLogger struct { func newRecallLogger(t *testing.T, tempDir string) *recallLogger { path := filepath.Join(tempDir, "test.log") - logFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + logFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600) require.NoError(t, err) return &recallLogger{ diff --git a/receiver/filestatsreceiver/integration_test.go b/receiver/filestatsreceiver/integration_test.go index 04338777824e..2fa08c197d97 100644 --- a/receiver/filestatsreceiver/integration_test.go +++ b/receiver/filestatsreceiver/integration_test.go @@ -22,9 +22,9 @@ import ( func Test_Integration(t *testing.T) { expectedFile := filepath.Join("testdata", "integration", "expected.yaml") tempDir := t.TempDir() - require.NoError(t, os.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("foo"), 0600)) - require.NoError(t, os.WriteFile(filepath.Join(tempDir, "bar.txt"), []byte("bar"), 0600)) - require.NoError(t, os.WriteFile(filepath.Join(tempDir, "foobar.txt"), []byte("foobar"), 0600)) + require.NoError(t, os.WriteFile(filepath.Join(tempDir, "foo.txt"), []byte("foo"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(tempDir, "bar.txt"), []byte("bar"), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(tempDir, "foobar.txt"), []byte("foobar"), 0o600)) scraperinttest.NewIntegrationTest( NewFactory(), scraperinttest.WithCustomConfig( diff --git a/receiver/filestatsreceiver/scraper_test.go b/receiver/filestatsreceiver/scraper_test.go index 0109aef57f24..7f9b3250dcb0 100644 --- a/receiver/filestatsreceiver/scraper_test.go +++ b/receiver/filestatsreceiver/scraper_test.go @@ -23,7 +23,7 @@ func Test_Scrape(t *testing.T) { require.NoError(t, err) require.Equal(t, 0, metrics.ResourceMetrics().Len()) logFile := filepath.Join(tmpDir, "my.log") - err = os.WriteFile(logFile, []byte("something"), 0600) + err = os.WriteFile(logFile, []byte("something"), 0o600) t.Cleanup(func() { _ = os.Remove(tmpDir) }) @@ -62,7 +62,7 @@ func Test_Scrape_All(t *testing.T) { require.Equal(t, int64(0), fileCount.Gauge().DataPoints().At(0).IntValue()) require.Equal(t, "file.count", fileCount.Name()) logFile := filepath.Join(tmpDir, "my.log") - err = os.WriteFile(logFile, []byte("something"), 0600) + err = os.WriteFile(logFile, []byte("something"), 0o600) t.Cleanup(func() { _ = os.Remove(tmpDir) }) diff --git a/receiver/fluentforwardreceiver/config.go b/receiver/fluentforwardreceiver/config.go index 1cd471848fa6..6ebd513ed190 100644 --- a/receiver/fluentforwardreceiver/config.go +++ b/receiver/fluentforwardreceiver/config.go @@ -5,7 +5,6 @@ package fluentforwardreceiver // import "github.com/open-telemetry/opentelemetry // Config defines configuration for the fluentforward receiver. type Config struct { - // The address to listen on for incoming Fluent Forward events. Should be // of the form `:` (TCP) or `unix://` (Unix // domain socket). diff --git a/receiver/githubreceiver/config.go b/receiver/githubreceiver/config.go index f29dc7c0a429..b070973df534 100644 --- a/receiver/githubreceiver/config.go +++ b/receiver/githubreceiver/config.go @@ -26,8 +26,10 @@ type Config struct { metadata.MetricsBuilderConfig `mapstructure:",squash"` } -var _ component.Config = (*Config)(nil) -var _ confmap.Unmarshaler = (*Config)(nil) +var ( + _ component.Config = (*Config)(nil) + _ confmap.Unmarshaler = (*Config)(nil) +) // Validate the configuration passed through the OTEL config.yaml func (cfg *Config) Validate() error { diff --git a/receiver/githubreceiver/factory.go b/receiver/githubreceiver/factory.go index a8936fa5d484..26c472d58fc3 100644 --- a/receiver/githubreceiver/factory.go +++ b/receiver/githubreceiver/factory.go @@ -96,7 +96,6 @@ func createAddScraperOpts( for key, cfg := range cfg.Scrapers { githubScraper, err := createGitHubScraper(ctx, params, key, cfg, factories) - if err != nil { return nil, fmt.Errorf("failed to create scraper %q: %w", key, err) } diff --git a/receiver/githubreceiver/internal/scraper.go b/receiver/githubreceiver/internal/scraper.go index e9fb4c7982f1..869e20639aef 100644 --- a/receiver/githubreceiver/internal/scraper.go +++ b/receiver/githubreceiver/internal/scraper.go @@ -19,5 +19,4 @@ type ScraperFactory interface { type Config any -type ScraperConfig struct { -} +type ScraperConfig struct{} diff --git a/receiver/githubreceiver/internal/scraper/githubscraper/github_scraper_test.go b/receiver/githubreceiver/internal/scraper/githubscraper/github_scraper_test.go index 8a0178865d65..a04653f585d7 100644 --- a/receiver/githubreceiver/internal/scraper/githubscraper/github_scraper_test.go +++ b/receiver/githubreceiver/internal/scraper/githubscraper/github_scraper_test.go @@ -134,7 +134,6 @@ func TestScrape(t *testing.T) { History: BranchHistoryTargetCommitHistoryCommitHistoryConnection{ Nodes: []CommitNode{ { - CommittedDate: time.Now().AddDate(0, 0, -1), Additions: 10, Deletions: 9, diff --git a/receiver/githubreceiver/internal/scraper/githubscraper/helpers_test.go b/receiver/githubreceiver/internal/scraper/githubscraper/helpers_test.go index d0ef2a801bf0..1741640c9416 100644 --- a/receiver/githubreceiver/internal/scraper/githubscraper/helpers_test.go +++ b/receiver/githubreceiver/internal/scraper/githubscraper/helpers_test.go @@ -797,7 +797,6 @@ func TestEvalCommits(t *testing.T) { History: BranchHistoryTargetCommitHistoryCommitHistoryConnection{ Nodes: []CommitNode{ { - CommittedDate: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), Additions: 10, Deletions: 9, @@ -831,7 +830,6 @@ func TestEvalCommits(t *testing.T) { History: BranchHistoryTargetCommitHistoryCommitHistoryConnection{ Nodes: []CommitNode{ { - CommittedDate: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), Additions: 10, Deletions: 9, @@ -843,7 +841,6 @@ func TestEvalCommits(t *testing.T) { History: BranchHistoryTargetCommitHistoryCommitHistoryConnection{ Nodes: []CommitNode{ { - CommittedDate: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC), Additions: 1, Deletions: 1, diff --git a/receiver/googlecloudmonitoringreceiver/config_test.go b/receiver/googlecloudmonitoringreceiver/config_test.go index 9d846d766bcf..36f09b2ac756 100644 --- a/receiver/googlecloudmonitoringreceiver/config_test.go +++ b/receiver/googlecloudmonitoringreceiver/config_test.go @@ -55,11 +55,13 @@ func TestValidateService(t *testing.T) { "Valid Service": { MetricConfig{ MetricName: "metric_name", - }, false}, + }, false, + }, "Empty MetricName": { MetricConfig{ MetricName: "", - }, true}, + }, true, + }, } for name, testCase := range testCases { diff --git a/receiver/googlecloudpubsubreceiver/config.go b/receiver/googlecloudpubsubreceiver/config.go index 3fded52da653..8dbdb8b9a3e7 100644 --- a/receiver/googlecloudpubsubreceiver/config.go +++ b/receiver/googlecloudpubsubreceiver/config.go @@ -13,7 +13,6 @@ import ( var subscriptionMatcher = regexp.MustCompile(`projects/[a-z][a-z0-9\-]*/subscriptions/`) type Config struct { - // Google Cloud Project ID where the Pubsub client will connect to ProjectID string `mapstructure:"project"` // User agent that will be used by the Pubsub client to connect to the service diff --git a/receiver/googlecloudpubsubreceiver/factory.go b/receiver/googlecloudpubsubreceiver/factory.go index e8ff793fb3b8..96ccc49d5814 100644 --- a/receiver/googlecloudpubsubreceiver/factory.go +++ b/receiver/googlecloudpubsubreceiver/factory.go @@ -69,7 +69,8 @@ func (factory *pubsubReceiverFactory) CreateTraces( _ context.Context, params receiver.Settings, cfg component.Config, - consumer consumer.Traces) (receiver.Traces, error) { + consumer consumer.Traces, +) (receiver.Traces, error) { err := cfg.(*Config).validateForTrace() if err != nil { return nil, err @@ -86,7 +87,8 @@ func (factory *pubsubReceiverFactory) CreateMetrics( _ context.Context, params receiver.Settings, cfg component.Config, - consumer consumer.Metrics) (receiver.Metrics, error) { + consumer consumer.Metrics, +) (receiver.Metrics, error) { err := cfg.(*Config).validateForMetric() if err != nil { return nil, err @@ -103,7 +105,8 @@ func (factory *pubsubReceiverFactory) CreateLogs( _ context.Context, params receiver.Settings, cfg component.Config, - consumer consumer.Logs) (receiver.Logs, error) { + consumer consumer.Logs, +) (receiver.Logs, error) { err := cfg.(*Config).validateForLog() if err != nil { return nil, err diff --git a/receiver/googlecloudpubsubreceiver/internal/handler.go b/receiver/googlecloudpubsubreceiver/internal/handler.go index fbb466fed8cb..fe18e1702f50 100644 --- a/receiver/googlecloudpubsubreceiver/internal/handler.go +++ b/receiver/googlecloudpubsubreceiver/internal/handler.go @@ -56,7 +56,8 @@ func NewHandler( client *pubsub.SubscriberClient, clientID string, subscription string, - callback func(ctx context.Context, message *pubsubpb.ReceivedMessage) error) (*StreamHandler, error) { + callback func(ctx context.Context, message *pubsubpb.ReceivedMessage) error, +) (*StreamHandler, error) { handler := StreamHandler{ logger: logger, client: client, @@ -197,7 +198,7 @@ func (handler *StreamHandler) responseStream(ctx context.Context, cancel context } } } else { - var s, grpcStatus = status.FromError(err) + s, grpcStatus := status.FromError(err) switch { case errors.Is(err, io.EOF): activeStreaming = false diff --git a/receiver/googlecloudpubsubreceiver/internal/log_entry.go b/receiver/googlecloudpubsubreceiver/internal/log_entry.go index e2b86f4ecf1d..282ed890e6f3 100644 --- a/receiver/googlecloudpubsubreceiver/internal/log_entry.go +++ b/receiver/googlecloudpubsubreceiver/internal/log_entry.go @@ -30,8 +30,10 @@ import ( var json = jsoniter.ConfigCompatibleWithStandardLibrary -var invalidTraceID = [16]byte{} -var invalidSpanID = [8]byte{} +var ( + invalidTraceID = [16]byte{} + invalidSpanID = [8]byte{} +) func cloudLoggingTraceToTraceIDBytes(trace string) [16]byte { // Format: projects/my-gcp-project/traces/4ebc71f1def9274798cac4e8960d0095 @@ -88,8 +90,10 @@ func cloudLoggingSeverityToNumber(severity string) plog.SeverityNumber { return plog.SeverityNumberUnspecified } -var desc protoreflect.MessageDescriptor -var descOnce sync.Once +var ( + desc protoreflect.MessageDescriptor + descOnce sync.Once +) func getLogEntryDescriptor() protoreflect.MessageDescriptor { descOnce.Do(func() { @@ -115,7 +119,6 @@ func TranslateLogEntry(_ context.Context, _ *zap.Logger, data []byte) (pcommon.R var src map[string]stdjson.RawMessage err := json.Unmarshal(data, &src) - if err != nil { return res, lr, err } @@ -491,6 +494,7 @@ func (opts translateOptions) translateMap(dst pcommon.Map, fd protoreflect.Field } return nil } + func translateAny(dst pcommon.Map, src map[string]stdjson.RawMessage) error { // protojson represents Any as the JSON representation of the actual // message, plus a special @type field containing the type URL of the diff --git a/receiver/googlecloudspannerreceiver/internal/datasource/databaseid.go b/receiver/googlecloudspannerreceiver/internal/datasource/databaseid.go index 07e9f787c51b..7d73d5f076f6 100644 --- a/receiver/googlecloudspannerreceiver/internal/datasource/databaseid.go +++ b/receiver/googlecloudspannerreceiver/internal/datasource/databaseid.go @@ -32,6 +32,7 @@ func (databaseID *DatabaseID) InstanceID() string { func (databaseID *DatabaseID) DatabaseName() string { return databaseID.databaseName } + func (databaseID *DatabaseID) ID() string { return databaseID.id } diff --git a/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality.go b/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality.go index dcafa414f783..7bb420da5ae9 100644 --- a/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality.go +++ b/receiver/googlecloudspannerreceiver/internal/filter/itemcardinality.go @@ -52,7 +52,8 @@ func (f *currentLimitByTimestamp) get() int { } func NewItemCardinalityFilter(metricName string, totalLimit int, limitByTimestamp int, - itemActivityPeriod time.Duration, logger *zap.Logger) (ItemFilter, error) { + itemActivityPeriod time.Duration, logger *zap.Logger, +) (ItemFilter, error) { if limitByTimestamp > totalLimit { return nil, fmt.Errorf("total limit %q is lower or equal to limit by timestamp %q", totalLimit, limitByTimestamp) } diff --git a/receiver/googlecloudspannerreceiver/internal/filterfactory/filterbuilder.go b/receiver/googlecloudspannerreceiver/internal/filterfactory/filterbuilder.go index b9a0a2a43abe..6895f97bf8cc 100644 --- a/receiver/googlecloudspannerreceiver/internal/filterfactory/filterbuilder.go +++ b/receiver/googlecloudspannerreceiver/internal/filterfactory/filterbuilder.go @@ -56,7 +56,8 @@ func (b filterBuilder) buildFilterByMetricPositiveTotalLimit() (map[string]filte } func (b filterBuilder) handleLowCardinalityGroups(groups []*metadata.MetricsMetadata, remainingTotalLimit int, - filterByMetric map[string]filter.ItemFilter) (int, error) { + filterByMetric map[string]filter.ItemFilter, +) (int, error) { if len(groups) == 0 { return remainingTotalLimit, nil } @@ -71,7 +72,8 @@ func (b filterBuilder) handleLowCardinalityGroups(groups []*metadata.MetricsMeta } func (b filterBuilder) handleHighCardinalityGroups(groups []*metadata.MetricsMetadata, remainingTotalLimit int, - filterByMetric map[string]filter.ItemFilter) (int, error) { + filterByMetric map[string]filter.ItemFilter, +) (int, error) { if len(groups) == 0 { return remainingTotalLimit, nil } @@ -91,7 +93,8 @@ func (b filterBuilder) handleHighCardinalityGroups(groups []*metadata.MetricsMet } func (b filterBuilder) constructFiltersForGroups(totalLimitPerMetric int, limitPerMetricByTimestamp int, - groups []*metadata.MetricsMetadata, remainingTotalLimit int, filterByMetric map[string]filter.ItemFilter) (int, error) { + groups []*metadata.MetricsMetadata, remainingTotalLimit int, filterByMetric map[string]filter.ItemFilter, +) (int, error) { newTotalLimit := remainingTotalLimit for _, metadataItem := range groups { diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricdatatype.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricdatatype.go index 93e2c0fa010a..b7aa4208370f 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricdatatype.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricdatatype.go @@ -18,7 +18,8 @@ type metricValueDataType struct { } func NewMetricType(dataType pmetric.MetricType, aggregationTemporality pmetric.AggregationTemporality, - isMonotonic bool) MetricType { + isMonotonic bool, +) MetricType { return metricValueDataType{ dataType: dataType, aggregationTemporality: aggregationTemporality, diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsbuilder_test.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsbuilder_test.go index 3ddbfde3ff78..1f6884105c85 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsbuilder_test.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsbuilder_test.go @@ -36,8 +36,7 @@ func (r *mockItemFilterResolver) Shutdown() error { return args.Error(0) } -type errorFilter struct { -} +type errorFilter struct{} func (f errorFilter) Filter(_ []*filter.Item) ([]*filter.Item, error) { return nil, errors.New("error on filter") @@ -343,7 +342,8 @@ func executeShutdown(t *testing.T, metricsBuilder MetricsBuilder, expectError bo } func executeMockedShutdown(t *testing.T, metricsBuilder MetricsBuilder, filterResolver *mockItemFilterResolver, - expectedError error) { + expectedError error, +) { filterResolver.On("Shutdown").Return(expectedError) _ = metricsBuilder.Shutdown() filterResolver.AssertExpectations(t) diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata.go index 497f3c1a1479..d53a9374978a 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricsmetadata.go @@ -111,7 +111,8 @@ func (metadata *MetricsMetadata) RowToMetricsDataPoints(databaseID *datasource.D } func (metadata *MetricsMetadata) toMetricsDataPoints(databaseID *datasource.DatabaseID, timestamp time.Time, - labelValues []LabelValue, metricValues []MetricValue) []*MetricsDataPoint { + labelValues []LabelValue, metricValues []MetricValue, +) []*MetricsDataPoint { dataPoints := make([]*MetricsDataPoint, len(metricValues)) for i, metricValue := range metricValues { diff --git a/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go b/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go index 0bb81e368886..2abc157c1a86 100644 --- a/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go +++ b/receiver/googlecloudspannerreceiver/internal/metadata/metricvalue.go @@ -141,7 +141,8 @@ func newNullFloat64MetricValue(metadata MetricValueMetadata, valueHolder any) Me } func NewMetricValueMetadata(name string, columnName string, dataType MetricType, unit string, - valueType ValueType) (MetricValueMetadata, error) { + valueType ValueType, +) (MetricValueMetadata, error) { var newMetricValueFunc newMetricValueFunction var valueHolderFunc valueHolderFunction diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/currentstatsreader.go b/receiver/googlecloudspannerreceiver/internal/statsreader/currentstatsreader.go index 3c6c50a06a45..89fc1e0cfaa3 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/currentstatsreader.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/currentstatsreader.go @@ -40,7 +40,8 @@ func newCurrentStatsReader( logger *zap.Logger, database *datasource.Database, metricsMetadata *metadata.MetricsMetadata, - config ReaderConfig) *currentStatsReader { + config ReaderConfig, +) *currentStatsReader { return ¤tStatsReader{ logger: logger, database: database, diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/databasereader.go b/receiver/googlecloudspannerreceiver/internal/statsreader/databasereader.go index 8574ce9b3044..b00f31ad9b49 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/databasereader.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/databasereader.go @@ -25,7 +25,8 @@ func NewDatabaseReader(ctx context.Context, databaseID *datasource.DatabaseID, serviceAccountPath string, readerConfig ReaderConfig, - logger *zap.Logger) (*DatabaseReader, error) { + logger *zap.Logger, +) (*DatabaseReader, error) { database, err := datasource.NewDatabase(ctx, databaseID, serviceAccountPath) if err != nil { return nil, fmt.Errorf("error occurred during client instantiation for database %q: %w", databaseID.ID(), err) @@ -41,7 +42,8 @@ func NewDatabaseReader(ctx context.Context, } func initializeReaders(logger *zap.Logger, parsedMetadata []*metadata.MetricsMetadata, - database *datasource.Database, readerConfig ReaderConfig) []Reader { + database *datasource.Database, readerConfig ReaderConfig, +) []Reader { readers := make([]Reader, len(parsedMetadata)) for i, mData := range parsedMetadata { diff --git a/receiver/googlecloudspannerreceiver/internal/statsreader/intervalstatsreader.go b/receiver/googlecloudspannerreceiver/internal/statsreader/intervalstatsreader.go index 03ffbc0ff337..fc7b6c131e92 100644 --- a/receiver/googlecloudspannerreceiver/internal/statsreader/intervalstatsreader.go +++ b/receiver/googlecloudspannerreceiver/internal/statsreader/intervalstatsreader.go @@ -36,7 +36,8 @@ func newIntervalStatsReader( logger *zap.Logger, database *datasource.Database, metricsMetadata *metadata.MetricsMetadata, - config ReaderConfig) *intervalStatsReader { + config ReaderConfig, +) *intervalStatsReader { reader := currentStatsReader{ logger: logger, database: database, diff --git a/receiver/googlecloudspannerreceiver/receiver.go b/receiver/googlecloudspannerreceiver/receiver.go index b13a0621288b..41a97594119f 100644 --- a/receiver/googlecloudspannerreceiver/receiver.go +++ b/receiver/googlecloudspannerreceiver/receiver.go @@ -110,7 +110,8 @@ func (r *googleCloudSpannerReceiver) initialize(ctx context.Context) error { } func (r *googleCloudSpannerReceiver) initializeProjectReaders(ctx context.Context, - parsedMetadata []*metadata.MetricsMetadata) error { + parsedMetadata []*metadata.MetricsMetadata, +) error { readerConfig := statsreader.ReaderConfig{ BackfillEnabled: r.config.BackfillEnabled, TopMetricsQueryMaxRows: r.config.TopMetricsQueryMaxRows, @@ -163,7 +164,8 @@ func (r *googleCloudSpannerReceiver) initializeMetricsBuilder(parsedMetadata []* } func newProjectReader(ctx context.Context, logger *zap.Logger, project Project, parsedMetadata []*metadata.MetricsMetadata, - readerConfig statsreader.ReaderConfig) (*statsreader.ProjectReader, error) { + readerConfig statsreader.ReaderConfig, +) (*statsreader.ProjectReader, error) { logger.Debug("Constructing project reader for project", zap.String("project id", project.ID)) databaseReadersCount := 0 diff --git a/receiver/haproxyreceiver/scraper.go b/receiver/haproxyreceiver/scraper.go index 851efef2d342..25bcbfa3557c 100644 --- a/receiver/haproxyreceiver/scraper.go +++ b/receiver/haproxyreceiver/scraper.go @@ -27,9 +27,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/haproxyreceiver/internal/metadata" ) -var ( - showStatsCommand = []byte("show stat\n") -) +var showStatsCommand = []byte("show stat\n") type scraper struct { cfg *Config diff --git a/receiver/hostmetricsreceiver/config.go b/receiver/hostmetricsreceiver/config.go index aae68f79e713..b6caa11f4a7c 100644 --- a/receiver/hostmetricsreceiver/config.go +++ b/receiver/hostmetricsreceiver/config.go @@ -35,8 +35,10 @@ type Config struct { MetadataCollectionInterval time.Duration `mapstructure:"metadata_collection_interval"` } -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/hostmetricsreceiver/hostmetrics_receiver_test.go b/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go index 993b08f95b7b..43bc911c8e65 100644 --- a/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go +++ b/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go @@ -222,8 +222,10 @@ func (m *mockConfig) SetRootPath(_ string) {} func (m *mockConfig) SetEnvMap(_ common.EnvMap) {} -type mockFactory struct{ mock.Mock } -type mockScraper struct{ mock.Mock } +type ( + mockFactory struct{ mock.Mock } + mockScraper struct{ mock.Mock } +) func (m *mockFactory) CreateDefaultConfig() internal.Config { return &mockConfig{} } func (m *mockFactory) CreateMetricsScraper(context.Context, receiver.Settings, internal.Config) (scraperhelper.Scraper, error) { diff --git a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go index 925936b85059..85edc10ccb10 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go @@ -21,8 +21,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/ucal" ) -const metricsLen = 2 -const hzInAMHz = 1_000_000 +const ( + metricsLen = 2 + hzInAMHz = 1_000_000 +) // scraper for CPU Metrics type scraper struct { diff --git a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/factory.go index 614133ccf20d..2686d11d0824 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/factory.go @@ -21,10 +21,8 @@ const ( TypeStr = "cpu" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. type Factory struct{} diff --git a/receiver/hostmetricsreceiver/internal/scraper/diskscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/diskscraper/factory.go index d78a7e973655..7fa835eca0ce 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/diskscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/diskscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "disk" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/factory.go index d375fea7d14f..48355074b2ff 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/factory.go @@ -22,14 +22,11 @@ const ( TypeStr = "filesystem" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // Type gets the type of the scraper config created by this Factory. func (f *Factory) Type() string { diff --git a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go index 7406b6e5592a..03aeb058d77e 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go @@ -488,7 +488,8 @@ func assertFileSystemUsageMetricValid( t *testing.T, metric pmetric.Metric, expectedDeviceDataPoints int, - expectedDeviceAttributes []map[string]pcommon.Value) { + expectedDeviceAttributes []map[string]pcommon.Value, +) { for i := 0; i < metric.Sum().DataPoints().Len(); i++ { for _, label := range []string{"device", "type", "mode", "mountpoint"} { internal.AssertSumMetricHasAttribute(t, metric, i, label) diff --git a/receiver/hostmetricsreceiver/internal/scraper/loadscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/loadscraper/factory.go index bdfc2ca9ecaf..49f87899d8d0 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/loadscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/loadscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "load" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/factory.go index 2a43b921720b..6c4024e4a3dc 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "memory" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/factory.go index a9fe64109e63..f42ecf8c1f78 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "network" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/factory.go index 588f9b4a655b..22ac5b217791 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "paging" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/factory.go index 256961a86f03..8c5b3df7fbf2 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/factory.go @@ -21,14 +21,11 @@ const ( TypeStr = "processes" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go index 467b1433f320..d7b14679f5e5 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go @@ -5,8 +5,10 @@ package processesscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processesscraper" -const enableProcessesCount = false -const enableProcessesCreated = false +const ( + enableProcessesCount = false + enableProcessesCreated = false +) func (s *scraper) getProcessesMetadata() (processesMetadata, error) { return processesMetadata{}, nil diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go index 5fd768da7d9d..9b4042d6e5f6 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go @@ -15,8 +15,10 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processesscraper/internal/metadata" ) -const enableProcessesCount = true -const enableProcessesCreated = runtime.GOOS == "openbsd" || runtime.GOOS == "linux" +const ( + enableProcessesCount = true + enableProcessesCreated = runtime.GOOS == "openbsd" || runtime.GOOS == "linux" +) func (s *scraper) getProcessesMetadata() (processesMetadata, error) { ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/factory.go index 8aeccf9af8b2..cae4a6b88202 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/factory.go @@ -24,10 +24,8 @@ const ( TypeStr = "process" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) var ( bootTimeCacheFeaturegateID = "hostmetrics.process.bootTimeCache" @@ -41,8 +39,7 @@ var ( ) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go index 0a918a112ba1..72f82417bd9d 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go @@ -401,7 +401,6 @@ func (s *scraper) scrapeAndAppendContextSwitchMetrics(ctx context.Context, now p } contextSwitches, err := handle.NumCtxSwitchesWithContext(ctx) - if err != nil { return err } @@ -418,7 +417,6 @@ func (s *scraper) scrapeAndAppendOpenFileDescriptorsMetric(ctx context.Context, } fds, err := handle.NumFDsWithContext(ctx) - if err != nil { return err } diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_darwin.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_darwin.go index 9d2463c504e5..b705367baa57 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_darwin.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_darwin.go @@ -60,5 +60,4 @@ func getProcessCommand(ctx context.Context, proc processHandle) (*commandMetadat command := &commandMetadata{command: cmdline, commandLine: cmdline} return command, nil - } diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go index c6b788c57d1c..e12f8f2ca545 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go @@ -109,7 +109,6 @@ func TestScrape(t *testing.T) { require.NoError(t, err, "Failed to initialize process scraper: %v", err) md, err := scraper.scrape(context.Background()) - // may receive some partial errors as a result of attempting to: // a) read native system processes on Windows (e.g. Registry process) // b) read info on processes that have just terminated @@ -272,7 +271,8 @@ func assertMetricMissing(t *testing.T, resourceMetrics pmetric.ResourceMetricsSl } func assertDiskIoMetricValid(t *testing.T, resourceMetrics pmetric.ResourceMetricsSlice, - startTime pcommon.Timestamp) { + startTime pcommon.Timestamp, +) { diskIoMetric := getMetric(t, "process.disk.io", resourceMetrics) if startTime != 0 { internal.AssertSumMetricStartTimeEquals(t, diskIoMetric, startTime) diff --git a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/factory.go b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/factory.go index bb7d540c7526..0eac31bc0bd2 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/factory.go +++ b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/factory.go @@ -23,14 +23,11 @@ const ( TypeStr = "system" ) -var ( - // scraperType is the component type used for the built scraper. - scraperType component.Type = component.MustNewType(TypeStr) -) +// scraperType is the component type used for the built scraper. +var scraperType component.Type = component.MustNewType(TypeStr) // Factory is the Factory for scraper. -type Factory struct { -} +type Factory struct{} // CreateDefaultConfig creates the default configuration for the Scraper. func (f *Factory) CreateDefaultConfig() internal.Config { diff --git a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper_test.go index 38171c5a8cf1..99a693812372 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper_test.go @@ -19,7 +19,7 @@ import ( func TestScrape(t *testing.T) { ctx := context.Background() - fakeDate := time.Date(2006, 01, 02, 03, 04, 05, 0, time.UTC) + fakeDate := time.Date(2006, 0o1, 0o2, 0o3, 0o4, 0o5, 0, time.UTC) s := newUptimeScraper(ctx, receivertest.NewNopSettings(), &Config{ MetricsBuilderConfig: metadata.DefaultMetricsBuilderConfig(), diff --git a/receiver/hostmetricsreceiver/internal/testutils.go b/receiver/hostmetricsreceiver/internal/testutils.go index c73ef17e6e38..7c7d82a4bcd5 100644 --- a/receiver/hostmetricsreceiver/internal/testutils.go +++ b/receiver/hostmetricsreceiver/internal/testutils.go @@ -59,6 +59,7 @@ func AssertGaugeMetricStartTimeEquals(t *testing.T, metric pmetric.Metric, start require.Equal(t, startTime, ddps.At(i).StartTimestamp()) } } + func AssertSameTimeStampForAllMetrics(t *testing.T, metrics pmetric.MetricSlice) { AssertSameTimeStampForMetrics(t, metrics, 0, metrics.Len()) } diff --git a/receiver/httpcheckreceiver/scraper_test.go b/receiver/httpcheckreceiver/scraper_test.go index 8f9b05a48490..6ade4a815a9c 100644 --- a/receiver/httpcheckreceiver/scraper_test.go +++ b/receiver/httpcheckreceiver/scraper_test.go @@ -159,18 +159,22 @@ func TestScaperScrape(t *testing.T) { t.Run(tc.desc, func(t *testing.T) { cfg := createDefaultConfig().(*Config) if len(tc.endpoint) > 0 { - cfg.Targets = []*targetConfig{{ - ClientConfig: confighttp.ClientConfig{ - Endpoint: tc.endpoint, - }}, + cfg.Targets = []*targetConfig{ + { + ClientConfig: confighttp.ClientConfig{ + Endpoint: tc.endpoint, + }, + }, } } else { ms := newMockServer(t, tc.expectedResponse) defer ms.Close() - cfg.Targets = []*targetConfig{{ - ClientConfig: confighttp.ClientConfig{ - Endpoint: ms.URL, - }}, + cfg.Targets = []*targetConfig{ + { + ClientConfig: confighttp.ClientConfig{ + Endpoint: ms.URL, + }, + }, } } scraper := newScraper(cfg, receivertest.NewNopSettings()) diff --git a/receiver/iisreceiver/recorder.go b/receiver/iisreceiver/recorder.go index 5cb6eaa293ed..afa2113f8c71 100644 --- a/receiver/iisreceiver/recorder.go +++ b/receiver/iisreceiver/recorder.go @@ -46,7 +46,8 @@ var sitePerfCounterRecorders = []perfCounterRecorderConf{ mb.RecordIisNetworkIoDataPoint(ts, int64(val), metadata.AttributeDirectionSent) }, "Total Connection Attempts (all instances)": func(mb *metadata.MetricsBuilder, ts pcommon.Timestamp, - val float64) { + val float64, + ) { mb.RecordIisConnectionAttemptCountDataPoint(ts, int64(val)) }, "Total Delete Requests": func(mb *metadata.MetricsBuilder, ts pcommon.Timestamp, val float64) { diff --git a/receiver/iisreceiver/scraper.go b/receiver/iisreceiver/scraper.go index ec1259947307..63f3a1f0ca09 100644 --- a/receiver/iisreceiver/scraper.go +++ b/receiver/iisreceiver/scraper.go @@ -151,7 +151,6 @@ func (rcvr *iisReceiver) scrapeInstanceMetrics(wrs []watcherRecorder, instanceTo }) } } - } var negativeDenominatorError = "A counter with a negative denominator value was detected.\r\n" diff --git a/receiver/iisreceiver/scraper_test.go b/receiver/iisreceiver/scraper_test.go index 632be6f11305..18bc30dc31f5 100644 --- a/receiver/iisreceiver/scraper_test.go +++ b/receiver/iisreceiver/scraper_test.go @@ -155,7 +155,6 @@ func TestMaxQueueItemAgeNegativeDenominatorScrapeFailure(t *testing.T) { require.NoError(t, pmetrictest.CompareMetrics(expectedMetrics, actualMetrics, pmetrictest.IgnoreMetricDataPointsOrder(), pmetrictest.IgnoreStartTimestamp(), pmetrictest.IgnoreTimestamp())) - } type mockPerfCounter struct { diff --git a/receiver/jaegerreceiver/config.go b/receiver/jaegerreceiver/config.go index 4ed9dda665ca..a636e47bed59 100644 --- a/receiver/jaegerreceiver/config.go +++ b/receiver/jaegerreceiver/config.go @@ -72,8 +72,10 @@ type Config struct { RemoteSampling *RemoteSamplingConfig `mapstructure:"remote_sampling"` } -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/jaegerreceiver/jaeger_agent_test.go b/receiver/jaegerreceiver/jaeger_agent_test.go index 3a80c3c1804c..1c0765052ef1 100644 --- a/receiver/jaegerreceiver/jaeger_agent_test.go +++ b/receiver/jaegerreceiver/jaeger_agent_test.go @@ -124,8 +124,7 @@ func initializeGRPCTestServer(t *testing.T, beforeServe func(server *grpc.Server return server, lis.Addr() } -type mockSamplingHandler struct { -} +type mockSamplingHandler struct{} func (*mockSamplingHandler) GetSamplingStrategy(context.Context, *api_v2.SamplingStrategyParameters) (*api_v2.SamplingStrategyResponse, error) { return &api_v2.SamplingStrategyResponse{StrategyType: api_v2.SamplingStrategyType_PROBABILISTIC}, nil diff --git a/receiver/jaegerreceiver/trace_receiver.go b/receiver/jaegerreceiver/trace_receiver.go index 1eb1159639d3..b7ab055bcb12 100644 --- a/receiver/jaegerreceiver/trace_receiver.go +++ b/receiver/jaegerreceiver/trace_receiver.go @@ -83,12 +83,10 @@ const ( protobufFormat = "protobuf" ) -var ( - acceptedThriftFormats = map[string]struct{}{ - "application/x-thrift": {}, - "application/vnd.apache.thrift.binary": {}, - } -) +var acceptedThriftFormats = map[string]struct{}{ + "application/x-thrift": {}, + "application/vnd.apache.thrift.binary": {}, +} // newJaegerReceiver creates a TracesReceiver that receives traffic as a Jaeger collector, and // also as a Jaeger agent. @@ -169,9 +167,11 @@ func consumeTraces(ctx context.Context, batch *jaeger.Batch, consumer consumer.T return len(batch.Spans), consumer.ConsumeTraces(ctx, td) } -var _ agent.Agent = (*agentHandler)(nil) -var _ api_v2.CollectorServiceServer = (*jReceiver)(nil) -var _ configmanager.ClientConfigManager = (*notImplementedConfigManager)(nil) +var ( + _ agent.Agent = (*agentHandler)(nil) + _ api_v2.CollectorServiceServer = (*jReceiver)(nil) + _ configmanager.ClientConfigManager = (*notImplementedConfigManager)(nil) +) var errNotImplemented = fmt.Errorf("not implemented") diff --git a/receiver/jmxreceiver/config.go b/receiver/jmxreceiver/config.go index b31534dae3bf..c971d036b95a 100644 --- a/receiver/jmxreceiver/config.go +++ b/receiver/jmxreceiver/config.go @@ -196,9 +196,13 @@ func (c *Config) validateJar(supportedJarDetails map[string]supportedJar, jar st return nil } -var validLogLevels = map[string]struct{}{"trace": {}, "debug": {}, "info": {}, "warn": {}, "error": {}, "off": {}} -var validTargetSystems = map[string]struct{}{"activemq": {}, "cassandra": {}, "hbase": {}, "hadoop": {}, - "jetty": {}, "jvm": {}, "kafka": {}, "kafka-consumer": {}, "kafka-producer": {}, "solr": {}, "tomcat": {}, "wildfly": {}} +var ( + validLogLevels = map[string]struct{}{"trace": {}, "debug": {}, "info": {}, "warn": {}, "error": {}, "off": {}} + validTargetSystems = map[string]struct{}{ + "activemq": {}, "cassandra": {}, "hbase": {}, "hadoop": {}, + "jetty": {}, "jvm": {}, "kafka": {}, "kafka-consumer": {}, "kafka-producer": {}, "solr": {}, "tomcat": {}, "wildfly": {}, + } +) var AdditionalTargetSystems = "n/a" // Separated into two functions for tests diff --git a/receiver/jmxreceiver/internal/subprocess/integration_test.go b/receiver/jmxreceiver/internal/subprocess/integration_test.go index 9d8910c6835e..1db48a33dbad 100644 --- a/receiver/jmxreceiver/internal/subprocess/integration_test.go +++ b/receiver/jmxreceiver/internal/subprocess/integration_test.go @@ -46,7 +46,7 @@ func (suite *SubprocessIntegrationSuite) SetupSuite() { _, err = scriptFile.Write([]byte(scriptContents)) require.NoError(t, err) - require.NoError(t, scriptFile.Chmod(0700)) + require.NoError(t, scriptFile.Chmod(0o700)) scriptFile.Close() suite.scriptPath = scriptFile.Name() diff --git a/receiver/k8sclusterreceiver/e2e_test.go b/receiver/k8sclusterreceiver/e2e_test.go index 97259ee4b675..dff9fac40fd1 100644 --- a/receiver/k8sclusterreceiver/e2e_test.go +++ b/receiver/k8sclusterreceiver/e2e_test.go @@ -25,9 +25,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest/pmetrictest" ) -const expectedFile = "./testdata/e2e/expected.yaml" -const testKubeConfig = "/tmp/kube-config-otelcol-e2e-testing" -const testObjectsDir = "./testdata/e2e/testobjects/" +const ( + expectedFile = "./testdata/e2e/expected.yaml" + testKubeConfig = "/tmp/kube-config-otelcol-e2e-testing" + testObjectsDir = "./testdata/e2e/testobjects/" +) // TestE2E tests the k8s cluster receiver with a real k8s cluster. // The test requires a prebuilt otelcontribcol image uploaded to a kind k8s cluster defined in @@ -37,7 +39,6 @@ const testObjectsDir = "./testdata/e2e/testobjects/" // make docker-otelcontribcol // KUBECONFIG=/tmp/kube-config-otelcol-e2e-testing kind load docker-image otelcontribcol:latest func TestE2E(t *testing.T) { - var expected pmetric.Metrics expected, err := golden.ReadMetrics(expectedFile) require.NoError(t, err) diff --git a/receiver/k8sclusterreceiver/internal/collection/collector.go b/receiver/k8sclusterreceiver/internal/collection/collector.go index aebec23baa42..8beff3ed03cb 100644 --- a/receiver/k8sclusterreceiver/internal/collection/collector.go +++ b/receiver/k8sclusterreceiver/internal/collection/collector.go @@ -46,7 +46,8 @@ type DataCollector struct { // NewDataCollector returns a DataCollector. func NewDataCollector(set receiver.Settings, ms *metadata.Store, - metricsBuilderConfig metadata.MetricsBuilderConfig, nodeConditionsToReport, allocatableTypesToReport []string) *DataCollector { + metricsBuilderConfig metadata.MetricsBuilderConfig, nodeConditionsToReport, allocatableTypesToReport []string, +) *DataCollector { return &DataCollector{ settings: set, metadataStore: ms, diff --git a/receiver/k8sclusterreceiver/internal/node/nodes.go b/receiver/k8sclusterreceiver/internal/node/nodes.go index f762b7e14ae3..0c2bf71debe4 100644 --- a/receiver/k8sclusterreceiver/internal/node/nodes.go +++ b/receiver/k8sclusterreceiver/internal/node/nodes.go @@ -64,7 +64,8 @@ func RecordMetrics(mb *imetadata.MetricsBuilder, node *corev1.Node, ts pcommon.T } func CustomMetrics(set receiver.Settings, rb *metadata.ResourceBuilder, node *corev1.Node, nodeConditionTypesToReport, - allocatableTypesToReport []string, ts pcommon.Timestamp) pmetric.ResourceMetrics { + allocatableTypesToReport []string, ts pcommon.Timestamp, +) pmetric.ResourceMetrics { rm := pmetric.NewResourceMetrics() sm := rm.ScopeMetrics().AppendEmpty() @@ -171,6 +172,7 @@ func getContainerRuntimeInfo(rawInfo string) (runtime string, version string) { } return "", "" } + func getNodeConditionMetric(nodeConditionTypeValue string) string { return fmt.Sprintf("k8s.node.condition_%s", strcase.ToSnake(nodeConditionTypeValue)) } diff --git a/receiver/k8sclusterreceiver/internal/node/nodes_test.go b/receiver/k8sclusterreceiver/internal/node/nodes_test.go index 0910c73fc32d..d047d33f4e36 100644 --- a/receiver/k8sclusterreceiver/internal/node/nodes_test.go +++ b/receiver/k8sclusterreceiver/internal/node/nodes_test.go @@ -61,6 +61,7 @@ func TestNodeMetricsReportCPUMetrics(t *testing.T) { ), ) } + func TestNodeOptionalMetrics(t *testing.T) { n := testutils.NewNode("2") rac := metadata.DefaultResourceAttributesConfig() @@ -94,6 +95,7 @@ func TestNodeOptionalMetrics(t *testing.T) { ), ) } + func TestNodeConditionValue(t *testing.T) { type args struct { node *corev1.Node diff --git a/receiver/k8sclusterreceiver/internal/testutils/objects.go b/receiver/k8sclusterreceiver/internal/testutils/objects.go index 4b8dddd6bc45..50330362c852 100644 --- a/receiver/k8sclusterreceiver/internal/testutils/objects.go +++ b/receiver/k8sclusterreceiver/internal/testutils/objects.go @@ -288,6 +288,7 @@ func NewEvictedTerminatedPodStatusWithContainer(containerName, containerID strin }, } } + func WithOwnerReferences(or []v1.OwnerReference, obj any) any { switch o := obj.(type) { case *corev1.Pod: diff --git a/receiver/k8sclusterreceiver/mock_exporter_test.go b/receiver/k8sclusterreceiver/mock_exporter_test.go index 63d7bf468ece..934fdc96cc09 100644 --- a/receiver/k8sclusterreceiver/mock_exporter_test.go +++ b/receiver/k8sclusterreceiver/mock_exporter_test.go @@ -12,8 +12,7 @@ import ( metadata "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/experimentalmetricmetadata" ) -type MockExporter struct { -} +type MockExporter struct{} func (m MockExporter) Start(context.Context, component.Host) error { return nil diff --git a/receiver/k8sclusterreceiver/receiver_test.go b/receiver/k8sclusterreceiver/receiver_test.go index ac579e38f2c0..cbbe10c65f3e 100644 --- a/receiver/k8sclusterreceiver/receiver_test.go +++ b/receiver/k8sclusterreceiver/receiver_test.go @@ -145,12 +145,14 @@ func TestReceiverWithManyResources(t *testing.T) { require.NoError(t, r.Shutdown(ctx)) } -var numCalls *atomic.Int32 -var consumeMetadataInvocation = func() { - if numCalls != nil { - numCalls.Add(1) +var ( + numCalls *atomic.Int32 + consumeMetadataInvocation = func() { + if numCalls != nil { + numCalls.Add(1) + } } -} +) func TestReceiverWithMetadata(t *testing.T) { tt, err := componenttest.SetupTelemetry(component.NewID(metadata.Type)) @@ -225,7 +227,8 @@ func setupReceiver( metricsConsumer consumer.Metrics, logsConsumer consumer.Logs, initialSyncTimeout time.Duration, - tt componenttest.TestTelemetry) *kubernetesReceiver { + tt componenttest.TestTelemetry, +) *kubernetesReceiver { distribution := distributionKubernetes if osQuotaClient != nil { distribution = distributionOpenShift diff --git a/receiver/k8sclusterreceiver/watcher_test.go b/receiver/k8sclusterreceiver/watcher_test.go index 5acda18ca7e1..c9b104e6d906 100644 --- a/receiver/k8sclusterreceiver/watcher_test.go +++ b/receiver/k8sclusterreceiver/watcher_test.go @@ -65,9 +65,10 @@ func TestSetupMetadataExporters(t *testing.T) { fields{ metadataConsumers: []metadataConsumer{(&mockExporterWithK8sMetadata{}).ConsumeMetadata}, }, - args{exporters: map[component.ID]component.Component{ - component.MustNewID("nop"): mockExporterWithK8sMetadata{}, - }, + args{ + exporters: map[component.ID]component.Component{ + component.MustNewID("nop"): mockExporterWithK8sMetadata{}, + }, metadataExportersFromConfig: []string{"nop"}, }, false, @@ -77,9 +78,10 @@ func TestSetupMetadataExporters(t *testing.T) { fields{ metadataConsumers: []metadataConsumer{}, }, - args{exporters: map[component.ID]component.Component{ - component.MustNewID("nop"): mockExporterWithK8sMetadata{}, - }, + args{ + exporters: map[component.ID]component.Component{ + component.MustNewID("nop"): mockExporterWithK8sMetadata{}, + }, metadataExportersFromConfig: []string{"nop/1"}, }, true, @@ -100,7 +102,7 @@ func TestSetupMetadataExporters(t *testing.T) { } func TestIsKindSupported(t *testing.T) { - var tests = []struct { + tests := []struct { name string client *fake.Clientset gvk schema.GroupVersionKind @@ -133,7 +135,7 @@ func TestIsKindSupported(t *testing.T) { } func TestPrepareSharedInformerFactory(t *testing.T) { - var tests = []struct { + tests := []struct { name string client *fake.Clientset }{ diff --git a/receiver/k8sobjectsreceiver/e2e_test.go b/receiver/k8sobjectsreceiver/e2e_test.go index 4498d888c821..03b491cfa555 100644 --- a/receiver/k8sobjectsreceiver/e2e_test.go +++ b/receiver/k8sobjectsreceiver/e2e_test.go @@ -27,9 +27,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest/plogtest" ) -const testKubeConfig = "/tmp/kube-config-otelcol-e2e-testing" -const testObjectsDir = "./testdata/e2e/testobjects/" -const expectedDir = "./testdata/e2e/expected/" +const ( + testKubeConfig = "/tmp/kube-config-otelcol-e2e-testing" + testObjectsDir = "./testdata/e2e/testobjects/" + expectedDir = "./testdata/e2e/expected/" +) type objAction int @@ -40,7 +42,6 @@ const ( ) func TestE2E(t *testing.T) { - k8sClient, err := k8stest.NewK8sClient(testKubeConfig) require.NoError(t, err) diff --git a/receiver/kafkametricsreceiver/broker_scraper.go b/receiver/kafkametricsreceiver/broker_scraper.go index 07aea6821634..444c68c30813 100644 --- a/receiver/kafkametricsreceiver/broker_scraper.go +++ b/receiver/kafkametricsreceiver/broker_scraper.go @@ -47,7 +47,7 @@ func (s *brokerScraper) shutdown(context.Context) error { } func (s *brokerScraper) scrape(context.Context) (pmetric.Metrics, error) { - var scrapeErrors = scrapererror.ScrapeErrors{} + scrapeErrors := scrapererror.ScrapeErrors{} if s.client == nil { client, err := newSaramaClient(s.config.Brokers, s.saramaConfig) @@ -103,7 +103,8 @@ func (s *brokerScraper) scrape(context.Context) (pmetric.Metrics, error) { } func createBrokerScraper(_ context.Context, cfg Config, saramaConfig *sarama.Config, - settings receiver.Settings) (scraperhelper.Scraper, error) { + settings receiver.Settings, +) (scraperhelper.Scraper, error) { s := brokerScraper{ settings: settings, config: cfg, diff --git a/receiver/kafkametricsreceiver/consumer_scraper.go b/receiver/kafkametricsreceiver/consumer_scraper.go index af3ef77713e3..bcd86435cc61 100644 --- a/receiver/kafkametricsreceiver/consumer_scraper.go +++ b/receiver/kafkametricsreceiver/consumer_scraper.go @@ -164,7 +164,8 @@ func (s *consumerScraper) scrape(context.Context) (pmetric.Metrics, error) { } func createConsumerScraper(_ context.Context, cfg Config, saramaConfig *sarama.Config, - settings receiver.Settings) (scraperhelper.Scraper, error) { + settings receiver.Settings, +) (scraperhelper.Scraper, error) { groupFilter, err := regexp.Compile(cfg.GroupMatch) if err != nil { return nil, fmt.Errorf("failed to compile group_match: %w", err) diff --git a/receiver/kafkametricsreceiver/factory.go b/receiver/kafkametricsreceiver/factory.go index c12eff109fc0..551ea684c080 100644 --- a/receiver/kafkametricsreceiver/factory.go +++ b/receiver/kafkametricsreceiver/factory.go @@ -48,7 +48,8 @@ func createMetricsReceiver( ctx context.Context, params receiver.Settings, cfg component.Config, - nextConsumer consumer.Metrics) (receiver.Metrics, error) { + nextConsumer consumer.Metrics, +) (receiver.Metrics, error) { c := cfg.(*Config) r, err := newMetricsReceiver(ctx, *c, params, nextConsumer) if err != nil { diff --git a/receiver/kafkametricsreceiver/scraper_test_helper.go b/receiver/kafkametricsreceiver/scraper_test_helper.go index b3867ea4b17a..e6542267043f 100644 --- a/receiver/kafkametricsreceiver/scraper_test_helper.go +++ b/receiver/kafkametricsreceiver/scraper_test_helper.go @@ -25,13 +25,17 @@ const ( testLogRetentionHours = 168 ) -var newSaramaClient = sarama.NewClient -var newClusterAdmin = sarama.NewClusterAdmin +var ( + newSaramaClient = sarama.NewClient + newClusterAdmin = sarama.NewClusterAdmin +) -var testTopics = []string{testTopic} -var testPartitions = []int32{1} -var testReplicas = []int32{1} -var testBrokers = make([]*sarama.Broker, 1) +var ( + testTopics = []string{testTopic} + testPartitions = []int32{1} + testReplicas = []int32{1} + testBrokers = make([]*sarama.Broker, 1) +) func mockNewSaramaClient([]string, *sarama.Config) (sarama.Client, error) { return newMockClient(), nil diff --git a/receiver/kafkametricsreceiver/topic_scraper.go b/receiver/kafkametricsreceiver/topic_scraper.go index ec682f0571eb..80d1e2fc2572 100644 --- a/receiver/kafkametricsreceiver/topic_scraper.go +++ b/receiver/kafkametricsreceiver/topic_scraper.go @@ -65,7 +65,7 @@ func (s *topicScraper) scrape(context.Context) (pmetric.Metrics, error) { return pmetric.Metrics{}, err } - var scrapeErrors = scrapererror.ScrapeErrors{} + scrapeErrors := scrapererror.ScrapeErrors{} now := pcommon.NewTimestampFromTime(time.Now()) diff --git a/receiver/kafkareceiver/config_test.go b/receiver/kafkareceiver/config_test.go index 2eb643b4275e..b5e7faa1dc93 100644 --- a/receiver/kafkareceiver/config_test.go +++ b/receiver/kafkareceiver/config_test.go @@ -68,7 +68,6 @@ func TestLoadConfig(t *testing.T) { }, }, { - id: component.NewIDWithName(metadata.Type, "logs"), expected: &Config{ Topic: "logs", diff --git a/receiver/kafkareceiver/jaeger_unmarshaler.go b/receiver/kafkareceiver/jaeger_unmarshaler.go index 48fad72042ca..ed001e9d11f1 100644 --- a/receiver/kafkareceiver/jaeger_unmarshaler.go +++ b/receiver/kafkareceiver/jaeger_unmarshaler.go @@ -13,8 +13,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger" ) -type jaegerProtoSpanUnmarshaler struct { -} +type jaegerProtoSpanUnmarshaler struct{} var _ TracesUnmarshaler = (*jaegerProtoSpanUnmarshaler)(nil) @@ -31,8 +30,7 @@ func (j jaegerProtoSpanUnmarshaler) Encoding() string { return "jaeger_proto" } -type jaegerJSONSpanUnmarshaler struct { -} +type jaegerJSONSpanUnmarshaler struct{} var _ TracesUnmarshaler = (*jaegerJSONSpanUnmarshaler)(nil) diff --git a/receiver/kafkareceiver/json_unmarshaler.go b/receiver/kafkareceiver/json_unmarshaler.go index 9ff02d03a6ea..33750457e71a 100644 --- a/receiver/kafkareceiver/json_unmarshaler.go +++ b/receiver/kafkareceiver/json_unmarshaler.go @@ -10,8 +10,7 @@ import ( "go.opentelemetry.io/collector/pdata/plog" ) -type jsonLogsUnmarshaler struct { -} +type jsonLogsUnmarshaler struct{} func newJSONLogsUnmarshaler() LogsUnmarshaler { return &jsonLogsUnmarshaler{} diff --git a/receiver/kafkareceiver/kafka_receiver.go b/receiver/kafkareceiver/kafka_receiver.go index 48ea87559a56..880724aa23b1 100644 --- a/receiver/kafkareceiver/kafka_receiver.go +++ b/receiver/kafkareceiver/kafka_receiver.go @@ -100,9 +100,11 @@ type kafkaLogsConsumer struct { maxFetchSize int32 } -var _ receiver.Traces = (*kafkaTracesConsumer)(nil) -var _ receiver.Metrics = (*kafkaMetricsConsumer)(nil) -var _ receiver.Logs = (*kafkaLogsConsumer)(nil) +var ( + _ receiver.Traces = (*kafkaTracesConsumer)(nil) + _ receiver.Metrics = (*kafkaMetricsConsumer)(nil) + _ receiver.Logs = (*kafkaLogsConsumer)(nil) +) func newTracesReceiver(config Config, set receiver.Settings, nextConsumer consumer.Traces) (*kafkaTracesConsumer, error) { telemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings) @@ -514,9 +516,11 @@ type logsConsumerGroupHandler struct { headerExtractor HeaderExtractor } -var _ sarama.ConsumerGroupHandler = (*tracesConsumerGroupHandler)(nil) -var _ sarama.ConsumerGroupHandler = (*metricsConsumerGroupHandler)(nil) -var _ sarama.ConsumerGroupHandler = (*logsConsumerGroupHandler)(nil) +var ( + _ sarama.ConsumerGroupHandler = (*tracesConsumerGroupHandler)(nil) + _ sarama.ConsumerGroupHandler = (*metricsConsumerGroupHandler)(nil) + _ sarama.ConsumerGroupHandler = (*logsConsumerGroupHandler)(nil) +) func (c *tracesConsumerGroupHandler) Setup(session sarama.ConsumerGroupSession) error { c.readyCloser.Do(func() { diff --git a/receiver/kubeletstatsreceiver/e2e_test.go b/receiver/kubeletstatsreceiver/e2e_test.go index 1dbf5a8c54b3..3411d2f2b9f2 100644 --- a/receiver/kubeletstatsreceiver/e2e_test.go +++ b/receiver/kubeletstatsreceiver/e2e_test.go @@ -28,7 +28,6 @@ import ( const testKubeConfig = "/tmp/kube-config-otelcol-e2e-testing" func TestE2E(t *testing.T) { - var expected pmetric.Metrics expectedFile := filepath.Join("testdata", "e2e", "expected.yaml") expected, err := golden.ReadMetrics(expectedFile) diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/cpu.go b/receiver/kubeletstatsreceiver/internal/kubelet/cpu.go index b1a767983ead..731be163ade3 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/cpu.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/cpu.go @@ -16,7 +16,8 @@ func addCPUMetrics( s *stats.CPUStats, currentTime pcommon.Timestamp, r resources, - nodeCPULimit float64) { + nodeCPULimit float64, +) { if s == nil { return } @@ -34,7 +35,8 @@ func addCPUUtilizationMetrics( usageCores float64, currentTime pcommon.Timestamp, r resources, - nodeCPULimit float64) { + nodeCPULimit float64, +) { cpuMetrics.Utilization(mb, currentTime, usageCores) if nodeCPULimit > 0 { diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/mem.go b/receiver/kubeletstatsreceiver/internal/kubelet/mem.go index d6aab65d7caf..653e0ed1dc89 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/mem.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/mem.go @@ -16,7 +16,8 @@ func addMemoryMetrics( s *stats.MemoryStats, currentTime pcommon.Timestamp, r resources, - nodeMemoryLimit float64) { + nodeMemoryLimit float64, +) { if s == nil { return } diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/metadata.go b/receiver/kubeletstatsreceiver/internal/kubelet/metadata.go index 55f539044a70..a2ffdb452dc4 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/metadata.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/metadata.go @@ -84,7 +84,8 @@ func getContainerResources(r *v1.ResourceRequirements) resources { } func NewMetadata(labels []MetadataLabel, podsMetadata *v1.PodList, nodeCap NodeCapacity, - detailedPVCResourceSetter func(rb *metadata.ResourceBuilder, volCacheID, volumeClaim, namespace string) error) Metadata { + detailedPVCResourceSetter func(rb *metadata.ResourceBuilder, volCacheID, volumeClaim, namespace string) error, +) Metadata { m := Metadata{ Labels: getLabelsMap(labels), PodsMetadata: podsMetadata, @@ -154,7 +155,8 @@ func getLabelsMap(metadataLabels []MetadataLabel) map[MetadataLabel]bool { // getExtraResources gets extra resources based on provided metadata label. func (m *Metadata) setExtraResources(rb *metadata.ResourceBuilder, podRef stats.PodReference, - extraMetadataLabel MetadataLabel, extraMetadataFrom string) error { + extraMetadataLabel MetadataLabel, extraMetadataFrom string, +) error { // Ensure MetadataLabel exists before proceeding. if !m.Labels[extraMetadataLabel] || len(m.Labels) == 0 { return nil diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/metrics.go b/receiver/kubeletstatsreceiver/internal/kubelet/metrics.go index afac93aa7953..e722f3d972ec 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/metrics.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/metrics.go @@ -17,7 +17,8 @@ func MetricsData( logger *zap.Logger, summary *stats.Summary, metadata Metadata, metricGroupsToCollect map[MetricGroup]bool, - mbs *metadata.MetricsBuilders) []pmetric.Metrics { + mbs *metadata.MetricsBuilders, +) []pmetric.Metrics { acc := &metricDataAccumulator{ metadata: metadata, logger: logger, diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/metrics_test.go b/receiver/kubeletstatsreceiver/internal/kubelet/metrics_test.go index 3698e912b3b6..94fef59f0946 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/metrics_test.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/metrics_test.go @@ -16,8 +16,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/kubeletstatsreceiver/internal/metadata" ) -type fakeRestClient struct { -} +type fakeRestClient struct{} func (f fakeRestClient) StatsSummary() ([]byte, error) { return os.ReadFile("../../testdata/stats-summary.json") diff --git a/receiver/kubeletstatsreceiver/internal/kubelet/resource.go b/receiver/kubeletstatsreceiver/internal/kubelet/resource.go index 31c3a4164ca9..01d04765a914 100644 --- a/receiver/kubeletstatsreceiver/internal/kubelet/resource.go +++ b/receiver/kubeletstatsreceiver/internal/kubelet/resource.go @@ -13,7 +13,8 @@ import ( ) func getContainerResource(rb *metadata.ResourceBuilder, sPod stats.PodStats, sContainer stats.ContainerStats, - k8sMetadata Metadata) (pcommon.Resource, error) { + k8sMetadata Metadata, +) (pcommon.Resource, error) { rb.SetK8sPodUID(sPod.PodRef.UID) rb.SetK8sPodName(sPod.PodRef.Name) rb.SetK8sNamespaceName(sPod.PodRef.Namespace) @@ -28,7 +29,8 @@ func getContainerResource(rb *metadata.ResourceBuilder, sPod stats.PodStats, sCo } func getVolumeResourceOptions(rb *metadata.ResourceBuilder, sPod stats.PodStats, vs stats.VolumeStats, - k8sMetadata Metadata) (pcommon.Resource, error) { + k8sMetadata Metadata, +) (pcommon.Resource, error) { rb.SetK8sPodUID(sPod.PodRef.UID) rb.SetK8sPodName(sPod.PodRef.Name) rb.SetK8sNamespaceName(sPod.PodRef.Namespace) diff --git a/receiver/kubeletstatsreceiver/mocked_objects_test.go b/receiver/kubeletstatsreceiver/mocked_objects_test.go index 3ad686b824d8..61797e1bc5c9 100644 --- a/receiver/kubeletstatsreceiver/mocked_objects_test.go +++ b/receiver/kubeletstatsreceiver/mocked_objects_test.go @@ -59,9 +59,11 @@ func getNodeWithMemoryCapacity(nodeName string, memoryCap string) *v1.Node { } } -var volumeClaim1 = getPVC("volume_claim_1", "kube-system", "storage-provisioner-token-qzlx6") -var volumeClaim2 = getPVC("volume_claim_2", "kube-system", "kube-proxy") -var volumeClaim3 = getPVC("volume_claim_3", "kube-system", "coredns-token-dzc5t") +var ( + volumeClaim1 = getPVC("volume_claim_1", "kube-system", "storage-provisioner-token-qzlx6") + volumeClaim2 = getPVC("volume_claim_2", "kube-system", "kube-proxy") + volumeClaim3 = getPVC("volume_claim_3", "kube-system", "coredns-token-dzc5t") +) func getPVC(claimName, namespace, volumeName string) *v1.PersistentVolumeClaim { return &v1.PersistentVolumeClaim{ diff --git a/receiver/lokireceiver/config.go b/receiver/lokireceiver/config.go index 66b497f27854..48f280fa314d 100644 --- a/receiver/lokireceiver/config.go +++ b/receiver/lokireceiver/config.go @@ -31,8 +31,10 @@ type Config struct { KeepTimestamp bool `mapstructure:"use_incoming_timestamp"` } -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/mongodbatlasreceiver/access_logs_test.go b/receiver/mongodbatlasreceiver/access_logs_test.go index 108d9e07f3c1..98b135ab7a97 100644 --- a/receiver/mongodbatlasreceiver/access_logs_test.go +++ b/receiver/mongodbatlasreceiver/access_logs_test.go @@ -103,7 +103,7 @@ func TestAccessLogToLogRecord(t *testing.T) { })) lr.SetObservedTimestamp(now) - lr.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2023, time.April, 26, 02, 38, 56, 444000000, time.UTC))) + lr.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2023, time.April, 26, 0o2, 38, 56, 444000000, time.UTC))) lr.SetSeverityNumber(plog.SeverityNumberInfo) lr.SetSeverityText(plog.SeverityNumberInfo.String()) @@ -125,7 +125,7 @@ func TestAccessLogToLogRecord(t *testing.T) { lr.SetObservedTimestamp(now) // Second log does not have internal timestamp in ISO8601, it has external in unixDate format with less precision - lr.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2023, time.April, 26, 02, 38, 56, 0, time.UTC))) + lr.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2023, time.April, 26, 0o2, 38, 56, 0, time.UTC))) lr.SetSeverityNumber(plog.SeverityNumberWarn) lr.SetSeverityText(plog.SeverityNumberWarn.String()) diff --git a/receiver/mongodbatlasreceiver/alerts.go b/receiver/mongodbatlasreceiver/alerts.go index 2be154637407..995f654f7e44 100644 --- a/receiver/mongodbatlasreceiver/alerts.go +++ b/receiver/mongodbatlasreceiver/alerts.go @@ -549,12 +549,12 @@ func (a *alertsReceiver) writeCheckpoint(ctx context.Context) error { func (a *alertsReceiver) applyFilters(pConf *ProjectConfig, alerts []mongodbatlas.Alert) []mongodbatlas.Alert { filtered := []mongodbatlas.Alert{} - var lastRecordedTime = pcommon.Timestamp(0).AsTime() + lastRecordedTime := pcommon.Timestamp(0).AsTime() if a.record.LastRecordedTime != nil { lastRecordedTime = *a.record.LastRecordedTime } // we need to maintain two timestamps in order to not conflict while iterating - var latestInPayload = pcommon.Timestamp(0).AsTime() + latestInPayload := pcommon.Timestamp(0).AsTime() for _, alert := range alerts { updatedTime, err := time.Parse(time.RFC3339, alert.Updated) diff --git a/receiver/mongodbatlasreceiver/mongodb_event_to_logdata.go b/receiver/mongodbatlasreceiver/mongodb_event_to_logdata.go index 2ac6a81c68fa..a141cd1f5d6e 100644 --- a/receiver/mongodbatlasreceiver/mongodb_event_to_logdata.go +++ b/receiver/mongodbatlasreceiver/mongodb_event_to_logdata.go @@ -25,8 +25,10 @@ const ( ) // jsonTimestampLayout for the timestamp format in the plog.Logs structure -const jsonTimestampLayout = "2006-01-02T15:04:05.000-07:00" -const consoleTimestampLayout = "2006-01-02T15:04:05.000-0700" +const ( + jsonTimestampLayout = "2006-01-02T15:04:05.000-07:00" + consoleTimestampLayout = "2006-01-02T15:04:05.000-0700" +) // Severity mapping of the mongodb atlas logs var severityMap = map[string]plog.SeverityNumber{ diff --git a/receiver/mongodbreceiver/client_test.go b/receiver/mongodbreceiver/client_test.go index b4657ef87fc3..9856e0a6389c 100644 --- a/receiver/mongodbreceiver/client_test.go +++ b/receiver/mongodbreceiver/client_test.go @@ -38,6 +38,7 @@ func (fc *fakeClient) Disconnect(ctx context.Context) error { args := fc.Called(ctx) return args.Error(0) } + func (fc *fakeClient) Connect(ctx context.Context) error { args := fc.Called(ctx) return args.Error(0) diff --git a/receiver/mysqlreceiver/client.go b/receiver/mysqlreceiver/client.go index 3aeabf1b777b..9e939d299533 100644 --- a/receiver/mysqlreceiver/client.go +++ b/receiver/mysqlreceiver/client.go @@ -429,7 +429,6 @@ func (c *mySQLClient) getReplicaStatusStats() ([]ReplicaStatusStats, error) { } rows, err := c.client.Query(query) - if err != nil { return nil, err } @@ -663,7 +662,6 @@ func (c *mySQLClient) getReplicaStatusStats() ([]ReplicaStatusStats, error) { } } err := rows.Scan(dest...) - if err != nil { return nil, err } diff --git a/receiver/mysqlreceiver/factory.go b/receiver/mysqlreceiver/factory.go index 2d2061861436..ae2e5d99a8e2 100644 --- a/receiver/mysqlreceiver/factory.go +++ b/receiver/mysqlreceiver/factory.go @@ -54,7 +54,6 @@ func createMetricsReceiver( ns := newMySQLScraper(params, cfg) scraper, err := scraperhelper.NewScraper(metadata.Type, ns.scrape, scraperhelper.WithStart(ns.start), scraperhelper.WithShutdown(ns.shutdown)) - if err != nil { return nil, err } diff --git a/receiver/mysqlreceiver/scraper_test.go b/receiver/mysqlreceiver/scraper_test.go index f2a1ef0ce5ba..c9008f037325 100644 --- a/receiver/mysqlreceiver/scraper_test.go +++ b/receiver/mysqlreceiver/scraper_test.go @@ -139,7 +139,7 @@ type mockClient struct { } func readFile(fname string) (map[string]string, error) { - var stats = map[string]string{} + stats := map[string]string{} file, err := os.Open(filepath.Join("testdata", "scraper", fname+".txt")) if err != nil { return nil, err diff --git a/receiver/nsxtreceiver/client.go b/receiver/nsxtreceiver/client.go index 49f5cba2320e..3f2c88949563 100644 --- a/receiver/nsxtreceiver/client.go +++ b/receiver/nsxtreceiver/client.go @@ -36,9 +36,7 @@ type nsxClient struct { logger *zap.Logger } -var ( - errUnauthorized = errors.New("STATUS 403, unauthorized") -) +var errUnauthorized = errors.New("STATUS 403, unauthorized") func newClient(ctx context.Context, c *Config, settings component.TelemetrySettings, host component.Host, logger *zap.Logger) (*nsxClient, error) { client, err := c.ClientConfig.ToClient(ctx, host, settings) @@ -133,7 +131,6 @@ func (c *nsxClient) InterfaceStatus( ctx, c.interfaceStatusEndpoint(class, nodeID, interfaceID), ) - if err != nil { return nil, fmt.Errorf("unable to get interface stats: %w", err) } diff --git a/receiver/opencensusreceiver/opencensus_test.go b/receiver/opencensusreceiver/opencensus_test.go index 668df1bd9438..9daba3a64d20 100644 --- a/receiver/opencensusreceiver/opencensus_test.go +++ b/receiver/opencensusreceiver/opencensus_test.go @@ -501,7 +501,8 @@ func TestOCReceiverTrace_HandleNextConsumerResponse(t *testing.T) { exportBidiFn := func( t *testing.T, cc *grpc.ClientConn, - msg *agenttracepb.ExportTraceServiceRequest) error { + msg *agenttracepb.ExportTraceServiceRequest, + ) error { acc := agenttracepb.NewTraceServiceClient(cc) stream, err := acc.Export(context.Background()) require.NoError(t, err) @@ -658,7 +659,8 @@ func TestOCReceiverMetrics_HandleNextConsumerResponse(t *testing.T) { exportBidiFn := func( t *testing.T, cc *grpc.ClientConn, - msg *agentmetricspb.ExportMetricsServiceRequest) error { + msg *agentmetricspb.ExportMetricsServiceRequest, + ) error { acc := agentmetricspb.NewMetricsServiceClient(cc) stream, err := acc.Export(context.Background()) require.NoError(t, err) diff --git a/receiver/opencensusreceiver/options.go b/receiver/opencensusreceiver/options.go index 3851fca059f4..893eee4b6763 100644 --- a/receiver/opencensusreceiver/options.go +++ b/receiver/opencensusreceiver/options.go @@ -36,6 +36,7 @@ func withGRPCServerSettings(settings configgrpc.ServerConfig) ocOption { gsvOpts := grpcServerSettings(settings) return gsvOpts } + func (gsvo grpcServerSettings) withReceiver(ocr *ocReceiver) { ocr.grpcServerSettings = configgrpc.ServerConfig(gsvo) } diff --git a/receiver/oracledbreceiver/scraper_test.go b/receiver/oracledbreceiver/scraper_test.go index 608cf1facd47..8d004393d2c5 100644 --- a/receiver/oracledbreceiver/scraper_test.go +++ b/receiver/oracledbreceiver/scraper_test.go @@ -34,8 +34,10 @@ func TestScraper_ErrorOnStart(t *testing.T) { var queryResponses = map[string][]metricRow{ statsSQL: {{"NAME": enqueueDeadlocks, "VALUE": "18"}, {"NAME": exchangeDeadlocks, "VALUE": "88898"}, {"NAME": executeCount, "VALUE": "178878"}, {"NAME": parseCountTotal, "VALUE": "1999"}, {"NAME": parseCountHard, "VALUE": "1"}, {"NAME": userCommits, "VALUE": "187778888"}, {"NAME": userRollbacks, "VALUE": "1898979879789"}, {"NAME": physicalReads, "VALUE": "1887777"}, {"NAME": sessionLogicalReads, "VALUE": "189"}, {"NAME": cpuTime, "VALUE": "1887"}, {"NAME": pgaMemory, "VALUE": "1999887"}, {"NAME": dbBlockGets, "VALUE": "42"}, {"NAME": consistentGets, "VALUE": "78944"}}, sessionCountSQL: {{"VALUE": "1"}}, - systemResourceLimitsSQL: {{"RESOURCE_NAME": "processes", "CURRENT_UTILIZATION": "3", "MAX_UTILIZATION": "10", "INITIAL_ALLOCATION": "100", "LIMIT_VALUE": "100"}, - {"RESOURCE_NAME": "locks", "CURRENT_UTILIZATION": "3", "MAX_UTILIZATION": "10", "INITIAL_ALLOCATION": "-1", "LIMIT_VALUE": "-1"}}, + systemResourceLimitsSQL: { + {"RESOURCE_NAME": "processes", "CURRENT_UTILIZATION": "3", "MAX_UTILIZATION": "10", "INITIAL_ALLOCATION": "100", "LIMIT_VALUE": "100"}, + {"RESOURCE_NAME": "locks", "CURRENT_UTILIZATION": "3", "MAX_UTILIZATION": "10", "INITIAL_ALLOCATION": "-1", "LIMIT_VALUE": "-1"}, + }, tablespaceUsageSQL: {{"TABLESPACE_NAME": "SYS", "USED_SPACE": "111288", "TABLESPACE_SIZE": "3518587", "BLOCK_SIZE": "8192"}}, } diff --git a/receiver/otelarrowreceiver/config.go b/receiver/otelarrowreceiver/config.go index abf09987e83e..0f674d656b09 100644 --- a/receiver/otelarrowreceiver/config.go +++ b/receiver/otelarrowreceiver/config.go @@ -56,8 +56,10 @@ type Config struct { Admission AdmissionConfig `mapstructure:"admission"` } -var _ component.Config = (*Config)(nil) -var _ component.ConfigValidator = (*ArrowConfig)(nil) +var ( + _ component.Config = (*Config)(nil) + _ component.ConfigValidator = (*ArrowConfig)(nil) +) func (cfg *ArrowConfig) Validate() error { if err := cfg.Zstd.Validate(); err != nil { diff --git a/receiver/otelarrowreceiver/internal/arrow/arrow_test.go b/receiver/otelarrowreceiver/internal/arrow/arrow_test.go index ec35cb2ef992..e432b207e8df 100644 --- a/receiver/otelarrowreceiver/internal/arrow/arrow_test.go +++ b/receiver/otelarrowreceiver/internal/arrow/arrow_test.go @@ -54,9 +54,11 @@ func defaultBQ() admission.Queue { return admission.NewBoundedQueue(noopTelemetry, 100000, 10) } -type compareJSONTraces struct{ ptrace.Traces } -type compareJSONMetrics struct{ pmetric.Metrics } -type compareJSONLogs struct{ plog.Logs } +type ( + compareJSONTraces struct{ ptrace.Traces } + compareJSONMetrics struct{ pmetric.Metrics } + compareJSONLogs struct{ plog.Logs } +) func (c compareJSONTraces) MarshalJSON() ([]byte, error) { var m ptrace.JSONMarshaler @@ -254,6 +256,7 @@ func (m mockConsumers) Traces() consumer.Traces { func (m mockConsumers) Logs() consumer.Logs { return m.logs } + func (m mockConsumers) Metrics() consumer.Metrics { return m.metrics } diff --git a/receiver/otelarrowreceiver/otelarrow.go b/receiver/otelarrowreceiver/otelarrow.go index ef5ce6f7f9a0..664d7a7d9d73 100644 --- a/receiver/otelarrowreceiver/otelarrow.go +++ b/receiver/otelarrowreceiver/otelarrow.go @@ -143,7 +143,6 @@ func (r *otelArrowReceiver) startProtocolServers(ctx context.Context, host compo } return arrowRecord.NewConsumer(opts...) }, r.boundedQueue, r.netReporter) - if err != nil { return err } diff --git a/receiver/otlpjsonfilereceiver/file_test.go b/receiver/otlpjsonfilereceiver/file_test.go index db75e5293a68..582c1dcb1c8e 100644 --- a/receiver/otlpjsonfilereceiver/file_test.go +++ b/receiver/otlpjsonfilereceiver/file_test.go @@ -54,7 +54,7 @@ func TestFileProfilesReceiver(t *testing.T) { b, err := marshaler.MarshalProfiles(pd) assert.NoError(t, err) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "profiles.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "profiles.json"), b, 0o600) assert.NoError(t, err) time.Sleep(1 * time.Second) @@ -81,7 +81,7 @@ func TestFileTracesReceiver(t *testing.T) { b, err := marshaler.MarshalTraces(td) assert.NoError(t, err) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "traces.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "traces.json"), b, 0o600) assert.NoError(t, err) time.Sleep(1 * time.Second) @@ -108,7 +108,7 @@ func TestFileMetricsReceiver(t *testing.T) { b, err := marshaler.MarshalMetrics(md) assert.NoError(t, err) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0o600) assert.NoError(t, err) time.Sleep(1 * time.Second) @@ -138,7 +138,7 @@ func TestFileMetricsReceiverWithReplay(t *testing.T) { b, err := marshaler.MarshalMetrics(md) assert.NoError(t, err) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0o600) assert.NoError(t, err) // Wait for the first poll to complete. @@ -173,7 +173,7 @@ func TestFileLogsReceiver(t *testing.T) { b, err := marshaler.MarshalLogs(ld) assert.NoError(t, err) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "logs.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "logs.json"), b, 0o600) assert.NoError(t, err) time.Sleep(1 * time.Second) @@ -271,7 +271,7 @@ func TestFileMixedSignals(t *testing.T) { b = append(b, '\n') b = append(b, b4...) b = append(b, '\n') - err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0600) + err = os.WriteFile(filepath.Join(tempFolder, "metrics.json"), b, 0o600) assert.NoError(t, err) time.Sleep(1 * time.Second) diff --git a/receiver/podmanreceiver/libpod_client.go b/receiver/podmanreceiver/libpod_client.go index 0e65155f2042..cf21882958b2 100644 --- a/receiver/podmanreceiver/libpod_client.go +++ b/receiver/podmanreceiver/libpod_client.go @@ -17,9 +17,7 @@ import ( "go.uber.org/zap" ) -var ( - errNoStatsFound = fmt.Errorf("No stats found") -) +var errNoStatsFound = fmt.Errorf("No stats found") type libpodClient struct { conn *http.Client diff --git a/receiver/podmanreceiver/libpod_client_test.go b/receiver/podmanreceiver/libpod_client_test.go index 80d50ffd265f..d5ccacfd035d 100644 --- a/receiver/podmanreceiver/libpod_client_test.go +++ b/receiver/podmanreceiver/libpod_client_test.go @@ -158,7 +158,6 @@ func TestList(t *testing.T) { assert.NoError(t, err) expectedContainer := container{ - AutoRemove: false, Command: []string{"nginx", "-g", "daemon off;"}, Created: "2022-05-28T11:25:35.999277074+02:00", diff --git a/receiver/podmanreceiver/podman_connection.go b/receiver/podmanreceiver/podman_connection.go index e9252dbc1bcf..ea8173bc7f62 100644 --- a/receiver/podmanreceiver/podman_connection.go +++ b/receiver/podmanreceiver/podman_connection.go @@ -108,7 +108,7 @@ func sshConnection(logger *zap.Logger, _url *url.URL, secure bool, key, passphra var authMethods []ssh.AuthMethod if len(signers) > 0 { - var dedup = make(map[string]ssh.Signer) + dedup := make(map[string]ssh.Signer) // Dedup signers based on fingerprint, ssh-agent keys override CONTAINER_SSHKEY for _, s := range signers { fp := ssh.FingerprintSHA256(s.PublicKey()) diff --git a/receiver/postgresqlreceiver/client_factory.go b/receiver/postgresqlreceiver/client_factory.go index c940bf2ba723..ac3d48ff90c1 100644 --- a/receiver/postgresqlreceiver/client_factory.go +++ b/receiver/postgresqlreceiver/client_factory.go @@ -14,14 +14,12 @@ import ( const connectionPoolGateID = "receiver.postgresql.connectionPool" -var ( - connectionPoolGate = featuregate.GlobalRegistry().MustRegister( - connectionPoolGateID, - featuregate.StageAlpha, - featuregate.WithRegisterDescription("Use of connection pooling"), - featuregate.WithRegisterFromVersion("0.96.0"), - featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/30831"), - ) +var connectionPoolGate = featuregate.GlobalRegistry().MustRegister( + connectionPoolGateID, + featuregate.StageAlpha, + featuregate.WithRegisterDescription("Use of connection pooling"), + featuregate.WithRegisterFromVersion("0.96.0"), + featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/30831"), ) type postgreSQLClientFactory interface { diff --git a/receiver/postgresqlreceiver/scraper.go b/receiver/postgresqlreceiver/scraper.go index 710249830ae7..1fe28994e68f 100644 --- a/receiver/postgresqlreceiver/scraper.go +++ b/receiver/postgresqlreceiver/scraper.go @@ -27,13 +27,11 @@ const ( defaultPostgreSQLDatabase = "postgres" ) -var ( - separateSchemaAttrGate = featuregate.GlobalRegistry().MustRegister( - separateSchemaAttrID, - featuregate.StageAlpha, - featuregate.WithRegisterDescription("Moves Schema Names into dedicated Attribute"), - featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/29559"), - ) +var separateSchemaAttrGate = featuregate.GlobalRegistry().MustRegister( + separateSchemaAttrID, + featuregate.StageAlpha, + featuregate.WithRegisterDescription("Moves Schema Names into dedicated Attribute"), + featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/29559"), ) type postgreSQLScraper struct { diff --git a/receiver/postgresqlreceiver/scraper_test.go b/receiver/postgresqlreceiver/scraper_test.go index e660e892d869..7f89d73ac91f 100644 --- a/receiver/postgresqlreceiver/scraper_test.go +++ b/receiver/postgresqlreceiver/scraper_test.go @@ -295,8 +295,10 @@ func TestScraperExcludeDatabase(t *testing.T) { runTest(false, "exclude.yaml") } -type mockClientFactory struct{ mock.Mock } -type mockClient struct{ mock.Mock } +type ( + mockClientFactory struct{ mock.Mock } + mockClient struct{ mock.Mock } +) var _ client = &mockClient{} diff --git a/receiver/prometheusreceiver/internal/appendable.go b/receiver/prometheusreceiver/internal/appendable.go index f6539169902c..086d2d639a29 100644 --- a/receiver/prometheusreceiver/internal/appendable.go +++ b/receiver/prometheusreceiver/internal/appendable.go @@ -39,7 +39,8 @@ func NewAppendable( useCreatedMetric bool, enableNativeHistograms bool, externalLabels labels.Labels, - trimSuffixes bool) (storage.Appendable, error) { + trimSuffixes bool, +) (storage.Appendable, error) { var metricAdjuster MetricsAdjuster if !useStartTimeMetric { metricAdjuster = NewInitialPointAdjuster(set.Logger, gcInterval, useCreatedMetric) diff --git a/receiver/prometheusreceiver/internal/metricfamily_test.go b/receiver/prometheusreceiver/internal/metricfamily_test.go index 586be1992912..0f377c36d487 100644 --- a/receiver/prometheusreceiver/internal/metricfamily_test.go +++ b/receiver/prometheusreceiver/internal/metricfamily_test.go @@ -170,7 +170,8 @@ func TestMetricGroupData_toDistributionUnitTest(t *testing.T) { at: 11, value: 66, metric: "histogram_with_created_bucket", - extraLabel: labels.Label{Name: "le", Value: "+Inf"}}, + extraLabel: labels.Label{Name: "le", Value: "+Inf"}, + }, }, want: func() pmetric.HistogramDataPoint { point := pmetric.NewHistogramDataPoint() diff --git a/receiver/prometheusreceiver/internal/starttimemetricadjuster.go b/receiver/prometheusreceiver/internal/starttimemetricadjuster.go index ca7ae2a29171..1b3eb51529f5 100644 --- a/receiver/prometheusreceiver/internal/starttimemetricadjuster.go +++ b/receiver/prometheusreceiver/internal/starttimemetricadjuster.go @@ -120,6 +120,7 @@ func (stma *startTimeMetricAdjuster) getStartTime(metrics pmetric.Metrics) (floa } return 0.0, errNoStartTimeMetrics } + func (stma *startTimeMetricAdjuster) matchStartTimeMetric(metricName string) bool { if stma.startTimeMetricRegex != nil { return stma.startTimeMetricRegex.MatchString(metricName) diff --git a/receiver/prometheusreceiver/internal/transaction.go b/receiver/prometheusreceiver/internal/transaction.go index 0c855efc7ad9..00728449629d 100644 --- a/receiver/prometheusreceiver/internal/transaction.go +++ b/receiver/prometheusreceiver/internal/transaction.go @@ -67,7 +67,8 @@ func newTransaction( settings receiver.Settings, obsrecv *receiverhelper.ObsReport, trimSuffixes bool, - enableNativeHistograms bool) *transaction { + enableNativeHistograms bool, +) *transaction { return &transaction{ ctx: ctx, families: make(map[resourceKey]map[scopeID]map[string]*metricFamily), @@ -298,7 +299,7 @@ func (t *transaction) AppendHistogram(_ storage.SeriesRef, ls labels.Labels, atM } func (t *transaction) AppendCTZeroSample(_ storage.SeriesRef, _ labels.Labels, _, _ int64) (storage.SeriesRef, error) { - //TODO: implement this func + // TODO: implement this func return 0, nil } @@ -470,7 +471,7 @@ func (t *transaction) Rollback() error { } func (t *transaction) UpdateMetadata(_ storage.SeriesRef, _ labels.Labels, _ metadata.Metadata) (storage.SeriesRef, error) { - //TODO: implement this func + // TODO: implement this func return 0, nil } diff --git a/receiver/prometheusreceiver/internal/util_test.go b/receiver/prometheusreceiver/internal/util_test.go index 755f531730cc..8ca44ff9f708 100644 --- a/receiver/prometheusreceiver/internal/util_test.go +++ b/receiver/prometheusreceiver/internal/util_test.go @@ -30,12 +30,18 @@ var testMetadata = map[string]scrape.MetricMetadata{ "poor_name": {Metric: "poor_name", Type: model.MetricTypeGauge, Help: "", Unit: ""}, "poor_name_count": {Metric: "poor_name_count", Type: model.MetricTypeCounter, Help: "", Unit: ""}, "scrape_foo": {Metric: "scrape_foo", Type: model.MetricTypeCounter, Help: "", Unit: ""}, - "example_process_start_time_seconds": {Metric: "example_process_start_time_seconds", - Type: model.MetricTypeGauge, Help: "", Unit: ""}, - "process_start_time_seconds": {Metric: "process_start_time_seconds", - Type: model.MetricTypeGauge, Help: "", Unit: ""}, - "subprocess_start_time_seconds": {Metric: "subprocess_start_time_seconds", - Type: model.MetricTypeGauge, Help: "", Unit: ""}, + "example_process_start_time_seconds": { + Metric: "example_process_start_time_seconds", + Type: model.MetricTypeGauge, Help: "", Unit: "", + }, + "process_start_time_seconds": { + Metric: "process_start_time_seconds", + Type: model.MetricTypeGauge, Help: "", Unit: "", + }, + "subprocess_start_time_seconds": { + Metric: "subprocess_start_time_seconds", + Type: model.MetricTypeGauge, Help: "", Unit: "", + }, } func TestTimestampFromMs(t *testing.T) { diff --git a/receiver/prometheusreceiver/metrics_receiver_helper_test.go b/receiver/prometheusreceiver/metrics_receiver_helper_test.go index cea8d429af86..1bda7ac42e90 100644 --- a/receiver/prometheusreceiver/metrics_receiver_helper_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_helper_test.go @@ -384,6 +384,7 @@ func isDefaultMetrics(m pmetric.Metric, normalizedNames bool) bool { } return false } + func isExtraScrapeMetrics(m pmetric.Metric) bool { switch m.Name() { case "scrape_body_size_bytes", "scrape_sample_limit", "scrape_timeout_seconds": @@ -393,11 +394,13 @@ func isExtraScrapeMetrics(m pmetric.Metric) bool { } } -type metricTypeComparator func(*testing.T, pmetric.Metric) -type numberPointComparator func(*testing.T, pmetric.NumberDataPoint) -type histogramPointComparator func(*testing.T, pmetric.HistogramDataPoint) -type summaryPointComparator func(*testing.T, pmetric.SummaryDataPoint) -type exponentialHistogramComparator func(*testing.T, pmetric.ExponentialHistogramDataPoint) +type ( + metricTypeComparator func(*testing.T, pmetric.Metric) + numberPointComparator func(*testing.T, pmetric.NumberDataPoint) + histogramPointComparator func(*testing.T, pmetric.HistogramDataPoint) + summaryPointComparator func(*testing.T, pmetric.SummaryDataPoint) + exponentialHistogramComparator func(*testing.T, pmetric.ExponentialHistogramDataPoint) +) type dataPointExpectation struct { numberPointComparator []numberPointComparator diff --git a/receiver/prometheusreceiver/metrics_receiver_non_numerical_test.go b/receiver/prometheusreceiver/metrics_receiver_non_numerical_test.go index 85c5986e1e7c..ac3c23561df5 100644 --- a/receiver/prometheusreceiver/metrics_receiver_non_numerical_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_non_numerical_test.go @@ -42,9 +42,7 @@ rpc_duration_seconds_sum 5000 rpc_duration_seconds_count 1000 ` -var ( - totalScrapes = 10 -) +var totalScrapes = 10 // TestStaleNaNs validates that staleness marker gets generated when the timeseries is no longer present func TestStaleNaNs(t *testing.T) { @@ -298,8 +296,11 @@ func verifyNormalNaNs(t *testing.T, td *testData, resourceMetrics []pmetric.Reso summaryPointComparator: []summaryPointComparator{ compareSummaryStartTimestamp(ts1), compareSummaryTimestamp(ts1), - compareSummary(1000, 5000, [][]float64{{0.01, math.Float64frombits(value.NormalNaN)}, - {0.9, math.Float64frombits(value.NormalNaN)}, {0.99, math.Float64frombits(value.NormalNaN)}}), + compareSummary(1000, 5000, [][]float64{ + {0.01, math.Float64frombits(value.NormalNaN)}, + {0.9, math.Float64frombits(value.NormalNaN)}, + {0.99, math.Float64frombits(value.NormalNaN)}, + }), }, }, }), diff --git a/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go b/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go index 67fa4e4105b0..e0a0718e5761 100644 --- a/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go +++ b/receiver/prometheusreceiver/metrics_receiver_scrape_config_files_test.go @@ -44,7 +44,7 @@ func TestScrapeConfigFiles(t *testing.T) { tmpDir := t.TempDir() cfgFileName := fmt.Sprintf("%s/test-scrape-config.yaml", tmpDir) scrapeConfigFileContent := fmt.Sprintf("scrape_configs:\n%s", string(marshalledScrapeConfigs)) - err = os.WriteFile(cfgFileName, []byte(scrapeConfigFileContent), 0400) + err = os.WriteFile(cfgFileName, []byte(scrapeConfigFileContent), 0o400) require.NoError(t, err) cfg.PrometheusConfig.ScrapeConfigs = []*config.ScrapeConfig{} cfg.PrometheusConfig.ScrapeConfigFiles = []string{cfgFileName} diff --git a/receiver/prometheusreceiver/metrics_reciever_metric_rename_test.go b/receiver/prometheusreceiver/metrics_reciever_metric_rename_test.go index adc0cadcb310..753debb6fa90 100644 --- a/receiver/prometheusreceiver/metrics_reciever_metric_rename_test.go +++ b/receiver/prometheusreceiver/metrics_reciever_metric_rename_test.go @@ -339,8 +339,10 @@ func verifyRenameLabel(t *testing.T, td *testData, resourceMetrics []pmetric.Res numberPointComparator: []numberPointComparator{ compareTimestamp(ts1), compareDoubleValue(120), - compareAttributes(map[string]string{"address": "localhost:9090/metrics", - "contentType": "application/json", "id": "metrics", "foo": "bar"}), + compareAttributes(map[string]string{ + "address": "localhost:9090/metrics", + "contentType": "application/json", "id": "metrics", "foo": "bar", + }), }, }, }), diff --git a/receiver/prometheusreceiver/targetallocator/manager_test.go b/receiver/prometheusreceiver/targetallocator/manager_test.go index 3bca1bcb31e6..d0aa13bf44d3 100644 --- a/receiver/prometheusreceiver/targetallocator/manager_test.go +++ b/receiver/prometheusreceiver/targetallocator/manager_test.go @@ -305,34 +305,42 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, "/jobs/job1/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, + { + Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, + { + Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, }, "/jobs/job2/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }}, }, }, @@ -360,11 +368,13 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { "__meta_prometheus_job": "node", }, }, - "job2": {Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, + "job2": { + Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }, }, }, @@ -398,34 +408,42 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, "/jobs/job1/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, + { + Targets: []string{"localhost:9090", "10.0.10.3:9100", "10.0.10.4:9100", "10.0.10.5:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090"}, + { + Targets: []string{"localhost:9090"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", "test": "aTest", - }}, + }, + }, }}, }, "/jobs/job2/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", - }}, + }, + }, }}, }, }, @@ -449,10 +467,12 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { "test": "aTest", }, }, - "job2": {Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, + "job2": { + Targets: []string{"10.0.40.2:9100", "10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", - }}, + }, + }, }, }, }, @@ -511,34 +531,42 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, "/jobs/job1/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090"}, + { + Targets: []string{"localhost:9090"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090"}, + { + Targets: []string{"localhost:9090"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, }, "/jobs/job3/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"10.0.40.3:9100"}, + { + Targets: []string{"10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }}, }, }, @@ -561,11 +589,13 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { "__meta_prometheus_job": "node", }, }, - "job3": {Targets: []string{"10.0.40.3:9100"}, + "job3": { + Targets: []string{"10.0.40.3:9100"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "alertmanager", - }}, + }, + }, }, }, }, @@ -640,18 +670,22 @@ func TestTargetAllocatorJobRetrieval(t *testing.T) { }, "/jobs/job1/targets": { mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090"}, + { + Targets: []string{"localhost:9090"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, mockTargetAllocatorResponseRaw{code: 200, data: []hTTPSDResponse{ - {Targets: []string{"localhost:9090"}, + { + Targets: []string{"localhost:9090"}, Labels: map[model.LabelName]model.LabelValue{ "__meta_datacenter": "london", "__meta_prometheus_job": "node", - }}, + }, + }, }}, }, }, diff --git a/receiver/pulsarreceiver/factory_test.go b/receiver/pulsarreceiver/factory_test.go index c86ae05ad4cb..7302ce2c1260 100644 --- a/receiver/pulsarreceiver/factory_test.go +++ b/receiver/pulsarreceiver/factory_test.go @@ -174,14 +174,11 @@ func TestWithLogsUnmarshalers(t *testing.T) { }) } -type customTracesUnmarshaler struct { -} +type customTracesUnmarshaler struct{} -type customMetricsUnmarshaler struct { -} +type customMetricsUnmarshaler struct{} -type customLogsUnmarshaler struct { -} +type customLogsUnmarshaler struct{} func (c customTracesUnmarshaler) Unmarshal([]byte) (ptrace.Traces, error) { panic("implement me") diff --git a/receiver/pulsarreceiver/jaeger_unmarshaler.go b/receiver/pulsarreceiver/jaeger_unmarshaler.go index 28791ddb600e..1e6573462b92 100644 --- a/receiver/pulsarreceiver/jaeger_unmarshaler.go +++ b/receiver/pulsarreceiver/jaeger_unmarshaler.go @@ -14,8 +14,7 @@ import ( ) // copy from kafka receiver -type jaegerProtoSpanUnmarshaler struct { -} +type jaegerProtoSpanUnmarshaler struct{} var _ TracesUnmarshaler = (*jaegerProtoSpanUnmarshaler)(nil) @@ -32,8 +31,7 @@ func (j jaegerProtoSpanUnmarshaler) Encoding() string { return "jaeger_proto" } -type jaegerJSONSpanUnmarshaler struct { -} +type jaegerJSONSpanUnmarshaler struct{} var _ TracesUnmarshaler = (*jaegerJSONSpanUnmarshaler)(nil) diff --git a/receiver/receivercreator/config_test.go b/receiver/receivercreator/config_test.go index f9f9eb85ae6f..ee8779de712e 100644 --- a/receiver/receivercreator/config_test.go +++ b/receiver/receivercreator/config_test.go @@ -200,7 +200,8 @@ func (*nopWithEndpointFactory) CreateLogs( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Logs) (rcvr.Logs, error) { + nextConsumer consumer.Logs, +) (rcvr.Logs, error) { return &nopWithEndpointReceiver{ Logs: nextConsumer, Settings: rcs, @@ -212,7 +213,8 @@ func (*nopWithEndpointFactory) CreateMetrics( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Metrics) (rcvr.Metrics, error) { + nextConsumer consumer.Metrics, +) (rcvr.Metrics, error) { return &nopWithEndpointReceiver{ Metrics: nextConsumer, Settings: rcs, @@ -224,7 +226,8 @@ func (*nopWithEndpointFactory) CreateTraces( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Traces) (rcvr.Traces, error) { + nextConsumer consumer.Traces, +) (rcvr.Traces, error) { return &nopWithEndpointReceiver{ Traces: nextConsumer, Settings: rcs, @@ -260,7 +263,8 @@ func (*nopWithoutEndpointFactory) CreateLogs( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Logs) (rcvr.Logs, error) { + nextConsumer consumer.Logs, +) (rcvr.Logs, error) { return &nopWithoutEndpointReceiver{ Logs: nextConsumer, Settings: rcs, @@ -272,7 +276,8 @@ func (*nopWithoutEndpointFactory) CreateMetrics( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Metrics) (rcvr.Metrics, error) { + nextConsumer consumer.Metrics, +) (rcvr.Metrics, error) { return &nopWithoutEndpointReceiver{ Metrics: nextConsumer, Settings: rcs, @@ -284,7 +289,8 @@ func (*nopWithoutEndpointFactory) CreateTraces( _ context.Context, rcs rcvr.Settings, cfg component.Config, - nextConsumer consumer.Traces) (rcvr.Traces, error) { + nextConsumer consumer.Traces, +) (rcvr.Traces, error) { return &nopWithoutEndpointReceiver{ Traces: nextConsumer, Settings: rcs, diff --git a/receiver/receivercreator/consumer.go b/receiver/receivercreator/consumer.go index 35fdf7efe8bb..24e5f7f94d36 100644 --- a/receiver/receivercreator/consumer.go +++ b/receiver/receivercreator/consumer.go @@ -16,9 +16,11 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/extension/observer" ) -var _ consumer.Logs = (*enhancingConsumer)(nil) -var _ consumer.Metrics = (*enhancingConsumer)(nil) -var _ consumer.Traces = (*enhancingConsumer)(nil) +var ( + _ consumer.Logs = (*enhancingConsumer)(nil) + _ consumer.Metrics = (*enhancingConsumer)(nil) + _ consumer.Traces = (*enhancingConsumer)(nil) +) // enhancingConsumer adds additional resource attributes from the given endpoint environment before passing the // telemetry to its next consumers. The added attributes vary based on the type of the endpoint. diff --git a/receiver/receivercreator/observerhandler.go b/receiver/receivercreator/observerhandler.go index de1d9689953b..cdf5ed82b626 100644 --- a/receiver/receivercreator/observerhandler.go +++ b/receiver/receivercreator/observerhandler.go @@ -16,9 +16,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/extension/observer" ) -var ( - _ observer.Notify = (*observerHandler)(nil) -) +var _ observer.Notify = (*observerHandler)(nil) const ( // tmpSetEndpointConfigKey denotes the observerHandler (not the user) has set an "endpoint" target field diff --git a/receiver/receivercreator/receiver_test.go b/receiver/receivercreator/receiver_test.go index 304570265db9..b12932d0b2fd 100644 --- a/receiver/receivercreator/receiver_test.go +++ b/receiver/receivercreator/receiver_test.go @@ -34,8 +34,7 @@ func TestCreateDefaultConfig(t *testing.T) { assert.NoError(t, componenttest.CheckConfigStruct(cfg)) } -type mockObserver struct { -} +type mockObserver struct{} func (m *mockObserver) Start(_ context.Context, _ component.Host) error { return nil diff --git a/receiver/saphanareceiver/client_test.go b/receiver/saphanareceiver/client_test.go index 045a7011f884..e8e3f2f4ea2e 100644 --- a/receiver/saphanareceiver/client_test.go +++ b/receiver/saphanareceiver/client_test.go @@ -137,7 +137,8 @@ func TestSimpleQueryOutput(t *testing.T) { { key: "value", addMetricFunction: func(*metadata.MetricsBuilder, pcommon.Timestamp, string, - map[string]string) error { + map[string]string, + ) error { // Function is a no-op as it's not required for this test return nil }, @@ -145,7 +146,8 @@ func TestSimpleQueryOutput(t *testing.T) { { key: "rate", addMetricFunction: func(*metadata.MetricsBuilder, pcommon.Timestamp, string, - map[string]string) error { + map[string]string, + ) error { // Function is a no-op as it's not required for this test return nil }, @@ -193,7 +195,8 @@ func TestNullOutput(t *testing.T) { { key: "value", addMetricFunction: func(*metadata.MetricsBuilder, pcommon.Timestamp, string, - map[string]string) error { + map[string]string, + ) error { // Function is a no-op as it's not required for this test return nil }, @@ -201,7 +204,8 @@ func TestNullOutput(t *testing.T) { { key: "rate", addMetricFunction: func(*metadata.MetricsBuilder, pcommon.Timestamp, string, - map[string]string) error { + map[string]string, + ) error { // Function is a no-op as it's not required for this test return nil }, diff --git a/receiver/saphanareceiver/queries.go b/receiver/saphanareceiver/queries.go index 3a6465016354..26a02b148909 100644 --- a/receiver/saphanareceiver/queries.go +++ b/receiver/saphanareceiver/queries.go @@ -21,7 +21,8 @@ type queryStat struct { } func (q *queryStat) collectStat(s *sapHanaScraper, m *monitoringQuery, now pcommon.Timestamp, - row map[string]string) error { + row map[string]string, +) error { if val, ok := row[q.key]; ok { resourceAttributes := map[string]string{} for _, attr := range m.orderedResourceLabels { @@ -63,14 +64,16 @@ var queries = []monitoringQuery{ { key: "active_services", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaServiceCountDataPoint(now, val, metadata.AttributeServiceStatusActive) }, }, { key: "inactive_services", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaServiceCountDataPoint(now, val, metadata.AttributeServiceStatusInactive) }, }, @@ -86,14 +89,16 @@ var queries = []monitoringQuery{ { key: "active_threads", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaServiceThreadCountDataPoint(now, val, metadata.AttributeThreadStatusActive) }, }, { key: "inactive_threads", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaServiceThreadCountDataPoint(now, val, metadata.AttributeThreadStatusInactive) }, }, @@ -109,56 +114,64 @@ var queries = []monitoringQuery{ { key: "main_data", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeMain, metadata.AttributeColumnMemorySubtypeData) }, }, { key: "main_dict", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeMain, metadata.AttributeColumnMemorySubtypeDict) }, }, { key: "main_index", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeMain, metadata.AttributeColumnMemorySubtypeIndex) }, }, { key: "main_misc", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeMain, metadata.AttributeColumnMemorySubtypeMisc) }, }, { key: "delta_data", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeDelta, metadata.AttributeColumnMemorySubtypeData) }, }, { key: "delta_dict", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeDelta, metadata.AttributeColumnMemorySubtypeDict) }, }, { key: "delta_index", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeDelta, metadata.AttributeColumnMemorySubtypeIndex) }, }, { key: "delta_misc", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaColumnMemoryUsedDataPoint(now, val, metadata.AttributeColumnMemoryTypeDelta, metadata.AttributeColumnMemorySubtypeMisc) }, }, @@ -174,14 +187,16 @@ var queries = []monitoringQuery{ { key: "fixed", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaRowStoreMemoryUsedDataPoint(now, val, metadata.AttributeRowMemoryTypeFixed) }, }, { key: "variable", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaRowStoreMemoryUsedDataPoint(now, val, metadata.AttributeRowMemoryTypeVariable) }, }, @@ -198,7 +213,8 @@ var queries = []monitoringQuery{ { key: "used_mem_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaComponentMemoryUsedDataPoint(now, val, row["component"]) }, }, @@ -215,7 +231,8 @@ var queries = []monitoringQuery{ { key: "connections", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaConnectionCountDataPoint(now, val, metadata.MapAttributeConnectionStatus[strings.ToLower(row["connection_status"])]) }, @@ -232,7 +249,8 @@ var queries = []monitoringQuery{ { key: "age", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaBackupLatestDataPoint(now, val) }, }, @@ -249,7 +267,8 @@ var queries = []monitoringQuery{ { key: "age", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaUptimeDataPoint(now, val, row["system"], row["database"]) }, }, @@ -265,7 +284,8 @@ var queries = []monitoringQuery{ { key: "alerts", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaAlertCountDataPoint(now, val, row["alert_rating"]) }, }, @@ -281,21 +301,24 @@ var queries = []monitoringQuery{ { key: "updates", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaTransactionCountDataPoint(now, val, metadata.AttributeTransactionTypeUpdate) }, }, { key: "commits", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaTransactionCountDataPoint(now, val, metadata.AttributeTransactionTypeCommit) }, }, { key: "rollbacks", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaTransactionCountDataPoint(now, val, metadata.AttributeTransactionTypeRollback) }, }, @@ -311,7 +334,8 @@ var queries = []monitoringQuery{ { key: "blocks", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaTransactionBlockedDataPoint(now, val) }, }, @@ -328,14 +352,16 @@ var queries = []monitoringQuery{ { key: "free_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaDiskSizeCurrentDataPoint(now, val, row["path"], row["usage_type"], metadata.AttributeDiskStateUsedFreeFree) }, }, { key: "used_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaDiskSizeCurrentDataPoint(now, val, row["path"], row["usage_type"], metadata.AttributeDiskStateUsedFreeUsed) }, }, @@ -351,21 +377,24 @@ var queries = []monitoringQuery{ { key: "limit", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaLicenseLimitDataPoint(now, val, row["system"], row["product"]) }, }, { key: "usage", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaLicensePeakDataPoint(now, val, row["system"], row["product"]) }, }, { key: "expiration", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaLicenseExpirationTimeDataPoint(now, val, row["system"], row["product"]) }, }, @@ -383,21 +412,24 @@ var queries = []monitoringQuery{ { key: "backlog_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaReplicationBacklogSizeDataPoint(now, val, row["host"], row["secondary"], row["port"], row["mode"]) }, }, { key: "backlog_time", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaReplicationBacklogTimeDataPoint(now, val, row["host"], row["secondary"], row["port"], row["mode"]) }, }, { key: "average_time", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaReplicationAverageTimeDataPoint(now, val, row["host"], row["secondary"], row["port"], row["mode"]) }, }, @@ -415,35 +447,40 @@ var queries = []monitoringQuery{ { key: "external", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaNetworkRequestFinishedCountDataPoint(now, val, metadata.AttributeInternalExternalRequestTypeExternal) }, }, { key: "internal", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaNetworkRequestFinishedCountDataPoint(now, val, metadata.AttributeInternalExternalRequestTypeInternal) }, }, { key: "active", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaNetworkRequestCountDataPoint(now, val, metadata.AttributeActivePendingRequestStateActive) }, }, { key: "pending", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaNetworkRequestCountDataPoint(now, val, metadata.AttributeActivePendingRequestStatePending) }, }, { key: "avg_time", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaNetworkRequestAverageTimeDataPoint(now, val) }, }, @@ -462,42 +499,48 @@ var queries = []monitoringQuery{ { key: "reads", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationCountDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeRead) }, }, { key: "writes", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationCountDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeWrite) }, }, { key: "read_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationSizeDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeRead) }, }, { key: "write_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationSizeDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeWrite) }, }, { key: "read_time", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationTimeDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeRead) }, }, { key: "write_time", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaVolumeOperationTimeDataPoint(now, val, row["path"], row["type"], metadata.AttributeVolumeOperationTypeWrite) }, }, @@ -516,84 +559,96 @@ var queries = []monitoringQuery{ { key: "logical_used", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryUsedDataPoint(now, val, row["service"], metadata.AttributeServiceMemoryUsedTypeLogical) }, }, { key: "physical_used", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryUsedDataPoint(now, val, row["service"], metadata.AttributeServiceMemoryUsedTypePhysical) }, }, { key: "code_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceCodeSizeDataPoint(now, val, row["service"]) }, }, { key: "stack_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceStackSizeDataPoint(now, val, row["service"]) }, }, { key: "heap_free", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryHeapCurrentDataPoint(now, val, row["service"], metadata.AttributeMemoryStateUsedFreeFree) }, }, { key: "heap_used", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryHeapCurrentDataPoint(now, val, row["service"], metadata.AttributeMemoryStateUsedFreeUsed) }, }, { key: "shared_free", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemorySharedCurrentDataPoint(now, val, row["service"], metadata.AttributeMemoryStateUsedFreeFree) }, }, { key: "shared_used", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemorySharedCurrentDataPoint(now, val, row["service"], metadata.AttributeMemoryStateUsedFreeUsed) }, }, { key: "compactors_allocated", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryCompactorsAllocatedDataPoint(now, val, row["service"]) }, }, { key: "compactors_freeable", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryCompactorsFreeableDataPoint(now, val, row["service"]) }, }, { key: "allocation_limit", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryLimitDataPoint(now, val, row["service"]) }, }, { key: "effective_limit", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaServiceMemoryEffectiveLimitDataPoint(now, val, row["service"]) }, }, @@ -618,91 +673,104 @@ var queries = []monitoringQuery{ { key: "estimated_max", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaMemoryUsedMaxDataPoint(now, val, row["schema"]) }, }, { key: "last_compressed", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaRecordCompressedCountDataPoint(now, val, row["schema"]) }, }, { key: "reads", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaOperationCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaOperationTypeRead) }, }, { key: "writes", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaOperationCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaOperationTypeWrite) }, }, { key: "merges", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaOperationCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaOperationTypeMerge) }, }, { key: "mem_main", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaMemoryUsedCurrentDataPoint(now, val, row["schema"], metadata.AttributeSchemaMemoryTypeMain) }, }, { key: "mem_delta", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaMemoryUsedCurrentDataPoint(now, val, row["schema"], metadata.AttributeSchemaMemoryTypeDelta) }, }, { key: "mem_history_main", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaMemoryUsedCurrentDataPoint(now, val, row["schema"], metadata.AttributeSchemaMemoryTypeHistoryMain) }, }, { key: "mem_history_delta", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaMemoryUsedCurrentDataPoint(now, val, row["schema"], metadata.AttributeSchemaMemoryTypeHistoryDelta) }, }, { key: "records_main", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaRecordCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaRecordTypeMain) }, }, { key: "records_delta", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaRecordCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaRecordTypeDelta) }, }, { key: "records_history_main", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaRecordCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaRecordTypeHistoryMain) }, }, { key: "records_history_delta", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - row map[string]string) error { + row map[string]string, + ) error { return mb.RecordSaphanaSchemaRecordCountDataPoint(now, val, row["schema"], metadata.AttributeSchemaRecordTypeHistoryDelta) }, }, @@ -722,91 +790,104 @@ var queries = []monitoringQuery{ { key: "free_physical_memory", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaHostMemoryCurrentDataPoint(now, val, metadata.AttributeMemoryStateUsedFreeFree) }, }, { key: "used_physical_memory", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaHostMemoryCurrentDataPoint(now, val, metadata.AttributeMemoryStateUsedFreeUsed) }, }, { key: "free_swap_space", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaHostSwapCurrentDataPoint(now, val, metadata.AttributeHostSwapStateFree) }, }, { key: "used_swap_space", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaHostSwapCurrentDataPoint(now, val, metadata.AttributeHostSwapStateUsed) }, }, { key: "instance_total_used", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaInstanceMemoryCurrentDataPoint(now, val, metadata.AttributeMemoryStateUsedFreeUsed) }, }, { key: "instance_total_used_peak", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaInstanceMemoryUsedPeakDataPoint(now, val) }, }, { key: "instance_total_free", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaInstanceMemoryCurrentDataPoint(now, val, metadata.AttributeMemoryStateUsedFreeFree) }, }, { key: "instance_code_size", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaInstanceCodeSizeDataPoint(now, val) }, }, { key: "instance_shared_memory_allocated", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaInstanceMemorySharedAllocatedDataPoint(now, val) }, }, { key: "cpu_user", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaCPUUsedDataPoint(now, val, metadata.AttributeCPUTypeUser) }, }, { key: "cpu_system", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaCPUUsedDataPoint(now, val, metadata.AttributeCPUTypeSystem) }, }, { key: "cpu_io_wait", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaCPUUsedDataPoint(now, val, metadata.AttributeCPUTypeIoWait) }, }, { key: "cpu_idle", addMetricFunction: func(mb *metadata.MetricsBuilder, now pcommon.Timestamp, val string, - _ map[string]string) error { + _ map[string]string, + ) error { return mb.RecordSaphanaCPUUsedDataPoint(now, val, metadata.AttributeCPUTypeIdle) }, }, @@ -824,7 +905,8 @@ var queries = []monitoringQuery{ } func (m *monitoringQuery) CollectMetrics(ctx context.Context, s *sapHanaScraper, client client, now pcommon.Timestamp, - errs *scrapererror.ScrapeErrors) { + errs *scrapererror.ScrapeErrors, +) { rows, err := client.collectDataFromQuery(ctx, m) if err != nil { errs.AddPartial(len(m.orderedStats), fmt.Errorf("error running query '%s': %w", m.query, err)) diff --git a/receiver/saphanareceiver/scraper_test.go b/receiver/saphanareceiver/scraper_test.go index 8cbf0325fda4..8e61e72e4877 100644 --- a/receiver/saphanareceiver/scraper_test.go +++ b/receiver/saphanareceiver/scraper_test.go @@ -16,10 +16,12 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest/pmetrictest" ) -const fullExpectedMetricsPath = "./testdata/expected_metrics/full.yaml" -const partialExpectedMetricsPath = "./testdata/expected_metrics/mostly_disabled.yaml" -const allQueryMetrics = "./testdata/mocked_queries/all_query_results.json" -const mostlyDisabledQueryMetrics = "./testdata/mocked_queries/mostly_disabled_results.json" +const ( + fullExpectedMetricsPath = "./testdata/expected_metrics/full.yaml" + partialExpectedMetricsPath = "./testdata/expected_metrics/mostly_disabled.yaml" + allQueryMetrics = "./testdata/mocked_queries/all_query_results.json" + mostlyDisabledQueryMetrics = "./testdata/mocked_queries/mostly_disabled_results.json" +) func TestScraper(t *testing.T) { t.Parallel() diff --git a/receiver/signalfxreceiver/config.go b/receiver/signalfxreceiver/config.go index 5330baccec95..d6b37881f11d 100644 --- a/receiver/signalfxreceiver/config.go +++ b/receiver/signalfxreceiver/config.go @@ -11,9 +11,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/internal/splunk" ) -var ( - errEmptyEndpoint = errors.New("empty endpoint") -) +var errEmptyEndpoint = errors.New("empty endpoint") // Config defines configuration for the SignalFx receiver. type Config struct { diff --git a/receiver/signalfxreceiver/factory.go b/receiver/signalfxreceiver/factory.go index 87f71817f67d..cb7b4f2c7ad9 100644 --- a/receiver/signalfxreceiver/factory.go +++ b/receiver/signalfxreceiver/factory.go @@ -113,5 +113,7 @@ func createLogsReceiver( return r, nil } -var receiverLock sync.Mutex -var receivers = map[*Config]*sfxReceiver{} +var ( + receiverLock sync.Mutex + receivers = map[*Config]*sfxReceiver{} +) diff --git a/receiver/simpleprometheusreceiver/receiver_test.go b/receiver/simpleprometheusreceiver/receiver_test.go index 5bc79e1bd2f6..d9b1307cea7a 100644 --- a/receiver/simpleprometheusreceiver/receiver_test.go +++ b/receiver/simpleprometheusreceiver/receiver_test.go @@ -221,7 +221,8 @@ func TestGetPrometheusConfig(t *testing.T) { Targets: []model.LabelSet{ { model.AddressLabel: model.LabelValue("localhost:1234"), - model.LabelName("key"): model.LabelValue("value")}, + model.LabelName("key"): model.LabelValue("value"), + }, }, }, }, diff --git a/receiver/skywalkingreceiver/config.go b/receiver/skywalkingreceiver/config.go index 02afbd1a8a43..9334891ec890 100644 --- a/receiver/skywalkingreceiver/config.go +++ b/receiver/skywalkingreceiver/config.go @@ -28,8 +28,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/skywalkingreceiver/skywalking_receiver_test.go b/receiver/skywalkingreceiver/skywalking_receiver_test.go index 02218321a97d..39e6b11f754f 100644 --- a/receiver/skywalkingreceiver/skywalking_receiver_test.go +++ b/receiver/skywalkingreceiver/skywalking_receiver_test.go @@ -25,9 +25,7 @@ import ( agent "skywalking.apache.org/repo/goapi/collect/language/agent/v3" ) -var ( - skywalkingReceiver = component.MustNewIDWithName("skywalking", "receiver_test") -) +var skywalkingReceiver = component.MustNewIDWithName("skywalking", "receiver_test") var traceJSON = []byte(` [{ diff --git a/receiver/snmpreceiver/integration_test.go b/receiver/snmpreceiver/integration_test.go index 0c757b42a31e..63a941e2c0e8 100644 --- a/receiver/snmpreceiver/integration_test.go +++ b/receiver/snmpreceiver/integration_test.go @@ -89,17 +89,15 @@ func TestIntegration(t *testing.T) { } } -var ( - snmpAgentContainerRequest = testcontainers.ContainerRequest{ - FromDockerfile: testcontainers.FromDockerfile{ - Context: filepath.Join("testdata", "integration", "docker"), - Dockerfile: "snmp_agent.Dockerfile", - }, - ExposedPorts: []string{"161/udp"}, - WaitingFor: wait.ForListeningPort("161/udp"). - WithStartupTimeout(2 * time.Minute), - } -) +var snmpAgentContainerRequest = testcontainers.ContainerRequest{ + FromDockerfile: testcontainers.FromDockerfile{ + Context: filepath.Join("testdata", "integration", "docker"), + Dockerfile: "snmp_agent.Dockerfile", + }, + ExposedPorts: []string{"161/udp"}, + WaitingFor: wait.ForListeningPort("161/udp"). + WithStartupTimeout(2 * time.Minute), +} func getContainer(t *testing.T, req testcontainers.ContainerRequest) testcontainers.Container { require.NoError(t, req.Validate()) diff --git a/receiver/snowflakereceiver/client_test.go b/receiver/snowflakereceiver/client_test.go index f4c0999395b1..7da44b41f598 100644 --- a/receiver/snowflakereceiver/client_test.go +++ b/receiver/snowflakereceiver/client_test.go @@ -146,15 +146,19 @@ func TestMetricQueries(t *testing.T) { { desc: "FetchDbMetrics", query: dbMetricsQuery, - columns: []string{"schemaname", "execution_status", "error_message", + columns: []string{ + "schemaname", "execution_status", "error_message", "query_type", "wh_name", "db_name", "wh_size", "username", "count_queryid", "queued_overload", "queued_repair", "queued_provision", "total_elapsed", "execution_time", "comp_time", "bytes_scanned", "bytes_written", "bytes_deleted", "bytes_spilled_local", "bytes_spilled_remote", "percentage_cache", "partitions_scanned", "rows_unloaded", "rows_deleted", - "rows_updated", "rows_inserted", "rows_produced"}, - params: []driver.Value{"a", "b", "c", "d", "e", "f", "g", "h", 1, 2.0, 3.0, 4.0, 5.0, 6.0, - 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0}, + "rows_updated", "rows_inserted", "rows_produced", + }, + params: []driver.Value{ + "a", "b", "c", "d", "e", "f", "g", "h", 1, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, + }, expect: dbMetric{ attributes: dbMetricAttributes{ userName: sql.NullString{ diff --git a/receiver/snowflakereceiver/scraper.go b/receiver/snowflakereceiver/scraper.go index 09a5600e3f12..2873a0f2af9e 100644 --- a/receiver/snowflakereceiver/scraper.go +++ b/receiver/snowflakereceiver/scraper.go @@ -108,7 +108,6 @@ func (s *snowflakeMetricsScraper) scrape(ctx context.Context) (pmetric.Metrics, func (s *snowflakeMetricsScraper) scrapeBillingMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { billingMetrics, err := s.client.FetchBillingMetrics(ctx) - if err != nil { errs <- err return @@ -123,7 +122,6 @@ func (s *snowflakeMetricsScraper) scrapeBillingMetrics(ctx context.Context, t pc func (s *snowflakeMetricsScraper) scrapeWarehouseBillingMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { warehouseBillingMetrics, err := s.client.FetchWarehouseBillingMetrics(ctx) - if err != nil { errs <- err return @@ -138,7 +136,6 @@ func (s *snowflakeMetricsScraper) scrapeWarehouseBillingMetrics(ctx context.Cont func (s *snowflakeMetricsScraper) scrapeLoginMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { loginMetrics, err := s.client.FetchLoginMetrics(ctx) - if err != nil { errs <- err return @@ -151,7 +148,6 @@ func (s *snowflakeMetricsScraper) scrapeLoginMetrics(ctx context.Context, t pcom func (s *snowflakeMetricsScraper) scrapeHighLevelQueryMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { highLevelQueryMetrics, err := s.client.FetchHighLevelQueryMetrics(ctx) - if err != nil { errs <- err return @@ -167,7 +163,6 @@ func (s *snowflakeMetricsScraper) scrapeHighLevelQueryMetrics(ctx context.Contex func (s *snowflakeMetricsScraper) scrapeDBMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { DBMetrics, err := s.client.FetchDbMetrics(ctx) - if err != nil { errs <- err return @@ -198,7 +193,6 @@ func (s *snowflakeMetricsScraper) scrapeDBMetrics(ctx context.Context, t pcommon func (s *snowflakeMetricsScraper) scrapeSessionMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { sessionMetrics, err := s.client.FetchSessionMetrics(ctx) - if err != nil { errs <- err return @@ -211,7 +205,6 @@ func (s *snowflakeMetricsScraper) scrapeSessionMetrics(ctx context.Context, t pc func (s *snowflakeMetricsScraper) scrapeSnowpipeMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { snowpipeMetrics, err := s.client.FetchSnowpipeMetrics(ctx) - if err != nil { errs <- err return @@ -224,7 +217,6 @@ func (s *snowflakeMetricsScraper) scrapeSnowpipeMetrics(ctx context.Context, t p func (s *snowflakeMetricsScraper) scrapeStorageMetrics(ctx context.Context, t pcommon.Timestamp, errs chan<- error) { storageMetrics, err := s.client.FetchStorageMetrics(ctx) - if err != nil { errs <- err return diff --git a/receiver/snowflakereceiver/scraper_test.go b/receiver/snowflakereceiver/scraper_test.go index d67f3e39b8ab..0620f8d64eba 100644 --- a/receiver/snowflakereceiver/scraper_test.go +++ b/receiver/snowflakereceiver/scraper_test.go @@ -108,15 +108,19 @@ func (m *mockDB) initMockDB() { }, { query: dbMetricsQuery, - columns: []string{"schemaname", "execution_status", "error_message", + columns: []string{ + "schemaname", "execution_status", "error_message", "query_type", "wh_name", "db_name", "wh_size", "username", "count_queryid", "queued_overload", "queued_repair", "queued_provision", "total_elapsed", "execution_time", "comp_time", "bytes_scanned", "bytes_written", "bytes_deleted", "bytes_spilled_local", "bytes_spilled_remote", "percentage_cache", "partitions_scanned", "rows_unloaded", "rows_deleted", - "rows_updated", "rows_inserted", "rows_produced"}, - params: []driver.Value{"a", "b", "c", "d", "e", "f", "g", "h", 1, 2.0, 3.0, 4.0, 5.0, 6.0, - 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0}, + "rows_updated", "rows_inserted", "rows_produced", + }, + params: []driver.Value{ + "a", "b", "c", "d", "e", "f", "g", "h", 1, 2.0, 3.0, 4.0, 5.0, 6.0, + 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, + }, }, { query: sessionMetricsQuery, diff --git a/receiver/solacereceiver/config.go b/receiver/solacereceiver/config.go index 2e4316c1c986..e8eaffa48894 100644 --- a/receiver/solacereceiver/config.go +++ b/receiver/solacereceiver/config.go @@ -80,8 +80,7 @@ type SaslXAuth2Config struct { } // SaslExternalConfig defines the configuration for the SASL External used in conjunction with TLS client authentication. -type SaslExternalConfig struct { -} +type SaslExternalConfig struct{} // FlowControl defines the configuration for what to do in backpressure scenarios, e.g. memorylimiter errors type FlowControl struct { diff --git a/receiver/solacereceiver/messaging_service_test.go b/receiver/solacereceiver/messaging_service_test.go index 1179b1311647..848b19557fc9 100644 --- a/receiver/solacereceiver/messaging_service_test.go +++ b/receiver/solacereceiver/messaging_service_test.go @@ -182,7 +182,7 @@ func TestNewAMQPMessagingServiceFactory(t *testing.T) { func TestAMQPDialFailure(t *testing.T) { const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + expectedErr := fmt.Errorf("some error") dialFunc = func(_ context.Context, addr string, _ *amqp.ConnOptions) (*amqp.Conn, error) { defer func() { dialFunc = amqp.Dial }() // reset dialFunc assert.Equal(t, expectedAddr, addr) @@ -207,7 +207,7 @@ func TestAMQPDialFailure(t *testing.T) { func TestAMQPDialConfigOptionsWithoutTLS(t *testing.T) { // try creating a service without a tls config calling dial expecting no tls config passed const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + expectedErr := fmt.Errorf("some error") expectedAuthConnOption := amqp.SASLTypeAnonymous() dialFunc = func(_ context.Context, addr string, opts *amqp.ConnOptions) (*amqp.Conn, error) { defer func() { dialFunc = amqp.Dial }() // reset dialFunc @@ -235,7 +235,7 @@ func TestAMQPDialConfigOptionsWithoutTLS(t *testing.T) { func TestAMQPDialConfigOptionsWithTLS(t *testing.T) { // try creating a service with a tls config calling dial const expectedAddr = "some-host:1234" - var expectedErr = fmt.Errorf("some error") + expectedErr := fmt.Errorf("some error") expectedAuthConnOption := amqp.SASLTypeAnonymous() expectedTLSConnOption := &tls.Config{ InsecureSkipVerify: false, @@ -636,8 +636,10 @@ type connMock struct { remaining *bytes.Reader } -type writeHandler func([]byte) (n int, err error) -type closeHandler func() error +type ( + writeHandler func([]byte) (n int, err error) + closeHandler func() error +) func (c *connMock) setWriteHandler(handler writeHandler) { atomic.StorePointer(&c.writeHandle, unsafe.Pointer(&handler)) @@ -679,18 +681,23 @@ func (c *connMock) Close() error { } return nil } + func (c *connMock) LocalAddr() net.Addr { return nil } + func (c *connMock) RemoteAddr() net.Addr { return nil } + func (c *connMock) SetDeadline(_ time.Time) error { return nil } + func (c *connMock) SetReadDeadline(_ time.Time) error { return nil } + func (c *connMock) SetWriteDeadline(_ time.Time) error { return nil } diff --git a/receiver/solacereceiver/unmarshaller_egress.go b/receiver/solacereceiver/unmarshaller_egress.go index 9a7f0997a152..c678e5f94e9a 100644 --- a/receiver/solacereceiver/unmarshaller_egress.go +++ b/receiver/solacereceiver/unmarshaller_egress.go @@ -41,7 +41,7 @@ func (u *brokerTraceEgressUnmarshallerV1) unmarshal(message *inboundMessage) (pt // unmarshalToSpanData will consume an solaceMessage and unmarshal it into a SpanData. // Returns an error if one occurred. func (u *brokerTraceEgressUnmarshallerV1) unmarshalToSpanData(message *inboundMessage) (*egress_v1.SpanData, error) { - var data = message.GetData() + data := message.GetData() if len(data) == 0 { return nil, errEmptyPayload } diff --git a/receiver/solacereceiver/unmarshaller_egress_test.go b/receiver/solacereceiver/unmarshaller_egress_test.go index 3bde7f1b4d53..048d64586777 100644 --- a/receiver/solacereceiver/unmarshaller_egress_test.go +++ b/receiver/solacereceiver/unmarshaller_egress_test.go @@ -283,7 +283,7 @@ func TestEgressUnmarshallerEgressSpan(t *testing.T) { }, }, } - var i = 1 + i := 1 for _, dataRef := range validEgressSpans { name := "valid span " + fmt.Sprint(i) i++ diff --git a/receiver/solacereceiver/unmarshaller_move.go b/receiver/solacereceiver/unmarshaller_move.go index aa220c277b1c..41dc73ebe40f 100644 --- a/receiver/solacereceiver/unmarshaller_move.go +++ b/receiver/solacereceiver/unmarshaller_move.go @@ -38,7 +38,7 @@ func (u *brokerTraceMoveUnmarshallerV1) unmarshal(message *inboundMessage) (ptra // unmarshalToSpanData will consume an solaceMessage and unmarshal it into a SpanData. // Returns an error if one occurred. func (u *brokerTraceMoveUnmarshallerV1) unmarshalToSpanData(message *inboundMessage) (*move_v1.SpanData, error) { - var data = message.GetData() + data := message.GetData() if len(data) == 0 { return nil, errEmptyPayload } diff --git a/receiver/solacereceiver/unmarshaller_receive.go b/receiver/solacereceiver/unmarshaller_receive.go index 53898937aee5..27d806b6157c 100644 --- a/receiver/solacereceiver/unmarshaller_receive.go +++ b/receiver/solacereceiver/unmarshaller_receive.go @@ -42,7 +42,7 @@ func (u *brokerTraceReceiveUnmarshallerV1) unmarshal(message *inboundMessage) (p // unmarshalToSpanData will consume an solaceMessage and unmarshal it into a SpanData. // Returns an error if one occurred. func (u *brokerTraceReceiveUnmarshallerV1) unmarshalToSpanData(message *inboundMessage) (*receive_v1.SpanData, error) { - var data = message.GetData() + data := message.GetData() if len(data) == 0 { return nil, errEmptyPayload } diff --git a/receiver/splunkenterprisereceiver/scraper.go b/receiver/splunkenterprisereceiver/scraper.go index 54af1eae90da..6652f634bf5f 100644 --- a/receiver/splunkenterprisereceiver/scraper.go +++ b/receiver/splunkenterprisereceiver/scraper.go @@ -24,9 +24,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/splunkenterprisereceiver/internal/metadata" ) -var ( - errMaxSearchWaitTimeExceeded = errors.New("maximum search wait time exceeded for metric") -) +var errMaxSearchWaitTimeExceeded = errors.New("maximum search wait time exceeded for metric") type splunkScraper struct { splunkClient *splunkEntClient @@ -116,7 +114,8 @@ func (s *splunkScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { fn func(ctx context.Context, now pcommon.Timestamp, errs chan error), ctx context.Context, now pcommon.Timestamp, - errs chan error) { + errs chan error, + ) { // actual function body defer wg.Done() fn(ctx, now, errs) diff --git a/receiver/splunkhecreceiver/receiver.go b/receiver/splunkhecreceiver/receiver.go index 6d095ef61101..4056b6823682 100644 --- a/receiver/splunkhecreceiver/receiver.go +++ b/receiver/splunkhecreceiver/receiver.go @@ -94,8 +94,10 @@ type splunkReceiver struct { ackExt ackextension.AckExtension } -var _ receiver.Metrics = (*splunkReceiver)(nil) -var _ receiver.Logs = (*splunkReceiver)(nil) +var ( + _ receiver.Metrics = (*splunkReceiver)(nil) + _ receiver.Logs = (*splunkReceiver)(nil) +) // newReceiver creates the Splunk HEC receiver with the given configuration. func newReceiver(settings receiver.Settings, config Config) (*splunkReceiver, error) { @@ -290,7 +292,6 @@ func (r *splunkReceiver) handleRawReq(resp http.ResponseWriter, req *http.Reques if encoding == gzipEncoding { reader := r.gzipReaderPool.Get().(*gzip.Reader) err := reader.Reset(bodyReader) - if err != nil { r.failRequest(resp, http.StatusBadRequest, errGzipReaderRespBody, err) _, _ = io.ReadAll(req.Body) diff --git a/receiver/splunkhecreceiver/receiver_test.go b/receiver/splunkhecreceiver/receiver_test.go index e09e2abfaead..b2f61c7064f5 100644 --- a/receiver/splunkhecreceiver/receiver_test.go +++ b/receiver/splunkhecreceiver/receiver_test.go @@ -1071,6 +1071,7 @@ func Test_splunkhecReceiver_handleRawReq(t *testing.T) { }) } } + func Test_splunkhecReceiver_Start(t *testing.T) { tests := []struct { name string @@ -1111,6 +1112,7 @@ func Test_splunkhecReceiver_Start(t *testing.T) { }) } } + func Test_splunkhecReceiver_handleAck(t *testing.T) { t.Parallel() config := createDefaultConfig().(*Config) diff --git a/receiver/splunkhecreceiver/splunk_to_logdata.go b/receiver/splunkhecreceiver/splunk_to_logdata.go index 7b76755ae8b7..2d052b013889 100644 --- a/receiver/splunkhecreceiver/splunk_to_logdata.go +++ b/receiver/splunkhecreceiver/splunk_to_logdata.go @@ -26,9 +26,7 @@ const ( queryTime = "time" ) -var ( - errCannotConvertValue = errors.New("cannot convert field value to attribute") -) +var errCannotConvertValue = errors.New("cannot convert field value to attribute") // splunkHecToLogData transforms splunk events into logs func splunkHecToLogData(logger *zap.Logger, events []*splunk.Event, resourceCustomizer func(pcommon.Resource), config *Config) (plog.Logs, error) { diff --git a/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go b/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go index 9801b2350abd..c0bfa0ecf07d 100644 --- a/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go +++ b/receiver/splunkhecreceiver/splunkhec_to_metricdata_test.go @@ -167,12 +167,13 @@ func Test_splunkV2ToMetricsData(t *testing.T) { intPt.SetTimestamp(pcommon.Timestamp(nanos)) return metrics }(), - hecConfig: &Config{HecToOtelAttrs: splunk.HecToOtelAttrs{ - Source: "mysource", - SourceType: "mysourcetype", - Index: "myindex", - Host: "myhost", - }, + hecConfig: &Config{ + HecToOtelAttrs: splunk.HecToOtelAttrs{ + Source: "mysource", + SourceType: "mysourcetype", + Index: "myindex", + Host: "myhost", + }, }, }, { diff --git a/receiver/sqlserverreceiver/config_others_test.go b/receiver/sqlserverreceiver/config_others_test.go index 5073bbcd28d0..55988498bad5 100644 --- a/receiver/sqlserverreceiver/config_others_test.go +++ b/receiver/sqlserverreceiver/config_others_test.go @@ -28,7 +28,8 @@ func TestValidateOtherOS(t *testing.T) { ControllerConfig: scraperhelper.NewDefaultControllerConfig(), }, expectedSuccess: true, - }, { + }, + { desc: "valid config with no metric settings", cfg: &Config{ ControllerConfig: scraperhelper.NewDefaultControllerConfig(), diff --git a/receiver/sqlserverreceiver/config_test.go b/receiver/sqlserverreceiver/config_test.go index d4d25cfac11e..28cff062fe89 100644 --- a/receiver/sqlserverreceiver/config_test.go +++ b/receiver/sqlserverreceiver/config_test.go @@ -31,7 +31,8 @@ func TestValidate(t *testing.T) { ControllerConfig: scraperhelper.NewDefaultControllerConfig(), }, expectedSuccess: true, - }, { + }, + { desc: "valid config with no metric settings", cfg: &Config{ ControllerConfig: scraperhelper.NewDefaultControllerConfig(), diff --git a/receiver/sqlserverreceiver/config_windows_test.go b/receiver/sqlserverreceiver/config_windows_test.go index c1e590088349..d0889c446dba 100644 --- a/receiver/sqlserverreceiver/config_windows_test.go +++ b/receiver/sqlserverreceiver/config_windows_test.go @@ -28,7 +28,8 @@ func TestValidateWindows(t *testing.T) { ControllerConfig: scraperhelper.NewDefaultControllerConfig(), }, expectedSuccess: true, - }, { + }, + { desc: "valid config with no metric settings", cfg: &Config{ ControllerConfig: scraperhelper.NewDefaultControllerConfig(), diff --git a/receiver/sqlserverreceiver/factory.go b/receiver/sqlserverreceiver/factory.go index 00c235170b71..4fcde3d2a573 100644 --- a/receiver/sqlserverreceiver/factory.go +++ b/receiver/sqlserverreceiver/factory.go @@ -122,7 +122,6 @@ func setupScrapers(params receiver.Settings, cfg *Config) ([]scraperhelper.Scrap scraper, err := scraperhelper.NewScraper(metadata.Type, sqlScraper.Scrape, scraperhelper.WithStart(sqlScraper.Start), scraperhelper.WithShutdown(sqlScraper.Shutdown)) - if err != nil { return nil, err } diff --git a/receiver/sqlserverreceiver/recorders_test.go b/receiver/sqlserverreceiver/recorders_test.go index 49449818faa0..2d4325a2da0b 100644 --- a/receiver/sqlserverreceiver/recorders_test.go +++ b/receiver/sqlserverreceiver/recorders_test.go @@ -41,7 +41,6 @@ func TestPerfCounterRecorders(t *testing.T) { } } }) - } // getAvailableCounters populates a map containing all available counters. diff --git a/receiver/sqlserverreceiver/scraper.go b/receiver/sqlserverreceiver/scraper.go index a373719cb0ed..5edfbce105e0 100644 --- a/receiver/sqlserverreceiver/scraper.go +++ b/receiver/sqlserverreceiver/scraper.go @@ -50,7 +50,8 @@ func newSQLServerScraper(id component.ID, telemetry sqlquery.TelemetryConfig, dbProviderFunc sqlquery.DbProviderFunc, clientProviderFunc sqlquery.ClientProviderFunc, - mb *metadata.MetricsBuilder) *sqlServerScraperHelper { + mb *metadata.MetricsBuilder, +) *sqlServerScraperHelper { return &sqlServerScraperHelper{ id: id, sqlQuery: query, @@ -183,7 +184,6 @@ func (s *sqlServerScraperHelper) recordDatabasePerfCounterMetrics(ctx context.Co const userConnCount = "User Connections" rows, err := s.client.QueryRows(ctx) - if err != nil { if errors.Is(err, sqlquery.ErrNullValueWarning) { s.logger.Warn("problems encountered getting metric rows", zap.Error(err)) @@ -272,7 +272,6 @@ func (s *sqlServerScraperHelper) recordDatabaseStatusMetrics(ctx context.Context const dbOffline = "db_offline" rows, err := s.client.QueryRows(ctx) - if err != nil { if errors.Is(err, sqlquery.ErrNullValueWarning) { s.logger.Warn("problems encountered getting metric rows", zap.Error(err)) diff --git a/receiver/sqlserverreceiver/scraper_windows_test.go b/receiver/sqlserverreceiver/scraper_windows_test.go index 680a9786dc61..8ea78b48b3b3 100644 --- a/receiver/sqlserverreceiver/scraper_windows_test.go +++ b/receiver/sqlserverreceiver/scraper_windows_test.go @@ -109,9 +109,11 @@ func TestSqlServerScraper(t *testing.T) { require.NoError(t, err) } -var goldenScrapePath = filepath.Join("testdata", "golden_scrape.yaml") -var goldenNamedInstanceScrapePath = filepath.Join("testdata", "golden_named_instance_scrape.yaml") -var dbInstance = "db-instance" +var ( + goldenScrapePath = filepath.Join("testdata", "golden_scrape.yaml") + goldenNamedInstanceScrapePath = filepath.Join("testdata", "golden_named_instance_scrape.yaml") + dbInstance = "db-instance" +) func TestScrape(t *testing.T) { t.Run("default", func(t *testing.T) { diff --git a/receiver/sshcheckreceiver/scraper.go b/receiver/sshcheckreceiver/scraper.go index ee5c2a7b2cee..9e15f70d7272 100644 --- a/receiver/sshcheckreceiver/scraper.go +++ b/receiver/sshcheckreceiver/scraper.go @@ -76,9 +76,7 @@ func timeout(deadline time.Time, timeout time.Duration) time.Duration { // is a bit awkward here, because the SFTP checks are not enabled by default and they would panic on nil // ref to the underlying Conn when SSH checks failed. func (s *sshcheckScraper) scrape(ctx context.Context) (_ pmetric.Metrics, err error) { - var ( - to time.Duration - ) + var to time.Duration // check cancellation select { case <-ctx.Done(): diff --git a/receiver/statsdreceiver/config_test.go b/receiver/statsdreceiver/config_test.go index f1129b37bde2..0ccda8f9132c 100644 --- a/receiver/statsdreceiver/config_test.go +++ b/receiver/statsdreceiver/config_test.go @@ -198,6 +198,7 @@ func TestValidate(t *testing.T) { }) } } + func TestConfig_Validate_MaxSize(t *testing.T) { for _, maxSize := range []int32{structure.MaximumMaxSize + 1, -1, -structure.MaximumMaxSize} { cfg := &Config{ @@ -216,6 +217,7 @@ func TestConfig_Validate_MaxSize(t *testing.T) { assert.ErrorContains(t, err, "histogram max_size out of range") } } + func TestConfig_Validate_HistogramGoodConfig(t *testing.T) { for _, maxSize := range []int32{structure.MaximumMaxSize, 0, 2} { cfg := &Config{ diff --git a/receiver/statsdreceiver/factory.go b/receiver/statsdreceiver/factory.go index 3cce2a72460f..f3cf38da4d5a 100644 --- a/receiver/statsdreceiver/factory.go +++ b/receiver/statsdreceiver/factory.go @@ -23,9 +23,7 @@ const ( defaultIsMonotonicCounter = false ) -var ( - defaultTimerHistogramMapping = []protocol.TimerHistogramMapping{{StatsdType: "timer", ObserverType: "gauge"}, {StatsdType: "histogram", ObserverType: "gauge"}, {StatsdType: "distribution", ObserverType: "gauge"}} -) +var defaultTimerHistogramMapping = []protocol.TimerHistogramMapping{{StatsdType: "timer", ObserverType: "gauge"}, {StatsdType: "histogram", ObserverType: "gauge"}, {StatsdType: "distribution", ObserverType: "gauge"}} // NewFactory creates a factory for the StatsD receiver. func NewFactory() receiver.Factory { diff --git a/receiver/statsdreceiver/internal/protocol/metric_translator.go b/receiver/statsdreceiver/internal/protocol/metric_translator.go index cd79d10e34db..1cec9821cffd 100644 --- a/receiver/statsdreceiver/internal/protocol/metric_translator.go +++ b/receiver/statsdreceiver/internal/protocol/metric_translator.go @@ -13,9 +13,7 @@ import ( "gonum.org/v1/gonum/stat" ) -var ( - statsDDefaultPercentiles = []float64{0, 10, 50, 90, 95, 100} -) +var statsDDefaultPercentiles = []float64{0, 10, 50, 90, 95, 100} func buildCounterMetric(parsedMetric statsDMetric, isMonotonicCounter bool) pmetric.ScopeMetrics { ilm := pmetric.NewScopeMetrics() diff --git a/receiver/statsdreceiver/internal/protocol/statsd_parser.go b/receiver/statsdreceiver/internal/protocol/statsd_parser.go index 8a2ad5237c77..ad8f6904792b 100644 --- a/receiver/statsdreceiver/internal/protocol/statsd_parser.go +++ b/receiver/statsdreceiver/internal/protocol/statsd_parser.go @@ -398,7 +398,7 @@ func parseMessageToMetric(line string, enableMetricType bool, enableSimpleTags b result.addition = true } - var metricType, additionalParts, _ = strings.Cut(rest, "|") + metricType, additionalParts, _ := strings.Cut(rest, "|") inType := MetricType(metricType) switch inType { case CounterType, GaugeType, HistogramType, TimingType, DistributionType: @@ -423,7 +423,7 @@ func parseMessageToMetric(line string, enableMetricType bool, enableSimpleTags b result.sampleRate = f case strings.HasPrefix(part, "#"): - var tagsStr = strings.TrimPrefix(part, "#") + tagsStr := strings.TrimPrefix(part, "#") // handle an empty tag set // where the tags part was still sent (some clients do this) diff --git a/receiver/statsdreceiver/receiver_test.go b/receiver/statsdreceiver/receiver_test.go index d4749c798f4c..11a12d9d951e 100644 --- a/receiver/statsdreceiver/receiver_test.go +++ b/receiver/statsdreceiver/receiver_test.go @@ -75,7 +75,7 @@ func TestStatsdReceiver_Flush(t *testing.T) { rcv, err := newReceiver(receivertest.NewNopSettings(), *cfg, nextConsumer) assert.NoError(t, err) r := rcv.(*statsdReceiver) - var metrics = pmetric.NewMetrics() + metrics := pmetric.NewMetrics() assert.NoError(t, r.Flush(ctx, metrics, nextConsumer)) assert.NoError(t, r.Start(ctx, componenttest.NewNopHost())) assert.NoError(t, r.Shutdown(ctx)) diff --git a/receiver/systemdreceiver/receiver.go b/receiver/systemdreceiver/receiver.go index ad21a0766210..02c2015552ad 100644 --- a/receiver/systemdreceiver/receiver.go +++ b/receiver/systemdreceiver/receiver.go @@ -8,8 +8,7 @@ import ( "go.opentelemetry.io/collector/component" ) -type systemdReceiver struct { -} +type systemdReceiver struct{} func (s systemdReceiver) Start(_ context.Context, _ component.Host) error { return nil diff --git a/receiver/tlscheckreceiver/factory.go b/receiver/tlscheckreceiver/factory.go index bc99c145abf7..5501c67ea042 100644 --- a/receiver/tlscheckreceiver/factory.go +++ b/receiver/tlscheckreceiver/factory.go @@ -15,9 +15,7 @@ import ( "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/tlscheckreceiver/internal/metadata" ) -var ( - errConfigNotTLSCheck = errors.New(`invalid config`) -) +var errConfigNotTLSCheck = errors.New(`invalid config`) // NewFactory creates a new filestats receiver factory. func NewFactory() receiver.Factory { diff --git a/receiver/vcenterreceiver/internal/mockserver/client_mock.go b/receiver/vcenterreceiver/internal/mockserver/client_mock.go index e28fe96a9207..5af34c9d2940 100644 --- a/receiver/vcenterreceiver/internal/mockserver/client_mock.go +++ b/receiver/vcenterreceiver/internal/mockserver/client_mock.go @@ -96,7 +96,7 @@ func routeRetreivePropertiesEx(t *testing.T, body map[string]any) ([]byte, error require.True(t, ok) specSet := rp["specSet"].(map[string]any) - var objectSetArray = false + objectSetArray := false objectSet, ok := specSet["objectSet"].(map[string]any) if !ok { objectSetArray = true diff --git a/receiver/vcenterreceiver/scraper.go b/receiver/vcenterreceiver/scraper.go index e4b4bae52f37..4268039f4ee2 100644 --- a/receiver/vcenterreceiver/scraper.go +++ b/receiver/vcenterreceiver/scraper.go @@ -96,9 +96,11 @@ func (v *vcenterMetricScraper) Start(ctx context.Context, _ component.Host) erro } return nil } + func (v *vcenterMetricScraper) Shutdown(ctx context.Context) error { return v.client.Disconnect(ctx) } + func (v *vcenterMetricScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { if v.client == nil { v.client = newVcenterClient(v.logger, v.config) diff --git a/receiver/wavefrontreceiver/wavefront_parser.go b/receiver/wavefrontreceiver/wavefront_parser.go index 7cc76eb8e8a8..7d4d412f5901 100644 --- a/receiver/wavefrontreceiver/wavefront_parser.go +++ b/receiver/wavefrontreceiver/wavefront_parser.go @@ -24,8 +24,10 @@ type WavefrontParser struct { ExtractCollectdTags bool `mapstructure:"extract_collectd_tags"` } -var _ protocol.Parser = (*WavefrontParser)(nil) -var _ protocol.ParserConfig = (*WavefrontParser)(nil) +var ( + _ protocol.Parser = (*WavefrontParser)(nil) + _ protocol.ParserConfig = (*WavefrontParser)(nil) +) // Only two chars can be espcaped per Wavafront SDK, see // https://github.com/wavefrontHQ/wavefront-sdk-go/blob/2c5891318fcd83c35c93bba2b411640495473333/senders/formatter.go#L20 diff --git a/receiver/webhookeventreceiver/receiver.go b/receiver/webhookeventreceiver/receiver.go index e8affb9088de..c8006dd2cd17 100644 --- a/receiver/webhookeventreceiver/receiver.go +++ b/receiver/webhookeventreceiver/receiver.go @@ -65,7 +65,6 @@ func newLogsReceiver(params receiver.Settings, cfg Config, consumer consumer.Log Transport: transport, ReceiverCreateSettings: params, }) - if err != nil { return nil, err } @@ -180,7 +179,6 @@ func (er *eventReceiver) handleReq(w http.ResponseWriter, r *http.Request, _ htt if encoding == "gzip" || encoding == "x-gzip" { reader := er.gzipPool.Get().(*gzip.Reader) err := reader.Reset(bodyReader) - if err != nil { er.failBadReq(ctx, w, http.StatusBadRequest, err) _, _ = io.ReadAll(r.Body) @@ -220,7 +218,8 @@ func (er *eventReceiver) handleHealthCheck(w http.ResponseWriter, _ *http.Reques func (er *eventReceiver) failBadReq(_ context.Context, w http.ResponseWriter, httpStatusCode int, - err error) { + err error, +) { jsonResp, err := jsoniter.Marshal(err.Error()) if err != nil { er.settings.Logger.Warn("failed to marshall error to json") diff --git a/receiver/webhookeventreceiver/req_to_log.go b/receiver/webhookeventreceiver/req_to_log.go index 5a8ceb13ddeb..18d419c3ef50 100644 --- a/receiver/webhookeventreceiver/req_to_log.go +++ b/receiver/webhookeventreceiver/req_to_log.go @@ -18,7 +18,8 @@ import ( func reqToLog(sc *bufio.Scanner, query url.Values, _ *Config, - settings receiver.Settings) (plog.Logs, int) { + settings receiver.Settings, +) (plog.Logs, int) { // we simply dont split the data passed into scan (i.e. scan the whole thing) // the downside to this approach is that only 1 log per request can be handled. // NOTE: logs will contain these newline characters which could have formatting diff --git a/receiver/windowsperfcountersreceiver/config.go b/receiver/windowsperfcountersreceiver/config.go index a6b865fe7cd5..2bf596a4267d 100644 --- a/receiver/windowsperfcountersreceiver/config.go +++ b/receiver/windowsperfcountersreceiver/config.go @@ -26,8 +26,7 @@ type MetricConfig struct { Sum SumMetric `mapstructure:"sum"` } -type GaugeMetric struct { -} +type GaugeMetric struct{} type SumMetric struct { Aggregation string `mapstructure:"aggregation"` diff --git a/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper.go b/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper.go index 7886d5238a2c..229a48a2a89e 100644 --- a/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper.go +++ b/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper.go @@ -179,7 +179,8 @@ func (s *scraper) scrape(context.Context) (pmetric.Metrics, error) { } func initializeMetricDps(metric pmetric.Metric, now pcommon.Timestamp, counterValue winperfcounters.CounterValue, - attributes map[string]string) { + attributes map[string]string, +) { var dps pmetric.NumberDataPointSlice if metric.Type() == pmetric.MetricTypeGauge { diff --git a/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper_test.go b/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper_test.go index b7e2ce005235..068359acfdc7 100644 --- a/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper_test.go +++ b/receiver/windowsperfcountersreceiver/windowsperfcounters_scraper_test.go @@ -531,7 +531,6 @@ func TestScrape(t *testing.T) { curMetricsNum := 0 for _, pc := range test.cfg.PerfCounters { - for counterIdx, counterCfg := range pc.Counters { counterValues := test.mockPerfCounters[counterIdx].counterValues scrapeErr := test.mockPerfCounters[counterIdx].scrapeErr diff --git a/receiver/zipkinreceiver/trace_receiver.go b/receiver/zipkinreceiver/trace_receiver.go index 23c77a186d4b..c3f5ceffc547 100644 --- a/receiver/zipkinreceiver/trace_receiver.go +++ b/receiver/zipkinreceiver/trace_receiver.go @@ -33,8 +33,10 @@ const ( receiverTransportV2PROTO = "http_v2_proto" ) -var errNextConsumerRespBody = []byte(`"Internal Server Error"`) -var errBadRequestRespBody = []byte(`"Bad Request"`) +var ( + errNextConsumerRespBody = []byte(`"Internal Server Error"`) + errBadRequestRespBody = []byte(`"Bad Request"`) +) // zipkinReceiver type is used to handle spans received in the Zipkin format. type zipkinReceiver struct { diff --git a/receiver/zookeeperreceiver/scraper.go b/receiver/zookeeperreceiver/scraper.go index 44bbf5ae1b51..4cec4adaca32 100644 --- a/receiver/zookeeperreceiver/scraper.go +++ b/receiver/zookeeperreceiver/scraper.go @@ -95,7 +95,6 @@ func (z *zookeeperMetricsScraper) scrape(ctx context.Context) (pmetric.Metrics, func (z *zookeeperMetricsScraper) runCommand(ctx context.Context, command string) ([]string, error) { conn, err := z.config.Dial(context.Background()) - if err != nil { z.logger.Error("failed to establish connection", zap.String("endpoint", z.config.Endpoint),