hostmetrics_receiver_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package hostmetricsreceiver
  4. import (
  5. "context"
  6. "errors"
  7. "runtime"
  8. "testing"
  9. "time"
  10. "github.com/shirou/gopsutil/v3/common"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/mock"
  13. "github.com/stretchr/testify/require"
  14. "go.opentelemetry.io/collector/component"
  15. "go.opentelemetry.io/collector/component/componenttest"
  16. "go.opentelemetry.io/collector/consumer"
  17. "go.opentelemetry.io/collector/consumer/consumertest"
  18. "go.opentelemetry.io/collector/pdata/pmetric"
  19. "go.opentelemetry.io/collector/receiver"
  20. "go.opentelemetry.io/collector/receiver/receivertest"
  21. "go.opentelemetry.io/collector/receiver/scraperhelper"
  22. conventions "go.opentelemetry.io/collector/semconv/v1.9.0"
  23. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal"
  24. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper"
  25. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/diskscraper"
  26. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/filesystemscraper"
  27. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/loadscraper"
  28. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/memoryscraper"
  29. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/networkscraper"
  30. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/pagingscraper"
  31. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processesscraper"
  32. "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/processscraper"
  33. )
  34. var standardMetrics = []string{
  35. "system.cpu.time",
  36. "system.cpu.load_average.1m",
  37. "system.cpu.load_average.5m",
  38. "system.cpu.load_average.15m",
  39. "system.disk.io",
  40. "system.disk.io_time",
  41. "system.disk.operations",
  42. "system.disk.operation_time",
  43. "system.disk.pending_operations",
  44. "system.filesystem.usage",
  45. "system.memory.usage",
  46. "system.network.connections",
  47. "system.network.dropped",
  48. "system.network.errors",
  49. "system.network.io",
  50. "system.network.packets",
  51. "system.paging.operations",
  52. "system.paging.usage",
  53. }
  54. var resourceMetrics = []string{
  55. "process.cpu.time",
  56. "process.memory.usage",
  57. "process.memory.virtual",
  58. "process.disk.io",
  59. }
  60. var systemSpecificMetrics = map[string][]string{
  61. "linux": {"system.disk.merged", "system.disk.weighted_io_time", "system.filesystem.inodes.usage", "system.paging.faults", "system.processes.created", "system.processes.count"},
  62. "darwin": {"system.filesystem.inodes.usage", "system.paging.faults", "system.processes.count"},
  63. "freebsd": {"system.filesystem.inodes.usage", "system.paging.faults", "system.processes.count"},
  64. "openbsd": {"system.filesystem.inodes.usage", "system.paging.faults", "system.processes.created", "system.processes.count"},
  65. "solaris": {"system.filesystem.inodes.usage", "system.paging.faults"},
  66. }
  67. var factories = map[string]internal.ScraperFactory{
  68. cpuscraper.TypeStr: &cpuscraper.Factory{},
  69. diskscraper.TypeStr: &diskscraper.Factory{},
  70. filesystemscraper.TypeStr: &filesystemscraper.Factory{},
  71. loadscraper.TypeStr: &loadscraper.Factory{},
  72. memoryscraper.TypeStr: &memoryscraper.Factory{},
  73. networkscraper.TypeStr: &networkscraper.Factory{},
  74. pagingscraper.TypeStr: &pagingscraper.Factory{},
  75. processesscraper.TypeStr: &processesscraper.Factory{},
  76. processscraper.TypeStr: &processscraper.Factory{},
  77. }
  78. type testEnv struct {
  79. env map[string]string
  80. }
  81. var _ environment = (*testEnv)(nil)
  82. func (e *testEnv) Lookup(k string) (string, bool) {
  83. v, ok := e.env[k]
  84. return v, ok
  85. }
  86. func (e *testEnv) Set(k, v string) error {
  87. e.env[k] = v
  88. return nil
  89. }
  90. func TestGatherMetrics_EndToEnd(t *testing.T) {
  91. scraperFactories = factories
  92. sink := new(consumertest.MetricsSink)
  93. cfg := &Config{
  94. ScraperControllerSettings: scraperhelper.ScraperControllerSettings{
  95. CollectionInterval: 100 * time.Millisecond,
  96. },
  97. Scrapers: map[string]internal.Config{
  98. cpuscraper.TypeStr: scraperFactories[cpuscraper.TypeStr].CreateDefaultConfig(),
  99. diskscraper.TypeStr: scraperFactories[diskscraper.TypeStr].CreateDefaultConfig(),
  100. filesystemscraper.TypeStr: (&filesystemscraper.Factory{}).CreateDefaultConfig(),
  101. loadscraper.TypeStr: scraperFactories[loadscraper.TypeStr].CreateDefaultConfig(),
  102. memoryscraper.TypeStr: scraperFactories[memoryscraper.TypeStr].CreateDefaultConfig(),
  103. networkscraper.TypeStr: scraperFactories[networkscraper.TypeStr].CreateDefaultConfig(),
  104. pagingscraper.TypeStr: scraperFactories[pagingscraper.TypeStr].CreateDefaultConfig(),
  105. processesscraper.TypeStr: scraperFactories[processesscraper.TypeStr].CreateDefaultConfig(),
  106. },
  107. }
  108. if runtime.GOOS == "linux" || runtime.GOOS == "windows" {
  109. cfg.Scrapers[processscraper.TypeStr] = scraperFactories[processscraper.TypeStr].CreateDefaultConfig()
  110. }
  111. receiver, err := NewFactory().CreateMetricsReceiver(context.Background(), creationSet, cfg, sink)
  112. require.NoError(t, err, "Failed to create metrics receiver: %v", err)
  113. ctx, cancelFn := context.WithCancel(context.Background())
  114. err = receiver.Start(ctx, componenttest.NewNopHost())
  115. require.NoError(t, err, "Failed to start metrics receiver: %v", err)
  116. defer func() { assert.NoError(t, receiver.Shutdown(context.Background())) }()
  117. // canceling the context provided to Start should not cancel any async processes initiated by the receiver
  118. cancelFn()
  119. const tick = 50 * time.Millisecond
  120. const waitFor = 10 * time.Second
  121. require.Eventuallyf(t, func() bool {
  122. got := sink.AllMetrics()
  123. if len(got) == 0 {
  124. return false
  125. }
  126. assertIncludesExpectedMetrics(t, got[0])
  127. return true
  128. }, waitFor, tick, "No metrics were collected after %v", waitFor)
  129. }
  130. func assertIncludesExpectedMetrics(t *testing.T, got pmetric.Metrics) {
  131. // get the superset of metrics returned by all resource metrics (excluding the first)
  132. returnedMetrics := make(map[string]struct{})
  133. returnedResourceMetrics := make(map[string]struct{})
  134. rms := got.ResourceMetrics()
  135. for i := 0; i < rms.Len(); i++ {
  136. rm := rms.At(i)
  137. metrics := getMetricSlice(t, rm)
  138. returnedMetricNames := getReturnedMetricNames(metrics)
  139. assert.EqualValues(t, conventions.SchemaURL, rm.SchemaUrl(),
  140. "SchemaURL is incorrect for metrics: %v", returnedMetricNames)
  141. if rm.Resource().Attributes().Len() == 0 {
  142. appendMapInto(returnedMetrics, returnedMetricNames)
  143. } else {
  144. appendMapInto(returnedResourceMetrics, returnedMetricNames)
  145. }
  146. }
  147. // verify the expected list of metrics returned (os dependent)
  148. var expectedMetrics []string
  149. expectedMetrics = append(expectedMetrics, standardMetrics...)
  150. expectedMetrics = append(expectedMetrics, systemSpecificMetrics[runtime.GOOS]...)
  151. assert.Equal(t, len(expectedMetrics), len(returnedMetrics))
  152. for _, expected := range expectedMetrics {
  153. assert.Contains(t, returnedMetrics, expected)
  154. }
  155. // verify the expected list of resource metrics returned (Linux & Windows only)
  156. if runtime.GOOS != "linux" && runtime.GOOS != "windows" {
  157. return
  158. }
  159. var expectedResourceMetrics []string
  160. expectedResourceMetrics = append(expectedResourceMetrics, resourceMetrics...)
  161. assert.Equal(t, len(expectedResourceMetrics), len(returnedResourceMetrics))
  162. for _, expected := range expectedResourceMetrics {
  163. assert.Contains(t, returnedResourceMetrics, expected)
  164. }
  165. }
  166. func getMetricSlice(t *testing.T, rm pmetric.ResourceMetrics) pmetric.MetricSlice {
  167. ilms := rm.ScopeMetrics()
  168. require.Equal(t, 1, ilms.Len())
  169. return ilms.At(0).Metrics()
  170. }
  171. func getReturnedMetricNames(metrics pmetric.MetricSlice) map[string]struct{} {
  172. metricNames := make(map[string]struct{})
  173. for i := 0; i < metrics.Len(); i++ {
  174. metricNames[metrics.At(i).Name()] = struct{}{}
  175. }
  176. return metricNames
  177. }
  178. func appendMapInto(m1 map[string]struct{}, m2 map[string]struct{}) {
  179. for k, v := range m2 {
  180. m1[k] = v
  181. }
  182. }
  183. const mockTypeStr = "mock"
  184. type mockConfig struct{}
  185. func (m *mockConfig) SetRootPath(_ string) {}
  186. func (m *mockConfig) SetEnvMap(_ common.EnvMap) {}
  187. type mockFactory struct{ mock.Mock }
  188. type mockScraper struct{ mock.Mock }
  189. func (m *mockFactory) CreateDefaultConfig() internal.Config { return &mockConfig{} }
  190. func (m *mockFactory) CreateMetricsScraper(context.Context, receiver.CreateSettings, internal.Config) (scraperhelper.Scraper, error) {
  191. args := m.MethodCalled("CreateMetricsScraper")
  192. return args.Get(0).(scraperhelper.Scraper), args.Error(1)
  193. }
  194. func (m *mockScraper) ID() component.ID { return component.NewID("") }
  195. func (m *mockScraper) Start(context.Context, component.Host) error { return nil }
  196. func (m *mockScraper) Shutdown(context.Context) error { return nil }
  197. func (m *mockScraper) Scrape(context.Context) (pmetric.Metrics, error) {
  198. return pmetric.NewMetrics(), errors.New("err1")
  199. }
  200. func TestGatherMetrics_ScraperKeyConfigError(t *testing.T) {
  201. scraperFactories = map[string]internal.ScraperFactory{}
  202. sink := new(consumertest.MetricsSink)
  203. cfg := &Config{Scrapers: map[string]internal.Config{"error": &mockConfig{}}}
  204. _, err := NewFactory().CreateMetricsReceiver(context.Background(), creationSet, cfg, sink)
  205. require.Error(t, err)
  206. }
  207. func TestGatherMetrics_CreateMetricsScraperError(t *testing.T) {
  208. mFactory := &mockFactory{}
  209. mFactory.On("CreateMetricsScraper").Return(&mockScraper{}, errors.New("err1"))
  210. scraperFactories = map[string]internal.ScraperFactory{mockTypeStr: mFactory}
  211. sink := new(consumertest.MetricsSink)
  212. cfg := &Config{Scrapers: map[string]internal.Config{mockTypeStr: &mockConfig{}}}
  213. _, err := NewFactory().CreateMetricsReceiver(context.Background(), creationSet, cfg, sink)
  214. require.Error(t, err)
  215. }
  216. type notifyingSink struct {
  217. receivedMetrics bool
  218. timesCalled int
  219. ch chan int
  220. }
  221. func (s *notifyingSink) Capabilities() consumer.Capabilities {
  222. return consumer.Capabilities{MutatesData: false}
  223. }
  224. func (s *notifyingSink) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {
  225. if md.MetricCount() > 0 {
  226. s.receivedMetrics = true
  227. }
  228. s.timesCalled++
  229. s.ch <- s.timesCalled
  230. return nil
  231. }
  232. func benchmarkScrapeMetrics(b *testing.B, cfg *Config) {
  233. scraperFactories = factories
  234. sink := &notifyingSink{ch: make(chan int, 10)}
  235. tickerCh := make(chan time.Time)
  236. options, err := createAddScraperOptions(context.Background(), receivertest.NewNopCreateSettings(), cfg, scraperFactories)
  237. require.NoError(b, err)
  238. options = append(options, scraperhelper.WithTickerChannel(tickerCh))
  239. receiver, err := scraperhelper.NewScraperControllerReceiver(&cfg.ScraperControllerSettings, receivertest.NewNopCreateSettings(), sink, options...)
  240. require.NoError(b, err)
  241. require.NoError(b, receiver.Start(context.Background(), componenttest.NewNopHost()))
  242. b.ResetTimer()
  243. for n := 0; n < b.N; n++ {
  244. tickerCh <- time.Now()
  245. <-sink.ch
  246. }
  247. if !sink.receivedMetrics {
  248. b.Fail()
  249. }
  250. }
  251. func Benchmark_ScrapeCpuMetrics(b *testing.B) {
  252. cfg := &Config{
  253. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  254. Scrapers: map[string]internal.Config{cpuscraper.TypeStr: (&cpuscraper.Factory{}).CreateDefaultConfig()},
  255. }
  256. benchmarkScrapeMetrics(b, cfg)
  257. }
  258. func Benchmark_ScrapeDiskMetrics(b *testing.B) {
  259. cfg := &Config{
  260. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  261. Scrapers: map[string]internal.Config{diskscraper.TypeStr: (&diskscraper.Factory{}).CreateDefaultConfig()},
  262. }
  263. benchmarkScrapeMetrics(b, cfg)
  264. }
  265. func Benchmark_ScrapeFileSystemMetrics(b *testing.B) {
  266. cfg := &Config{
  267. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  268. Scrapers: map[string]internal.Config{filesystemscraper.TypeStr: (&filesystemscraper.Factory{}).CreateDefaultConfig()},
  269. }
  270. benchmarkScrapeMetrics(b, cfg)
  271. }
  272. func Benchmark_ScrapeLoadMetrics(b *testing.B) {
  273. cfg := &Config{
  274. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  275. Scrapers: map[string]internal.Config{loadscraper.TypeStr: (&loadscraper.Factory{}).CreateDefaultConfig()},
  276. }
  277. benchmarkScrapeMetrics(b, cfg)
  278. }
  279. func Benchmark_ScrapeMemoryMetrics(b *testing.B) {
  280. cfg := &Config{
  281. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  282. Scrapers: map[string]internal.Config{memoryscraper.TypeStr: (&memoryscraper.Factory{}).CreateDefaultConfig()},
  283. }
  284. benchmarkScrapeMetrics(b, cfg)
  285. }
  286. func Benchmark_ScrapeNetworkMetrics(b *testing.B) {
  287. cfg := &Config{
  288. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  289. Scrapers: map[string]internal.Config{networkscraper.TypeStr: (&networkscraper.Factory{}).CreateDefaultConfig()},
  290. }
  291. benchmarkScrapeMetrics(b, cfg)
  292. }
  293. func Benchmark_ScrapeProcessesMetrics(b *testing.B) {
  294. cfg := &Config{
  295. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  296. Scrapers: map[string]internal.Config{processesscraper.TypeStr: (&processesscraper.Factory{}).CreateDefaultConfig()},
  297. }
  298. benchmarkScrapeMetrics(b, cfg)
  299. }
  300. func Benchmark_ScrapePagingMetrics(b *testing.B) {
  301. cfg := &Config{
  302. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  303. Scrapers: map[string]internal.Config{pagingscraper.TypeStr: (&pagingscraper.Factory{}).CreateDefaultConfig()},
  304. }
  305. benchmarkScrapeMetrics(b, cfg)
  306. }
  307. func Benchmark_ScrapeProcessMetrics(b *testing.B) {
  308. if runtime.GOOS != "linux" && runtime.GOOS != "windows" {
  309. b.Skip("skipping test on non linux/windows")
  310. }
  311. cfg := &Config{
  312. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  313. Scrapers: map[string]internal.Config{processscraper.TypeStr: (&processscraper.Factory{}).CreateDefaultConfig()},
  314. }
  315. benchmarkScrapeMetrics(b, cfg)
  316. }
  317. func Benchmark_ScrapeSystemMetrics(b *testing.B) {
  318. cfg := &Config{
  319. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  320. Scrapers: map[string]internal.Config{
  321. cpuscraper.TypeStr: (&cpuscraper.Factory{}).CreateDefaultConfig(),
  322. diskscraper.TypeStr: (&diskscraper.Factory{}).CreateDefaultConfig(),
  323. filesystemscraper.TypeStr: (&filesystemscraper.Factory{}).CreateDefaultConfig(),
  324. loadscraper.TypeStr: (&loadscraper.Factory{}).CreateDefaultConfig(),
  325. memoryscraper.TypeStr: (&memoryscraper.Factory{}).CreateDefaultConfig(),
  326. networkscraper.TypeStr: (&networkscraper.Factory{}).CreateDefaultConfig(),
  327. pagingscraper.TypeStr: (&pagingscraper.Factory{}).CreateDefaultConfig(),
  328. processesscraper.TypeStr: (&processesscraper.Factory{}).CreateDefaultConfig(),
  329. },
  330. }
  331. benchmarkScrapeMetrics(b, cfg)
  332. }
  333. func Benchmark_ScrapeSystemAndProcessMetrics(b *testing.B) {
  334. if runtime.GOOS != "linux" && runtime.GOOS != "windows" {
  335. b.Skip("skipping test on non linux/windows")
  336. }
  337. cfg := &Config{
  338. ScraperControllerSettings: scraperhelper.NewDefaultScraperControllerSettings(""),
  339. Scrapers: map[string]internal.Config{
  340. cpuscraper.TypeStr: &cpuscraper.Config{},
  341. diskscraper.TypeStr: &diskscraper.Config{},
  342. filesystemscraper.TypeStr: (&filesystemscraper.Factory{}).CreateDefaultConfig(),
  343. loadscraper.TypeStr: &loadscraper.Config{},
  344. memoryscraper.TypeStr: &memoryscraper.Config{},
  345. networkscraper.TypeStr: &networkscraper.Config{},
  346. pagingscraper.TypeStr: (&pagingscraper.Factory{}).CreateDefaultConfig(),
  347. processesscraper.TypeStr: &processesscraper.Config{},
  348. },
  349. }
  350. benchmarkScrapeMetrics(b, cfg)
  351. }