prometheus_resource_metrics_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package stats
  14. import (
  15. "fmt"
  16. "testing"
  17. "time"
  18. "github.com/prometheus/client_golang/prometheus"
  19. dto "github.com/prometheus/client_model/go"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/stretchr/testify/mock"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
  24. )
  25. const (
  26. errorName = "scrape_error"
  27. errorHelp = "1 if there was an error while getting container metrics, 0 otherwise"
  28. )
  29. var (
  30. noError = float64(0)
  31. hasError = float64(1)
  32. )
  33. type mockSummaryProvider struct {
  34. mock.Mock
  35. }
  36. func (m *mockSummaryProvider) Get(updateStats bool) (*statsapi.Summary, error) {
  37. args := m.Called(updateStats)
  38. return args.Get(0).(*statsapi.Summary), args.Error(1)
  39. }
  40. func (m *mockSummaryProvider) GetCPUAndMemoryStats() (*statsapi.Summary, error) {
  41. args := m.Called()
  42. return args.Get(0).(*statsapi.Summary), args.Error(1)
  43. }
  44. type collectResult struct {
  45. desc *prometheus.Desc
  46. metric *dto.Metric
  47. }
  48. func TestCollectResourceMetrics(t *testing.T) {
  49. testTime := metav1.Now()
  50. for _, tc := range []struct {
  51. description string
  52. config ResourceMetricsConfig
  53. summary *statsapi.Summary
  54. summaryErr error
  55. expectedMetrics []collectResult
  56. }{
  57. {
  58. description: "error getting summary",
  59. config: ResourceMetricsConfig{},
  60. summary: nil,
  61. summaryErr: fmt.Errorf("failed to get summary"),
  62. expectedMetrics: []collectResult{
  63. {
  64. desc: prometheus.NewDesc(errorName, errorHelp, []string{}, nil),
  65. metric: &dto.Metric{Gauge: &dto.Gauge{Value: &hasError}},
  66. },
  67. },
  68. },
  69. {
  70. description: "arbitrary node metrics",
  71. config: ResourceMetricsConfig{
  72. NodeMetrics: []NodeResourceMetric{
  73. {
  74. Name: "node_foo",
  75. Description: "a metric from nodestats",
  76. ValueFn: func(s statsapi.NodeStats) (*float64, time.Time) {
  77. if s.CPU == nil {
  78. return nil, time.Time{}
  79. }
  80. v := float64(*s.CPU.UsageCoreNanoSeconds) / float64(time.Second)
  81. return &v, s.CPU.Time.Time
  82. },
  83. },
  84. {
  85. Name: "node_bar",
  86. Description: "another metric from nodestats",
  87. ValueFn: func(s statsapi.NodeStats) (*float64, time.Time) {
  88. if s.Memory == nil {
  89. return nil, time.Time{}
  90. }
  91. v := float64(*s.Memory.WorkingSetBytes)
  92. return &v, s.Memory.Time.Time
  93. },
  94. },
  95. },
  96. },
  97. summary: &statsapi.Summary{
  98. Node: statsapi.NodeStats{
  99. CPU: &statsapi.CPUStats{
  100. Time: testTime,
  101. UsageCoreNanoSeconds: uint64Ptr(10000000000),
  102. },
  103. Memory: &statsapi.MemoryStats{
  104. Time: testTime,
  105. WorkingSetBytes: uint64Ptr(1000),
  106. },
  107. },
  108. },
  109. summaryErr: nil,
  110. expectedMetrics: []collectResult{
  111. {
  112. desc: prometheus.NewDesc("node_foo", "a metric from nodestats", []string{}, nil),
  113. metric: &dto.Metric{Gauge: &dto.Gauge{Value: float64Ptr(10)}},
  114. },
  115. {
  116. desc: prometheus.NewDesc("node_bar", "another metric from nodestats", []string{}, nil),
  117. metric: &dto.Metric{Gauge: &dto.Gauge{Value: float64Ptr(1000)}},
  118. },
  119. {
  120. desc: prometheus.NewDesc(errorName, errorHelp, []string{}, nil),
  121. metric: &dto.Metric{Gauge: &dto.Gauge{Value: &noError}},
  122. },
  123. },
  124. },
  125. {
  126. description: "arbitrary container metrics for different container, pods and namespaces",
  127. config: ResourceMetricsConfig{
  128. ContainerMetrics: []ContainerResourceMetric{
  129. {
  130. Name: "container_foo",
  131. Description: "a metric from container stats",
  132. ValueFn: func(s statsapi.ContainerStats) (*float64, time.Time) {
  133. if s.CPU == nil {
  134. return nil, time.Time{}
  135. }
  136. v := float64(*s.CPU.UsageCoreNanoSeconds) / float64(time.Second)
  137. return &v, s.CPU.Time.Time
  138. },
  139. },
  140. {
  141. Name: "container_bar",
  142. Description: "another metric from container stats",
  143. ValueFn: func(s statsapi.ContainerStats) (*float64, time.Time) {
  144. if s.Memory == nil {
  145. return nil, time.Time{}
  146. }
  147. v := float64(*s.Memory.WorkingSetBytes)
  148. return &v, s.Memory.Time.Time
  149. },
  150. },
  151. },
  152. },
  153. summary: &statsapi.Summary{
  154. Pods: []statsapi.PodStats{
  155. {
  156. PodRef: statsapi.PodReference{
  157. Name: "pod_a",
  158. Namespace: "namespace_a",
  159. },
  160. Containers: []statsapi.ContainerStats{
  161. {
  162. Name: "container_a",
  163. CPU: &statsapi.CPUStats{
  164. Time: testTime,
  165. UsageCoreNanoSeconds: uint64Ptr(10000000000),
  166. },
  167. Memory: &statsapi.MemoryStats{
  168. Time: testTime,
  169. WorkingSetBytes: uint64Ptr(1000),
  170. },
  171. },
  172. {
  173. Name: "container_b",
  174. CPU: &statsapi.CPUStats{
  175. Time: testTime,
  176. UsageCoreNanoSeconds: uint64Ptr(10000000000),
  177. },
  178. Memory: &statsapi.MemoryStats{
  179. Time: testTime,
  180. WorkingSetBytes: uint64Ptr(1000),
  181. },
  182. },
  183. },
  184. },
  185. {
  186. PodRef: statsapi.PodReference{
  187. Name: "pod_b",
  188. Namespace: "namespace_b",
  189. },
  190. Containers: []statsapi.ContainerStats{
  191. {
  192. Name: "container_a",
  193. CPU: &statsapi.CPUStats{
  194. Time: testTime,
  195. UsageCoreNanoSeconds: uint64Ptr(10000000000),
  196. },
  197. Memory: &statsapi.MemoryStats{
  198. Time: testTime,
  199. WorkingSetBytes: uint64Ptr(1000),
  200. },
  201. },
  202. },
  203. },
  204. },
  205. },
  206. summaryErr: nil,
  207. expectedMetrics: []collectResult{
  208. {
  209. desc: prometheus.NewDesc("container_foo", "a metric from container stats", []string{"container", "pod", "namespace"}, nil),
  210. metric: &dto.Metric{
  211. Gauge: &dto.Gauge{Value: float64Ptr(10)},
  212. Label: []*dto.LabelPair{
  213. {Name: stringPtr("container"), Value: stringPtr("container_a")},
  214. {Name: stringPtr("namespace"), Value: stringPtr("namespace_a")},
  215. {Name: stringPtr("pod"), Value: stringPtr("pod_a")},
  216. },
  217. },
  218. },
  219. {
  220. desc: prometheus.NewDesc("container_bar", "another metric from container stats", []string{"container", "pod", "namespace"}, nil),
  221. metric: &dto.Metric{
  222. Gauge: &dto.Gauge{Value: float64Ptr(1000)},
  223. Label: []*dto.LabelPair{
  224. {Name: stringPtr("container"), Value: stringPtr("container_a")},
  225. {Name: stringPtr("namespace"), Value: stringPtr("namespace_a")},
  226. {Name: stringPtr("pod"), Value: stringPtr("pod_a")},
  227. },
  228. },
  229. },
  230. {
  231. desc: prometheus.NewDesc("container_foo", "a metric from container stats", []string{"container", "pod", "namespace"}, nil),
  232. metric: &dto.Metric{
  233. Gauge: &dto.Gauge{Value: float64Ptr(10)},
  234. Label: []*dto.LabelPair{
  235. {Name: stringPtr("container"), Value: stringPtr("container_b")},
  236. {Name: stringPtr("namespace"), Value: stringPtr("namespace_a")},
  237. {Name: stringPtr("pod"), Value: stringPtr("pod_a")},
  238. },
  239. },
  240. },
  241. {
  242. desc: prometheus.NewDesc("container_bar", "another metric from container stats", []string{"container", "pod", "namespace"}, nil),
  243. metric: &dto.Metric{
  244. Gauge: &dto.Gauge{Value: float64Ptr(1000)},
  245. Label: []*dto.LabelPair{
  246. {Name: stringPtr("container"), Value: stringPtr("container_b")},
  247. {Name: stringPtr("namespace"), Value: stringPtr("namespace_a")},
  248. {Name: stringPtr("pod"), Value: stringPtr("pod_a")},
  249. },
  250. },
  251. },
  252. {
  253. desc: prometheus.NewDesc("container_foo", "a metric from container stats", []string{"container", "pod", "namespace"}, nil),
  254. metric: &dto.Metric{
  255. Gauge: &dto.Gauge{Value: float64Ptr(10)},
  256. Label: []*dto.LabelPair{
  257. {Name: stringPtr("container"), Value: stringPtr("container_a")},
  258. {Name: stringPtr("namespace"), Value: stringPtr("namespace_b")},
  259. {Name: stringPtr("pod"), Value: stringPtr("pod_b")},
  260. },
  261. },
  262. },
  263. {
  264. desc: prometheus.NewDesc("container_bar", "another metric from container stats", []string{"container", "pod", "namespace"}, nil),
  265. metric: &dto.Metric{
  266. Gauge: &dto.Gauge{Value: float64Ptr(1000)},
  267. Label: []*dto.LabelPair{
  268. {Name: stringPtr("container"), Value: stringPtr("container_a")},
  269. {Name: stringPtr("namespace"), Value: stringPtr("namespace_b")},
  270. {Name: stringPtr("pod"), Value: stringPtr("pod_b")},
  271. },
  272. },
  273. },
  274. {
  275. desc: prometheus.NewDesc(errorName, errorHelp, []string{}, nil),
  276. metric: &dto.Metric{Gauge: &dto.Gauge{Value: &noError}},
  277. },
  278. },
  279. },
  280. } {
  281. t.Run(tc.description, func(t *testing.T) {
  282. provider := &mockSummaryProvider{}
  283. provider.On("GetCPUAndMemoryStats").Return(tc.summary, tc.summaryErr)
  284. collector := NewPrometheusResourceMetricCollector(provider, tc.config)
  285. metrics := collectMetrics(t, collector, len(tc.expectedMetrics))
  286. for i := range metrics {
  287. assertEqual(t, metrics[i], tc.expectedMetrics[i])
  288. }
  289. })
  290. }
  291. }
  292. // collectMetrics is a wrapper around a prometheus.Collector which returns the metrics added to the metric channel as a slice.metric
  293. // It will block indefinitely if the collector does not collect exactly numMetrics.
  294. func collectMetrics(t *testing.T, collector prometheus.Collector, numMetrics int) (results []collectResult) {
  295. metricsCh := make(chan prometheus.Metric)
  296. done := make(chan struct{})
  297. go func() {
  298. collector.Collect(metricsCh)
  299. done <- struct{}{}
  300. }()
  301. for i := 0; i < numMetrics; i++ {
  302. metric := <-metricsCh
  303. metricProto := &dto.Metric{}
  304. assert.NoError(t, metric.Write(metricProto))
  305. results = append(results, collectResult{desc: metric.Desc(), metric: metricProto})
  306. }
  307. <-done
  308. return
  309. }
  310. // assertEqual asserts for semanitic equality for fields we care about
  311. func assertEqual(t *testing.T, expected, actual collectResult) {
  312. assert.Equal(t, expected.desc.String(), actual.desc.String())
  313. assert.Equal(t, *expected.metric.Gauge.Value, *actual.metric.Gauge.Value, "for desc: %v", expected.desc.String())
  314. assert.Equal(t, len(expected.metric.Label), len(actual.metric.Label))
  315. if len(expected.metric.Label) == len(actual.metric.Label) {
  316. for i := range expected.metric.Label {
  317. assert.Equal(t, *expected.metric.Label[i], *actual.metric.Label[i], "for desc: %v", expected.desc.String())
  318. }
  319. }
  320. }
  321. func stringPtr(s string) *string {
  322. return &s
  323. }
  324. func uint64Ptr(u uint64) *uint64 {
  325. return &u
  326. }
  327. func float64Ptr(f float64) *float64 {
  328. return &f
  329. }