dns_autoscaling.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 autoscaling
  14. import (
  15. "context"
  16. "fmt"
  17. "math"
  18. "strings"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/api/resource"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "k8s.io/apimachinery/pkg/util/wait"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. e2enode "k8s.io/kubernetes/test/e2e/framework/node"
  28. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  29. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  30. "github.com/onsi/ginkgo"
  31. )
  32. // Constants used in dns-autoscaling test.
  33. const (
  34. DNSdefaultTimeout = 5 * time.Minute
  35. ClusterAddonLabelKey = "k8s-app"
  36. DNSLabelName = "kube-dns"
  37. DNSAutoscalerLabelName = "kube-dns-autoscaler"
  38. )
  39. var _ = SIGDescribe("DNS horizontal autoscaling", func() {
  40. f := framework.NewDefaultFramework("dns-autoscaling")
  41. var c clientset.Interface
  42. var previousParams map[string]string
  43. var originDNSReplicasCount int
  44. var DNSParams1 DNSParamsLinear
  45. var DNSParams2 DNSParamsLinear
  46. var DNSParams3 DNSParamsLinear
  47. ginkgo.BeforeEach(func() {
  48. e2eskipper.SkipUnlessProviderIs("gce", "gke")
  49. c = f.ClientSet
  50. nodes, err := e2enode.GetReadySchedulableNodes(c)
  51. framework.ExpectNoError(err)
  52. nodeCount := len(nodes.Items)
  53. ginkgo.By("Collecting original replicas count and DNS scaling params")
  54. originDNSReplicasCount, err = getDNSReplicas(c)
  55. framework.ExpectNoError(err)
  56. pcm, err := fetchDNSScalingConfigMap(c)
  57. framework.ExpectNoError(err)
  58. previousParams = pcm.Data
  59. if nodeCount <= 500 {
  60. DNSParams1 = DNSParamsLinear{
  61. nodesPerReplica: 1,
  62. }
  63. DNSParams2 = DNSParamsLinear{
  64. nodesPerReplica: 2,
  65. }
  66. DNSParams3 = DNSParamsLinear{
  67. nodesPerReplica: 3,
  68. coresPerReplica: 3,
  69. }
  70. } else {
  71. // In large clusters, avoid creating/deleting too many DNS pods,
  72. // it is supposed to be correctness test, not performance one.
  73. // The default setup is: 256 cores/replica, 16 nodes/replica.
  74. // With nodeCount > 500, nodes/13, nodes/14, nodes/15 and nodes/16
  75. // are different numbers.
  76. DNSParams1 = DNSParamsLinear{
  77. nodesPerReplica: 13,
  78. }
  79. DNSParams2 = DNSParamsLinear{
  80. nodesPerReplica: 14,
  81. }
  82. DNSParams3 = DNSParamsLinear{
  83. nodesPerReplica: 15,
  84. coresPerReplica: 15,
  85. }
  86. }
  87. })
  88. // This test is separated because it is slow and need to run serially.
  89. // Will take around 5 minutes to run on a 4 nodes cluster.
  90. ginkgo.It("[Serial] [Slow] kube-dns-autoscaler should scale kube-dns pods when cluster size changed", func() {
  91. numNodes, err := e2enode.TotalRegistered(c)
  92. framework.ExpectNoError(err)
  93. ginkgo.By("Replace the dns autoscaling parameters with testing parameters")
  94. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams1)))
  95. framework.ExpectNoError(err)
  96. defer func() {
  97. ginkgo.By("Restoring initial dns autoscaling parameters")
  98. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(previousParams))
  99. framework.ExpectNoError(err)
  100. ginkgo.By("Wait for number of running and ready kube-dns pods recover")
  101. label := labels.SelectorFromSet(labels.Set(map[string]string{ClusterAddonLabelKey: DNSLabelName}))
  102. _, err := e2epod.WaitForPodsWithLabelRunningReady(c, metav1.NamespaceSystem, label, originDNSReplicasCount, DNSdefaultTimeout)
  103. framework.ExpectNoError(err)
  104. }()
  105. ginkgo.By("Wait for kube-dns scaled to expected number")
  106. getExpectReplicasLinear := getExpectReplicasFuncLinear(c, &DNSParams1)
  107. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  108. framework.ExpectNoError(err)
  109. originalSizes := make(map[string]int)
  110. for _, mig := range strings.Split(framework.TestContext.CloudConfig.NodeInstanceGroup, ",") {
  111. size, err := framework.GroupSize(mig)
  112. framework.ExpectNoError(err)
  113. ginkgo.By(fmt.Sprintf("Initial size of %s: %d", mig, size))
  114. originalSizes[mig] = size
  115. }
  116. ginkgo.By("Manually increase cluster size")
  117. increasedSizes := make(map[string]int)
  118. for key, val := range originalSizes {
  119. increasedSizes[key] = val + 1
  120. }
  121. setMigSizes(increasedSizes)
  122. err = WaitForClusterSizeFunc(c,
  123. func(size int) bool { return size == numNodes+len(originalSizes) }, scaleUpTimeout)
  124. framework.ExpectNoError(err)
  125. ginkgo.By("Wait for kube-dns scaled to expected number")
  126. getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams1)
  127. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  128. framework.ExpectNoError(err)
  129. ginkgo.By("Replace the dns autoscaling parameters with another testing parameters")
  130. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams3)))
  131. framework.ExpectNoError(err)
  132. ginkgo.By("Wait for kube-dns scaled to expected number")
  133. getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams3)
  134. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  135. framework.ExpectNoError(err)
  136. ginkgo.By("Restoring cluster size")
  137. setMigSizes(originalSizes)
  138. err = e2enode.WaitForReadyNodes(c, numNodes, scaleDownTimeout)
  139. framework.ExpectNoError(err)
  140. ginkgo.By("Wait for kube-dns scaled to expected number")
  141. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  142. framework.ExpectNoError(err)
  143. })
  144. // TODO: Get rid of [DisabledForLargeClusters] tag when issue #55779 is fixed.
  145. ginkgo.It("[DisabledForLargeClusters] kube-dns-autoscaler should scale kube-dns pods in both nonfaulty and faulty scenarios", func() {
  146. ginkgo.By("Replace the dns autoscaling parameters with testing parameters")
  147. err := updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams1)))
  148. framework.ExpectNoError(err)
  149. defer func() {
  150. ginkgo.By("Restoring initial dns autoscaling parameters")
  151. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(previousParams))
  152. framework.ExpectNoError(err)
  153. }()
  154. ginkgo.By("Wait for kube-dns scaled to expected number")
  155. getExpectReplicasLinear := getExpectReplicasFuncLinear(c, &DNSParams1)
  156. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  157. framework.ExpectNoError(err)
  158. ginkgo.By("--- Scenario: should scale kube-dns based on changed parameters ---")
  159. ginkgo.By("Replace the dns autoscaling parameters with another testing parameters")
  160. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams3)))
  161. framework.ExpectNoError(err)
  162. ginkgo.By("Wait for kube-dns scaled to expected number")
  163. getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams3)
  164. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  165. framework.ExpectNoError(err)
  166. ginkgo.By("--- Scenario: should re-create scaling parameters with default value when parameters got deleted ---")
  167. ginkgo.By("Delete the ConfigMap for autoscaler")
  168. err = deleteDNSScalingConfigMap(c)
  169. framework.ExpectNoError(err)
  170. ginkgo.By("Wait for the ConfigMap got re-created")
  171. _, err = waitForDNSConfigMapCreated(c, DNSdefaultTimeout)
  172. framework.ExpectNoError(err)
  173. ginkgo.By("Replace the dns autoscaling parameters with another testing parameters")
  174. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams2)))
  175. framework.ExpectNoError(err)
  176. ginkgo.By("Wait for kube-dns scaled to expected number")
  177. getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams2)
  178. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  179. framework.ExpectNoError(err)
  180. ginkgo.By("--- Scenario: should recover after autoscaler pod got deleted ---")
  181. ginkgo.By("Delete the autoscaler pod for kube-dns")
  182. err = deleteDNSAutoscalerPod(c)
  183. framework.ExpectNoError(err)
  184. ginkgo.By("Replace the dns autoscaling parameters with another testing parameters")
  185. err = updateDNSScalingConfigMap(c, packDNSScalingConfigMap(packLinearParams(&DNSParams1)))
  186. framework.ExpectNoError(err)
  187. ginkgo.By("Wait for kube-dns scaled to expected number")
  188. getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams1)
  189. err = waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)
  190. framework.ExpectNoError(err)
  191. })
  192. })
  193. // DNSParamsLinear is a struct for number of DNS pods.
  194. type DNSParamsLinear struct {
  195. nodesPerReplica float64
  196. coresPerReplica float64
  197. min int
  198. max int
  199. }
  200. type getExpectReplicasFunc func(c clientset.Interface) int
  201. func getExpectReplicasFuncLinear(c clientset.Interface, params *DNSParamsLinear) getExpectReplicasFunc {
  202. return func(c clientset.Interface) int {
  203. var replicasFromNodes float64
  204. var replicasFromCores float64
  205. nodes, err := e2enode.GetReadySchedulableNodes(c)
  206. framework.ExpectNoError(err)
  207. if params.nodesPerReplica > 0 {
  208. replicasFromNodes = math.Ceil(float64(len(nodes.Items)) / params.nodesPerReplica)
  209. }
  210. if params.coresPerReplica > 0 {
  211. replicasFromCores = math.Ceil(float64(getScheduableCores(nodes.Items)) / params.coresPerReplica)
  212. }
  213. return int(math.Max(1.0, math.Max(replicasFromNodes, replicasFromCores)))
  214. }
  215. }
  216. func getScheduableCores(nodes []v1.Node) int64 {
  217. var sc resource.Quantity
  218. for _, node := range nodes {
  219. if !node.Spec.Unschedulable {
  220. sc.Add(node.Status.Capacity[v1.ResourceCPU])
  221. }
  222. }
  223. scInt64, scOk := sc.AsInt64()
  224. if !scOk {
  225. framework.Logf("Unable to compute integer values of schedulable cores in the cluster")
  226. return 0
  227. }
  228. return scInt64
  229. }
  230. func fetchDNSScalingConfigMap(c clientset.Interface) (*v1.ConfigMap, error) {
  231. cm, err := c.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(context.TODO(), DNSAutoscalerLabelName, metav1.GetOptions{})
  232. if err != nil {
  233. return nil, err
  234. }
  235. return cm, nil
  236. }
  237. func deleteDNSScalingConfigMap(c clientset.Interface) error {
  238. if err := c.CoreV1().ConfigMaps(metav1.NamespaceSystem).Delete(context.TODO(), DNSAutoscalerLabelName, nil); err != nil {
  239. return err
  240. }
  241. framework.Logf("DNS autoscaling ConfigMap deleted.")
  242. return nil
  243. }
  244. func packLinearParams(params *DNSParamsLinear) map[string]string {
  245. paramsMap := make(map[string]string)
  246. paramsMap["linear"] = fmt.Sprintf("{\"nodesPerReplica\": %v,\"coresPerReplica\": %v,\"min\": %v,\"max\": %v}",
  247. params.nodesPerReplica,
  248. params.coresPerReplica,
  249. params.min,
  250. params.max)
  251. return paramsMap
  252. }
  253. func packDNSScalingConfigMap(params map[string]string) *v1.ConfigMap {
  254. configMap := v1.ConfigMap{}
  255. configMap.ObjectMeta.Name = DNSAutoscalerLabelName
  256. configMap.ObjectMeta.Namespace = metav1.NamespaceSystem
  257. configMap.Data = params
  258. return &configMap
  259. }
  260. func updateDNSScalingConfigMap(c clientset.Interface, configMap *v1.ConfigMap) error {
  261. _, err := c.CoreV1().ConfigMaps(metav1.NamespaceSystem).Update(context.TODO(), configMap, metav1.UpdateOptions{})
  262. if err != nil {
  263. return err
  264. }
  265. framework.Logf("DNS autoscaling ConfigMap updated.")
  266. return nil
  267. }
  268. func getDNSReplicas(c clientset.Interface) (int, error) {
  269. label := labels.SelectorFromSet(labels.Set(map[string]string{ClusterAddonLabelKey: DNSLabelName}))
  270. listOpts := metav1.ListOptions{LabelSelector: label.String()}
  271. deployments, err := c.AppsV1().Deployments(metav1.NamespaceSystem).List(context.TODO(), listOpts)
  272. if err != nil {
  273. return 0, err
  274. }
  275. if len(deployments.Items) != 1 {
  276. return 0, fmt.Errorf("expected 1 DNS deployment, got %v", len(deployments.Items))
  277. }
  278. deployment := deployments.Items[0]
  279. return int(*(deployment.Spec.Replicas)), nil
  280. }
  281. func deleteDNSAutoscalerPod(c clientset.Interface) error {
  282. label := labels.SelectorFromSet(labels.Set(map[string]string{ClusterAddonLabelKey: DNSAutoscalerLabelName}))
  283. listOpts := metav1.ListOptions{LabelSelector: label.String()}
  284. pods, err := c.CoreV1().Pods(metav1.NamespaceSystem).List(context.TODO(), listOpts)
  285. if err != nil {
  286. return err
  287. }
  288. if len(pods.Items) != 1 {
  289. return fmt.Errorf("expected 1 autoscaler pod, got %v", len(pods.Items))
  290. }
  291. podName := pods.Items[0].Name
  292. if err := c.CoreV1().Pods(metav1.NamespaceSystem).Delete(context.TODO(), podName, nil); err != nil {
  293. return err
  294. }
  295. framework.Logf("DNS autoscaling pod %v deleted.", podName)
  296. return nil
  297. }
  298. func waitForDNSReplicasSatisfied(c clientset.Interface, getExpected getExpectReplicasFunc, timeout time.Duration) (err error) {
  299. var current int
  300. var expected int
  301. framework.Logf("Waiting up to %v for kube-dns to reach expected replicas", timeout)
  302. condition := func() (bool, error) {
  303. current, err = getDNSReplicas(c)
  304. if err != nil {
  305. return false, err
  306. }
  307. expected = getExpected(c)
  308. if current != expected {
  309. framework.Logf("Replicas not as expected: got %v, expected %v", current, expected)
  310. return false, nil
  311. }
  312. return true, nil
  313. }
  314. if err = wait.Poll(2*time.Second, timeout, condition); err != nil {
  315. return fmt.Errorf("err waiting for DNS replicas to satisfy %v, got %v: %v", expected, current, err)
  316. }
  317. framework.Logf("kube-dns reaches expected replicas: %v", expected)
  318. return nil
  319. }
  320. func waitForDNSConfigMapCreated(c clientset.Interface, timeout time.Duration) (configMap *v1.ConfigMap, err error) {
  321. framework.Logf("Waiting up to %v for DNS autoscaling ConfigMap got re-created", timeout)
  322. condition := func() (bool, error) {
  323. configMap, err = fetchDNSScalingConfigMap(c)
  324. if err != nil {
  325. return false, nil
  326. }
  327. return true, nil
  328. }
  329. if err = wait.Poll(time.Second, timeout, condition); err != nil {
  330. return nil, fmt.Errorf("err waiting for DNS autoscaling ConfigMap got re-created: %v", err)
  331. }
  332. return configMap, nil
  333. }