rest_metrics_client_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. Copyright 2017 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. "fmt"
  16. "testing"
  17. "time"
  18. autoscalingapi "k8s.io/api/autoscaling/v2beta2"
  19. "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/api/meta/testrestmapper"
  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/apimachinery/pkg/runtime/schema"
  26. core "k8s.io/client-go/testing"
  27. "k8s.io/kubernetes/pkg/api/legacyscheme"
  28. _ "k8s.io/kubernetes/pkg/apis/apps/install"
  29. cmapi "k8s.io/metrics/pkg/apis/custom_metrics/v1beta2"
  30. emapi "k8s.io/metrics/pkg/apis/external_metrics/v1beta1"
  31. metricsapi "k8s.io/metrics/pkg/apis/metrics/v1beta1"
  32. metricsfake "k8s.io/metrics/pkg/client/clientset/versioned/fake"
  33. cmfake "k8s.io/metrics/pkg/client/custom_metrics/fake"
  34. emfake "k8s.io/metrics/pkg/client/external_metrics/fake"
  35. "github.com/stretchr/testify/assert"
  36. )
  37. type restClientTestCase struct {
  38. desiredMetricValues PodMetricsInfo
  39. desiredError error
  40. // "timestamps" here are actually the offset in minutes from a base timestamp
  41. targetTimestamp int
  42. window time.Duration
  43. reportedMetricPoints []metricPoint
  44. reportedPodMetrics [][]int64
  45. singleObject *autoscalingapi.CrossVersionObjectReference
  46. namespace string
  47. selector labels.Selector
  48. resourceName v1.ResourceName
  49. metricName string
  50. metricSelector *metav1.LabelSelector
  51. metricLabelSelector labels.Selector
  52. }
  53. func (tc *restClientTestCase) prepareTestClient(t *testing.T) (*metricsfake.Clientset, *cmfake.FakeCustomMetricsClient, *emfake.FakeExternalMetricsClient) {
  54. namespace := "test-namespace"
  55. tc.namespace = namespace
  56. podNamePrefix := "test-pod"
  57. podLabels := map[string]string{"name": podNamePrefix}
  58. tc.selector = labels.SelectorFromSet(podLabels)
  59. // it's a resource test if we have a resource name
  60. isResource := len(tc.resourceName) > 0
  61. // it's an external test if we have a metric selector
  62. isExternal := tc.metricSelector != nil
  63. fakeMetricsClient := &metricsfake.Clientset{}
  64. fakeCMClient := &cmfake.FakeCustomMetricsClient{}
  65. fakeEMClient := &emfake.FakeExternalMetricsClient{}
  66. if isResource {
  67. fakeMetricsClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  68. metrics := &metricsapi.PodMetricsList{}
  69. for i, containers := range tc.reportedPodMetrics {
  70. metric := metricsapi.PodMetrics{
  71. ObjectMeta: metav1.ObjectMeta{
  72. Name: fmt.Sprintf("%s-%d", podNamePrefix, i),
  73. Namespace: namespace,
  74. Labels: podLabels,
  75. },
  76. Timestamp: metav1.Time{Time: offsetTimestampBy(tc.targetTimestamp)},
  77. Window: metav1.Duration{Duration: tc.window},
  78. Containers: []metricsapi.ContainerMetrics{},
  79. }
  80. for j, cpu := range containers {
  81. cm := metricsapi.ContainerMetrics{
  82. Name: fmt.Sprintf("%s-%d-container-%d", podNamePrefix, i, j),
  83. Usage: v1.ResourceList{
  84. v1.ResourceCPU: *resource.NewMilliQuantity(
  85. cpu,
  86. resource.DecimalSI),
  87. v1.ResourceMemory: *resource.NewQuantity(
  88. int64(1024*1024),
  89. resource.BinarySI),
  90. },
  91. }
  92. metric.Containers = append(metric.Containers, cm)
  93. }
  94. metrics.Items = append(metrics.Items, metric)
  95. }
  96. return true, metrics, nil
  97. })
  98. } else if isExternal {
  99. fakeEMClient.AddReactor("list", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  100. listAction := action.(core.ListAction)
  101. assert.Equal(t, tc.metricName, listAction.GetResource().Resource, "the metric requested should have matched the one specified.")
  102. assert.Equal(t, tc.metricLabelSelector, listAction.GetListRestrictions().Labels, "the metric selector should have matched the one specified")
  103. metrics := emapi.ExternalMetricValueList{}
  104. for _, metricPoint := range tc.reportedMetricPoints {
  105. timestamp := offsetTimestampBy(metricPoint.timestamp)
  106. metric := emapi.ExternalMetricValue{
  107. Value: *resource.NewMilliQuantity(int64(metricPoint.level), resource.DecimalSI),
  108. Timestamp: metav1.Time{Time: timestamp},
  109. MetricName: tc.metricName,
  110. }
  111. metrics.Items = append(metrics.Items, metric)
  112. }
  113. return true, &metrics, nil
  114. })
  115. } else {
  116. fakeCMClient.AddReactor("get", "*", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  117. getForAction := action.(cmfake.GetForAction)
  118. assert.Equal(t, tc.metricName, getForAction.GetMetricName(), "the metric requested should have matched the one specified")
  119. if getForAction.GetName() == "*" {
  120. // multiple objects
  121. metrics := cmapi.MetricValueList{}
  122. assert.Equal(t, "pods", getForAction.GetResource().Resource, "type of object that we requested multiple metrics for should have been pods")
  123. for i, metricPoint := range tc.reportedMetricPoints {
  124. timestamp := offsetTimestampBy(metricPoint.timestamp)
  125. metric := cmapi.MetricValue{
  126. DescribedObject: v1.ObjectReference{
  127. Kind: "Pod",
  128. APIVersion: "v1",
  129. Name: fmt.Sprintf("%s-%d", podNamePrefix, i),
  130. },
  131. Value: *resource.NewMilliQuantity(int64(metricPoint.level), resource.DecimalSI),
  132. Timestamp: metav1.Time{Time: timestamp},
  133. Metric: cmapi.MetricIdentifier{
  134. Name: tc.metricName,
  135. },
  136. }
  137. metrics.Items = append(metrics.Items, metric)
  138. }
  139. return true, &metrics, nil
  140. } else {
  141. name := getForAction.GetName()
  142. mapper := testrestmapper.TestOnlyStaticRESTMapper(legacyscheme.Scheme)
  143. assert.NotNil(t, tc.singleObject, "should have only requested a single-object metric when we asked for metrics for a single object")
  144. gk := schema.FromAPIVersionAndKind(tc.singleObject.APIVersion, tc.singleObject.Kind).GroupKind()
  145. mapping, err := mapper.RESTMapping(gk)
  146. if err != nil {
  147. return true, nil, fmt.Errorf("unable to get mapping for %s: %v", gk.String(), err)
  148. }
  149. groupResource := mapping.Resource.GroupResource()
  150. assert.Equal(t, groupResource.String(), getForAction.GetResource().Resource, "should have requested metrics for the resource matching the GroupKind passed in")
  151. assert.Equal(t, tc.singleObject.Name, name, "should have requested metrics for the object matching the name passed in")
  152. metricPoint := tc.reportedMetricPoints[0]
  153. timestamp := offsetTimestampBy(metricPoint.timestamp)
  154. metrics := &cmapi.MetricValueList{
  155. Items: []cmapi.MetricValue{
  156. {
  157. DescribedObject: v1.ObjectReference{
  158. Kind: tc.singleObject.Kind,
  159. APIVersion: tc.singleObject.APIVersion,
  160. Name: tc.singleObject.Name,
  161. },
  162. Timestamp: metav1.Time{Time: timestamp},
  163. Metric: cmapi.MetricIdentifier{
  164. Name: tc.metricName,
  165. },
  166. Value: *resource.NewMilliQuantity(int64(metricPoint.level), resource.DecimalSI),
  167. },
  168. },
  169. }
  170. return true, metrics, nil
  171. }
  172. })
  173. }
  174. return fakeMetricsClient, fakeCMClient, fakeEMClient
  175. }
  176. func (tc *restClientTestCase) verifyResults(t *testing.T, metrics PodMetricsInfo, timestamp time.Time, err error) {
  177. if tc.desiredError != nil {
  178. assert.Error(t, err, "there should be an error retrieving the metrics")
  179. assert.Contains(t, fmt.Sprintf("%v", err), fmt.Sprintf("%v", tc.desiredError), "the error message should be as expected")
  180. return
  181. }
  182. assert.NoError(t, err, "there should be no error retrieving the metrics")
  183. assert.NotNil(t, metrics, "there should be metrics returned")
  184. if len(metrics) != len(tc.desiredMetricValues) {
  185. t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
  186. } else {
  187. for k, m := range metrics {
  188. if !m.Timestamp.Equal(tc.desiredMetricValues[k].Timestamp) ||
  189. m.Window != tc.desiredMetricValues[k].Window ||
  190. m.Value != tc.desiredMetricValues[k].Value {
  191. t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
  192. break
  193. }
  194. }
  195. }
  196. targetTimestamp := offsetTimestampBy(tc.targetTimestamp)
  197. assert.True(t, targetTimestamp.Equal(timestamp), fmt.Sprintf("the timestamp should be as expected (%s) but was %s", targetTimestamp, timestamp))
  198. }
  199. func (tc *restClientTestCase) runTest(t *testing.T) {
  200. var err error
  201. testMetricsClient, testCMClient, testEMClient := tc.prepareTestClient(t)
  202. metricsClient := NewRESTMetricsClient(testMetricsClient.MetricsV1beta1(), testCMClient, testEMClient)
  203. isResource := len(tc.resourceName) > 0
  204. isExternal := tc.metricSelector != nil
  205. if isResource {
  206. info, timestamp, err := metricsClient.GetResourceMetric(v1.ResourceName(tc.resourceName), tc.namespace, tc.selector)
  207. tc.verifyResults(t, info, timestamp, err)
  208. } else if isExternal {
  209. tc.metricLabelSelector, err = metav1.LabelSelectorAsSelector(tc.metricSelector)
  210. if err != nil {
  211. t.Errorf("invalid metric selector: %+v", tc.metricSelector)
  212. }
  213. val, timestamp, err := metricsClient.GetExternalMetric(tc.metricName, tc.namespace, tc.metricLabelSelector)
  214. info := make(PodMetricsInfo, len(val))
  215. for i, metricVal := range val {
  216. info[fmt.Sprintf("%v-val-%v", tc.metricName, i)] = PodMetric{Value: metricVal}
  217. }
  218. tc.verifyResults(t, info, timestamp, err)
  219. } else if tc.singleObject == nil {
  220. info, timestamp, err := metricsClient.GetRawMetric(tc.metricName, tc.namespace, tc.selector, tc.metricLabelSelector)
  221. tc.verifyResults(t, info, timestamp, err)
  222. } else {
  223. val, timestamp, err := metricsClient.GetObjectMetric(tc.metricName, tc.namespace, tc.singleObject, tc.metricLabelSelector)
  224. info := PodMetricsInfo{tc.singleObject.Name: {Value: val}}
  225. tc.verifyResults(t, info, timestamp, err)
  226. }
  227. }
  228. func TestRESTClientCPU(t *testing.T) {
  229. targetTimestamp := 1
  230. window := 30 * time.Second
  231. tc := restClientTestCase{
  232. desiredMetricValues: PodMetricsInfo{
  233. "test-pod-0": {Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  234. "test-pod-1": {Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  235. "test-pod-2": {Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  236. },
  237. resourceName: v1.ResourceCPU,
  238. targetTimestamp: targetTimestamp,
  239. window: window,
  240. reportedPodMetrics: [][]int64{{5000}, {5000}, {5000}},
  241. }
  242. tc.runTest(t)
  243. }
  244. func TestRESTClientExternal(t *testing.T) {
  245. tc := restClientTestCase{
  246. desiredMetricValues: PodMetricsInfo{
  247. "external-val-0": {Value: 10000}, "external-val-1": {Value: 20000}, "external-val-2": {Value: 10000},
  248. },
  249. metricSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
  250. metricName: "external",
  251. targetTimestamp: 1,
  252. reportedMetricPoints: []metricPoint{{10000, 1}, {20000, 1}, {10000, 1}},
  253. }
  254. tc.runTest(t)
  255. }
  256. func TestRESTClientQPS(t *testing.T) {
  257. targetTimestamp := 1
  258. tc := restClientTestCase{
  259. desiredMetricValues: PodMetricsInfo{
  260. "test-pod-0": {Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  261. "test-pod-1": {Value: 20000, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  262. "test-pod-2": {Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  263. },
  264. metricName: "qps",
  265. targetTimestamp: targetTimestamp,
  266. reportedMetricPoints: []metricPoint{{10000, 1}, {20000, 1}, {10000, 1}},
  267. }
  268. tc.runTest(t)
  269. }
  270. func TestRESTClientSingleObject(t *testing.T) {
  271. tc := restClientTestCase{
  272. desiredMetricValues: PodMetricsInfo{"some-dep": {Value: 10}},
  273. metricName: "queue-length",
  274. targetTimestamp: 1,
  275. reportedMetricPoints: []metricPoint{{10, 1}},
  276. singleObject: &autoscalingapi.CrossVersionObjectReference{
  277. APIVersion: "apps/v1",
  278. Kind: "Deployment",
  279. Name: "some-dep",
  280. },
  281. }
  282. tc.runTest(t)
  283. }
  284. func TestRESTClientQpsSumEqualZero(t *testing.T) {
  285. targetTimestamp := 0
  286. tc := restClientTestCase{
  287. desiredMetricValues: PodMetricsInfo{
  288. "test-pod-0": {Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  289. "test-pod-1": {Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  290. "test-pod-2": {Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: metricServerDefaultMetricWindow},
  291. },
  292. metricName: "qps",
  293. targetTimestamp: targetTimestamp,
  294. reportedMetricPoints: []metricPoint{{0, 0}, {0, 0}, {0, 0}},
  295. }
  296. tc.runTest(t)
  297. }
  298. func TestRESTClientExternalSumEqualZero(t *testing.T) {
  299. tc := restClientTestCase{
  300. desiredMetricValues: PodMetricsInfo{
  301. "external-val-0": {Value: 0}, "external-val-1": {Value: 0}, "external-val-2": {Value: 0},
  302. },
  303. metricSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
  304. metricName: "external",
  305. targetTimestamp: 0,
  306. reportedMetricPoints: []metricPoint{{0, 0}, {0, 0}, {0, 0}},
  307. }
  308. tc.runTest(t)
  309. }
  310. func TestRESTClientQpsEmptyMetrics(t *testing.T) {
  311. tc := restClientTestCase{
  312. metricName: "qps",
  313. desiredError: fmt.Errorf("no metrics returned from custom metrics API"),
  314. reportedMetricPoints: []metricPoint{},
  315. }
  316. tc.runTest(t)
  317. }
  318. func TestRESTClientExternalEmptyMetrics(t *testing.T) {
  319. tc := restClientTestCase{
  320. metricName: "external",
  321. metricSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"label": "value"}},
  322. desiredError: fmt.Errorf("no metrics returned from external metrics API"),
  323. reportedMetricPoints: []metricPoint{},
  324. }
  325. tc.runTest(t)
  326. }
  327. func TestRESTClientCPUEmptyMetrics(t *testing.T) {
  328. tc := restClientTestCase{
  329. resourceName: v1.ResourceCPU,
  330. desiredError: fmt.Errorf("no metrics returned from resource metrics API"),
  331. reportedMetricPoints: []metricPoint{},
  332. reportedPodMetrics: [][]int64{},
  333. }
  334. tc.runTest(t)
  335. }
  336. func TestRESTClientCPUEmptyMetricsForOnePod(t *testing.T) {
  337. targetTimestamp := 1
  338. window := 30 * time.Second
  339. tc := restClientTestCase{
  340. resourceName: v1.ResourceCPU,
  341. desiredMetricValues: PodMetricsInfo{
  342. "test-pod-0": {Value: 100, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  343. "test-pod-1": {Value: 700, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
  344. },
  345. targetTimestamp: targetTimestamp,
  346. window: window,
  347. reportedPodMetrics: [][]int64{{100}, {300, 400}, {}},
  348. }
  349. tc.runTest(t)
  350. }