legacy_replica_calculator_test.go 22 KB

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