autoscaling_utils.go 20 KB

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