limit_range.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 scheduling
  14. import (
  15. "context"
  16. "fmt"
  17. "reflect"
  18. "strconv"
  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/runtime"
  25. "k8s.io/apimachinery/pkg/util/uuid"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. "k8s.io/apimachinery/pkg/watch"
  28. "k8s.io/client-go/tools/cache"
  29. watchtools "k8s.io/client-go/tools/watch"
  30. "k8s.io/kubernetes/test/e2e/framework"
  31. e2eservice "k8s.io/kubernetes/test/e2e/framework/service"
  32. "github.com/onsi/ginkgo"
  33. "github.com/onsi/gomega"
  34. )
  35. const (
  36. podName = "pfpod"
  37. )
  38. var _ = SIGDescribe("LimitRange", func() {
  39. f := framework.NewDefaultFramework("limitrange")
  40. /*
  41. Release : v1.18
  42. Testname: LimitRange, resources
  43. Description: Creating a Limitrange and verifying the creation of Limitrange, updating the Limitrange and validating the Limitrange. Creating Pods with resources and validate the pod resources are applied to the Limitrange
  44. */
  45. framework.ConformanceIt("should create a LimitRange with defaults and ensure pod has those defaults applied.", func() {
  46. ginkgo.By("Creating a LimitRange")
  47. min := getResourceList("50m", "100Mi", "100Gi")
  48. max := getResourceList("500m", "500Mi", "500Gi")
  49. defaultLimit := getResourceList("500m", "500Mi", "500Gi")
  50. defaultRequest := getResourceList("100m", "200Mi", "200Gi")
  51. maxLimitRequestRatio := v1.ResourceList{}
  52. value := strconv.Itoa(time.Now().Nanosecond()) + string(uuid.NewUUID())
  53. limitRange := newLimitRange("limit-range", value, v1.LimitTypeContainer,
  54. min, max,
  55. defaultLimit, defaultRequest,
  56. maxLimitRequestRatio)
  57. ginkgo.By("Setting up watch")
  58. selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
  59. options := metav1.ListOptions{LabelSelector: selector.String()}
  60. limitRanges, err := f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).List(context.TODO(), options)
  61. framework.ExpectNoError(err, "failed to query for limitRanges")
  62. framework.ExpectEqual(len(limitRanges.Items), 0)
  63. options = metav1.ListOptions{
  64. LabelSelector: selector.String(),
  65. ResourceVersion: limitRanges.ListMeta.ResourceVersion,
  66. }
  67. listCompleted := make(chan bool, 1)
  68. lw := &cache.ListWatch{
  69. ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
  70. options.LabelSelector = selector.String()
  71. limitRanges, err := f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).List(context.TODO(), options)
  72. if err == nil {
  73. select {
  74. case listCompleted <- true:
  75. framework.Logf("observed the limitRanges list")
  76. return limitRanges, err
  77. default:
  78. framework.Logf("channel blocked")
  79. }
  80. }
  81. return limitRanges, err
  82. },
  83. WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
  84. options.LabelSelector = selector.String()
  85. return f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Watch(context.TODO(), options)
  86. },
  87. }
  88. _, _, w, _ := watchtools.NewIndexerInformerWatcher(lw, &v1.LimitRange{})
  89. defer w.Stop()
  90. ginkgo.By("Submitting a LimitRange")
  91. limitRange, err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Create(context.TODO(), limitRange, metav1.CreateOptions{})
  92. framework.ExpectNoError(err)
  93. ginkgo.By("Verifying LimitRange creation was observed")
  94. select {
  95. case <-listCompleted:
  96. select {
  97. case event, _ := <-w.ResultChan():
  98. if event.Type != watch.Added {
  99. framework.Failf("Failed to observe limitRange creation : %v", event)
  100. }
  101. case <-time.After(e2eservice.RespondingTimeout):
  102. framework.Failf("Timeout while waiting for LimitRange creation")
  103. }
  104. case <-time.After(e2eservice.RespondingTimeout):
  105. framework.Failf("Timeout while waiting for LimitRange list complete")
  106. }
  107. ginkgo.By("Fetching the LimitRange to ensure it has proper values")
  108. limitRange, err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Get(context.TODO(), limitRange.Name, metav1.GetOptions{})
  109. framework.ExpectNoError(err)
  110. expected := v1.ResourceRequirements{Requests: defaultRequest, Limits: defaultLimit}
  111. actual := v1.ResourceRequirements{Requests: limitRange.Spec.Limits[0].DefaultRequest, Limits: limitRange.Spec.Limits[0].Default}
  112. err = equalResourceRequirement(expected, actual)
  113. framework.ExpectNoError(err)
  114. ginkgo.By("Creating a Pod with no resource requirements")
  115. pod := f.NewTestPod("pod-no-resources", v1.ResourceList{}, v1.ResourceList{})
  116. pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  117. framework.ExpectNoError(err)
  118. ginkgo.By("Ensuring Pod has resource requirements applied from LimitRange")
  119. pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  120. framework.ExpectNoError(err)
  121. for i := range pod.Spec.Containers {
  122. err = equalResourceRequirement(expected, pod.Spec.Containers[i].Resources)
  123. if err != nil {
  124. // Print the pod to help in debugging.
  125. framework.Logf("Pod %+v does not have the expected requirements", pod)
  126. framework.ExpectNoError(err)
  127. }
  128. }
  129. ginkgo.By("Creating a Pod with partial resource requirements")
  130. pod = f.NewTestPod("pod-partial-resources", getResourceList("", "150Mi", "150Gi"), getResourceList("300m", "", ""))
  131. pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  132. framework.ExpectNoError(err)
  133. ginkgo.By("Ensuring Pod has merged resource requirements applied from LimitRange")
  134. pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  135. framework.ExpectNoError(err)
  136. // This is an interesting case, so it's worth a comment
  137. // If you specify a Limit, and no Request, the Limit will default to the Request
  138. // This means that the LimitRange.DefaultRequest will ONLY take affect if a container.resources.limit is not supplied
  139. expected = v1.ResourceRequirements{Requests: getResourceList("300m", "150Mi", "150Gi"), Limits: getResourceList("300m", "500Mi", "500Gi")}
  140. for i := range pod.Spec.Containers {
  141. err = equalResourceRequirement(expected, pod.Spec.Containers[i].Resources)
  142. if err != nil {
  143. // Print the pod to help in debugging.
  144. framework.Logf("Pod %+v does not have the expected requirements", pod)
  145. framework.ExpectNoError(err)
  146. }
  147. }
  148. ginkgo.By("Failing to create a Pod with less than min resources")
  149. pod = f.NewTestPod(podName, getResourceList("10m", "50Mi", "50Gi"), v1.ResourceList{})
  150. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  151. framework.ExpectError(err)
  152. ginkgo.By("Failing to create a Pod with more than max resources")
  153. pod = f.NewTestPod(podName, getResourceList("600m", "600Mi", "600Gi"), v1.ResourceList{})
  154. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  155. framework.ExpectError(err)
  156. ginkgo.By("Updating a LimitRange")
  157. newMin := getResourceList("9m", "49Mi", "49Gi")
  158. limitRange.Spec.Limits[0].Min = newMin
  159. limitRange, err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Update(context.TODO(), limitRange, metav1.UpdateOptions{})
  160. framework.ExpectNoError(err)
  161. ginkgo.By("Verifying LimitRange updating is effective")
  162. err = wait.Poll(time.Second*2, time.Second*20, func() (bool, error) {
  163. limitRange, err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Get(context.TODO(), limitRange.Name, metav1.GetOptions{})
  164. framework.ExpectNoError(err)
  165. return reflect.DeepEqual(limitRange.Spec.Limits[0].Min, newMin), nil
  166. })
  167. framework.ExpectNoError(err)
  168. ginkgo.By("Creating a Pod with less than former min resources")
  169. pod = f.NewTestPod(podName, getResourceList("10m", "50Mi", "50Gi"), v1.ResourceList{})
  170. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  171. framework.ExpectNoError(err)
  172. ginkgo.By("Failing to create a Pod with more than max resources")
  173. pod = f.NewTestPod(podName, getResourceList("600m", "600Mi", "600Gi"), v1.ResourceList{})
  174. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  175. framework.ExpectError(err)
  176. ginkgo.By("Deleting a LimitRange")
  177. err = f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).Delete(context.TODO(), limitRange.Name, metav1.NewDeleteOptions(30))
  178. framework.ExpectNoError(err)
  179. ginkgo.By("Verifying the LimitRange was deleted")
  180. gomega.Expect(wait.Poll(time.Second*5, e2eservice.RespondingTimeout, func() (bool, error) {
  181. selector := labels.SelectorFromSet(labels.Set(map[string]string{"name": limitRange.Name}))
  182. options := metav1.ListOptions{LabelSelector: selector.String()}
  183. limitRanges, err := f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).List(context.TODO(), options)
  184. if err != nil {
  185. framework.Logf("Unable to retrieve LimitRanges: %v", err)
  186. return false, nil
  187. }
  188. if len(limitRanges.Items) == 0 {
  189. framework.Logf("limitRange is already deleted")
  190. return true, nil
  191. }
  192. if len(limitRanges.Items) > 0 {
  193. if limitRanges.Items[0].ObjectMeta.DeletionTimestamp == nil {
  194. framework.Logf("deletion has not yet been observed")
  195. return false, nil
  196. }
  197. return true, nil
  198. }
  199. return false, nil
  200. }))
  201. framework.ExpectNoError(err, "kubelet never observed the termination notice")
  202. ginkgo.By("Creating a Pod with more than former max resources")
  203. pod = f.NewTestPod(podName+"2", getResourceList("600m", "600Mi", "600Gi"), v1.ResourceList{})
  204. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  205. framework.ExpectNoError(err)
  206. })
  207. })
  208. func equalResourceRequirement(expected v1.ResourceRequirements, actual v1.ResourceRequirements) error {
  209. framework.Logf("Verifying requests: expected %v with actual %v", expected.Requests, actual.Requests)
  210. err := equalResourceList(expected.Requests, actual.Requests)
  211. if err != nil {
  212. return err
  213. }
  214. framework.Logf("Verifying limits: expected %v with actual %v", expected.Limits, actual.Limits)
  215. err = equalResourceList(expected.Limits, actual.Limits)
  216. return err
  217. }
  218. func equalResourceList(expected v1.ResourceList, actual v1.ResourceList) error {
  219. for k, v := range expected {
  220. if actualValue, found := actual[k]; !found || (v.Cmp(actualValue) != 0) {
  221. return fmt.Errorf("resource %v expected %v actual %v", k, v.String(), actualValue.String())
  222. }
  223. }
  224. for k, v := range actual {
  225. if expectedValue, found := expected[k]; !found || (v.Cmp(expectedValue) != 0) {
  226. return fmt.Errorf("resource %v expected %v actual %v", k, expectedValue.String(), v.String())
  227. }
  228. }
  229. return nil
  230. }
  231. func getResourceList(cpu, memory string, ephemeralStorage string) v1.ResourceList {
  232. res := v1.ResourceList{}
  233. if cpu != "" {
  234. res[v1.ResourceCPU] = resource.MustParse(cpu)
  235. }
  236. if memory != "" {
  237. res[v1.ResourceMemory] = resource.MustParse(memory)
  238. }
  239. if ephemeralStorage != "" {
  240. res[v1.ResourceEphemeralStorage] = resource.MustParse(ephemeralStorage)
  241. }
  242. return res
  243. }
  244. // newLimitRange returns a limit range with specified data
  245. func newLimitRange(name, value string, limitType v1.LimitType,
  246. min, max,
  247. defaultLimit, defaultRequest,
  248. maxLimitRequestRatio v1.ResourceList) *v1.LimitRange {
  249. return &v1.LimitRange{
  250. ObjectMeta: metav1.ObjectMeta{
  251. Name: name,
  252. Labels: map[string]string{
  253. "time": value,
  254. },
  255. },
  256. Spec: v1.LimitRangeSpec{
  257. Limits: []v1.LimitRangeItem{
  258. {
  259. Type: limitType,
  260. Min: min,
  261. Max: max,
  262. Default: defaultLimit,
  263. DefaultRequest: defaultRequest,
  264. MaxLimitRequestRatio: maxLimitRequestRatio,
  265. },
  266. },
  267. },
  268. }
  269. }