legacy_metrics_client_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. Copyright 2015 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 metrics
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "testing"
  19. "time"
  20. "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/api/resource"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "k8s.io/apimachinery/pkg/runtime"
  25. "k8s.io/client-go/kubernetes/fake"
  26. restclient "k8s.io/client-go/rest"
  27. core "k8s.io/client-go/testing"
  28. heapster "k8s.io/heapster/metrics/api/v1/types"
  29. metricsapi "k8s.io/metrics/pkg/apis/metrics/v1alpha1"
  30. "github.com/stretchr/testify/assert"
  31. )
  32. var fixedTimestamp = time.Date(2015, time.November, 10, 12, 30, 0, 0, time.UTC)
  33. func (w fakeResponseWrapper) DoRaw() ([]byte, error) {
  34. return w.raw, nil
  35. }
  36. func (w fakeResponseWrapper) Stream() (io.ReadCloser, error) {
  37. return nil, nil
  38. }
  39. func newFakeResponseWrapper(raw []byte) fakeResponseWrapper {
  40. return fakeResponseWrapper{raw: raw}
  41. }
  42. type fakeResponseWrapper struct {
  43. raw []byte
  44. }
  45. // timestamp is used for establishing order on metricPoints
  46. type metricPoint struct {
  47. level uint64
  48. timestamp int
  49. }
  50. type testCase struct {
  51. desiredMetricValues PodMetricsInfo
  52. desiredError error
  53. replicas int
  54. targetTimestamp int
  55. window time.Duration
  56. reportedMetricsPoints [][]metricPoint
  57. reportedPodMetrics [][]int64
  58. namespace string
  59. selector labels.Selector
  60. metricSelector labels.Selector
  61. resourceName v1.ResourceName
  62. metricName string
  63. }
  64. func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset {
  65. namespace := "test-namespace"
  66. tc.namespace = namespace
  67. podNamePrefix := "test-pod"
  68. podLabels := map[string]string{"name": podNamePrefix}
  69. tc.selector = labels.SelectorFromSet(podLabels)
  70. // it's a resource test if we have a resource name
  71. isResource := len(tc.resourceName) > 0
  72. fakeClient := &fake.Clientset{}
  73. fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  74. obj := &v1.PodList{}
  75. for i := 0; i < tc.replicas; i++ {
  76. podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
  77. pod := buildPod(namespace, podName, podLabels, v1.PodRunning, "1024")
  78. obj.Items = append(obj.Items, pod)
  79. }
  80. return true, obj, nil
  81. })
  82. if isResource {
  83. fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
  84. metrics := metricsapi.PodMetricsList{}
  85. for i, containers := range tc.reportedPodMetrics {
  86. metric := metricsapi.PodMetrics{
  87. ObjectMeta: metav1.ObjectMeta{
  88. Name: fmt.Sprintf("%s-%d", podNamePrefix, i),
  89. Namespace: namespace,
  90. },
  91. Timestamp: metav1.Time{Time: offsetTimestampBy(tc.targetTimestamp)},
  92. Window: metav1.Duration{Duration: tc.window},
  93. Containers: []metricsapi.ContainerMetrics{},
  94. }
  95. for j, cpu := range containers {
  96. cm := metricsapi.ContainerMetrics{
  97. Name: fmt.Sprintf("%s-%d-container-%d", podNamePrefix, i, j),
  98. Usage: v1.ResourceList{
  99. v1.ResourceCPU: *resource.NewMilliQuantity(
  100. cpu,
  101. resource.DecimalSI),
  102. v1.ResourceMemory: *resource.NewQuantity(
  103. int64(1024*1024),
  104. resource.BinarySI),
  105. },
  106. }
  107. metric.Containers = append(metric.Containers, cm)
  108. }
  109. metrics.Items = append(metrics.Items, metric)
  110. }
  111. heapsterRawMemResponse, _ := json.Marshal(&metrics)
  112. return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
  113. })
  114. } else {
  115. fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
  116. metrics := heapster.MetricResultList{}
  117. var latestTimestamp time.Time
  118. for _, reportedMetricPoints := range tc.reportedMetricsPoints {
  119. var heapsterMetricPoints []heapster.MetricPoint
  120. for _, reportedMetricPoint := range reportedMetricPoints {
  121. timestamp := offsetTimestampBy(reportedMetricPoint.timestamp)
  122. if latestTimestamp.Before(timestamp) {
  123. latestTimestamp = timestamp
  124. }
  125. heapsterMetricPoint := heapster.MetricPoint{Timestamp: timestamp, Value: reportedMetricPoint.level, FloatValue: nil}
  126. heapsterMetricPoints = append(heapsterMetricPoints, heapsterMetricPoint)
  127. }
  128. metric := heapster.MetricResult{
  129. Metrics: heapsterMetricPoints,
  130. LatestTimestamp: latestTimestamp,
  131. }
  132. metrics.Items = append(metrics.Items, metric)
  133. }
  134. heapsterRawMemResponse, _ := json.Marshal(&metrics)
  135. return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
  136. })
  137. }
  138. return fakeClient
  139. }
  140. func buildPod(namespace, podName string, podLabels map[string]string, phase v1.PodPhase, request string) v1.Pod {
  141. return v1.Pod{
  142. ObjectMeta: metav1.ObjectMeta{
  143. Name: podName,
  144. Namespace: namespace,
  145. Labels: podLabels,
  146. },
  147. Spec: v1.PodSpec{
  148. Containers: []v1.Container{
  149. {
  150. Resources: v1.ResourceRequirements{
  151. Requests: v1.ResourceList{
  152. v1.ResourceCPU: resource.MustParse(request),
  153. },
  154. },
  155. },
  156. },
  157. },
  158. Status: v1.PodStatus{
  159. Phase: phase,
  160. Conditions: []v1.PodCondition{
  161. {
  162. Type: v1.PodReady,
  163. Status: v1.ConditionTrue,
  164. },
  165. },
  166. },
  167. }
  168. }
  169. func (tc *testCase) verifyResults(t *testing.T, metrics PodMetricsInfo, timestamp time.Time, err error) {
  170. if tc.desiredError != nil {
  171. assert.Error(t, err, "there should be an error retrieving the metrics")
  172. assert.Contains(t, fmt.Sprintf("%v", err), fmt.Sprintf("%v", tc.desiredError), "the error message should be eas expected")
  173. return
  174. }
  175. assert.NoError(t, err, "there should be no error retrieving the metrics")
  176. assert.NotNil(t, metrics, "there should be metrics returned")
  177. if len(metrics) != len(tc.desiredMetricValues) {
  178. t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
  179. } else {
  180. for k, m := range metrics {
  181. if !m.Timestamp.Equal(tc.desiredMetricValues[k].Timestamp) ||
  182. m.Window != tc.desiredMetricValues[k].Window ||
  183. m.Value != tc.desiredMetricValues[k].Value {
  184. t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
  185. break
  186. }
  187. }
  188. }
  189. targetTimestamp := offsetTimestampBy(tc.targetTimestamp)
  190. assert.True(t, targetTimestamp.Equal(timestamp), fmt.Sprintf("the timestamp should be as expected (%s) but was %s", targetTimestamp, timestamp))
  191. }
  192. func (tc *testCase) runTest(t *testing.T) {
  193. testClient := tc.prepareTestClient(t)
  194. metricsClient := NewHeapsterMetricsClient(testClient, DefaultHeapsterNamespace, DefaultHeapsterScheme, DefaultHeapsterService, DefaultHeapsterPort)
  195. isResource := len(tc.resourceName) > 0
  196. if isResource {
  197. info, timestamp, err := metricsClient.GetResourceMetric(tc.resourceName, tc.namespace, tc.selector)
  198. tc.verifyResults(t, info, timestamp, err)
  199. } else {
  200. info, timestamp, err := metricsClient.GetRawMetric(tc.metricName, tc.namespace, tc.selector, tc.metricSelector)
  201. tc.verifyResults(t, info, timestamp, err)
  202. }
  203. }
  204. func TestCPU(t *testing.T) {
  205. targetTimestamp := 1
  206. window := 30 * time.Second
  207. tc := testCase{
  208. replicas: 3,
  209. desiredMetricValues: PodMetricsInfo{
  210. "test-pod-0": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  211. "test-pod-1": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  212. "test-pod-2": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  213. },
  214. resourceName: v1.ResourceCPU,
  215. targetTimestamp: targetTimestamp,
  216. window: window,
  217. reportedPodMetrics: [][]int64{{5000}, {5000}, {5000}},
  218. }
  219. tc.runTest(t)
  220. }
  221. func TestQPS(t *testing.T) {
  222. targetTimestamp := 1
  223. tc := testCase{
  224. replicas: 3,
  225. desiredMetricValues: PodMetricsInfo{
  226. "test-pod-0": PodMetric{Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  227. "test-pod-1": PodMetric{Value: 20000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  228. "test-pod-2": PodMetric{Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  229. },
  230. metricName: "qps",
  231. targetTimestamp: targetTimestamp,
  232. reportedMetricsPoints: [][]metricPoint{{{10, 1}}, {{20, 1}}, {{10, 1}}},
  233. }
  234. tc.runTest(t)
  235. }
  236. func TestQpsSumEqualZero(t *testing.T) {
  237. targetTimestamp := 0
  238. tc := testCase{
  239. replicas: 3,
  240. desiredMetricValues: PodMetricsInfo{
  241. "test-pod-0": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  242. "test-pod-1": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  243. "test-pod-2": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  244. },
  245. metricName: "qps",
  246. targetTimestamp: targetTimestamp,
  247. reportedMetricsPoints: [][]metricPoint{{{0, 0}}, {{0, 0}}, {{0, 0}}},
  248. }
  249. tc.runTest(t)
  250. }
  251. func TestCPUMoreMetrics(t *testing.T) {
  252. targetTimestamp := 10
  253. window := 30 * time.Second
  254. tc := testCase{
  255. replicas: 5,
  256. desiredMetricValues: PodMetricsInfo{
  257. "test-pod-0": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  258. "test-pod-1": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  259. "test-pod-2": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  260. "test-pod-3": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  261. "test-pod-4": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  262. },
  263. resourceName: v1.ResourceCPU,
  264. targetTimestamp: targetTimestamp,
  265. window: window,
  266. reportedPodMetrics: [][]int64{{1000, 2000, 2000}, {5000}, {1000, 1000, 1000, 2000}, {4000, 1000}, {5000}},
  267. }
  268. tc.runTest(t)
  269. }
  270. func TestCPUMissingMetrics(t *testing.T) {
  271. targetTimestamp := 0
  272. window := 30 * time.Second
  273. tc := testCase{
  274. replicas: 3,
  275. desiredMetricValues: PodMetricsInfo{
  276. "test-pod-0": PodMetric{Value: 4000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  277. },
  278. resourceName: v1.ResourceCPU,
  279. targetTimestamp: targetTimestamp,
  280. window: window,
  281. reportedPodMetrics: [][]int64{{4000}},
  282. }
  283. tc.runTest(t)
  284. }
  285. func TestQpsMissingMetrics(t *testing.T) {
  286. tc := testCase{
  287. replicas: 3,
  288. desiredError: fmt.Errorf("requested metrics for 3 pods, got metrics for 1"),
  289. metricName: "qps",
  290. targetTimestamp: 1,
  291. reportedMetricsPoints: [][]metricPoint{{{4000, 4}}},
  292. }
  293. tc.runTest(t)
  294. }
  295. func TestQpsSuperfluousMetrics(t *testing.T) {
  296. tc := testCase{
  297. replicas: 3,
  298. desiredError: fmt.Errorf("requested metrics for 3 pods, got metrics for 6"),
  299. metricName: "qps",
  300. reportedMetricsPoints: [][]metricPoint{{{1000, 1}}, {{2000, 4}}, {{2000, 1}}, {{4000, 5}}, {{2000, 1}}, {{4000, 4}}},
  301. }
  302. tc.runTest(t)
  303. }
  304. func TestCPUEmptyMetrics(t *testing.T) {
  305. tc := testCase{
  306. replicas: 3,
  307. resourceName: v1.ResourceCPU,
  308. desiredError: fmt.Errorf("no metrics returned from heapster"),
  309. reportedMetricsPoints: [][]metricPoint{},
  310. reportedPodMetrics: [][]int64{},
  311. }
  312. tc.runTest(t)
  313. }
  314. func TestQpsEmptyEntries(t *testing.T) {
  315. targetTimestamp := 4
  316. tc := testCase{
  317. replicas: 3,
  318. metricName: "qps",
  319. desiredMetricValues: PodMetricsInfo{
  320. "test-pod-0": PodMetric{Value: 4000000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  321. "test-pod-2": PodMetric{Value: 2000000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
  322. },
  323. targetTimestamp: targetTimestamp,
  324. reportedMetricsPoints: [][]metricPoint{{{4000, 4}}, {}, {{2000, 4}}},
  325. }
  326. tc.runTest(t)
  327. }
  328. func TestCPUZeroReplicas(t *testing.T) {
  329. tc := testCase{
  330. replicas: 0,
  331. resourceName: v1.ResourceCPU,
  332. desiredError: fmt.Errorf("no metrics returned from heapster"),
  333. reportedPodMetrics: [][]int64{},
  334. }
  335. tc.runTest(t)
  336. }
  337. func TestCPUEmptyMetricsForOnePod(t *testing.T) {
  338. targetTimestamp := 0
  339. window := 30 * time.Second
  340. tc := testCase{
  341. replicas: 3,
  342. resourceName: v1.ResourceCPU,
  343. desiredMetricValues: PodMetricsInfo{
  344. "test-pod-0": PodMetric{Value: 100, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  345. "test-pod-1": PodMetric{Value: 700, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  346. },
  347. targetTimestamp: targetTimestamp,
  348. window: window,
  349. reportedPodMetrics: [][]int64{{100}, {300, 400}, {}},
  350. }
  351. tc.runTest(t)
  352. }
  353. func offsetTimestampBy(t int) time.Time {
  354. return fixedTimestamp.Add(time.Duration(t) * time.Minute)
  355. }