util.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. /*
  2. Copyright 2018 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 util
  14. import (
  15. "context"
  16. "net/http"
  17. "net/http/httptest"
  18. v1 "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/client-go/informers"
  21. coreinformers "k8s.io/client-go/informers/core/v1"
  22. clientset "k8s.io/client-go/kubernetes"
  23. "k8s.io/client-go/tools/cache"
  24. "k8s.io/client-go/tools/events"
  25. "k8s.io/klog"
  26. "k8s.io/kubernetes/pkg/api/legacyscheme"
  27. pvutil "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/util"
  28. "k8s.io/kubernetes/pkg/scheduler"
  29. "k8s.io/kubernetes/test/integration/framework"
  30. )
  31. // ShutdownFunc represents the function handle to be called, typically in a defer handler, to shutdown a running module
  32. type ShutdownFunc func()
  33. // StartApiserver starts a local API server for testing and returns the handle to the URL and the shutdown function to stop it.
  34. func StartApiserver() (string, ShutdownFunc) {
  35. h := &framework.MasterHolder{Initialized: make(chan struct{})}
  36. s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  37. <-h.Initialized
  38. h.M.GenericAPIServer.Handler.ServeHTTP(w, req)
  39. }))
  40. _, _, closeFn := framework.RunAMasterUsingServer(framework.NewIntegrationTestMasterConfig(), s, h)
  41. shutdownFunc := func() {
  42. klog.Infof("destroying API server")
  43. closeFn()
  44. s.Close()
  45. klog.Infof("destroyed API server")
  46. }
  47. return s.URL, shutdownFunc
  48. }
  49. // StartScheduler configures and starts a scheduler given a handle to the clientSet interface
  50. // and event broadcaster. It returns the running scheduler and the shutdown function to stop it.
  51. func StartScheduler(clientSet clientset.Interface) (*scheduler.Scheduler, coreinformers.PodInformer, ShutdownFunc) {
  52. ctx, cancel := context.WithCancel(context.Background())
  53. informerFactory := informers.NewSharedInformerFactory(clientSet, 0)
  54. podInformer := informerFactory.Core().V1().Pods()
  55. evtBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{
  56. Interface: clientSet.EventsV1beta1().Events("")})
  57. evtBroadcaster.StartRecordingToSink(ctx.Done())
  58. recorder := evtBroadcaster.NewRecorder(
  59. legacyscheme.Scheme,
  60. v1.DefaultSchedulerName,
  61. )
  62. sched, err := createScheduler(clientSet, informerFactory, podInformer, recorder, ctx.Done())
  63. if err != nil {
  64. klog.Fatalf("Error creating scheduler: %v", err)
  65. }
  66. informerFactory.Start(ctx.Done())
  67. go sched.Run(ctx)
  68. shutdownFunc := func() {
  69. klog.Infof("destroying scheduler")
  70. cancel()
  71. klog.Infof("destroyed scheduler")
  72. }
  73. return sched, podInformer, shutdownFunc
  74. }
  75. // StartFakePVController is a simplified pv controller logic that sets PVC VolumeName and annotation for each PV binding.
  76. // TODO(mborsz): Use a real PV controller here.
  77. func StartFakePVController(clientSet clientset.Interface) ShutdownFunc {
  78. ctx, cancel := context.WithCancel(context.Background())
  79. informerFactory := informers.NewSharedInformerFactory(clientSet, 0)
  80. pvInformer := informerFactory.Core().V1().PersistentVolumes()
  81. syncPV := func(obj *v1.PersistentVolume) {
  82. if obj.Spec.ClaimRef != nil {
  83. claimRef := obj.Spec.ClaimRef
  84. pvc, err := clientSet.CoreV1().PersistentVolumeClaims(claimRef.Namespace).Get(ctx, claimRef.Name, metav1.GetOptions{})
  85. if err != nil {
  86. klog.Errorf("error while getting %v/%v: %v", claimRef.Namespace, claimRef.Name, err)
  87. return
  88. }
  89. if pvc.Spec.VolumeName == "" {
  90. pvc.Spec.VolumeName = obj.Name
  91. metav1.SetMetaDataAnnotation(&pvc.ObjectMeta, pvutil.AnnBindCompleted, "yes")
  92. _, err := clientSet.CoreV1().PersistentVolumeClaims(claimRef.Namespace).Update(ctx, pvc, metav1.UpdateOptions{})
  93. if err != nil {
  94. klog.Errorf("error while getting %v/%v: %v", claimRef.Namespace, claimRef.Name, err)
  95. return
  96. }
  97. }
  98. }
  99. }
  100. pvInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  101. AddFunc: func(obj interface{}) {
  102. syncPV(obj.(*v1.PersistentVolume))
  103. },
  104. UpdateFunc: func(_, obj interface{}) {
  105. syncPV(obj.(*v1.PersistentVolume))
  106. },
  107. })
  108. informerFactory.Start(ctx.Done())
  109. return ShutdownFunc(cancel)
  110. }
  111. // createScheduler create a scheduler with given informer factory and default name.
  112. func createScheduler(
  113. clientSet clientset.Interface,
  114. informerFactory informers.SharedInformerFactory,
  115. podInformer coreinformers.PodInformer,
  116. recorder events.EventRecorder,
  117. stopCh <-chan struct{},
  118. ) (*scheduler.Scheduler, error) {
  119. return scheduler.New(
  120. clientSet,
  121. informerFactory,
  122. podInformer,
  123. recorder,
  124. stopCh,
  125. )
  126. }