hostmetrics_linux.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. //go:build linux
  4. package hostmetricsreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver"
  5. import (
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "github.com/shirou/gopsutil/v3/common"
  10. )
  11. var gopsutilEnvVars = map[common.EnvKeyType]string{
  12. common.HostProcEnvKey: "/proc",
  13. common.HostSysEnvKey: "/sys",
  14. common.HostEtcEnvKey: "/etc",
  15. common.HostVarEnvKey: "/var",
  16. common.HostRunEnvKey: "/run",
  17. common.HostDevEnvKey: "/dev",
  18. }
  19. // This exists to validate that different instances of the hostmetricsreceiver do not
  20. // have inconsistent root_path configurations. The root_path is passed down to gopsutil
  21. // through env vars, so it must be consistent across the process.
  22. var globalRootPath string
  23. func validateRootPath(rootPath string) error {
  24. if rootPath == "" || rootPath == "/" {
  25. return nil
  26. }
  27. if globalRootPath != "" && rootPath != globalRootPath {
  28. return fmt.Errorf("inconsistent root_path configuration detected between hostmetricsreceivers: `%s` != `%s`", globalRootPath, rootPath)
  29. }
  30. globalRootPath = rootPath
  31. if _, err := os.Stat(rootPath); err != nil {
  32. return fmt.Errorf("invalid root_path: %w", err)
  33. }
  34. return nil
  35. }
  36. func setGoPsutilEnvVars(rootPath string, env environment) common.EnvMap {
  37. m := common.EnvMap{}
  38. if rootPath == "" || rootPath == "/" {
  39. return m
  40. }
  41. for envVarKey, defaultValue := range gopsutilEnvVars {
  42. _, ok := env.Lookup(string(envVarKey))
  43. if ok {
  44. continue // don't override if existing env var is set
  45. }
  46. m[envVarKey] = filepath.Join(rootPath, defaultValue)
  47. }
  48. return m
  49. }