Skip to content

Commit 36fc426

Browse files
authored
[receiver/hostmetrics] Remove the need to set environment variables (#23861)
1 parent 57417bf commit 36fc426

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+313
-198
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Use this changelog template to create an entry for release notes.
2+
# If your change doesn't affect end users, such as a test fix or a tooling change,
3+
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
4+
5+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
6+
change_type: enhancement
7+
8+
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
9+
component: hostmetricsreceiver
10+
11+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
12+
note: Remove the need to set environment variables with hostmetricsreceiver
13+
14+
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
15+
issues: [23861]
16+
17+
# (Optional) One or more lines of additional information to render under the primary note.
18+
# These lines will be padded with 2 spaces and then inserted directly into the document.
19+
# Use pipe (|) for multiline entries.
20+
subtext:

receiver/hostmetricsreceiver/config.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func (cfg *Config) Validate() error {
3636
if len(cfg.Scrapers) == 0 {
3737
err = multierr.Append(err, errors.New("must specify at least one scraper when using hostmetrics receiver"))
3838
}
39-
err = multierr.Append(err, validateRootPath(cfg.RootPath, &osEnv{}))
39+
err = multierr.Append(err, validateRootPath(cfg.RootPath))
4040
return err
4141
}
4242

@@ -78,6 +78,8 @@ func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error {
7878
}
7979

8080
collectorCfg.SetRootPath(cfg.RootPath)
81+
envMap := setGoPsutilEnvVars(cfg.RootPath, &osEnv{})
82+
collectorCfg.SetEnvMap(envMap)
8183

8284
cfg.Scrapers[key] = collectorCfg
8385
}

receiver/hostmetricsreceiver/config_test.go

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"testing"
99
"time"
1010

11+
"github.com/shirou/gopsutil/v3/common"
1112
"github.com/stretchr/testify/assert"
1213
"github.com/stretchr/testify/require"
1314
"go.opentelemetry.io/collector/component"
@@ -44,7 +45,11 @@ func TestLoadConfig(t *testing.T) {
4445
r0 := cfg.Receivers[component.NewID(metadata.Type)]
4546
defaultConfigCPUScraper := factory.CreateDefaultConfig()
4647
defaultConfigCPUScraper.(*Config).Scrapers = map[string]internal.Config{
47-
cpuscraper.TypeStr: (&cpuscraper.Factory{}).CreateDefaultConfig(),
48+
cpuscraper.TypeStr: func() internal.Config {
49+
cfg := (&cpuscraper.Factory{}).CreateDefaultConfig()
50+
cfg.SetEnvMap(common.EnvMap{})
51+
return cfg
52+
}(),
4853
}
4954

5055
assert.Equal(t, defaultConfigCPUScraper, r0)
@@ -56,31 +61,58 @@ func TestLoadConfig(t *testing.T) {
5661
InitialDelay: time.Second,
5762
},
5863
Scrapers: map[string]internal.Config{
59-
cpuscraper.TypeStr: (&cpuscraper.Factory{}).CreateDefaultConfig(),
60-
diskscraper.TypeStr: (&diskscraper.Factory{}).CreateDefaultConfig(),
64+
cpuscraper.TypeStr: func() internal.Config {
65+
cfg := (&cpuscraper.Factory{}).CreateDefaultConfig()
66+
cfg.SetEnvMap(common.EnvMap{})
67+
return cfg
68+
}(),
69+
diskscraper.TypeStr: func() internal.Config {
70+
cfg := (&diskscraper.Factory{}).CreateDefaultConfig()
71+
cfg.SetEnvMap(common.EnvMap{})
72+
return cfg
73+
}(),
6174
loadscraper.TypeStr: (func() internal.Config {
6275
cfg := (&loadscraper.Factory{}).CreateDefaultConfig()
6376
cfg.(*loadscraper.Config).CPUAverage = true
77+
cfg.SetEnvMap(common.EnvMap{})
6478
return cfg
6579
})(),
66-
filesystemscraper.TypeStr: (&filesystemscraper.Factory{}).CreateDefaultConfig(),
67-
memoryscraper.TypeStr: (&memoryscraper.Factory{}).CreateDefaultConfig(),
80+
filesystemscraper.TypeStr: func() internal.Config {
81+
cfg := (&filesystemscraper.Factory{}).CreateDefaultConfig()
82+
cfg.SetEnvMap(common.EnvMap{})
83+
return cfg
84+
}(),
85+
memoryscraper.TypeStr: func() internal.Config {
86+
cfg := (&memoryscraper.Factory{}).CreateDefaultConfig()
87+
cfg.SetEnvMap(common.EnvMap{})
88+
return cfg
89+
}(),
6890
networkscraper.TypeStr: (func() internal.Config {
6991
cfg := (&networkscraper.Factory{}).CreateDefaultConfig()
7092
cfg.(*networkscraper.Config).Include = networkscraper.MatchConfig{
7193
Interfaces: []string{"test1"},
7294
Config: filterset.Config{MatchType: "strict"},
7395
}
96+
cfg.SetEnvMap(common.EnvMap{})
7497
return cfg
7598
})(),
76-
processesscraper.TypeStr: (&processesscraper.Factory{}).CreateDefaultConfig(),
77-
pagingscraper.TypeStr: (&pagingscraper.Factory{}).CreateDefaultConfig(),
99+
processesscraper.TypeStr: func() internal.Config {
100+
cfg := (&processesscraper.Factory{}).CreateDefaultConfig()
101+
cfg.SetEnvMap(common.EnvMap{})
102+
return cfg
103+
}(),
104+
pagingscraper.TypeStr: func() internal.Config {
105+
cfg := (&pagingscraper.Factory{}).CreateDefaultConfig()
106+
cfg.SetEnvMap(common.EnvMap{})
107+
return cfg
108+
}(),
78109
processscraper.TypeStr: (func() internal.Config {
79110
cfg := (&processscraper.Factory{}).CreateDefaultConfig()
80111
cfg.(*processscraper.Config).Include = processscraper.MatchConfig{
81112
Names: []string{"test2", "test3"},
82113
Config: filterset.Config{MatchType: "regexp"},
83114
}
115+
cfg.SetEnvMap(common.EnvMap{})
84116
return cfg
85117
})(),
86118
},

receiver/hostmetricsreceiver/factory.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,6 @@ func createMetricsReceiver(
7676
return nil, err
7777
}
7878

79-
if err = setGoPsutilEnvVars(oCfg.RootPath, &osEnv{}); err != nil {
80-
return nil, err
81-
}
82-
8379
return scraperhelper.NewScraperControllerReceiver(
8480
&oCfg.ScraperControllerSettings,
8581
set,

receiver/hostmetricsreceiver/hostmetrics_linux.go

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,25 @@ import (
99
"fmt"
1010
"os"
1111
"path/filepath"
12+
13+
"github.com/shirou/gopsutil/v3/common"
1214
)
1315

14-
var gopsutilEnvVars = map[string]string{
15-
"HOST_PROC": "/proc",
16-
"HOST_SYS": "/sys",
17-
"HOST_ETC": "/etc",
18-
"HOST_VAR": "/var",
19-
"HOST_RUN": "/run",
20-
"HOST_DEV": "/dev",
16+
var gopsutilEnvVars = map[common.EnvKeyType]string{
17+
common.HostProcEnvKey: "/proc",
18+
common.HostSysEnvKey: "/sys",
19+
common.HostEtcEnvKey: "/etc",
20+
common.HostVarEnvKey: "/var",
21+
common.HostRunEnvKey: "/run",
22+
common.HostDevEnvKey: "/dev",
2123
}
2224

2325
// This exists to validate that different instances of the hostmetricsreceiver do not
2426
// have inconsistent root_path configurations. The root_path is passed down to gopsutil
2527
// through env vars, so it must be consistent across the process.
2628
var globalRootPath string
2729

28-
func validateRootPath(rootPath string, _ environment) error {
30+
func validateRootPath(rootPath string) error {
2931
if rootPath == "" || rootPath == "/" {
3032
return nil
3133
}
@@ -42,19 +44,18 @@ func validateRootPath(rootPath string, _ environment) error {
4244
return nil
4345
}
4446

45-
func setGoPsutilEnvVars(rootPath string, env environment) error {
47+
func setGoPsutilEnvVars(rootPath string, env environment) common.EnvMap {
48+
m := common.EnvMap{}
4649
if rootPath == "" || rootPath == "/" {
47-
return nil
50+
return m
4851
}
4952

5053
for envVarKey, defaultValue := range gopsutilEnvVars {
51-
_, ok := env.Lookup(envVarKey)
54+
_, ok := env.Lookup(string(envVarKey))
5255
if ok {
5356
continue // don't override if existing env var is set
5457
}
55-
if err := env.Set(envVarKey, filepath.Join(rootPath, defaultValue)); err != nil {
56-
return err
57-
}
58+
m[envVarKey] = filepath.Join(rootPath, defaultValue)
5859
}
59-
return nil
60+
return m
6061
}

receiver/hostmetricsreceiver/hostmetrics_linux_test.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"path/filepath"
1010
"testing"
1111

12+
"github.com/shirou/gopsutil/v3/common"
1213
"github.com/stretchr/testify/assert"
1314
"github.com/stretchr/testify/require"
1415
"go.opentelemetry.io/collector/component"
@@ -20,16 +21,15 @@ import (
2021
)
2122

2223
func TestConsistentRootPaths(t *testing.T) {
23-
env := &testEnv{env: map[string]string{"HOST_PROC": "testdata"}}
2424
// use testdata because it's a directory that exists - don't actually use any files in it
25-
assert.Nil(t, testValidate("testdata", env))
26-
assert.Nil(t, testValidate("", env))
27-
assert.Nil(t, testValidate("/", env))
25+
assert.Nil(t, testValidate("testdata"))
26+
assert.Nil(t, testValidate(""))
27+
assert.Nil(t, testValidate("/"))
2828
}
2929

3030
func TestInconsistentRootPaths(t *testing.T) {
3131
globalRootPath = "foo"
32-
err := testValidate("testdata", &testEnv{})
32+
err := testValidate("testdata")
3333
assert.EqualError(t, err, "inconsistent root_path configuration detected between hostmetricsreceivers: `foo` != `testdata`")
3434
}
3535

@@ -47,6 +47,13 @@ func TestLoadConfigRootPath(t *testing.T) {
4747
expectedConfig.RootPath = "testdata"
4848
cpuScraperCfg := (&cpuscraper.Factory{}).CreateDefaultConfig()
4949
cpuScraperCfg.SetRootPath("testdata")
50+
cpuScraperCfg.SetEnvMap(common.EnvMap{
51+
common.HostDevEnvKey: "testdata/dev",
52+
common.HostEtcEnvKey: "testdata/etc",
53+
common.HostRunEnvKey: "testdata/run",
54+
common.HostSysEnvKey: "testdata/sys",
55+
common.HostVarEnvKey: "testdata/var",
56+
})
5057
expectedConfig.Scrapers = map[string]internal.Config{cpuscraper.TypeStr: cpuScraperCfg}
5158

5259
assert.Equal(t, expectedConfig, r)
@@ -61,8 +68,8 @@ func TestLoadInvalidConfig_RootPathNotExist(t *testing.T) {
6168
globalRootPath = ""
6269
}
6370

64-
func testValidate(rootPath string, env environment) error {
65-
err := validateRootPath(rootPath, env)
71+
func testValidate(rootPath string) error {
72+
err := validateRootPath(rootPath)
6673
globalRootPath = ""
6774
return err
6875
}

receiver/hostmetricsreceiver/hostmetrics_others.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,19 @@
55

66
package hostmetricsreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver"
77

8-
import "fmt"
8+
import (
9+
"fmt"
910

10-
func validateRootPath(rootPath string, _ environment) error {
11+
"github.com/shirou/gopsutil/v3/common"
12+
)
13+
14+
func validateRootPath(rootPath string) error {
1115
if rootPath == "" {
1216
return nil
1317
}
1418
return fmt.Errorf("root_path is supported on linux only")
1519
}
1620

17-
func setGoPsutilEnvVars(_ string, _ environment) error {
18-
return nil
21+
func setGoPsutilEnvVars(_ string, _ environment) common.EnvMap {
22+
return common.EnvMap{}
1923
}

receiver/hostmetricsreceiver/hostmetrics_others_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ import (
1212
)
1313

1414
func TestRootPathNotAllowedOnOS(t *testing.T) {
15-
assert.NotNil(t, validateRootPath("testdata", &testEnv{}))
15+
assert.NotNil(t, validateRootPath("testdata"))
1616
}
1717

1818
func TestRootPathUnset(t *testing.T) {
19-
assert.Nil(t, validateRootPath("", &testEnv{}))
19+
assert.Nil(t, validateRootPath(""))
2020
}

receiver/hostmetricsreceiver/hostmetrics_receiver_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"testing"
1111
"time"
1212

13+
"github.com/shirou/gopsutil/v3/common"
1314
"github.com/stretchr/testify/assert"
1415
"github.com/stretchr/testify/mock"
1516
"github.com/stretchr/testify/require"
@@ -215,6 +216,8 @@ type mockConfig struct{}
215216

216217
func (m *mockConfig) SetRootPath(_ string) {}
217218

219+
func (m *mockConfig) SetEnvMap(_ common.EnvMap) {}
220+
218221
type mockFactory struct{ mock.Mock }
219222
type mockScraper struct{ mock.Mock }
220223

receiver/hostmetricsreceiver/internal/perfcounters/perfcounter_scraper_mock.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func NewMockPerfCounterScraperError(scrapeErr, getObjectErr, getValuesErr, initE
2828
}
2929

3030
// start is a no-op
31-
func (p *MockPerfCounterScraperError) Initialize(objects ...string) error {
31+
func (p *MockPerfCounterScraperError) Initialize(_ ...string) error {
3232
if p.initError != nil {
3333
return p.initError
3434
}
@@ -52,7 +52,7 @@ type mockPerfDataCollectionError struct {
5252

5353
// GetObject returns the specified getObjectErr or an object that will return a subsequent
5454
// error if getObjectErr is nil
55-
func (p mockPerfDataCollectionError) GetObject(objectName string) (PerfDataObject, error) {
55+
func (p mockPerfDataCollectionError) GetObject(_ string) (PerfDataObject, error) {
5656
if p.getObjectErr != nil {
5757
return nil, p.getObjectErr
5858
}
@@ -65,11 +65,11 @@ type mockPerfDataObjectError struct {
6565
}
6666

6767
// Filter is a no-op
68-
func (obj mockPerfDataObjectError) Filter(includeFS, excludeFS filterset.FilterSet, includeTotal bool) {
68+
func (obj mockPerfDataObjectError) Filter(_, _ filterset.FilterSet, _ bool) {
6969
}
7070

7171
// GetValues returns the specified getValuesErr
72-
func (obj mockPerfDataObjectError) GetValues(counterNames ...string) ([]*CounterValues, error) {
72+
func (obj mockPerfDataObjectError) GetValues(_ ...string) ([]*CounterValues, error) {
7373
return nil, obj.getValuesErr
7474
}
7575

@@ -101,7 +101,7 @@ func NewMockPerfCounterScraper(objectsAndValuesToReturn map[string]map[string][]
101101
}
102102

103103
// start is a no-op
104-
func (p *MockPerfCounterScraper) Initialize(objects ...string) error {
104+
func (p *MockPerfCounterScraper) Initialize(_ ...string) error {
105105
return nil
106106
}
107107

@@ -144,7 +144,7 @@ type mockPerfDataObject struct {
144144
}
145145

146146
// Filter is a no-op
147-
func (obj mockPerfDataObject) Filter(includeFS, excludeFS filterset.FilterSet, includeTotal bool) {
147+
func (obj mockPerfDataObject) Filter(_, _ filterset.FilterSet, _ bool) {
148148
}
149149

150150
// GetValues returns the specified counter values

0 commit comments

Comments
 (0)