util.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. Copyright 2019 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 volumescheduling
  14. import (
  15. "context"
  16. "net/http"
  17. "net/http/httptest"
  18. "testing"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. "k8s.io/apimachinery/pkg/util/uuid"
  24. "k8s.io/apimachinery/pkg/util/wait"
  25. "k8s.io/apiserver/pkg/admission"
  26. "k8s.io/client-go/informers"
  27. coreinformers "k8s.io/client-go/informers/core/v1"
  28. clientset "k8s.io/client-go/kubernetes"
  29. restclient "k8s.io/client-go/rest"
  30. "k8s.io/client-go/tools/events"
  31. "k8s.io/kubernetes/pkg/api/legacyscheme"
  32. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  33. "k8s.io/kubernetes/pkg/scheduler"
  34. "k8s.io/kubernetes/test/integration/framework"
  35. )
  36. type testContext struct {
  37. closeFn framework.CloseFunc
  38. httpServer *httptest.Server
  39. ns *v1.Namespace
  40. clientSet *clientset.Clientset
  41. informerFactory informers.SharedInformerFactory
  42. scheduler *scheduler.Scheduler
  43. ctx context.Context
  44. cancelFn context.CancelFunc
  45. }
  46. // initTestMaster initializes a test environment and creates a master with default
  47. // configuration.
  48. func initTestMaster(t *testing.T, nsPrefix string, admission admission.Interface) *testContext {
  49. ctx, cancelFunc := context.WithCancel(context.Background())
  50. testCtx := testContext{
  51. ctx: ctx,
  52. cancelFn: cancelFunc,
  53. }
  54. // 1. Create master
  55. h := &framework.MasterHolder{Initialized: make(chan struct{})}
  56. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  57. <-h.Initialized
  58. h.M.GenericAPIServer.Handler.ServeHTTP(w, req)
  59. }))
  60. masterConfig := framework.NewIntegrationTestMasterConfig()
  61. if admission != nil {
  62. masterConfig.GenericConfig.AdmissionControl = admission
  63. }
  64. _, testCtx.httpServer, testCtx.closeFn = framework.RunAMasterUsingServer(masterConfig, s, h)
  65. if nsPrefix != "default" {
  66. testCtx.ns = framework.CreateTestingNamespace(nsPrefix+string(uuid.NewUUID()), s, t)
  67. } else {
  68. testCtx.ns = framework.CreateTestingNamespace("default", s, t)
  69. }
  70. // 2. Create kubeclient
  71. testCtx.clientSet = clientset.NewForConfigOrDie(
  72. &restclient.Config{
  73. QPS: -1, Host: s.URL,
  74. ContentConfig: restclient.ContentConfig{
  75. GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"},
  76. },
  77. },
  78. )
  79. return &testCtx
  80. }
  81. // initTestSchedulerWithOptions initializes a test environment and creates a scheduler with default
  82. // configuration and other options.
  83. func initTestSchedulerWithOptions(
  84. t *testing.T,
  85. testCtx *testContext,
  86. resyncPeriod time.Duration,
  87. ) *testContext {
  88. // 1. Create scheduler
  89. testCtx.informerFactory = informers.NewSharedInformerFactory(testCtx.clientSet, resyncPeriod)
  90. podInformer := testCtx.informerFactory.Core().V1().Pods()
  91. eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{
  92. Interface: testCtx.clientSet.EventsV1beta1().Events(""),
  93. })
  94. recorder := eventBroadcaster.NewRecorder(
  95. legacyscheme.Scheme,
  96. v1.DefaultSchedulerName,
  97. )
  98. var err error
  99. testCtx.scheduler, err = createSchedulerWithPodInformer(
  100. testCtx.clientSet, podInformer, testCtx.informerFactory, recorder, testCtx.ctx.Done())
  101. if err != nil {
  102. t.Fatalf("Couldn't create scheduler: %v", err)
  103. }
  104. eventBroadcaster.StartRecordingToSink(testCtx.ctx.Done())
  105. testCtx.informerFactory.Start(testCtx.scheduler.StopEverything)
  106. testCtx.informerFactory.WaitForCacheSync(testCtx.scheduler.StopEverything)
  107. go testCtx.scheduler.Run(testCtx.ctx)
  108. return testCtx
  109. }
  110. // createSchedulerWithPodInformer creates a new scheduler.
  111. func createSchedulerWithPodInformer(
  112. clientSet clientset.Interface,
  113. podInformer coreinformers.PodInformer,
  114. informerFactory informers.SharedInformerFactory,
  115. recorder events.EventRecorder,
  116. stopCh <-chan struct{},
  117. ) (*scheduler.Scheduler, error) {
  118. return scheduler.New(
  119. clientSet,
  120. informerFactory,
  121. podInformer,
  122. recorder,
  123. stopCh,
  124. )
  125. }
  126. // cleanupTest deletes the scheduler and the test namespace. It should be called
  127. // at the end of a test.
  128. func cleanupTest(t *testing.T, testCtx *testContext) {
  129. // Kill the scheduler.
  130. testCtx.cancelFn()
  131. // Cleanup nodes.
  132. testCtx.clientSet.CoreV1().Nodes().DeleteCollection(context.TODO(), nil, metav1.ListOptions{})
  133. framework.DeleteTestingNamespace(testCtx.ns, testCtx.httpServer, t)
  134. testCtx.closeFn()
  135. }
  136. // waitForPodToScheduleWithTimeout waits for a pod to get scheduled and returns
  137. // an error if it does not scheduled within the given timeout.
  138. func waitForPodToScheduleWithTimeout(cs clientset.Interface, pod *v1.Pod, timeout time.Duration) error {
  139. return wait.Poll(100*time.Millisecond, timeout, podScheduled(cs, pod.Namespace, pod.Name))
  140. }
  141. // waitForPodToSchedule waits for a pod to get scheduled and returns an error if
  142. // it does not get scheduled within the timeout duration (30 seconds).
  143. func waitForPodToSchedule(cs clientset.Interface, pod *v1.Pod) error {
  144. return waitForPodToScheduleWithTimeout(cs, pod, 30*time.Second)
  145. }
  146. // waitForPodUnscheduleWithTimeout waits for a pod to fail scheduling and returns
  147. // an error if it does not become unschedulable within the given timeout.
  148. func waitForPodUnschedulableWithTimeout(cs clientset.Interface, pod *v1.Pod, timeout time.Duration) error {
  149. return wait.Poll(100*time.Millisecond, timeout, podUnschedulable(cs, pod.Namespace, pod.Name))
  150. }
  151. // waitForPodUnschedule waits for a pod to fail scheduling and returns
  152. // an error if it does not become unschedulable within the timeout duration (30 seconds).
  153. func waitForPodUnschedulable(cs clientset.Interface, pod *v1.Pod) error {
  154. return waitForPodUnschedulableWithTimeout(cs, pod, 30*time.Second)
  155. }
  156. // podScheduled returns true if a node is assigned to the given pod.
  157. func podScheduled(c clientset.Interface, podNamespace, podName string) wait.ConditionFunc {
  158. return func() (bool, error) {
  159. pod, err := c.CoreV1().Pods(podNamespace).Get(context.TODO(), podName, metav1.GetOptions{})
  160. if err != nil {
  161. // This could be a connection error so we want to retry.
  162. return false, nil
  163. }
  164. if pod.Spec.NodeName == "" {
  165. return false, nil
  166. }
  167. return true, nil
  168. }
  169. }
  170. // podUnschedulable returns a condition function that returns true if the given pod
  171. // gets unschedulable status.
  172. func podUnschedulable(c clientset.Interface, podNamespace, podName string) wait.ConditionFunc {
  173. return func() (bool, error) {
  174. pod, err := c.CoreV1().Pods(podNamespace).Get(context.TODO(), podName, metav1.GetOptions{})
  175. if err != nil {
  176. // This could be a connection error so we want to retry.
  177. return false, nil
  178. }
  179. _, cond := podutil.GetPodCondition(&pod.Status, v1.PodScheduled)
  180. return cond != nil && cond.Status == v1.ConditionFalse &&
  181. cond.Reason == v1.PodReasonUnschedulable, nil
  182. }
  183. }