autoscaling_utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 autoscaling
  14. import (
  15. "context"
  16. "fmt"
  17. "strconv"
  18. "sync"
  19. "time"
  20. autoscalingv1 "k8s.io/api/autoscaling/v1"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apimachinery/pkg/util/intstr"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. clientset "k8s.io/client-go/kubernetes"
  27. api "k8s.io/kubernetes/pkg/apis/core"
  28. "k8s.io/kubernetes/test/e2e/framework"
  29. e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl"
  30. e2erc "k8s.io/kubernetes/test/e2e/framework/rc"
  31. e2eservice "k8s.io/kubernetes/test/e2e/framework/service"
  32. testutils "k8s.io/kubernetes/test/utils"
  33. "github.com/onsi/ginkgo"
  34. scaleclient "k8s.io/client-go/scale"
  35. imageutils "k8s.io/kubernetes/test/utils/image"
  36. )
  37. const (
  38. dynamicConsumptionTimeInSeconds = 30
  39. dynamicRequestSizeInMillicores = 100
  40. dynamicRequestSizeInMegabytes = 100
  41. dynamicRequestSizeCustomMetric = 10
  42. port = 80
  43. targetPort = 8080
  44. timeoutRC = 120 * time.Second
  45. startServiceTimeout = time.Minute
  46. startServiceInterval = 5 * time.Second
  47. rcIsNil = "ERROR: replicationController = nil"
  48. deploymentIsNil = "ERROR: deployment = nil"
  49. rsIsNil = "ERROR: replicaset = nil"
  50. invalidKind = "ERROR: invalid workload kind for resource consumer"
  51. customMetricName = "QPS"
  52. serviceInitializationTimeout = 2 * time.Minute
  53. serviceInitializationInterval = 15 * time.Second
  54. )
  55. var (
  56. resourceConsumerImage = imageutils.GetE2EImage(imageutils.ResourceConsumer)
  57. )
  58. var (
  59. // KindRC is the GVK for ReplicationController
  60. KindRC = schema.GroupVersionKind{Version: "v1", Kind: "ReplicationController"}
  61. // KindDeployment is the GVK for Deployment
  62. KindDeployment = schema.GroupVersionKind{Group: "apps", Version: "v1beta2", Kind: "Deployment"}
  63. // KindReplicaSet is the GVK for ReplicaSet
  64. KindReplicaSet = schema.GroupVersionKind{Group: "apps", Version: "v1beta2", Kind: "ReplicaSet"}
  65. )
  66. /*
  67. ResourceConsumer is a tool for testing. It helps create specified usage of CPU or memory (Warning: memory not supported)
  68. typical use case:
  69. rc.ConsumeCPU(600)
  70. // ... check your assumption here
  71. rc.ConsumeCPU(300)
  72. // ... check your assumption here
  73. */
  74. type ResourceConsumer struct {
  75. name string
  76. controllerName string
  77. kind schema.GroupVersionKind
  78. nsName string
  79. clientSet clientset.Interface
  80. scaleClient scaleclient.ScalesGetter
  81. cpu chan int
  82. mem chan int
  83. customMetric chan int
  84. stopCPU chan int
  85. stopMem chan int
  86. stopCustomMetric chan int
  87. stopWaitGroup sync.WaitGroup
  88. consumptionTimeInSeconds int
  89. sleepTime time.Duration
  90. requestSizeInMillicores int
  91. requestSizeInMegabytes int
  92. requestSizeCustomMetric int
  93. }
  94. // NewDynamicResourceConsumer is a wrapper to create a new dynamic ResourceConsumer
  95. func NewDynamicResourceConsumer(name, nsName string, kind schema.GroupVersionKind, replicas, initCPUTotal, initMemoryTotal, initCustomMetric int, cpuLimit, memLimit int64, clientset clientset.Interface, scaleClient scaleclient.ScalesGetter) *ResourceConsumer {
  96. return newResourceConsumer(name, nsName, kind, replicas, initCPUTotal, initMemoryTotal, initCustomMetric, dynamicConsumptionTimeInSeconds,
  97. dynamicRequestSizeInMillicores, dynamicRequestSizeInMegabytes, dynamicRequestSizeCustomMetric, cpuLimit, memLimit, clientset, scaleClient, nil, nil)
  98. }
  99. /*
  100. NewResourceConsumer creates new ResourceConsumer
  101. initCPUTotal argument is in millicores
  102. initMemoryTotal argument is in megabytes
  103. memLimit argument is in megabytes, memLimit is a maximum amount of memory that can be consumed by a single pod
  104. cpuLimit argument is in millicores, cpuLimit is a maximum amount of cpu that can be consumed by a single pod
  105. */
  106. func newResourceConsumer(name, nsName string, kind schema.GroupVersionKind, replicas, initCPUTotal, initMemoryTotal, initCustomMetric, consumptionTimeInSeconds, requestSizeInMillicores,
  107. requestSizeInMegabytes int, requestSizeCustomMetric int, cpuLimit, memLimit int64, clientset clientset.Interface, scaleClient scaleclient.ScalesGetter, podAnnotations, serviceAnnotations map[string]string) *ResourceConsumer {
  108. if podAnnotations == nil {
  109. podAnnotations = make(map[string]string)
  110. }
  111. if serviceAnnotations == nil {
  112. serviceAnnotations = make(map[string]string)
  113. }
  114. runServiceAndWorkloadForResourceConsumer(clientset, nsName, name, kind, replicas, cpuLimit, memLimit, podAnnotations, serviceAnnotations)
  115. rc := &ResourceConsumer{
  116. name: name,
  117. controllerName: name + "-ctrl",
  118. kind: kind,
  119. nsName: nsName,
  120. clientSet: clientset,
  121. scaleClient: scaleClient,
  122. cpu: make(chan int),
  123. mem: make(chan int),
  124. customMetric: make(chan int),
  125. stopCPU: make(chan int),
  126. stopMem: make(chan int),
  127. stopCustomMetric: make(chan int),
  128. consumptionTimeInSeconds: consumptionTimeInSeconds,
  129. sleepTime: time.Duration(consumptionTimeInSeconds) * time.Second,
  130. requestSizeInMillicores: requestSizeInMillicores,
  131. requestSizeInMegabytes: requestSizeInMegabytes,
  132. requestSizeCustomMetric: requestSizeCustomMetric,
  133. }
  134. go rc.makeConsumeCPURequests()
  135. rc.ConsumeCPU(initCPUTotal)
  136. go rc.makeConsumeMemRequests()
  137. rc.ConsumeMem(initMemoryTotal)
  138. go rc.makeConsumeCustomMetric()
  139. rc.ConsumeCustomMetric(initCustomMetric)
  140. return rc
  141. }
  142. // ConsumeCPU consumes given number of CPU
  143. func (rc *ResourceConsumer) ConsumeCPU(millicores int) {
  144. framework.Logf("RC %s: consume %v millicores in total", rc.name, millicores)
  145. rc.cpu <- millicores
  146. }
  147. // ConsumeMem consumes given number of Mem
  148. func (rc *ResourceConsumer) ConsumeMem(megabytes int) {
  149. framework.Logf("RC %s: consume %v MB in total", rc.name, megabytes)
  150. rc.mem <- megabytes
  151. }
  152. // ConsumeCustomMetric consumes given number of custom metric
  153. func (rc *ResourceConsumer) ConsumeCustomMetric(amount int) {
  154. framework.Logf("RC %s: consume custom metric %v in total", rc.name, amount)
  155. rc.customMetric <- amount
  156. }
  157. func (rc *ResourceConsumer) makeConsumeCPURequests() {
  158. defer ginkgo.GinkgoRecover()
  159. rc.stopWaitGroup.Add(1)
  160. defer rc.stopWaitGroup.Done()
  161. sleepTime := time.Duration(0)
  162. millicores := 0
  163. for {
  164. select {
  165. case millicores = <-rc.cpu:
  166. framework.Logf("RC %s: setting consumption to %v millicores in total", rc.name, millicores)
  167. case <-time.After(sleepTime):
  168. framework.Logf("RC %s: sending request to consume %d millicores", rc.name, millicores)
  169. rc.sendConsumeCPURequest(millicores)
  170. sleepTime = rc.sleepTime
  171. case <-rc.stopCPU:
  172. framework.Logf("RC %s: stopping CPU consumer", rc.name)
  173. return
  174. }
  175. }
  176. }
  177. func (rc *ResourceConsumer) makeConsumeMemRequests() {
  178. defer ginkgo.GinkgoRecover()
  179. rc.stopWaitGroup.Add(1)
  180. defer rc.stopWaitGroup.Done()
  181. sleepTime := time.Duration(0)
  182. megabytes := 0
  183. for {
  184. select {
  185. case megabytes = <-rc.mem:
  186. framework.Logf("RC %s: setting consumption to %v MB in total", rc.name, megabytes)
  187. case <-time.After(sleepTime):
  188. framework.Logf("RC %s: sending request to consume %d MB", rc.name, megabytes)
  189. rc.sendConsumeMemRequest(megabytes)
  190. sleepTime = rc.sleepTime
  191. case <-rc.stopMem:
  192. framework.Logf("RC %s: stopping mem consumer", rc.name)
  193. return
  194. }
  195. }
  196. }
  197. func (rc *ResourceConsumer) makeConsumeCustomMetric() {
  198. defer ginkgo.GinkgoRecover()
  199. rc.stopWaitGroup.Add(1)
  200. defer rc.stopWaitGroup.Done()
  201. sleepTime := time.Duration(0)
  202. delta := 0
  203. for {
  204. select {
  205. case delta = <-rc.customMetric:
  206. framework.Logf("RC %s: setting bump of metric %s to %d in total", rc.name, customMetricName, delta)
  207. case <-time.After(sleepTime):
  208. framework.Logf("RC %s: sending request to consume %d of custom metric %s", rc.name, delta, customMetricName)
  209. rc.sendConsumeCustomMetric(delta)
  210. sleepTime = rc.sleepTime
  211. case <-rc.stopCustomMetric:
  212. framework.Logf("RC %s: stopping metric consumer", rc.name)
  213. return
  214. }
  215. }
  216. }
  217. func (rc *ResourceConsumer) sendConsumeCPURequest(millicores int) {
  218. ctx, cancel := context.WithTimeout(context.Background(), framework.SingleCallTimeout)
  219. defer cancel()
  220. err := wait.PollImmediate(serviceInitializationInterval, serviceInitializationTimeout, func() (bool, error) {
  221. proxyRequest, err := e2eservice.GetServicesProxyRequest(rc.clientSet, rc.clientSet.CoreV1().RESTClient().Post())
  222. framework.ExpectNoError(err)
  223. req := proxyRequest.Namespace(rc.nsName).
  224. Name(rc.controllerName).
  225. Suffix("ConsumeCPU").
  226. Param("millicores", strconv.Itoa(millicores)).
  227. Param("durationSec", strconv.Itoa(rc.consumptionTimeInSeconds)).
  228. Param("requestSizeMillicores", strconv.Itoa(rc.requestSizeInMillicores))
  229. framework.Logf("ConsumeCPU URL: %v", *req.URL())
  230. _, err = req.DoRaw(ctx)
  231. if err != nil {
  232. framework.Logf("ConsumeCPU failure: %v", err)
  233. return false, nil
  234. }
  235. return true, nil
  236. })
  237. framework.ExpectNoError(err)
  238. }
  239. // sendConsumeMemRequest sends POST request for memory consumption
  240. func (rc *ResourceConsumer) sendConsumeMemRequest(megabytes int) {
  241. ctx, cancel := context.WithTimeout(context.Background(), framework.SingleCallTimeout)
  242. defer cancel()
  243. err := wait.PollImmediate(serviceInitializationInterval, serviceInitializationTimeout, func() (bool, error) {
  244. proxyRequest, err := e2eservice.GetServicesProxyRequest(rc.clientSet, rc.clientSet.CoreV1().RESTClient().Post())
  245. framework.ExpectNoError(err)
  246. req := proxyRequest.Namespace(rc.nsName).
  247. Name(rc.controllerName).
  248. Suffix("ConsumeMem").
  249. Param("megabytes", strconv.Itoa(megabytes)).
  250. Param("durationSec", strconv.Itoa(rc.consumptionTimeInSeconds)).
  251. Param("requestSizeMegabytes", strconv.Itoa(rc.requestSizeInMegabytes))
  252. framework.Logf("ConsumeMem URL: %v", *req.URL())
  253. _, err = req.DoRaw(ctx)
  254. if err != nil {
  255. framework.Logf("ConsumeMem failure: %v", err)
  256. return false, nil
  257. }
  258. return true, nil
  259. })
  260. framework.ExpectNoError(err)
  261. }
  262. // sendConsumeCustomMetric sends POST request for custom metric consumption
  263. func (rc *ResourceConsumer) sendConsumeCustomMetric(delta int) {
  264. ctx, cancel := context.WithTimeout(context.Background(), framework.SingleCallTimeout)
  265. defer cancel()
  266. err := wait.PollImmediate(serviceInitializationInterval, serviceInitializationTimeout, func() (bool, error) {
  267. proxyRequest, err := e2eservice.GetServicesProxyRequest(rc.clientSet, rc.clientSet.CoreV1().RESTClient().Post())
  268. framework.ExpectNoError(err)
  269. req := proxyRequest.Namespace(rc.nsName).
  270. Name(rc.controllerName).
  271. Suffix("BumpMetric").
  272. Param("metric", customMetricName).
  273. Param("delta", strconv.Itoa(delta)).
  274. Param("durationSec", strconv.Itoa(rc.consumptionTimeInSeconds)).
  275. Param("requestSizeMetrics", strconv.Itoa(rc.requestSizeCustomMetric))
  276. framework.Logf("ConsumeCustomMetric URL: %v", *req.URL())
  277. _, err = req.DoRaw(ctx)
  278. if err != nil {
  279. framework.Logf("ConsumeCustomMetric failure: %v", err)
  280. return false, nil
  281. }
  282. return true, nil
  283. })
  284. framework.ExpectNoError(err)
  285. }
  286. // GetReplicas get the replicas
  287. func (rc *ResourceConsumer) GetReplicas() int {
  288. switch rc.kind {
  289. case KindRC:
  290. replicationController, err := rc.clientSet.CoreV1().ReplicationControllers(rc.nsName).Get(context.TODO(), rc.name, metav1.GetOptions{})
  291. framework.ExpectNoError(err)
  292. if replicationController == nil {
  293. framework.Failf(rcIsNil)
  294. }
  295. return int(replicationController.Status.ReadyReplicas)
  296. case KindDeployment:
  297. deployment, err := rc.clientSet.AppsV1().Deployments(rc.nsName).Get(context.TODO(), rc.name, metav1.GetOptions{})
  298. framework.ExpectNoError(err)
  299. if deployment == nil {
  300. framework.Failf(deploymentIsNil)
  301. }
  302. return int(deployment.Status.ReadyReplicas)
  303. case KindReplicaSet:
  304. rs, err := rc.clientSet.AppsV1().ReplicaSets(rc.nsName).Get(context.TODO(), rc.name, metav1.GetOptions{})
  305. framework.ExpectNoError(err)
  306. if rs == nil {
  307. framework.Failf(rsIsNil)
  308. }
  309. return int(rs.Status.ReadyReplicas)
  310. default:
  311. framework.Failf(invalidKind)
  312. }
  313. return 0
  314. }
  315. // GetHpa get the corresponding horizontalPodAutoscaler object
  316. func (rc *ResourceConsumer) GetHpa(name string) (*autoscalingv1.HorizontalPodAutoscaler, error) {
  317. return rc.clientSet.AutoscalingV1().HorizontalPodAutoscalers(rc.nsName).Get(context.TODO(), name, metav1.GetOptions{})
  318. }
  319. // WaitForReplicas wait for the desired replicas
  320. func (rc *ResourceConsumer) WaitForReplicas(desiredReplicas int, duration time.Duration) {
  321. interval := 20 * time.Second
  322. err := wait.PollImmediate(interval, duration, func() (bool, error) {
  323. replicas := rc.GetReplicas()
  324. framework.Logf("waiting for %d replicas (current: %d)", desiredReplicas, replicas)
  325. return replicas == desiredReplicas, nil // Expected number of replicas found. Exit.
  326. })
  327. framework.ExpectNoErrorWithOffset(1, err, "timeout waiting %v for %d replicas", duration, desiredReplicas)
  328. }
  329. // EnsureDesiredReplicasInRange ensure the replicas is in a desired range
  330. func (rc *ResourceConsumer) EnsureDesiredReplicasInRange(minDesiredReplicas, maxDesiredReplicas int, duration time.Duration, hpaName string) {
  331. interval := 10 * time.Second
  332. err := wait.PollImmediate(interval, duration, func() (bool, error) {
  333. replicas := rc.GetReplicas()
  334. framework.Logf("expecting there to be in [%d, %d] replicas (are: %d)", minDesiredReplicas, maxDesiredReplicas, replicas)
  335. as, err := rc.GetHpa(hpaName)
  336. if err != nil {
  337. framework.Logf("Error getting HPA: %s", err)
  338. } else {
  339. framework.Logf("HPA status: %+v", as.Status)
  340. }
  341. if replicas < minDesiredReplicas {
  342. return false, fmt.Errorf("number of replicas below target")
  343. } else if replicas > maxDesiredReplicas {
  344. return false, fmt.Errorf("number of replicas above target")
  345. } else {
  346. return false, nil // Expected number of replicas found. Continue polling until timeout.
  347. }
  348. })
  349. // The call above always returns an error, but if it is timeout, it's OK (condition satisfied all the time).
  350. if err == wait.ErrWaitTimeout {
  351. framework.Logf("Number of replicas was stable over %v", duration)
  352. return
  353. }
  354. framework.ExpectNoErrorWithOffset(1, err)
  355. }
  356. // Pause stops background goroutines responsible for consuming resources.
  357. func (rc *ResourceConsumer) Pause() {
  358. ginkgo.By(fmt.Sprintf("HPA pausing RC %s", rc.name))
  359. rc.stopCPU <- 0
  360. rc.stopMem <- 0
  361. rc.stopCustomMetric <- 0
  362. rc.stopWaitGroup.Wait()
  363. }
  364. // Resume starts background goroutines responsible for consuming resources.
  365. func (rc *ResourceConsumer) Resume() {
  366. ginkgo.By(fmt.Sprintf("HPA resuming RC %s", rc.name))
  367. go rc.makeConsumeCPURequests()
  368. go rc.makeConsumeMemRequests()
  369. go rc.makeConsumeCustomMetric()
  370. }
  371. // CleanUp clean up the background goroutines responsible for consuming resources.
  372. func (rc *ResourceConsumer) CleanUp() {
  373. ginkgo.By(fmt.Sprintf("Removing consuming RC %s", rc.name))
  374. close(rc.stopCPU)
  375. close(rc.stopMem)
  376. close(rc.stopCustomMetric)
  377. rc.stopWaitGroup.Wait()
  378. // Wait some time to ensure all child goroutines are finished.
  379. time.Sleep(10 * time.Second)
  380. kind := rc.kind.GroupKind()
  381. framework.ExpectNoError(framework.DeleteResourceAndWaitForGC(rc.clientSet, kind, rc.nsName, rc.name))
  382. framework.ExpectNoError(rc.clientSet.CoreV1().Services(rc.nsName).Delete(context.TODO(), rc.name, nil))
  383. framework.ExpectNoError(framework.DeleteResourceAndWaitForGC(rc.clientSet, api.Kind("ReplicationController"), rc.nsName, rc.controllerName))
  384. framework.ExpectNoError(rc.clientSet.CoreV1().Services(rc.nsName).Delete(context.TODO(), rc.controllerName, nil))
  385. }
  386. func runServiceAndWorkloadForResourceConsumer(c clientset.Interface, ns, name string, kind schema.GroupVersionKind, replicas int, cpuLimitMillis, memLimitMb int64, podAnnotations, serviceAnnotations map[string]string) {
  387. ginkgo.By(fmt.Sprintf("Running consuming RC %s via %s with %v replicas", name, kind, replicas))
  388. _, err := c.CoreV1().Services(ns).Create(context.TODO(), &v1.Service{
  389. ObjectMeta: metav1.ObjectMeta{
  390. Name: name,
  391. Annotations: serviceAnnotations,
  392. },
  393. Spec: v1.ServiceSpec{
  394. Ports: []v1.ServicePort{{
  395. Port: port,
  396. TargetPort: intstr.FromInt(targetPort),
  397. }},
  398. Selector: map[string]string{
  399. "name": name,
  400. },
  401. },
  402. }, metav1.CreateOptions{})
  403. framework.ExpectNoError(err)
  404. rcConfig := testutils.RCConfig{
  405. Client: c,
  406. Image: resourceConsumerImage,
  407. Name: name,
  408. Namespace: ns,
  409. Timeout: timeoutRC,
  410. Replicas: replicas,
  411. CpuRequest: cpuLimitMillis,
  412. CpuLimit: cpuLimitMillis,
  413. MemRequest: memLimitMb * 1024 * 1024, // MemLimit is in bytes
  414. MemLimit: memLimitMb * 1024 * 1024,
  415. Annotations: podAnnotations,
  416. }
  417. switch kind {
  418. case KindRC:
  419. framework.ExpectNoError(e2erc.RunRC(rcConfig))
  420. case KindDeployment:
  421. dpConfig := testutils.DeploymentConfig{
  422. RCConfig: rcConfig,
  423. }
  424. ginkgo.By(fmt.Sprintf("creating deployment %s in namespace %s", dpConfig.Name, dpConfig.Namespace))
  425. dpConfig.NodeDumpFunc = framework.DumpNodeDebugInfo
  426. dpConfig.ContainerDumpFunc = e2ekubectl.LogFailedContainers
  427. framework.ExpectNoError(testutils.RunDeployment(dpConfig))
  428. case KindReplicaSet:
  429. rsConfig := testutils.ReplicaSetConfig{
  430. RCConfig: rcConfig,
  431. }
  432. ginkgo.By(fmt.Sprintf("creating replicaset %s in namespace %s", rsConfig.Name, rsConfig.Namespace))
  433. framework.ExpectNoError(runReplicaSet(rsConfig))
  434. default:
  435. framework.Failf(invalidKind)
  436. }
  437. ginkgo.By(fmt.Sprintf("Running controller"))
  438. controllerName := name + "-ctrl"
  439. _, err = c.CoreV1().Services(ns).Create(context.TODO(), &v1.Service{
  440. ObjectMeta: metav1.ObjectMeta{
  441. Name: controllerName,
  442. },
  443. Spec: v1.ServiceSpec{
  444. Ports: []v1.ServicePort{{
  445. Port: port,
  446. TargetPort: intstr.FromInt(targetPort),
  447. }},
  448. Selector: map[string]string{
  449. "name": controllerName,
  450. },
  451. },
  452. }, metav1.CreateOptions{})
  453. framework.ExpectNoError(err)
  454. dnsClusterFirst := v1.DNSClusterFirst
  455. controllerRcConfig := testutils.RCConfig{
  456. Client: c,
  457. Image: imageutils.GetE2EImage(imageutils.Agnhost),
  458. Name: controllerName,
  459. Namespace: ns,
  460. Timeout: timeoutRC,
  461. Replicas: 1,
  462. Command: []string{"/agnhost", "resource-consumer-controller", "--consumer-service-name=" + name, "--consumer-service-namespace=" + ns, "--consumer-port=80"},
  463. DNSPolicy: &dnsClusterFirst,
  464. }
  465. framework.ExpectNoError(e2erc.RunRC(controllerRcConfig))
  466. // Wait for endpoints to propagate for the controller service.
  467. framework.ExpectNoError(framework.WaitForServiceEndpointsNum(
  468. c, ns, controllerName, 1, startServiceInterval, startServiceTimeout))
  469. }
  470. // CreateCPUHorizontalPodAutoscaler create a horizontalPodAutoscaler with CPU target
  471. // for consuming resources.
  472. func CreateCPUHorizontalPodAutoscaler(rc *ResourceConsumer, cpu, minReplicas, maxRepl int32) *autoscalingv1.HorizontalPodAutoscaler {
  473. hpa := &autoscalingv1.HorizontalPodAutoscaler{
  474. ObjectMeta: metav1.ObjectMeta{
  475. Name: rc.name,
  476. Namespace: rc.nsName,
  477. },
  478. Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
  479. ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
  480. APIVersion: rc.kind.GroupVersion().String(),
  481. Kind: rc.kind.Kind,
  482. Name: rc.name,
  483. },
  484. MinReplicas: &minReplicas,
  485. MaxReplicas: maxRepl,
  486. TargetCPUUtilizationPercentage: &cpu,
  487. },
  488. }
  489. hpa, errHPA := rc.clientSet.AutoscalingV1().HorizontalPodAutoscalers(rc.nsName).Create(context.TODO(), hpa, metav1.CreateOptions{})
  490. framework.ExpectNoError(errHPA)
  491. return hpa
  492. }
  493. // DeleteHorizontalPodAutoscaler delete the horizontalPodAutoscaler for consuming resources.
  494. func DeleteHorizontalPodAutoscaler(rc *ResourceConsumer, autoscalerName string) {
  495. rc.clientSet.AutoscalingV1().HorizontalPodAutoscalers(rc.nsName).Delete(context.TODO(), autoscalerName, nil)
  496. }
  497. // runReplicaSet launches (and verifies correctness) of a replicaset.
  498. func runReplicaSet(config testutils.ReplicaSetConfig) error {
  499. ginkgo.By(fmt.Sprintf("creating replicaset %s in namespace %s", config.Name, config.Namespace))
  500. config.NodeDumpFunc = framework.DumpNodeDebugInfo
  501. config.ContainerDumpFunc = e2ekubectl.LogFailedContainers
  502. return testutils.RunReplicaSet(config)
  503. }