legacy_horizontal_test.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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 podautoscaler
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "math"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "testing"
  23. "time"
  24. autoscalingv1 "k8s.io/api/autoscaling/v1"
  25. autoscalingv2 "k8s.io/api/autoscaling/v2beta1"
  26. "k8s.io/api/core/v1"
  27. "k8s.io/apimachinery/pkg/api/meta/testrestmapper"
  28. "k8s.io/apimachinery/pkg/api/resource"
  29. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  30. "k8s.io/apimachinery/pkg/labels"
  31. "k8s.io/apimachinery/pkg/runtime"
  32. "k8s.io/apimachinery/pkg/watch"
  33. "k8s.io/client-go/informers"
  34. "k8s.io/client-go/kubernetes/fake"
  35. restclient "k8s.io/client-go/rest"
  36. scalefake "k8s.io/client-go/scale/fake"
  37. core "k8s.io/client-go/testing"
  38. "k8s.io/kubernetes/pkg/api/legacyscheme"
  39. "k8s.io/kubernetes/pkg/controller"
  40. "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics"
  41. heapster "k8s.io/heapster/metrics/api/v1/types"
  42. metricsapi "k8s.io/metrics/pkg/apis/metrics/v1alpha1"
  43. "github.com/stretchr/testify/assert"
  44. _ "k8s.io/kubernetes/pkg/apis/apps/install"
  45. _ "k8s.io/kubernetes/pkg/apis/autoscaling/install"
  46. _ "k8s.io/kubernetes/pkg/apis/core/install"
  47. )
  48. func (w fakeResponseWrapper) DoRaw() ([]byte, error) {
  49. return w.raw, nil
  50. }
  51. func (w fakeResponseWrapper) Stream() (io.ReadCloser, error) {
  52. return nil, nil
  53. }
  54. func newFakeResponseWrapper(raw []byte) fakeResponseWrapper {
  55. return fakeResponseWrapper{raw: raw}
  56. }
  57. type fakeResponseWrapper struct {
  58. raw []byte
  59. }
  60. type legacyTestCase struct {
  61. sync.Mutex
  62. minReplicas int32
  63. maxReplicas int32
  64. initialReplicas int32
  65. desiredReplicas int32
  66. // CPU target utilization as a percentage of the requested resources.
  67. CPUTarget int32
  68. CPUCurrent int32
  69. verifyCPUCurrent bool
  70. reportedLevels []uint64
  71. reportedCPURequests []resource.Quantity
  72. reportedPodReadiness []v1.ConditionStatus
  73. scaleUpdated bool
  74. statusUpdated bool
  75. eventCreated bool
  76. verifyEvents bool
  77. useMetricsAPI bool
  78. metricsTarget []autoscalingv2.MetricSpec
  79. // Channel with names of HPA objects which we have reconciled.
  80. processed chan string
  81. // Target resource information.
  82. resource *fakeResource
  83. // Last scale time
  84. lastScaleTime *metav1.Time
  85. recommendations []timestampedRecommendation
  86. finished bool
  87. }
  88. // Needs to be called under a lock.
  89. func (tc *legacyTestCase) computeCPUCurrent() {
  90. if len(tc.reportedLevels) != len(tc.reportedCPURequests) || len(tc.reportedLevels) == 0 {
  91. return
  92. }
  93. reported := 0
  94. for _, r := range tc.reportedLevels {
  95. reported += int(r)
  96. }
  97. requested := 0
  98. for _, req := range tc.reportedCPURequests {
  99. requested += int(req.MilliValue())
  100. }
  101. tc.CPUCurrent = int32(100 * reported / requested)
  102. }
  103. func (tc *legacyTestCase) prepareTestClient(t *testing.T) (*fake.Clientset, *scalefake.FakeScaleClient) {
  104. namespace := "test-namespace"
  105. hpaName := "test-hpa"
  106. podNamePrefix := "test-pod"
  107. labelSet := map[string]string{"name": podNamePrefix}
  108. selector := labels.SelectorFromSet(labelSet).String()
  109. tc.Lock()
  110. tc.scaleUpdated = false
  111. tc.statusUpdated = false
  112. tc.eventCreated = false
  113. tc.processed = make(chan string, 100)
  114. if tc.CPUCurrent == 0 {
  115. tc.computeCPUCurrent()
  116. }
  117. if tc.resource == nil {
  118. tc.resource = &fakeResource{
  119. name: "test-rc",
  120. apiVersion: "v1",
  121. kind: "ReplicationController",
  122. }
  123. }
  124. tc.Unlock()
  125. fakeClient := &fake.Clientset{}
  126. fakeClient.AddReactor("list", "horizontalpodautoscalers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  127. tc.Lock()
  128. defer tc.Unlock()
  129. obj := &autoscalingv2.HorizontalPodAutoscalerList{
  130. Items: []autoscalingv2.HorizontalPodAutoscaler{
  131. {
  132. ObjectMeta: metav1.ObjectMeta{
  133. Name: hpaName,
  134. Namespace: namespace,
  135. SelfLink: "experimental/v1/namespaces/" + namespace + "/horizontalpodautoscalers/" + hpaName,
  136. },
  137. Spec: autoscalingv2.HorizontalPodAutoscalerSpec{
  138. ScaleTargetRef: autoscalingv2.CrossVersionObjectReference{
  139. Kind: tc.resource.kind,
  140. Name: tc.resource.name,
  141. APIVersion: tc.resource.apiVersion,
  142. },
  143. MinReplicas: &tc.minReplicas,
  144. MaxReplicas: tc.maxReplicas,
  145. },
  146. Status: autoscalingv2.HorizontalPodAutoscalerStatus{
  147. CurrentReplicas: tc.initialReplicas,
  148. DesiredReplicas: tc.initialReplicas,
  149. },
  150. },
  151. },
  152. }
  153. if tc.CPUTarget > 0.0 {
  154. obj.Items[0].Spec.Metrics = []autoscalingv2.MetricSpec{
  155. {
  156. Type: autoscalingv2.ResourceMetricSourceType,
  157. Resource: &autoscalingv2.ResourceMetricSource{
  158. Name: v1.ResourceCPU,
  159. TargetAverageUtilization: &tc.CPUTarget,
  160. },
  161. },
  162. }
  163. }
  164. if len(tc.metricsTarget) > 0 {
  165. obj.Items[0].Spec.Metrics = append(obj.Items[0].Spec.Metrics, tc.metricsTarget...)
  166. }
  167. if len(obj.Items[0].Spec.Metrics) == 0 {
  168. // manually add in the defaulting logic
  169. obj.Items[0].Spec.Metrics = []autoscalingv2.MetricSpec{
  170. {
  171. Type: autoscalingv2.ResourceMetricSourceType,
  172. Resource: &autoscalingv2.ResourceMetricSource{
  173. Name: v1.ResourceCPU,
  174. },
  175. },
  176. }
  177. }
  178. // and... convert to autoscaling v1 to return the right type
  179. objv1, err := unsafeConvertToVersionVia(obj, autoscalingv1.SchemeGroupVersion)
  180. if err != nil {
  181. return true, nil, err
  182. }
  183. return true, objv1, nil
  184. })
  185. fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  186. tc.Lock()
  187. defer tc.Unlock()
  188. obj := &v1.PodList{}
  189. for i := 0; i < len(tc.reportedCPURequests); i++ {
  190. podReadiness := v1.ConditionTrue
  191. if tc.reportedPodReadiness != nil {
  192. podReadiness = tc.reportedPodReadiness[i]
  193. }
  194. podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
  195. pod := v1.Pod{
  196. Status: v1.PodStatus{
  197. StartTime: &metav1.Time{Time: time.Now().Add(-3 * time.Minute)},
  198. Phase: v1.PodRunning,
  199. Conditions: []v1.PodCondition{
  200. {
  201. Type: v1.PodReady,
  202. Status: podReadiness,
  203. },
  204. },
  205. },
  206. ObjectMeta: metav1.ObjectMeta{
  207. Name: podName,
  208. Namespace: namespace,
  209. Labels: map[string]string{
  210. "name": podNamePrefix,
  211. },
  212. },
  213. Spec: v1.PodSpec{
  214. Containers: []v1.Container{
  215. {
  216. Resources: v1.ResourceRequirements{
  217. Requests: v1.ResourceList{
  218. v1.ResourceCPU: tc.reportedCPURequests[i],
  219. },
  220. },
  221. },
  222. },
  223. },
  224. }
  225. obj.Items = append(obj.Items, pod)
  226. }
  227. return true, obj, nil
  228. })
  229. fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
  230. tc.Lock()
  231. defer tc.Unlock()
  232. var heapsterRawMemResponse []byte
  233. if tc.useMetricsAPI {
  234. metrics := metricsapi.PodMetricsList{}
  235. for i, cpu := range tc.reportedLevels {
  236. podMetric := metricsapi.PodMetrics{
  237. ObjectMeta: metav1.ObjectMeta{
  238. Name: fmt.Sprintf("%s-%d", podNamePrefix, i),
  239. Namespace: namespace,
  240. },
  241. Timestamp: metav1.Time{Time: time.Now()},
  242. Containers: []metricsapi.ContainerMetrics{
  243. {
  244. Name: "container",
  245. Usage: v1.ResourceList{
  246. v1.ResourceCPU: *resource.NewMilliQuantity(
  247. int64(cpu),
  248. resource.DecimalSI),
  249. v1.ResourceMemory: *resource.NewQuantity(
  250. int64(1024*1024),
  251. resource.BinarySI),
  252. },
  253. },
  254. },
  255. }
  256. metrics.Items = append(metrics.Items, podMetric)
  257. }
  258. heapsterRawMemResponse, _ = json.Marshal(&metrics)
  259. } else {
  260. // only return the pods that we actually asked for
  261. proxyAction := action.(core.ProxyGetAction)
  262. pathParts := strings.Split(proxyAction.GetPath(), "/")
  263. // pathParts should look like [ api, v1, model, namespaces, $NS, pod-list, $PODS, metrics, $METRIC... ]
  264. if len(pathParts) < 9 {
  265. return true, nil, fmt.Errorf("invalid heapster path %q", proxyAction.GetPath())
  266. }
  267. podNames := strings.Split(pathParts[7], ",")
  268. podPresent := make([]bool, len(tc.reportedLevels))
  269. for _, name := range podNames {
  270. if len(name) <= len(podNamePrefix)+1 {
  271. return true, nil, fmt.Errorf("unknown pod %q", name)
  272. }
  273. num, err := strconv.Atoi(name[len(podNamePrefix)+1:])
  274. if err != nil {
  275. return true, nil, fmt.Errorf("unknown pod %q", name)
  276. }
  277. podPresent[num] = true
  278. }
  279. timestamp := time.Now()
  280. metrics := heapster.MetricResultList{}
  281. for i, level := range tc.reportedLevels {
  282. if !podPresent[i] {
  283. continue
  284. }
  285. metric := heapster.MetricResult{
  286. Metrics: []heapster.MetricPoint{{Timestamp: timestamp, Value: level, FloatValue: nil}},
  287. LatestTimestamp: timestamp,
  288. }
  289. metrics.Items = append(metrics.Items, metric)
  290. }
  291. heapsterRawMemResponse, _ = json.Marshal(&metrics)
  292. }
  293. return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
  294. })
  295. fakeClient.AddReactor("update", "horizontalpodautoscalers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  296. obj := func() *autoscalingv1.HorizontalPodAutoscaler {
  297. tc.Lock()
  298. defer tc.Unlock()
  299. obj := action.(core.UpdateAction).GetObject().(*autoscalingv1.HorizontalPodAutoscaler)
  300. assert.Equal(t, namespace, obj.Namespace, "the HPA namespace should be as expected")
  301. assert.Equal(t, hpaName, obj.Name, "the HPA name should be as expected")
  302. assert.Equal(t, tc.desiredReplicas, obj.Status.DesiredReplicas, "the desired replica count reported in the object status should be as expected")
  303. if tc.verifyCPUCurrent {
  304. if assert.NotNil(t, obj.Status.CurrentCPUUtilizationPercentage, "the reported CPU utilization percentage should be non-nil") {
  305. assert.Equal(t, tc.CPUCurrent, *obj.Status.CurrentCPUUtilizationPercentage, "the report CPU utilization percentage should be as expected")
  306. }
  307. }
  308. tc.statusUpdated = true
  309. return obj
  310. }()
  311. // Every time we reconcile HPA object we are updating status.
  312. tc.processed <- obj.Name
  313. return true, obj, nil
  314. })
  315. fakeScaleClient := &scalefake.FakeScaleClient{}
  316. fakeScaleClient.AddReactor("get", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  317. tc.Lock()
  318. defer tc.Unlock()
  319. obj := &autoscalingv1.Scale{
  320. ObjectMeta: metav1.ObjectMeta{
  321. Name: tc.resource.name,
  322. Namespace: namespace,
  323. },
  324. Spec: autoscalingv1.ScaleSpec{
  325. Replicas: tc.initialReplicas,
  326. },
  327. Status: autoscalingv1.ScaleStatus{
  328. Replicas: tc.initialReplicas,
  329. Selector: selector,
  330. },
  331. }
  332. return true, obj, nil
  333. })
  334. fakeScaleClient.AddReactor("get", "deployments", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  335. tc.Lock()
  336. defer tc.Unlock()
  337. obj := &autoscalingv1.Scale{
  338. ObjectMeta: metav1.ObjectMeta{
  339. Name: tc.resource.name,
  340. Namespace: namespace,
  341. },
  342. Spec: autoscalingv1.ScaleSpec{
  343. Replicas: tc.initialReplicas,
  344. },
  345. Status: autoscalingv1.ScaleStatus{
  346. Replicas: tc.initialReplicas,
  347. Selector: selector,
  348. },
  349. }
  350. return true, obj, nil
  351. })
  352. fakeScaleClient.AddReactor("get", "replicasets", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  353. tc.Lock()
  354. defer tc.Unlock()
  355. obj := &autoscalingv1.Scale{
  356. ObjectMeta: metav1.ObjectMeta{
  357. Name: tc.resource.name,
  358. Namespace: namespace,
  359. },
  360. Spec: autoscalingv1.ScaleSpec{
  361. Replicas: tc.initialReplicas,
  362. },
  363. Status: autoscalingv1.ScaleStatus{
  364. Replicas: tc.initialReplicas,
  365. Selector: selector,
  366. },
  367. }
  368. return true, obj, nil
  369. })
  370. fakeScaleClient.AddReactor("update", "replicationcontrollers", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  371. tc.Lock()
  372. defer tc.Unlock()
  373. obj := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale)
  374. replicas := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale).Spec.Replicas
  375. assert.Equal(t, tc.desiredReplicas, replicas, "the replica count of the RC should be as expected")
  376. tc.scaleUpdated = true
  377. return true, obj, nil
  378. })
  379. fakeScaleClient.AddReactor("update", "deployments", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  380. tc.Lock()
  381. defer tc.Unlock()
  382. obj := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale)
  383. replicas := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale).Spec.Replicas
  384. assert.Equal(t, tc.desiredReplicas, replicas, "the replica count of the deployment should be as expected")
  385. tc.scaleUpdated = true
  386. return true, obj, nil
  387. })
  388. fakeScaleClient.AddReactor("update", "replicasets", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  389. tc.Lock()
  390. defer tc.Unlock()
  391. obj := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale)
  392. replicas := action.(core.UpdateAction).GetObject().(*autoscalingv1.Scale).Spec.Replicas
  393. assert.Equal(t, tc.desiredReplicas, replicas, "the replica count of the replicaset should be as expected")
  394. tc.scaleUpdated = true
  395. return true, obj, nil
  396. })
  397. fakeWatch := watch.NewFake()
  398. fakeClient.AddWatchReactor("*", core.DefaultWatchReactor(fakeWatch, nil))
  399. return fakeClient, fakeScaleClient
  400. }
  401. func (tc *legacyTestCase) verifyResults(t *testing.T) {
  402. tc.Lock()
  403. defer tc.Unlock()
  404. assert.Equal(t, tc.initialReplicas != tc.desiredReplicas, tc.scaleUpdated, "the scale should only be updated if we expected a change in replicas")
  405. assert.True(t, tc.statusUpdated, "the status should have been updated")
  406. if tc.verifyEvents {
  407. assert.Equal(t, tc.initialReplicas != tc.desiredReplicas, tc.eventCreated, "an event should have been created only if we expected a change in replicas")
  408. }
  409. }
  410. func (tc *legacyTestCase) runTest(t *testing.T) {
  411. testClient, testScaleClient := tc.prepareTestClient(t)
  412. metricsClient := metrics.NewHeapsterMetricsClient(testClient, metrics.DefaultHeapsterNamespace, metrics.DefaultHeapsterScheme, metrics.DefaultHeapsterService, metrics.DefaultHeapsterPort)
  413. eventClient := &fake.Clientset{}
  414. eventClient.AddReactor("*", "events", func(action core.Action) (handled bool, ret runtime.Object, err error) {
  415. tc.Lock()
  416. defer tc.Unlock()
  417. if tc.finished {
  418. return true, &v1.Event{}, nil
  419. }
  420. create, ok := action.(core.CreateAction)
  421. if !ok {
  422. return false, nil, nil
  423. }
  424. obj := create.GetObject().(*v1.Event)
  425. if tc.verifyEvents {
  426. switch obj.Reason {
  427. case "SuccessfulRescale":
  428. assert.Equal(t, fmt.Sprintf("New size: %d; reason: cpu resource utilization (percentage of request) above target", tc.desiredReplicas), obj.Message)
  429. case "DesiredReplicasComputed":
  430. assert.Equal(t, fmt.Sprintf(
  431. "Computed the desired num of replicas: %d (avgCPUutil: %d, current replicas: %d)",
  432. tc.desiredReplicas,
  433. (int64(tc.reportedLevels[0])*100)/tc.reportedCPURequests[0].MilliValue(), tc.initialReplicas), obj.Message)
  434. default:
  435. assert.False(t, true, fmt.Sprintf("Unexpected event: %s / %s", obj.Reason, obj.Message))
  436. }
  437. }
  438. tc.eventCreated = true
  439. return true, obj, nil
  440. })
  441. informerFactory := informers.NewSharedInformerFactory(testClient, controller.NoResyncPeriodFunc())
  442. defaultDownscaleStabilisationWindow := 5 * time.Minute
  443. hpaController := NewHorizontalController(
  444. eventClient.CoreV1(),
  445. testScaleClient,
  446. testClient.AutoscalingV1(),
  447. testrestmapper.TestOnlyStaticRESTMapper(legacyscheme.Scheme),
  448. metricsClient,
  449. informerFactory.Autoscaling().V1().HorizontalPodAutoscalers(),
  450. informerFactory.Core().V1().Pods(),
  451. controller.NoResyncPeriodFunc(),
  452. defaultDownscaleStabilisationWindow,
  453. defaultTestingTolerance,
  454. defaultTestingCpuInitializationPeriod,
  455. defaultTestingDelayOfInitialReadinessStatus,
  456. )
  457. hpaController.hpaListerSynced = alwaysReady
  458. if tc.recommendations != nil {
  459. hpaController.recommendations["test-namespace/test-hpa"] = tc.recommendations
  460. }
  461. stop := make(chan struct{})
  462. defer close(stop)
  463. informerFactory.Start(stop)
  464. go hpaController.Run(stop)
  465. // Wait for HPA to be processed.
  466. <-tc.processed
  467. tc.Lock()
  468. tc.finished = true
  469. if tc.verifyEvents {
  470. tc.Unlock()
  471. // We need to wait for events to be broadcasted (sleep for longer than record.sleepDuration).
  472. time.Sleep(2 * time.Second)
  473. } else {
  474. tc.Unlock()
  475. }
  476. tc.verifyResults(t)
  477. }
  478. func TestLegacyScaleUp(t *testing.T) {
  479. tc := legacyTestCase{
  480. minReplicas: 2,
  481. maxReplicas: 6,
  482. initialReplicas: 3,
  483. desiredReplicas: 5,
  484. CPUTarget: 30,
  485. verifyCPUCurrent: true,
  486. reportedLevels: []uint64{300, 500, 700},
  487. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  488. useMetricsAPI: true,
  489. }
  490. tc.runTest(t)
  491. }
  492. func TestLegacyScaleUpUnreadyLessScale(t *testing.T) {
  493. tc := legacyTestCase{
  494. minReplicas: 2,
  495. maxReplicas: 6,
  496. initialReplicas: 3,
  497. desiredReplicas: 4,
  498. CPUTarget: 30,
  499. verifyCPUCurrent: false,
  500. reportedLevels: []uint64{300, 500, 700},
  501. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  502. reportedPodReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionTrue},
  503. useMetricsAPI: true,
  504. }
  505. tc.runTest(t)
  506. }
  507. func TestLegacyScaleUpUnreadyNoScale(t *testing.T) {
  508. tc := legacyTestCase{
  509. minReplicas: 2,
  510. maxReplicas: 6,
  511. initialReplicas: 3,
  512. desiredReplicas: 3,
  513. CPUTarget: 30,
  514. CPUCurrent: 40,
  515. verifyCPUCurrent: true,
  516. reportedLevels: []uint64{400, 500, 700},
  517. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  518. reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
  519. useMetricsAPI: true,
  520. }
  521. tc.runTest(t)
  522. }
  523. func TestLegacyScaleUpDeployment(t *testing.T) {
  524. tc := legacyTestCase{
  525. minReplicas: 2,
  526. maxReplicas: 6,
  527. initialReplicas: 3,
  528. desiredReplicas: 5,
  529. CPUTarget: 30,
  530. verifyCPUCurrent: true,
  531. reportedLevels: []uint64{300, 500, 700},
  532. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  533. useMetricsAPI: true,
  534. resource: &fakeResource{
  535. name: "test-dep",
  536. apiVersion: "apps/v1",
  537. kind: "Deployment",
  538. },
  539. }
  540. tc.runTest(t)
  541. }
  542. func TestLegacyScaleUpReplicaSet(t *testing.T) {
  543. tc := legacyTestCase{
  544. minReplicas: 2,
  545. maxReplicas: 6,
  546. initialReplicas: 3,
  547. desiredReplicas: 5,
  548. CPUTarget: 30,
  549. verifyCPUCurrent: true,
  550. reportedLevels: []uint64{300, 500, 700},
  551. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  552. useMetricsAPI: true,
  553. resource: &fakeResource{
  554. name: "test-replicaset",
  555. apiVersion: "apps/v1",
  556. kind: "ReplicaSet",
  557. },
  558. }
  559. tc.runTest(t)
  560. }
  561. func TestLegacyScaleUpCM(t *testing.T) {
  562. tc := legacyTestCase{
  563. minReplicas: 2,
  564. maxReplicas: 6,
  565. initialReplicas: 3,
  566. desiredReplicas: 4,
  567. CPUTarget: 0,
  568. metricsTarget: []autoscalingv2.MetricSpec{
  569. {
  570. Type: autoscalingv2.PodsMetricSourceType,
  571. Pods: &autoscalingv2.PodsMetricSource{
  572. MetricName: "qps",
  573. TargetAverageValue: resource.MustParse("15.0"),
  574. },
  575. },
  576. },
  577. reportedLevels: []uint64{20, 10, 30},
  578. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  579. }
  580. tc.runTest(t)
  581. }
  582. func TestLegacyScaleUpCMUnreadyNoLessScale(t *testing.T) {
  583. tc := legacyTestCase{
  584. minReplicas: 2,
  585. maxReplicas: 6,
  586. initialReplicas: 3,
  587. desiredReplicas: 6,
  588. CPUTarget: 0,
  589. metricsTarget: []autoscalingv2.MetricSpec{
  590. {
  591. Type: autoscalingv2.PodsMetricSourceType,
  592. Pods: &autoscalingv2.PodsMetricSource{
  593. MetricName: "qps",
  594. TargetAverageValue: resource.MustParse("15.0"),
  595. },
  596. },
  597. },
  598. reportedLevels: []uint64{50, 10, 30},
  599. reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse},
  600. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  601. }
  602. tc.runTest(t)
  603. }
  604. func TestLegacyScaleUpCMUnreadyNoScaleWouldScaleDown(t *testing.T) {
  605. tc := legacyTestCase{
  606. minReplicas: 2,
  607. maxReplicas: 6,
  608. initialReplicas: 3,
  609. desiredReplicas: 6,
  610. CPUTarget: 0,
  611. metricsTarget: []autoscalingv2.MetricSpec{
  612. {
  613. Type: autoscalingv2.PodsMetricSourceType,
  614. Pods: &autoscalingv2.PodsMetricSource{
  615. MetricName: "qps",
  616. TargetAverageValue: resource.MustParse("15.0"),
  617. },
  618. },
  619. },
  620. reportedLevels: []uint64{50, 15, 30},
  621. reportedPodReadiness: []v1.ConditionStatus{v1.ConditionFalse, v1.ConditionTrue, v1.ConditionFalse},
  622. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  623. }
  624. tc.runTest(t)
  625. }
  626. func TestLegacyScaleDown(t *testing.T) {
  627. tc := legacyTestCase{
  628. minReplicas: 2,
  629. maxReplicas: 6,
  630. initialReplicas: 5,
  631. desiredReplicas: 3,
  632. CPUTarget: 50,
  633. verifyCPUCurrent: true,
  634. reportedLevels: []uint64{100, 300, 500, 250, 250},
  635. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  636. useMetricsAPI: true,
  637. recommendations: []timestampedRecommendation{},
  638. }
  639. tc.runTest(t)
  640. }
  641. func TestLegacyScaleDownCM(t *testing.T) {
  642. tc := legacyTestCase{
  643. minReplicas: 2,
  644. maxReplicas: 6,
  645. initialReplicas: 5,
  646. desiredReplicas: 3,
  647. CPUTarget: 0,
  648. metricsTarget: []autoscalingv2.MetricSpec{
  649. {
  650. Type: autoscalingv2.PodsMetricSourceType,
  651. Pods: &autoscalingv2.PodsMetricSource{
  652. MetricName: "qps",
  653. TargetAverageValue: resource.MustParse("20.0"),
  654. },
  655. },
  656. },
  657. reportedLevels: []uint64{12, 12, 12, 12, 12},
  658. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  659. recommendations: []timestampedRecommendation{},
  660. }
  661. tc.runTest(t)
  662. }
  663. func TestLegacyScaleDownIgnoresUnreadyPods(t *testing.T) {
  664. tc := legacyTestCase{
  665. minReplicas: 2,
  666. maxReplicas: 6,
  667. initialReplicas: 5,
  668. desiredReplicas: 2,
  669. CPUTarget: 50,
  670. CPUCurrent: 30,
  671. verifyCPUCurrent: true,
  672. reportedLevels: []uint64{100, 300, 500, 250, 250},
  673. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  674. useMetricsAPI: true,
  675. reportedPodReadiness: []v1.ConditionStatus{v1.ConditionTrue, v1.ConditionTrue, v1.ConditionTrue, v1.ConditionFalse, v1.ConditionFalse},
  676. recommendations: []timestampedRecommendation{},
  677. }
  678. tc.runTest(t)
  679. }
  680. func LegacyTestTolerance(t *testing.T) {
  681. tc := legacyTestCase{
  682. minReplicas: 1,
  683. maxReplicas: 5,
  684. initialReplicas: 3,
  685. desiredReplicas: 3,
  686. CPUTarget: 100,
  687. reportedLevels: []uint64{1010, 1030, 1020},
  688. reportedCPURequests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  689. useMetricsAPI: true,
  690. }
  691. tc.runTest(t)
  692. }
  693. func LegacyTestToleranceCM(t *testing.T) {
  694. tc := legacyTestCase{
  695. minReplicas: 1,
  696. maxReplicas: 5,
  697. initialReplicas: 3,
  698. desiredReplicas: 3,
  699. metricsTarget: []autoscalingv2.MetricSpec{
  700. {
  701. Type: autoscalingv2.PodsMetricSourceType,
  702. Pods: &autoscalingv2.PodsMetricSource{
  703. MetricName: "qps",
  704. TargetAverageValue: resource.MustParse("20.0"),
  705. },
  706. },
  707. },
  708. reportedLevels: []uint64{20, 21, 21},
  709. reportedCPURequests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  710. }
  711. tc.runTest(t)
  712. }
  713. func LegacyTestMinReplicas(t *testing.T) {
  714. tc := legacyTestCase{
  715. minReplicas: 2,
  716. maxReplicas: 5,
  717. initialReplicas: 3,
  718. desiredReplicas: 2,
  719. CPUTarget: 90,
  720. reportedLevels: []uint64{10, 95, 10},
  721. reportedCPURequests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  722. useMetricsAPI: true,
  723. }
  724. tc.runTest(t)
  725. }
  726. func LegacyTestZeroReplicas(t *testing.T) {
  727. tc := legacyTestCase{
  728. minReplicas: 3,
  729. maxReplicas: 5,
  730. initialReplicas: 0,
  731. desiredReplicas: 0,
  732. CPUTarget: 90,
  733. reportedLevels: []uint64{},
  734. reportedCPURequests: []resource.Quantity{},
  735. useMetricsAPI: true,
  736. }
  737. tc.runTest(t)
  738. }
  739. func LegacyTestTooFewReplicas(t *testing.T) {
  740. tc := legacyTestCase{
  741. minReplicas: 3,
  742. maxReplicas: 5,
  743. initialReplicas: 2,
  744. desiredReplicas: 3,
  745. CPUTarget: 90,
  746. reportedLevels: []uint64{},
  747. reportedCPURequests: []resource.Quantity{},
  748. useMetricsAPI: true,
  749. }
  750. tc.runTest(t)
  751. }
  752. func LegacyTestTooManyReplicas(t *testing.T) {
  753. tc := legacyTestCase{
  754. minReplicas: 3,
  755. maxReplicas: 5,
  756. initialReplicas: 10,
  757. desiredReplicas: 5,
  758. CPUTarget: 90,
  759. reportedLevels: []uint64{},
  760. reportedCPURequests: []resource.Quantity{},
  761. useMetricsAPI: true,
  762. }
  763. tc.runTest(t)
  764. }
  765. func LegacyTestMaxReplicas(t *testing.T) {
  766. tc := legacyTestCase{
  767. minReplicas: 2,
  768. maxReplicas: 5,
  769. initialReplicas: 3,
  770. desiredReplicas: 5,
  771. CPUTarget: 90,
  772. reportedLevels: []uint64{8000, 9500, 1000},
  773. reportedCPURequests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  774. useMetricsAPI: true,
  775. }
  776. tc.runTest(t)
  777. }
  778. func TestLegacySuperfluousMetrics(t *testing.T) {
  779. tc := legacyTestCase{
  780. minReplicas: 2,
  781. maxReplicas: 6,
  782. initialReplicas: 4,
  783. desiredReplicas: 6,
  784. CPUTarget: 100,
  785. reportedLevels: []uint64{4000, 9500, 3000, 7000, 3200, 2000},
  786. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  787. useMetricsAPI: true,
  788. }
  789. tc.runTest(t)
  790. }
  791. func LegacyTestMissingMetrics(t *testing.T) {
  792. tc := legacyTestCase{
  793. minReplicas: 2,
  794. maxReplicas: 6,
  795. initialReplicas: 4,
  796. desiredReplicas: 3,
  797. CPUTarget: 100,
  798. reportedLevels: []uint64{400, 95},
  799. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  800. useMetricsAPI: true,
  801. }
  802. tc.runTest(t)
  803. }
  804. func LegacyTestEmptyMetrics(t *testing.T) {
  805. tc := legacyTestCase{
  806. minReplicas: 2,
  807. maxReplicas: 6,
  808. initialReplicas: 4,
  809. desiredReplicas: 4,
  810. CPUTarget: 100,
  811. reportedLevels: []uint64{},
  812. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  813. useMetricsAPI: true,
  814. }
  815. tc.runTest(t)
  816. }
  817. func LegacyTestEmptyCPURequest(t *testing.T) {
  818. tc := legacyTestCase{
  819. minReplicas: 1,
  820. maxReplicas: 5,
  821. initialReplicas: 1,
  822. desiredReplicas: 1,
  823. CPUTarget: 100,
  824. reportedLevels: []uint64{200},
  825. useMetricsAPI: true,
  826. }
  827. tc.runTest(t)
  828. }
  829. func LegacyTestEventCreated(t *testing.T) {
  830. tc := legacyTestCase{
  831. minReplicas: 1,
  832. maxReplicas: 5,
  833. initialReplicas: 1,
  834. desiredReplicas: 2,
  835. CPUTarget: 50,
  836. reportedLevels: []uint64{200},
  837. reportedCPURequests: []resource.Quantity{resource.MustParse("0.2")},
  838. verifyEvents: true,
  839. useMetricsAPI: true,
  840. }
  841. tc.runTest(t)
  842. }
  843. func LegacyTestEventNotCreated(t *testing.T) {
  844. tc := legacyTestCase{
  845. minReplicas: 1,
  846. maxReplicas: 5,
  847. initialReplicas: 2,
  848. desiredReplicas: 2,
  849. CPUTarget: 50,
  850. reportedLevels: []uint64{200, 200},
  851. reportedCPURequests: []resource.Quantity{resource.MustParse("0.4"), resource.MustParse("0.4")},
  852. verifyEvents: true,
  853. useMetricsAPI: true,
  854. }
  855. tc.runTest(t)
  856. }
  857. func LegacyTestMissingReports(t *testing.T) {
  858. tc := legacyTestCase{
  859. minReplicas: 1,
  860. maxReplicas: 5,
  861. initialReplicas: 4,
  862. desiredReplicas: 2,
  863. CPUTarget: 50,
  864. reportedLevels: []uint64{200},
  865. reportedCPURequests: []resource.Quantity{resource.MustParse("0.2")},
  866. useMetricsAPI: true,
  867. }
  868. tc.runTest(t)
  869. }
  870. func LegacyTestUpscaleCap(t *testing.T) {
  871. tc := legacyTestCase{
  872. minReplicas: 1,
  873. maxReplicas: 100,
  874. initialReplicas: 3,
  875. desiredReplicas: 6,
  876. CPUTarget: 10,
  877. reportedLevels: []uint64{100, 200, 300},
  878. reportedCPURequests: []resource.Quantity{resource.MustParse("0.1"), resource.MustParse("0.1"), resource.MustParse("0.1")},
  879. useMetricsAPI: true,
  880. }
  881. tc.runTest(t)
  882. }
  883. // TestComputedToleranceAlgImplementation is a regression test which
  884. // back-calculates a minimal percentage for downscaling based on a small percentage
  885. // increase in pod utilization which is calibrated against the tolerance value.
  886. func LegacyTestComputedToleranceAlgImplementation(t *testing.T) {
  887. startPods := int32(10)
  888. // 150 mCPU per pod.
  889. totalUsedCPUOfAllPods := uint64(startPods * 150)
  890. // Each pod starts out asking for 2X what is really needed.
  891. // This means we will have a 50% ratio of used/requested
  892. totalRequestedCPUOfAllPods := int32(2 * totalUsedCPUOfAllPods)
  893. requestedToUsed := float64(totalRequestedCPUOfAllPods / int32(totalUsedCPUOfAllPods))
  894. // Spread the amount we ask over 10 pods. We can add some jitter later in reportedLevels.
  895. perPodRequested := totalRequestedCPUOfAllPods / startPods
  896. // Force a minimal scaling event by satisfying (tolerance < 1 - resourcesUsedRatio).
  897. target := math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .01
  898. finalCPUPercentTarget := int32(target * 100)
  899. resourcesUsedRatio := float64(totalUsedCPUOfAllPods) / float64(float64(totalRequestedCPUOfAllPods)*target)
  900. // i.e. .60 * 20 -> scaled down expectation.
  901. finalPods := int32(math.Ceil(resourcesUsedRatio * float64(startPods)))
  902. // To breach tolerance we will create a utilization ratio difference of tolerance to usageRatioToleranceValue)
  903. tc := legacyTestCase{
  904. minReplicas: 0,
  905. maxReplicas: 1000,
  906. initialReplicas: startPods,
  907. desiredReplicas: finalPods,
  908. CPUTarget: finalCPUPercentTarget,
  909. reportedLevels: []uint64{
  910. totalUsedCPUOfAllPods / 10,
  911. totalUsedCPUOfAllPods / 10,
  912. totalUsedCPUOfAllPods / 10,
  913. totalUsedCPUOfAllPods / 10,
  914. totalUsedCPUOfAllPods / 10,
  915. totalUsedCPUOfAllPods / 10,
  916. totalUsedCPUOfAllPods / 10,
  917. totalUsedCPUOfAllPods / 10,
  918. totalUsedCPUOfAllPods / 10,
  919. totalUsedCPUOfAllPods / 10,
  920. },
  921. reportedCPURequests: []resource.Quantity{
  922. resource.MustParse(fmt.Sprint(perPodRequested+100) + "m"),
  923. resource.MustParse(fmt.Sprint(perPodRequested-100) + "m"),
  924. resource.MustParse(fmt.Sprint(perPodRequested+10) + "m"),
  925. resource.MustParse(fmt.Sprint(perPodRequested-10) + "m"),
  926. resource.MustParse(fmt.Sprint(perPodRequested+2) + "m"),
  927. resource.MustParse(fmt.Sprint(perPodRequested-2) + "m"),
  928. resource.MustParse(fmt.Sprint(perPodRequested+1) + "m"),
  929. resource.MustParse(fmt.Sprint(perPodRequested-1) + "m"),
  930. resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
  931. resource.MustParse(fmt.Sprint(perPodRequested) + "m"),
  932. },
  933. useMetricsAPI: true,
  934. }
  935. tc.runTest(t)
  936. // Reuse the data structure above, now testing "unscaling".
  937. // Now, we test that no scaling happens if we are in a very close margin to the tolerance
  938. target = math.Abs(1/(requestedToUsed*(1-defaultTestingTolerance))) + .004
  939. finalCPUPercentTarget = int32(target * 100)
  940. tc.CPUTarget = finalCPUPercentTarget
  941. tc.initialReplicas = startPods
  942. tc.desiredReplicas = startPods
  943. tc.runTest(t)
  944. }
  945. func TestLegacyScaleUpRCImmediately(t *testing.T) {
  946. time := metav1.Time{Time: time.Now()}
  947. tc := legacyTestCase{
  948. minReplicas: 2,
  949. maxReplicas: 6,
  950. initialReplicas: 1,
  951. desiredReplicas: 2,
  952. verifyCPUCurrent: false,
  953. reportedLevels: []uint64{0, 0, 0, 0},
  954. reportedCPURequests: []resource.Quantity{resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0"), resource.MustParse("1.0")},
  955. useMetricsAPI: true,
  956. lastScaleTime: &time,
  957. }
  958. tc.runTest(t)
  959. }
  960. func TestLegacyScaleDownRCImmediately(t *testing.T) {
  961. time := metav1.Time{Time: time.Now()}
  962. tc := legacyTestCase{
  963. minReplicas: 2,
  964. maxReplicas: 5,
  965. initialReplicas: 6,
  966. desiredReplicas: 5,
  967. CPUTarget: 50,
  968. reportedLevels: []uint64{8000, 9500, 1000},
  969. reportedCPURequests: []resource.Quantity{resource.MustParse("0.9"), resource.MustParse("1.0"), resource.MustParse("1.1")},
  970. useMetricsAPI: true,
  971. lastScaleTime: &time,
  972. }
  973. tc.runTest(t)
  974. }
  975. // TODO: add more tests