legacy_replica_calculator_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. Copyright 2016 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 podautoscaler
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "math"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. "time"
  22. "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/api/resource"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/runtime"
  26. "k8s.io/client-go/informers"
  27. "k8s.io/client-go/kubernetes/fake"
  28. restclient "k8s.io/client-go/rest"
  29. core "k8s.io/client-go/testing"
  30. "k8s.io/client-go/tools/cache"
  31. "k8s.io/kubernetes/pkg/controller"
  32. "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics"
  33. heapster "k8s.io/heapster/metrics/api/v1/types"
  34. metricsapi "k8s.io/metrics/pkg/apis/metrics/v1alpha1"
  35. "github.com/stretchr/testify/assert"
  36. "github.com/stretchr/testify/require"
  37. )
  38. type legacyReplicaCalcTestCase struct {
  39. currentReplicas int32
  40. expectedReplicas int32
  41. expectedError error
  42. timestamp time.Time
  43. resource *resourceInfo
  44. metric *metricInfo
  45. podReadiness []v1.ConditionStatus
  46. }
  47. func (tc *legacyReplicaCalcTestCase) prepareTestClient(t *testing.T) *fake.Clientset {
  48. fakeClient := &fake.Clientset{}
  49. fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  50. obj := &v1.PodList{}
  51. for i := 0; i < int(tc.currentReplicas); i++ {
  52. podReadiness := v1.ConditionTrue
  53. if tc.podReadiness != nil {
  54. podReadiness = tc.podReadiness[i]
  55. }
  56. podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
  57. pod := v1.Pod{
  58. Status: v1.PodStatus{
  59. Phase: v1.PodRunning,
  60. StartTime: &metav1.Time{Time: time.Now().Add(-3 * time.Minute)},
  61. Conditions: []v1.PodCondition{
  62. {
  63. Type: v1.PodReady,
  64. Status: podReadiness,
  65. },
  66. },
  67. },
  68. ObjectMeta: metav1.ObjectMeta{
  69. Name: podName,
  70. Namespace: testNamespace,
  71. Labels: map[string]string{
  72. "name": podNamePrefix,
  73. },
  74. },
  75. Spec: v1.PodSpec{
  76. Containers: []v1.Container{{}, {}},
  77. },
  78. }
  79. if tc.resource != nil && i < len(tc.resource.requests) {
  80. pod.Spec.Containers[0].Resources = v1.ResourceRequirements{
  81. Requests: v1.ResourceList{
  82. tc.resource.name: tc.resource.requests[i],
  83. },
  84. }
  85. pod.Spec.Containers[1].Resources = v1.ResourceRequirements{
  86. Requests: v1.ResourceList{
  87. tc.resource.name: tc.resource.requests[i],
  88. },
  89. }
  90. }
  91. obj.Items = append(obj.Items, pod)
  92. }
  93. return true, obj, nil
  94. })
  95. fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
  96. var heapsterRawMemResponse []byte
  97. if tc.resource != nil {
  98. metrics := metricsapi.PodMetricsList{}
  99. for i, resValue := range tc.resource.levels {
  100. podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
  101. if len(tc.resource.podNames) > i {
  102. podName = tc.resource.podNames[i]
  103. }
  104. podMetric := metricsapi.PodMetrics{
  105. ObjectMeta: metav1.ObjectMeta{
  106. Name: podName,
  107. Namespace: testNamespace,
  108. },
  109. Timestamp: metav1.Time{Time: tc.timestamp},
  110. Containers: make([]metricsapi.ContainerMetrics, numContainersPerPod),
  111. }
  112. for i := 0; i < numContainersPerPod; i++ {
  113. podMetric.Containers[i] = metricsapi.ContainerMetrics{
  114. Name: fmt.Sprintf("container%v", i),
  115. Usage: v1.ResourceList{
  116. v1.ResourceName(tc.resource.name): *resource.NewMilliQuantity(
  117. int64(resValue),
  118. resource.DecimalSI),
  119. },
  120. }
  121. }
  122. metrics.Items = append(metrics.Items, podMetric)
  123. }
  124. heapsterRawMemResponse, _ = json.Marshal(&metrics)
  125. } else {
  126. // only return the pods that we actually asked for
  127. proxyAction := action.(core.ProxyGetAction)
  128. pathParts := strings.Split(proxyAction.GetPath(), "/")
  129. // pathParts should look like [ api, v1, model, namespaces, $NS, pod-list, $PODS, metrics, $METRIC... ]
  130. if len(pathParts) < 9 {
  131. return true, nil, fmt.Errorf("invalid heapster path %q", proxyAction.GetPath())
  132. }
  133. podNames := strings.Split(pathParts[7], ",")
  134. podPresent := make([]bool, len(tc.metric.levels))
  135. for _, name := range podNames {
  136. if len(name) <= len(podNamePrefix)+1 {
  137. return true, nil, fmt.Errorf("unknown pod %q", name)
  138. }
  139. num, err := strconv.Atoi(name[len(podNamePrefix)+1:])
  140. if err != nil {
  141. return true, nil, fmt.Errorf("unknown pod %q", name)
  142. }
  143. podPresent[num] = true
  144. }
  145. timestamp := tc.timestamp
  146. metrics := heapster.MetricResultList{}
  147. for i, level := range tc.metric.levels {
  148. if !podPresent[i] {
  149. continue
  150. }
  151. floatVal := float64(tc.metric.levels[i]) / 1000.0
  152. metric := heapster.MetricResult{
  153. Metrics: []heapster.MetricPoint{{Timestamp: timestamp, Value: uint64(level), FloatValue: &floatVal}},
  154. LatestTimestamp: timestamp,
  155. }
  156. metrics.Items = append(metrics.Items, metric)
  157. }
  158. heapsterRawMemResponse, _ = json.Marshal(&metrics)
  159. }
  160. return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
  161. })
  162. return fakeClient
  163. }
  164. func (tc *legacyReplicaCalcTestCase) runTest(t *testing.T) {
  165. testClient := tc.prepareTestClient(t)
  166. metricsClient := metrics.NewHeapsterMetricsClient(testClient, metrics.DefaultHeapsterNamespace, metrics.DefaultHeapsterScheme, metrics.DefaultHeapsterService, metrics.DefaultHeapsterPort)
  167. informerFactory := informers.NewSharedInformerFactory(testClient, controller.NoResyncPeriodFunc())
  168. informer := informerFactory.Core().V1().Pods()
  169. replicaCalc := NewReplicaCalculator(metricsClient, informer.Lister(), defaultTestingTolerance, defaultTestingCpuInitializationPeriod, defaultTestingDelayOfInitialReadinessStatus)
  170. stop := make(chan struct{})
  171. defer close(stop)
  172. informerFactory.Start(stop)
  173. if !cache.WaitForNamedCacheSync("HPA", stop, informer.Informer().HasSynced) {
  174. return
  175. }
  176. selector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{
  177. MatchLabels: map[string]string{"name": podNamePrefix},
  178. })
  179. if err != nil {
  180. require.Nil(t, err, "something went horribly wrong...")
  181. }
  182. if tc.resource != nil {
  183. outReplicas, outUtilization, outRawValue, outTimestamp, err := replicaCalc.GetResourceReplicas(tc.currentReplicas, tc.resource.targetUtilization, tc.resource.name, testNamespace, selector)
  184. if tc.expectedError != nil {
  185. require.Error(t, err, "there should be an error calculating the replica count")
  186. assert.Contains(t, err.Error(), tc.expectedError.Error(), "the error message should have contained the expected error message")
  187. return
  188. }
  189. require.NoError(t, err, "there should not have been an error calculating the replica count")
  190. assert.Equal(t, tc.expectedReplicas, outReplicas, "replicas should be as expected")
  191. assert.Equal(t, tc.resource.expectedUtilization, outUtilization, "utilization should be as expected")
  192. assert.Equal(t, tc.resource.expectedValue, outRawValue, "raw value should be as expected")
  193. assert.True(t, tc.timestamp.Equal(outTimestamp), "timestamp should be as expected")
  194. } else {
  195. outReplicas, outUtilization, outTimestamp, err := replicaCalc.GetMetricReplicas(tc.currentReplicas, tc.metric.targetUtilization, tc.metric.name, testNamespace, selector, nil)
  196. if tc.expectedError != nil {
  197. require.Error(t, err, "there should be an error calculating the replica count")
  198. assert.Contains(t, err.Error(), tc.expectedError.Error(), "the error message should have contained the expected error message")
  199. return
  200. }
  201. require.NoError(t, err, "there should not have been an error calculating the replica count")
  202. assert.Equal(t, tc.expectedReplicas, outReplicas, "replicas should be as expected")
  203. assert.Equal(t, tc.metric.expectedUtilization, outUtilization, "utilization should be as expected")
  204. assert.True(t, tc.timestamp.Equal(outTimestamp), "timestamp should be as expected")
  205. }
  206. }
  207. func TestLegacyReplicaCalcDisjointResourcesMetrics(t *testing.T) {
  208. tc := legacyReplicaCalcTestCase{
  209. currentReplicas: 1,
  210. expectedError: fmt.Errorf("no metrics returned matched known pods"),
  211. resource: &resourceInfo{
  212. name: v1.ResourceCPU,
  213. requests: []resource.Quantity{resource.MustParse("1.0")},
  214. levels: []int64{100},
  215. podNames: []string{"an-older-pod-name"},
  216. targetUtilization: 100,
  217. },
  218. }
  219. tc.runTest(t)
  220. }
  221. func TestLegacyReplicaCalcScaleUp(t *testing.T) {
  222. tc := legacyReplicaCalcTestCase{
  223. currentReplicas: 3,
  224. expectedReplicas: 5,
  225. resource: &resourceInfo{
  226. name: v1.ResourceCPU,
  227. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  228. levels: []int64{300, 500, 700},
  229. targetUtilization: 30,
  230. expectedUtilization: 50,
  231. expectedValue: numContainersPerPod * 500,
  232. },
  233. }
  234. tc.runTest(t)
  235. }
  236. func TestLegacyReplicaCalcScaleUpUnreadyLessScale(t *testing.T) {
  237. tc := legacyReplicaCalcTestCase{
  238. currentReplicas: 3,
  239. expectedReplicas: 4,
  240. podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
  241. resource: &resourceInfo{
  242. name: v1.ResourceCPU,
  243. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  244. levels: []int64{300, 500, 700},
  245. targetUtilization: 30,
  246. expectedUtilization: 60,
  247. expectedValue: numContainersPerPod * 600,
  248. },
  249. }
  250. tc.runTest(t)
  251. }
  252. func TestLegacyReplicaCalcScaleUpUnreadyNoScale(t *testing.T) {
  253. tc := legacyReplicaCalcTestCase{
  254. currentReplicas: 3,
  255. expectedReplicas: 3,
  256. podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
  257. resource: &resourceInfo{
  258. name: v1.ResourceCPU,
  259. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  260. levels: []int64{400, 500, 700},
  261. targetUtilization: 30,
  262. expectedUtilization: 40,
  263. expectedValue: numContainersPerPod * 400,
  264. },
  265. }
  266. tc.runTest(t)
  267. }
  268. func TestLegacyReplicaCalcScaleUpCM(t *testing.T) {
  269. tc := legacyReplicaCalcTestCase{
  270. currentReplicas: 3,
  271. expectedReplicas: 4,
  272. metric: &metricInfo{
  273. name: "qps",
  274. levels: []int64{20000, 10000, 30000},
  275. targetUtilization: 15000,
  276. expectedUtilization: 20000,
  277. },
  278. }
  279. tc.runTest(t)
  280. }
  281. func TestLegacyReplicaCalcScaleUpCMUnreadyNoLessScale(t *testing.T) {
  282. tc := legacyReplicaCalcTestCase{
  283. currentReplicas: 3,
  284. expectedReplicas: 6,
  285. podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse},
  286. metric: &metricInfo{
  287. name: "qps",
  288. levels: []int64{50000, 10000, 30000},
  289. targetUtilization: 15000,
  290. expectedUtilization: 30000,
  291. },
  292. }
  293. tc.runTest(t)
  294. }
  295. func TestLegacyReplicaCalcScaleUpCMUnreadyScale(t *testing.T) {
  296. tc := legacyReplicaCalcTestCase{
  297. currentReplicas: 3,
  298. expectedReplicas: 7,
  299. podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse},
  300. metric: &metricInfo{
  301. name: "qps",
  302. levels: []int64{50000, 15000, 30000},
  303. targetUtilization: 15000,
  304. expectedUtilization: 31666,
  305. },
  306. }
  307. tc.runTest(t)
  308. }
  309. func TestLegacyReplicaCalcScaleDown(t *testing.T) {
  310. tc := legacyReplicaCalcTestCase{
  311. currentReplicas: 5,
  312. expectedReplicas: 3,
  313. resource: &resourceInfo{
  314. name: v1.ResourceCPU,
  315. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  316. levels: []int64{100, 300, 500, 250, 250},
  317. targetUtilization: 50,
  318. expectedUtilization: 28,
  319. expectedValue: numContainersPerPod * 280,
  320. },
  321. }
  322. tc.runTest(t)
  323. }
  324. func TestLegacyReplicaCalcScaleDownCM(t *testing.T) {
  325. tc := legacyReplicaCalcTestCase{
  326. currentReplicas: 5,
  327. expectedReplicas: 3,
  328. metric: &metricInfo{
  329. name: "qps",
  330. levels: []int64{12000, 12000, 12000, 12000, 12000},
  331. targetUtilization: 20000,
  332. expectedUtilization: 12000,
  333. },
  334. }
  335. tc.runTest(t)
  336. }
  337. func TestLegacyReplicaCalcScaleDownIgnoresUnreadyPods(t *testing.T) {
  338. tc := legacyReplicaCalcTestCase{
  339. currentReplicas: 5,
  340. expectedReplicas: 2,
  341. podReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
  342. resource: &resourceInfo{
  343. name: v1.ResourceCPU,
  344. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  345. levels: []int64{100, 300, 500, 250, 250},
  346. targetUtilization: 50,
  347. expectedUtilization: 30,
  348. expectedValue: numContainersPerPod * 300,
  349. },
  350. }
  351. tc.runTest(t)
  352. }
  353. func TestLegacyReplicaCalcTolerance(t *testing.T) {
  354. tc := legacyReplicaCalcTestCase{
  355. currentReplicas: 3,
  356. expectedReplicas: 3,
  357. resource: &resourceInfo{
  358. name: v1.ResourceCPU,
  359. requests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  360. levels: []int64{1010, 1030, 1020},
  361. targetUtilization: 100,
  362. expectedUtilization: 102,
  363. expectedValue: numContainersPerPod * 1020,
  364. },
  365. }
  366. tc.runTest(t)
  367. }
  368. func TestLegacyReplicaCalcToleranceCM(t *testing.T) {
  369. tc := legacyReplicaCalcTestCase{
  370. currentReplicas: 3,
  371. expectedReplicas: 3,
  372. metric: &metricInfo{
  373. name: "qps",
  374. levels: []int64{20000, 21000, 21000},
  375. targetUtilization: 20000,
  376. expectedUtilization: 20666,
  377. },
  378. }
  379. tc.runTest(t)
  380. }
  381. func TestLegacyReplicaCalcSuperfluousMetrics(t *testing.T) {
  382. tc := legacyReplicaCalcTestCase{
  383. currentReplicas: 4,
  384. expectedReplicas: 24,
  385. resource: &resourceInfo{
  386. name: v1.ResourceCPU,
  387. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  388. levels: []int64{4000, 9500, 3000, 7000, 3200, 2000},
  389. targetUtilization: 100,
  390. expectedUtilization: 587,
  391. expectedValue: numContainersPerPod * 5875,
  392. },
  393. }
  394. tc.runTest(t)
  395. }
  396. func TestLegacyReplicaCalcMissingMetrics(t *testing.T) {
  397. tc := legacyReplicaCalcTestCase{
  398. currentReplicas: 4,
  399. expectedReplicas: 3,
  400. resource: &resourceInfo{
  401. name: v1.ResourceCPU,
  402. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  403. levels: []int64{400, 95},
  404. targetUtilization: 100,
  405. expectedUtilization: 24,
  406. expectedValue: 495, // numContainersPerPod * 247, for sufficiently large values of 247
  407. },
  408. }
  409. tc.runTest(t)
  410. }
  411. func TestLegacyReplicaCalcEmptyMetrics(t *testing.T) {
  412. tc := legacyReplicaCalcTestCase{
  413. currentReplicas: 4,
  414. expectedError: fmt.Errorf("unable to get metrics for resource cpu: no metrics returned from heapster"),
  415. resource: &resourceInfo{
  416. name: v1.ResourceCPU,
  417. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  418. levels: []int64{},
  419. targetUtilization: 100,
  420. },
  421. }
  422. tc.runTest(t)
  423. }
  424. func TestLegacyReplicaCalcEmptyCPURequest(t *testing.T) {
  425. tc := legacyReplicaCalcTestCase{
  426. currentReplicas: 1,
  427. expectedError: fmt.Errorf("missing request for"),
  428. resource: &resourceInfo{
  429. name: v1.ResourceCPU,
  430. requests: []resource.Quantity{},
  431. levels: []int64{200},
  432. targetUtilization: 100,
  433. },
  434. }
  435. tc.runTest(t)
  436. }
  437. func TestLegacyReplicaCalcMissingMetricsNoChangeEq(t *testing.T) {
  438. tc := legacyReplicaCalcTestCase{
  439. currentReplicas: 2,
  440. expectedReplicas: 2,
  441. resource: &resourceInfo{
  442. name: v1.ResourceCPU,
  443. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
  444. levels: []int64{1000},
  445. targetUtilization: 100,
  446. expectedUtilization: 100,
  447. expectedValue: numContainersPerPod * 1000,
  448. },
  449. }
  450. tc.runTest(t)
  451. }
  452. func TestLegacyReplicaCalcMissingMetricsNoChangeGt(t *testing.T) {
  453. tc := legacyReplicaCalcTestCase{
  454. currentReplicas: 2,
  455. expectedReplicas: 2,
  456. resource: &resourceInfo{
  457. name: v1.ResourceCPU,
  458. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
  459. levels: []int64{1900},
  460. targetUtilization: 100,
  461. expectedUtilization: 190,
  462. expectedValue: numContainersPerPod * 1900,
  463. },
  464. }
  465. tc.runTest(t)
  466. }
  467. func TestLegacyReplicaCalcMissingMetricsNoChangeLt(t *testing.T) {
  468. tc := legacyReplicaCalcTestCase{
  469. currentReplicas: 2,
  470. expectedReplicas: 2,
  471. resource: &resourceInfo{
  472. name: v1.ResourceCPU,
  473. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0")},
  474. levels: []int64{600},
  475. targetUtilization: 100,
  476. expectedUtilization: 60,
  477. expectedValue: numContainersPerPod * 600,
  478. },
  479. }
  480. tc.runTest(t)
  481. }
  482. func TestLegacyReplicaCalcMissingMetricsUnreadyNoChange(t *testing.T) {
  483. tc := legacyReplicaCalcTestCase{
  484. currentReplicas: 3,
  485. expectedReplicas: 3,
  486. podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
  487. resource: &resourceInfo{
  488. name: v1.ResourceCPU,
  489. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  490. levels: []int64{100, 450},
  491. targetUtilization: 50,
  492. expectedUtilization: 45,
  493. expectedValue: numContainersPerPod * 450,
  494. },
  495. }
  496. tc.runTest(t)
  497. }
  498. func TestLegacyReplicaCalcMissingMetricsUnreadyScaleUp(t *testing.T) {
  499. tc := legacyReplicaCalcTestCase{
  500. currentReplicas: 3,
  501. expectedReplicas: 4,
  502. podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
  503. resource: &resourceInfo{
  504. name: v1.ResourceCPU,
  505. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  506. levels: []int64{100, 2000},
  507. targetUtilization: 50,
  508. expectedUtilization: 200,
  509. expectedValue: numContainersPerPod * 2000,
  510. },
  511. }
  512. tc.runTest(t)
  513. }
  514. func TestLegacyReplicaCalcMissingMetricsUnreadyScaleDown(t *testing.T) {
  515. tc := legacyReplicaCalcTestCase{
  516. currentReplicas: 4,
  517. expectedReplicas: 3,
  518. podReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue},
  519. resource: &resourceInfo{
  520. name: v1.ResourceCPU,
  521. requests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  522. levels: []int64{100, 100, 100},
  523. targetUtilization: 50,
  524. expectedUtilization: 10,
  525. expectedValue: numContainersPerPod * 100,
  526. },
  527. }
  528. tc.runTest(t)
  529. }
  530. // TestComputedToleranceAlgImplementation is a regression test which
  531. // back-calculates a minimal percentage for downscaling based on a small percentage
  532. // increase in pod utilization which is calibrated against the tolerance value.
  533. func TestLegacyReplicaCalcComputedToleranceAlgImplementation(t *testing.T) {
  534. startPods := int32(10)
  535. // 150 mCPU per pod.
  536. totalUsedCPUOfAllPods := int64(startPods * 150)
  537. // Each pod starts out asking for 2X what is really needed.
  538. // This means we will have a 50% ratio of used/requested
  539. totalRequestedCPUOfAllPods := int32(2 * totalUsedCPUOfAllPods)
  540. requestedToUsed := float64(totalRequestedCPUOfAllPods / int32(totalUsedCPUOfAllPods))
  541. // Spread the amount we ask over 10 pods. We can add some jitter later in reportedLevels.
  542. perPodRequested := totalRequestedCPUOfAllPods / startPods
  543. // Force a minimal scaling event by satisfying (tolerance < 1 - resourcesUsedRatio).
  544. target := math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .01
  545. finalCPUPercentTarget := int32(target * 100)
  546. resourcesUsedRatio := float64(totalUsedCPUOfAllPods) / float64(float64(totalRequestedCPUOfAllPods)*target)
  547. // i.e. .60 * 20 -> scaled down expectation.
  548. finalPods := int32(math.Ceil(resourcesUsedRatio * float64(startPods)))
  549. // To breach tolerance we will create a utilization ratio difference of tolerance to usageRatioToleranceValue)
  550. tc := legacyReplicaCalcTestCase{
  551. currentReplicas: startPods,
  552. expectedReplicas: finalPods,
  553. resource: &resourceInfo{
  554. name: v1.ResourceCPU,
  555. levels: []int64{
  556. totalUsedCPUOfAllPods / 10,
  557. totalUsedCPUOfAllPods / 10,
  558. totalUsedCPUOfAllPods / 10,
  559. totalUsedCPUOfAllPods / 10,
  560. totalUsedCPUOfAllPods / 10,
  561. totalUsedCPUOfAllPods / 10,
  562. totalUsedCPUOfAllPods / 10,
  563. totalUsedCPUOfAllPods / 10,
  564. totalUsedCPUOfAllPods / 10,
  565. totalUsedCPUOfAllPods / 10,
  566. },
  567. requests: []resource.Quantity{
  568. resource.MustParse(fmt.Sprint(perPodRequested+100) + "m"),
  569. resource.MustParse(fmt.Sprint(perPodRequested-100) + "m"),
  570. resource.MustParse(fmt.Sprint(perPodRequested+10) + "m"),
  571. resource.MustParse(fmt.Sprint(perPodRequested-10) + "m"),
  572. resource.MustParse(fmt.Sprint(perPodRequested+2) + "m"),
  573. resource.MustParse(fmt.Sprint(perPodRequested-2) + "m"),
  574. resource.MustParse(fmt.Sprint(perPodRequested+1) + "m"),
  575. resource.MustParse(fmt.Sprint(perPodRequested-1) + "m"),
  576. resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
  577. resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
  578. },
  579. targetUtilization: finalCPUPercentTarget,
  580. expectedUtilization: int32(totalUsedCPUOfAllPods*100) / totalRequestedCPUOfAllPods,
  581. expectedValue: numContainersPerPod * totalUsedCPUOfAllPods / 10,
  582. },
  583. }
  584. tc.runTest(t)
  585. // Reuse the data structure above, now testing "unscaling".
  586. // Now, we test that no scaling happens if we are in a very close margin to the tolerance
  587. target = math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .004
  588. finalCPUPercentTarget = int32(target * 100)
  589. tc.resource.targetUtilization = finalCPUPercentTarget
  590. tc.currentReplicas = startPods
  591. tc.expectedReplicas = startPods
  592. tc.runTest(t)
  593. }
  594. // TODO: add more tests