diff --git a/receiver/hostmetricsreceiver/config.go b/receiver/hostmetricsreceiver/config.go index 33a9e576fb4a..04412bc6fbfe 100644 --- a/receiver/hostmetricsreceiver/config.go +++ b/receiver/hostmetricsreceiver/config.go @@ -85,8 +85,6 @@ func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error { } scraperCfg.SetRootPath(cfg.RootPath) - envMap := setGoPsutilEnvVars(cfg.RootPath, &osEnv{}) - scraperCfg.SetEnvMap(envMap) cfg.Scrapers[key] = scraperCfg } diff --git a/receiver/hostmetricsreceiver/config_test.go b/receiver/hostmetricsreceiver/config_test.go index 6546ff5dac06..8c9e228eaa2b 100644 --- a/receiver/hostmetricsreceiver/config_test.go +++ b/receiver/hostmetricsreceiver/config_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" @@ -47,7 +46,6 @@ func TestLoadConfig(t *testing.T) { cfg.Scrapers = map[component.Type]internal.Config{ cpuscraper.Type: func() internal.Config { cfg := (&cpuscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), } @@ -65,28 +63,23 @@ func TestLoadConfig(t *testing.T) { Scrapers: map[component.Type]internal.Config{ cpuscraper.Type: func() internal.Config { cfg := (&cpuscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), diskscraper.Type: func() internal.Config { cfg := (&diskscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), loadscraper.Type: (func() internal.Config { cfg := (&loadscraper.Factory{}).CreateDefaultConfig() cfg.(*loadscraper.Config).CPUAverage = true - cfg.SetEnvMap(common.EnvMap{}) return cfg })(), filesystemscraper.Type: func() internal.Config { cfg := (&filesystemscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), memoryscraper.Type: func() internal.Config { cfg := (&memoryscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), networkscraper.Type: (func() internal.Config { @@ -95,17 +88,14 @@ func TestLoadConfig(t *testing.T) { Interfaces: []string{"test1"}, Config: filterset.Config{MatchType: "strict"}, } - cfg.SetEnvMap(common.EnvMap{}) return cfg })(), processesscraper.Type: func() internal.Config { cfg := (&processesscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), pagingscraper.Type: func() internal.Config { cfg := (&pagingscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg }(), processscraper.Type: (func() internal.Config { @@ -114,12 +104,10 @@ func TestLoadConfig(t *testing.T) { Names: []string{"test2", "test3"}, Config: filterset.Config{MatchType: "regexp"}, } - cfg.SetEnvMap(common.EnvMap{}) return cfg })(), systemscraper.Type: (func() internal.Config { cfg := (&systemscraper.Factory{}).CreateDefaultConfig() - cfg.SetEnvMap(common.EnvMap{}) return cfg })(), }, diff --git a/receiver/hostmetricsreceiver/factory.go b/receiver/hostmetricsreceiver/factory.go index 7d3cecae62f0..8efe4c907527 100644 --- a/receiver/hostmetricsreceiver/factory.go +++ b/receiver/hostmetricsreceiver/factory.go @@ -6,7 +6,6 @@ package hostmetricsreceiver // import "github.com/open-telemetry/opentelemetry-c import ( "context" "fmt" - "os" "time" "github.com/shirou/gopsutil/v4/host" @@ -106,19 +105,22 @@ func createLogsReceiver( func createAddScraperOptions( ctx context.Context, set receiver.Settings, - config *Config, + cfg *Config, factories map[component.Type]internal.ScraperFactory, ) ([]scraperhelper.ScraperControllerOption, error) { - scraperControllerOptions := make([]scraperhelper.ScraperControllerOption, 0, len(config.Scrapers)) + scraperControllerOptions := make([]scraperhelper.ScraperControllerOption, 0, len(cfg.Scrapers)) - for key, cfg := range config.Scrapers { - hostMetricsScraper, ok, err := createHostMetricsScraper(ctx, set, key, cfg, factories) + envMap := setGoPsutilEnvVars(cfg.RootPath) + + for key, cfg := range cfg.Scrapers { + scrp, ok, err := createHostMetricsScraper(ctx, set, key, cfg, factories) if err != nil { return nil, fmt.Errorf("failed to create scraper for key %q: %w", key, err) } if ok { - scraperControllerOptions = append(scraperControllerOptions, scraperhelper.AddScraper(metadata.Type, hostMetricsScraper)) + scrp = internal.NewEnvVarScraper(scrp, envMap) + scraperControllerOptions = append(scraperControllerOptions, scraperhelper.AddScraper(metadata.Type, scrp)) continue } @@ -139,15 +141,3 @@ func createHostMetricsScraper(ctx context.Context, set receiver.Settings, key co s, err = factory.CreateMetricsScraper(ctx, set, cfg) return } - -type environment interface { - Lookup(k string) (string, bool) -} - -type osEnv struct{} - -var _ environment = (*osEnv)(nil) - -func (e *osEnv) Lookup(k string) (string, bool) { - return os.LookupEnv(k) -} diff --git a/receiver/hostmetricsreceiver/hostmetrics_linux.go b/receiver/hostmetricsreceiver/hostmetrics_linux.go index 43b83fcea692..866b62069f53 100644 --- a/receiver/hostmetricsreceiver/hostmetrics_linux.go +++ b/receiver/hostmetricsreceiver/hostmetrics_linux.go @@ -44,14 +44,14 @@ func validateRootPath(rootPath string) error { return nil } -func setGoPsutilEnvVars(rootPath string, env environment) common.EnvMap { +func setGoPsutilEnvVars(rootPath string) common.EnvMap { m := common.EnvMap{} if rootPath == "" || rootPath == "/" { return m } for envVarKey, defaultValue := range gopsutilEnvVars { - _, ok := env.Lookup(string(envVarKey)) + _, ok := os.LookupEnv(string(envVarKey)) if ok { continue // don't override if existing env var is set } diff --git a/receiver/hostmetricsreceiver/hostmetrics_linux_test.go b/receiver/hostmetricsreceiver/hostmetrics_linux_test.go index 814d62ebcc95..7722e0bd2b12 100644 --- a/receiver/hostmetricsreceiver/hostmetrics_linux_test.go +++ b/receiver/hostmetricsreceiver/hostmetrics_linux_test.go @@ -46,16 +46,16 @@ func TestLoadConfigRootPath(t *testing.T) { expectedConfig.RootPath = "testdata" cpuScraperCfg := (&cpuscraper.Factory{}).CreateDefaultConfig() cpuScraperCfg.SetRootPath("testdata") - cpuScraperCfg.SetEnvMap(common.EnvMap{ + expectedConfig.Scrapers = map[component.Type]internal.Config{cpuscraper.Type: cpuScraperCfg} + assert.Equal(t, expectedConfig, cfg) + expectedEnvMap := common.EnvMap{ common.HostDevEnvKey: "testdata/dev", common.HostEtcEnvKey: "testdata/etc", common.HostRunEnvKey: "testdata/run", common.HostSysEnvKey: "testdata/sys", common.HostVarEnvKey: "testdata/var", - }) - expectedConfig.Scrapers = map[component.Type]internal.Config{cpuscraper.Type: cpuScraperCfg} - - assert.Equal(t, expectedConfig, cfg) + } + assert.Equal(t, expectedEnvMap, setGoPsutilEnvVars("testdata")) } func TestLoadInvalidConfig_RootPathNotExist(t *testing.T) { diff --git a/receiver/hostmetricsreceiver/hostmetrics_others.go b/receiver/hostmetricsreceiver/hostmetrics_others.go index c7b34190967c..161dc6e51efa 100644 --- a/receiver/hostmetricsreceiver/hostmetrics_others.go +++ b/receiver/hostmetricsreceiver/hostmetrics_others.go @@ -18,6 +18,6 @@ func validateRootPath(rootPath string) error { return fmt.Errorf("root_path is supported on linux only") } -func setGoPsutilEnvVars(_ string, _ environment) common.EnvMap { +func setGoPsutilEnvVars(_ string) common.EnvMap { return common.EnvMap{} } diff --git a/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go b/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go index 02768160ff68..6c58e81dc063 100644 --- a/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go +++ b/receiver/hostmetricsreceiver/hostmetrics_receiver_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/collector/component" @@ -72,22 +71,6 @@ var systemSpecificMetrics = map[string][]string{ "solaris": {"system.filesystem.inodes.usage", "system.paging.faults"}, } -type testEnv struct { - env map[string]string -} - -var _ environment = (*testEnv)(nil) - -func (e *testEnv) Lookup(k string) (string, bool) { - v, ok := e.env[k] - return v, ok -} - -func (e *testEnv) Set(k, v string) error { - e.env[k] = v - return nil -} - func TestGatherMetrics_EndToEnd(t *testing.T) { sink := new(consumertest.MetricsSink) @@ -205,8 +188,6 @@ type mockConfig struct{} func (m *mockConfig) SetRootPath(_ string) {} -func (m *mockConfig) SetEnvMap(_ common.EnvMap) {} - type errFactory struct{} func (m *errFactory) CreateDefaultConfig() internal.Config { return &mockConfig{} } @@ -221,9 +202,8 @@ func TestGatherMetrics_ScraperKeyConfigError(t *testing.T) { scraperFactories = tmp }() - sink := new(consumertest.MetricsSink) cfg := &Config{Scrapers: map[component.Type]internal.Config{component.MustNewType("error"): &mockConfig{}}} - _, err := NewFactory().CreateMetrics(context.Background(), creationSet, cfg, sink) + _, err := NewFactory().CreateMetrics(context.Background(), creationSet, cfg, consumertest.NewNop()) require.Error(t, err) } @@ -235,9 +215,8 @@ func TestGatherMetrics_CreateMetricsScraperError(t *testing.T) { scraperFactories = tmp }() - sink := new(consumertest.MetricsSink) cfg := &Config{Scrapers: map[component.Type]internal.Config{mockType: &mockConfig{}}} - _, err := NewFactory().CreateMetrics(context.Background(), creationSet, cfg, sink) + _, err := NewFactory().CreateMetrics(context.Background(), creationSet, cfg, consumertest.NewNop()) require.Error(t, err) } diff --git a/receiver/hostmetricsreceiver/integration_test.go b/receiver/hostmetricsreceiver/integration_test.go index ec4a2de201f1..9e765e3714f7 100644 --- a/receiver/hostmetricsreceiver/integration_test.go +++ b/receiver/hostmetricsreceiver/integration_test.go @@ -72,7 +72,6 @@ func Test_ProcessScrapeWithCustomRootPath(t *testing.T) { rCfg.RootPath = rootPath pCfg := (&processscraper.Factory{}).CreateDefaultConfig().(*processscraper.Config) pCfg.SetRootPath(rootPath) - pCfg.SetEnvMap(setGoPsutilEnvVars(rootPath, &osEnv{})) rCfg.Scrapers = map[component.Type]internal.Config{ processscraper.Type: pCfg, } @@ -102,7 +101,6 @@ func Test_ProcessScrapeWithBadRootPathAndEnvVar(t *testing.T) { rCfg.CollectionInterval = time.Second pCfg := (&processscraper.Factory{}).CreateDefaultConfig().(*processscraper.Config) pCfg.SetRootPath(badRootPath) - pCfg.SetEnvMap(setGoPsutilEnvVars(badRootPath, &osEnv{})) rCfg.Scrapers = map[component.Type]internal.Config{ processscraper.Type: pCfg, } diff --git a/receiver/hostmetricsreceiver/internal/scraper.go b/receiver/hostmetricsreceiver/internal/scraper.go index d5ff2c376401..7cbb8872df32 100644 --- a/receiver/hostmetricsreceiver/internal/scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper.go @@ -7,6 +7,8 @@ import ( "context" "github.com/shirou/gopsutil/v4/common" + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/pdata/pmetric" "go.opentelemetry.io/collector/receiver" "go.opentelemetry.io/collector/scraper" ) @@ -24,18 +26,36 @@ type ScraperFactory interface { // Config is the configuration of a scraper. type Config interface { SetRootPath(rootPath string) - SetEnvMap(envMap common.EnvMap) } type ScraperConfig struct { - RootPath string `mapstructure:"-"` - EnvMap common.EnvMap `mapstructure:"-"` + RootPath string `mapstructure:"-"` } func (p *ScraperConfig) SetRootPath(rootPath string) { p.RootPath = rootPath } -func (p *ScraperConfig) SetEnvMap(envMap common.EnvMap) { - p.EnvMap = envMap +type EnvVarScraper struct { + delegate scraper.Metrics + envMap common.EnvMap +} + +func NewEnvVarScraper(delegate scraper.Metrics, envMap common.EnvMap) scraper.Metrics { + return &EnvVarScraper{delegate: delegate, envMap: envMap} +} + +func (evs *EnvVarScraper) Start(ctx context.Context, host component.Host) error { + ctx = context.WithValue(ctx, common.EnvKey, evs.envMap) + return evs.delegate.Start(ctx, host) +} + +func (evs *EnvVarScraper) ScrapeMetrics(ctx context.Context) (pmetric.Metrics, error) { + ctx = context.WithValue(ctx, common.EnvKey, evs.envMap) + return evs.delegate.ScrapeMetrics(ctx) +} + +func (evs *EnvVarScraper) Shutdown(ctx context.Context) error { + ctx = context.WithValue(ctx, common.EnvKey, evs.envMap) + return evs.delegate.Shutdown(ctx) } diff --git a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go index 09dda75ffe9e..3fdec1d8dcb7 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/cpu_scraper.go @@ -8,7 +8,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/host" "go.opentelemetry.io/collector/component" @@ -50,7 +49,6 @@ func newCPUScraper(_ context.Context, settings receiver.Settings, cfg *Config) * } func (s *cpuScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -60,7 +58,6 @@ func (s *cpuScraper) start(ctx context.Context, _ component.Host) error { } func (s *cpuScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) now := pcommon.NewTimestampFromTime(s.now()) cpuTimes, err := s.times(ctx, true /*percpu=*/) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/diskscraper/disk_scraper_others.go b/receiver/hostmetricsreceiver/internal/scraper/diskscraper/disk_scraper_others.go index a3b7d505ff2b..5fac6c5d0eab 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/diskscraper/disk_scraper_others.go +++ b/receiver/hostmetricsreceiver/internal/scraper/diskscraper/disk_scraper_others.go @@ -10,7 +10,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/disk" "github.com/shirou/gopsutil/v4/host" "go.opentelemetry.io/collector/component" @@ -66,7 +65,6 @@ func newDiskScraper(_ context.Context, settings receiver.Settings, cfg *Config) } func (s *diskScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -78,8 +76,6 @@ func (s *diskScraper) start(ctx context.Context, _ component.Host) error { } func (s *diskScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) - now := pcommon.NewTimestampFromTime(time.Now()) ioCounters, err := s.ioCounters(ctx) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper.go index 2f543cce920f..0304b3ab9289 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper.go @@ -58,7 +58,6 @@ func newFileSystemScraper(_ context.Context, settings receiver.Settings, cfg *Co } func (s *filesystemsScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -69,7 +68,6 @@ func (s *filesystemsScraper) start(ctx context.Context, _ component.Host) error } func (s *filesystemsScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) now := pcommon.NewTimestampFromTime(time.Now()) var errors scrapererror.ScrapeErrors diff --git a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go index f4b3b9471a36..8143102f3d07 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper/filesystem_scraper_test.go @@ -391,9 +391,9 @@ func TestScrape(t *testing.T) { for k, v := range test.osEnv { envMap[k] = v } - test.config.EnvMap = envMap + ctx := context.WithValue(context.Background(), common.EnvKey, envMap) test.config.SetRootPath(test.rootPath) - scraper, err := newFileSystemScraper(context.Background(), receivertest.NewNopSettings(), &test.config) + scraper, err := newFileSystemScraper(ctx, receivertest.NewNopSettings(), &test.config) if test.newErrRegex != "" { require.Error(t, err) require.Regexp(t, test.newErrRegex, err) @@ -411,14 +411,14 @@ func TestScrape(t *testing.T) { scraper.bootTime = test.bootTimeFunc } - err = scraper.start(context.Background(), componenttest.NewNopHost()) + err = scraper.start(ctx, componenttest.NewNopHost()) if test.initializationErr != "" { assert.EqualError(t, err, test.initializationErr) return } require.NoError(t, err, "Failed to initialize file system scraper: %v", err) - md, err := scraper.scrape(context.Background()) + md, err := scraper.scrape(ctx) if test.expectedErr != "" { assert.ErrorContains(t, err, test.expectedErr) diff --git a/receiver/hostmetricsreceiver/internal/scraper/loadscraper/load_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/loadscraper/load_scraper.go index 7aaf3894e0a2..c24113eb7327 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/loadscraper/load_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/loadscraper/load_scraper.go @@ -9,7 +9,6 @@ import ( "runtime" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/load" "go.opentelemetry.io/collector/component" @@ -44,7 +43,6 @@ func newLoadScraper(_ context.Context, settings receiver.Settings, cfg *Config) // start func (s *loadScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -85,7 +83,6 @@ func (s *loadScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { } now := pcommon.NewTimestampFromTime(time.Now()) - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) avgLoadValues, err := s.load(ctx) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/memory_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/memory_scraper.go index ef93613edbea..bacd792c8bc1 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/memory_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/memoryscraper/memory_scraper.go @@ -9,7 +9,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/mem" "go.opentelemetry.io/collector/component" @@ -30,7 +29,6 @@ type memoryScraper struct { settings receiver.Settings config *Config mb *metadata.MetricsBuilder - envMap common.EnvMap // for mocking gopsutil mem.VirtualMemory bootTime func(context.Context) (uint64, error) @@ -43,7 +41,6 @@ func newMemoryScraper(_ context.Context, settings receiver.Settings, cfg *Config } func (s *memoryScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.envMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -58,8 +55,6 @@ func (s *memoryScraper) recordMemoryLimitMetric(now pcommon.Timestamp, memInfo * } func (s *memoryScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { - ctx = context.WithValue(ctx, common.EnvKey, s.envMap) - now := pcommon.NewTimestampFromTime(time.Now()) memInfo, err := s.virtualMemory(ctx) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_linux.go b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_linux.go index 20361cb70d27..7870741df98a 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_linux.go +++ b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_linux.go @@ -10,7 +10,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "go.opentelemetry.io/collector/pdata/pcommon" ) @@ -29,11 +28,10 @@ var allTCPStates = []string{ "TIME_WAIT", } -func (s *networkScraper) recordNetworkConntrackMetrics() error { +func (s *networkScraper) recordNetworkConntrackMetrics(ctx context.Context) error { if !s.config.MetricsBuilderConfig.Metrics.SystemNetworkConntrackCount.Enabled && !s.config.MetricsBuilderConfig.Metrics.SystemNetworkConntrackMax.Enabled { return nil } - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) now := pcommon.NewTimestampFromTime(time.Now()) conntrack, err := s.conntrack(ctx) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_others.go b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_others.go index 5d2f6575f527..a24fb6ae7e9e 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_others.go +++ b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_others.go @@ -4,6 +4,9 @@ //go:build !linux package networkscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/networkscraper" +import ( + "context" +) var allTCPStates = []string{ "CLOSE_WAIT", @@ -20,6 +23,6 @@ var allTCPStates = []string{ "TIME_WAIT", } -func (s *networkScraper) recordNetworkConntrackMetrics() error { +func (s *networkScraper) recordNetworkConntrackMetrics(context.Context) error { return nil } diff --git a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_scraper.go index 7c8627c57c49..c3d06bcb16fc 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/networkscraper/network_scraper.go @@ -8,7 +8,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/net" "go.opentelemetry.io/collector/component" @@ -73,7 +72,6 @@ func newNetworkScraper(_ context.Context, settings receiver.Settings, cfg *Confi } func (s *networkScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -84,20 +82,20 @@ func (s *networkScraper) start(ctx context.Context, _ component.Host) error { return nil } -func (s *networkScraper) scrape(_ context.Context) (pmetric.Metrics, error) { +func (s *networkScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { var errors scrapererror.ScrapeErrors - err := s.recordNetworkCounterMetrics() + err := s.recordNetworkCounterMetrics(ctx) if err != nil { errors.AddPartial(networkMetricsLen, err) } - err = s.recordNetworkConnectionsMetrics() + err = s.recordNetworkConnectionsMetrics(ctx) if err != nil { errors.AddPartial(connectionsMetricsLen, err) } - err = s.recordNetworkConntrackMetrics() + err = s.recordNetworkConntrackMetrics(ctx) if err != nil { errors.AddPartial(connectionsMetricsLen, err) } @@ -105,8 +103,7 @@ func (s *networkScraper) scrape(_ context.Context) (pmetric.Metrics, error) { return s.mb.Emit(), errors.Combine() } -func (s *networkScraper) recordNetworkCounterMetrics() error { - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) +func (s *networkScraper) recordNetworkCounterMetrics(ctx context.Context) error { now := pcommon.NewTimestampFromTime(time.Now()) // get total stats only @@ -156,12 +153,11 @@ func (s *networkScraper) recordNetworkIOMetric(now pcommon.Timestamp, ioCounters } } -func (s *networkScraper) recordNetworkConnectionsMetrics() error { +func (s *networkScraper) recordNetworkConnectionsMetrics(ctx context.Context) error { if !s.config.Metrics.SystemNetworkConnections.Enabled { return nil } - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) now := pcommon.NewTimestampFromTime(time.Now()) connections, err := s.connections(ctx, "tcp") diff --git a/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/paging_scraper_others.go b/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/paging_scraper_others.go index 26feb5f91a3d..5baebcd4b6da 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/paging_scraper_others.go +++ b/receiver/hostmetricsreceiver/internal/scraper/pagingscraper/paging_scraper_others.go @@ -10,7 +10,6 @@ import ( "fmt" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/mem" "go.opentelemetry.io/collector/component" @@ -51,7 +50,6 @@ func newPagingScraper(_ context.Context, settings receiver.Settings, cfg *Config } func (s *pagingScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -61,7 +59,7 @@ func (s *pagingScraper) start(ctx context.Context, _ component.Host) error { return nil } -func (s *pagingScraper) scrape(_ context.Context) (pmetric.Metrics, error) { +func (s *pagingScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { var errors scrapererror.ScrapeErrors err := s.scrapePagingUsageMetric() @@ -69,7 +67,7 @@ func (s *pagingScraper) scrape(_ context.Context) (pmetric.Metrics, error) { errors.AddPartial(pagingUsageMetricsLen, err) } - err = s.scrapePagingMetrics() + err = s.scrapePagingMetrics(ctx) if err != nil { errors.AddPartial(pagingMetricsLen, err) } @@ -109,8 +107,7 @@ func (s *pagingScraper) recordPagingUtilizationDataPoints(now pcommon.Timestamp, } } -func (s *pagingScraper) scrapePagingMetrics() error { - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) +func (s *pagingScraper) scrapePagingMetrics(ctx context.Context) error { now := pcommon.NewTimestampFromTime(time.Now()) swap, err := s.swapMemory(ctx) if err != nil { diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper.go index 6b17e407d5d6..e2d125c992ae 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper.go @@ -7,7 +7,6 @@ import ( "context" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/load" "github.com/shirou/gopsutil/v4/process" @@ -39,7 +38,7 @@ type processesScraper struct { // for mocking gopsutil getMiscStats func(context.Context) (*load.MiscStat, error) - getProcesses func() ([]proc, error) + getProcesses func(context.Context) ([]proc, error) bootTime func(context.Context) (uint64, error) } @@ -59,8 +58,7 @@ func newProcessesScraper(_ context.Context, settings receiver.Settings, cfg *Con settings: settings, config: cfg, getMiscStats: load.MiscWithContext, - getProcesses: func() ([]proc, error) { - ctx := context.WithValue(context.Background(), common.EnvKey, cfg.EnvMap) + getProcesses: func(ctx context.Context) ([]proc, error) { ps, err := process.ProcessesWithContext(ctx) ret := make([]proc, len(ps)) for i := range ps { @@ -73,7 +71,6 @@ func newProcessesScraper(_ context.Context, settings receiver.Settings, cfg *Con } func (s *processesScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -83,14 +80,14 @@ func (s *processesScraper) start(ctx context.Context, _ component.Host) error { return nil } -func (s *processesScraper) scrape(_ context.Context) (pmetric.Metrics, error) { +func (s *processesScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { now := pcommon.NewTimestampFromTime(time.Now()) md := pmetric.NewMetrics() metrics := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics() metrics.EnsureCapacity(metricsLength) - processMetadata, err := s.getProcessesMetadata() + processMetadata, err := s.getProcessesMetadata(ctx) if err != nil { return pmetric.NewMetrics(), scrapererror.NewPartialScrapeError(err, metricsLength) } diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go index f0c5a0ee325e..2aca055f3963 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_fallback.go @@ -5,11 +5,15 @@ package processesscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processesscraper" +import ( + "context" +) + const ( enableProcessesCount = false enableProcessesCreated = false ) -func (s *processesScraper) getProcessesMetadata() (processesMetadata, error) { +func (s *processesScraper) getProcessesMetadata(context.Context) (processesMetadata, error) { return processesMetadata{}, nil } diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_test.go index b306d93f8167..32109918a752 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_test.go @@ -33,7 +33,7 @@ func TestScrape(t *testing.T) { type testCase struct { name string getMiscStats func(context.Context) (*load.MiscStat, error) - getProcesses func() ([]proc, error) + getProcesses func(context.Context) ([]proc, error) expectedErr string validate func(*testing.T, pmetric.MetricSlice) } @@ -44,7 +44,7 @@ func TestScrape(t *testing.T) { }, { name: "FakeData", getMiscStats: func(context.Context) (*load.MiscStat, error) { return &fakeData, nil }, - getProcesses: func() ([]proc, error) { return fakeProcessesData, nil }, + getProcesses: func(context.Context) ([]proc, error) { return fakeProcessesData, nil }, validate: validateFakeData, }, { name: "ErrorFromMiscStat", @@ -52,11 +52,11 @@ func TestScrape(t *testing.T) { expectedErr: "err1", }, { name: "ErrorFromProcesses", - getProcesses: func() ([]proc, error) { return nil, errors.New("err2") }, + getProcesses: func(context.Context) ([]proc, error) { return nil, errors.New("err2") }, expectedErr: "err2", }, { name: "ErrorFromProcessShouldBeIgnored", - getProcesses: func() ([]proc, error) { return []proc{errProcess{}}, nil }, + getProcesses: func(context.Context) ([]proc, error) { return []proc{errProcess{}}, nil }, }, { name: "Validate Start Time", validate: validateStartTime, diff --git a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go index c9389ce5d62b..6e6a7b59cc81 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processesscraper/processes_scraper_unix.go @@ -9,7 +9,6 @@ import ( "context" "runtime" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/process" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processesscraper/internal/metadata" @@ -20,9 +19,8 @@ const ( enableProcessesCreated = runtime.GOOS == "openbsd" || runtime.GOOS == "linux" ) -func (s *processesScraper) getProcessesMetadata() (processesMetadata, error) { - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) - processes, err := s.getProcesses() +func (s *processesScraper) getProcessesMetadata(ctx context.Context) (processesMetadata, error) { + processes, err := s.getProcesses(ctx) if err != nil { return processesMetadata{}, err } diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go index 2631c9b7e551..6acad63b04ab 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper.go @@ -10,7 +10,6 @@ import ( "runtime" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/host" "github.com/shirou/gopsutil/v4/process" @@ -118,7 +117,7 @@ func (s *processScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { host.EnableBootTimeCache(true) } - data, err := s.getProcessMetadata() + data, err := s.getProcessMetadata(ctx) if err != nil { var partialErr scrapererror.PartialScrapeError if !errors.As(err, &partialErr) { @@ -129,7 +128,6 @@ func (s *processScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { } presentPIDs := make(map[int32]struct{}, len(data)) - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) for _, md := range data { presentPIDs[md.pid] = struct{}{} @@ -198,8 +196,7 @@ func (s *processScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { // for all currently running processes. If errors occur obtaining information // for some processes, an error will be returned, but any processes that were // successfully obtained will still be returned. -func (s *processScraper) getProcessMetadata() ([]*processMetadata, error) { - ctx := context.WithValue(context.Background(), common.EnvKey, s.config.EnvMap) +func (s *processScraper) getProcessMetadata(ctx context.Context) ([]*processMetadata, error) { handles, err := s.getProcessHandles(ctx) if err != nil { return nil, err diff --git a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go index a3d911e98256..0f398367f475 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go +++ b/receiver/hostmetricsreceiver/internal/scraper/processscraper/process_scraper_test.go @@ -90,7 +90,7 @@ func TestScrape(t *testing.T) { test.mutateMetricsConfig(t, &metricsBuilderConfig.Metrics) } cfg := &Config{MetricsBuilderConfig: metricsBuilderConfig} - cfg.EnvMap = common.EnvMap{ + envMap := common.EnvMap{ common.HostProcEnvKey: "/proc", common.HostSysEnvKey: "/sys", common.HostEtcEnvKey: "/etc", @@ -99,16 +99,17 @@ func TestScrape(t *testing.T) { common.HostDevEnvKey: "/dev", common.HostProcMountinfo: "", } + ctx := context.WithValue(context.Background(), common.EnvKey, envMap) scraper, err := newProcessScraper(receivertest.NewNopSettings(), cfg) if test.mutateScraper != nil { test.mutateScraper(scraper) } scraper.getProcessCreateTime = func(processHandle, context.Context) (int64, error) { return createTime, nil } require.NoError(t, err, "Failed to create process scraper: %v", err) - err = scraper.start(context.Background(), componenttest.NewNopHost()) + err = scraper.start(ctx, componenttest.NewNopHost()) require.NoError(t, err, "Failed to initialize process scraper: %v", err) - md, err := scraper.scrape(context.Background()) + md, err := scraper.scrape(ctx) // 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 diff --git a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper.go b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper.go index 36c6b98263c3..351f4030dcf4 100644 --- a/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper.go +++ b/receiver/hostmetricsreceiver/internal/scraper/systemscraper/system_scraper.go @@ -7,7 +7,6 @@ import ( "context" "time" - "github.com/shirou/gopsutil/v4/common" "github.com/shirou/gopsutil/v4/host" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/pdata/pcommon" @@ -34,7 +33,6 @@ func newUptimeScraper(_ context.Context, settings receiver.Settings, cfg *Config } func (s *systemsScraper) start(ctx context.Context, _ component.Host) error { - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) bootTime, err := s.bootTime(ctx) if err != nil { return err @@ -46,7 +44,6 @@ func (s *systemsScraper) start(ctx context.Context, _ component.Host) error { func (s *systemsScraper) scrape(ctx context.Context) (pmetric.Metrics, error) { now := pcommon.NewTimestampFromTime(time.Now()) - ctx = context.WithValue(ctx, common.EnvKey, s.config.EnvMap) uptime, err := s.uptime(ctx) if err != nil {