server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. Copyright 2014 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 app implements a Server object for running the scheduler.
  14. package app
  15. import (
  16. "context"
  17. "fmt"
  18. "io"
  19. "net/http"
  20. "os"
  21. goruntime "runtime"
  22. "github.com/spf13/cobra"
  23. "k8s.io/api/core/v1"
  24. eventsv1beta1 "k8s.io/api/events/v1beta1"
  25. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  26. "k8s.io/apiserver/pkg/authentication/authenticator"
  27. "k8s.io/apiserver/pkg/authorization/authorizer"
  28. genericapifilters "k8s.io/apiserver/pkg/endpoints/filters"
  29. apirequest "k8s.io/apiserver/pkg/endpoints/request"
  30. genericfilters "k8s.io/apiserver/pkg/server/filters"
  31. "k8s.io/apiserver/pkg/server/healthz"
  32. "k8s.io/apiserver/pkg/server/mux"
  33. "k8s.io/apiserver/pkg/server/routes"
  34. "k8s.io/apiserver/pkg/util/term"
  35. "k8s.io/client-go/kubernetes/scheme"
  36. corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
  37. "k8s.io/client-go/tools/events"
  38. "k8s.io/client-go/tools/leaderelection"
  39. "k8s.io/client-go/tools/record"
  40. cliflag "k8s.io/component-base/cli/flag"
  41. "k8s.io/component-base/cli/globalflag"
  42. "k8s.io/component-base/logs"
  43. "k8s.io/component-base/metrics/legacyregistry"
  44. "k8s.io/component-base/version"
  45. "k8s.io/component-base/version/verflag"
  46. "k8s.io/klog"
  47. schedulerserverconfig "k8s.io/kubernetes/cmd/kube-scheduler/app/config"
  48. "k8s.io/kubernetes/cmd/kube-scheduler/app/options"
  49. "k8s.io/kubernetes/pkg/api/legacyscheme"
  50. "k8s.io/kubernetes/pkg/scheduler"
  51. kubeschedulerconfig "k8s.io/kubernetes/pkg/scheduler/apis/config"
  52. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  53. "k8s.io/kubernetes/pkg/scheduler/metrics"
  54. "k8s.io/kubernetes/pkg/util/configz"
  55. utilflag "k8s.io/kubernetes/pkg/util/flag"
  56. )
  57. // Option configures a framework.Registry.
  58. type Option func(framework.Registry) error
  59. // NewSchedulerCommand creates a *cobra.Command object with default parameters and registryOptions
  60. func NewSchedulerCommand(registryOptions ...Option) *cobra.Command {
  61. opts, err := options.NewOptions()
  62. if err != nil {
  63. klog.Fatalf("unable to initialize command options: %v", err)
  64. }
  65. cmd := &cobra.Command{
  66. Use: "kube-scheduler",
  67. Long: `The Kubernetes scheduler is a policy-rich, topology-aware,
  68. workload-specific function that significantly impacts availability, performance,
  69. and capacity. The scheduler needs to take into account individual and collective
  70. resource requirements, quality of service requirements, hardware/software/policy
  71. constraints, affinity and anti-affinity specifications, data locality, inter-workload
  72. interference, deadlines, and so on. Workload-specific requirements will be exposed
  73. through the API as necessary. See [scheduling](https://kubernetes.io/docs/concepts/scheduling/)
  74. for more information about scheduling and the kube-scheduler component.`,
  75. Run: func(cmd *cobra.Command, args []string) {
  76. if err := runCommand(cmd, args, opts, registryOptions...); err != nil {
  77. fmt.Fprintf(os.Stderr, "%v\n", err)
  78. os.Exit(1)
  79. }
  80. },
  81. }
  82. fs := cmd.Flags()
  83. namedFlagSets := opts.Flags()
  84. verflag.AddFlags(namedFlagSets.FlagSet("global"))
  85. globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name())
  86. for _, f := range namedFlagSets.FlagSets {
  87. fs.AddFlagSet(f)
  88. }
  89. usageFmt := "Usage:\n %s\n"
  90. cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
  91. cmd.SetUsageFunc(func(cmd *cobra.Command) error {
  92. fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
  93. cliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)
  94. return nil
  95. })
  96. cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
  97. fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
  98. cliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)
  99. })
  100. cmd.MarkFlagFilename("config", "yaml", "yml", "json")
  101. return cmd
  102. }
  103. // runCommand runs the scheduler.
  104. func runCommand(cmd *cobra.Command, args []string, opts *options.Options, registryOptions ...Option) error {
  105. verflag.PrintAndExitIfRequested()
  106. utilflag.PrintFlags(cmd.Flags())
  107. if len(args) != 0 {
  108. fmt.Fprint(os.Stderr, "arguments are not supported\n")
  109. }
  110. if errs := opts.Validate(); len(errs) > 0 {
  111. return utilerrors.NewAggregate(errs)
  112. }
  113. if len(opts.WriteConfigTo) > 0 {
  114. c := &schedulerserverconfig.Config{}
  115. if err := opts.ApplyTo(c); err != nil {
  116. return err
  117. }
  118. if err := options.WriteConfigFile(opts.WriteConfigTo, &c.ComponentConfig); err != nil {
  119. return err
  120. }
  121. klog.Infof("Wrote configuration to: %s\n", opts.WriteConfigTo)
  122. return nil
  123. }
  124. c, err := opts.Config()
  125. if err != nil {
  126. return err
  127. }
  128. // Get the completed config
  129. cc := c.Complete()
  130. // Configz registration.
  131. if cz, err := configz.New("componentconfig"); err == nil {
  132. cz.Set(cc.ComponentConfig)
  133. } else {
  134. return fmt.Errorf("unable to register configz: %s", err)
  135. }
  136. ctx, cancel := context.WithCancel(context.Background())
  137. defer cancel()
  138. return Run(ctx, cc, registryOptions...)
  139. }
  140. // Run executes the scheduler based on the given configuration. It only returns on error or when context is done.
  141. func Run(ctx context.Context, cc schedulerserverconfig.CompletedConfig, outOfTreeRegistryOptions ...Option) error {
  142. // To help debugging, immediately log version
  143. klog.V(1).Infof("Starting Kubernetes Scheduler version %+v", version.Get())
  144. outOfTreeRegistry := make(framework.Registry)
  145. for _, option := range outOfTreeRegistryOptions {
  146. if err := option(outOfTreeRegistry); err != nil {
  147. return err
  148. }
  149. }
  150. // Prepare event clients.
  151. if _, err := cc.Client.Discovery().ServerResourcesForGroupVersion(eventsv1beta1.SchemeGroupVersion.String()); err == nil {
  152. cc.Broadcaster = events.NewBroadcaster(&events.EventSinkImpl{Interface: cc.EventClient.Events("")})
  153. cc.Recorder = cc.Broadcaster.NewRecorder(scheme.Scheme, cc.ComponentConfig.SchedulerName)
  154. } else {
  155. recorder := cc.CoreBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: cc.ComponentConfig.SchedulerName})
  156. cc.Recorder = record.NewEventRecorderAdapter(recorder)
  157. }
  158. // Create the scheduler.
  159. sched, err := scheduler.New(cc.Client,
  160. cc.InformerFactory,
  161. cc.PodInformer,
  162. cc.Recorder,
  163. ctx.Done(),
  164. scheduler.WithName(cc.ComponentConfig.SchedulerName),
  165. scheduler.WithAlgorithmSource(cc.ComponentConfig.AlgorithmSource),
  166. scheduler.WithHardPodAffinitySymmetricWeight(cc.ComponentConfig.HardPodAffinitySymmetricWeight),
  167. scheduler.WithPreemptionDisabled(cc.ComponentConfig.DisablePreemption),
  168. scheduler.WithPercentageOfNodesToScore(cc.ComponentConfig.PercentageOfNodesToScore),
  169. scheduler.WithBindTimeoutSeconds(cc.ComponentConfig.BindTimeoutSeconds),
  170. scheduler.WithFrameworkOutOfTreeRegistry(outOfTreeRegistry),
  171. scheduler.WithFrameworkPlugins(cc.ComponentConfig.Plugins),
  172. scheduler.WithFrameworkPluginConfig(cc.ComponentConfig.PluginConfig),
  173. scheduler.WithPodMaxBackoffSeconds(cc.ComponentConfig.PodMaxBackoffSeconds),
  174. scheduler.WithPodInitialBackoffSeconds(cc.ComponentConfig.PodInitialBackoffSeconds),
  175. )
  176. if err != nil {
  177. return err
  178. }
  179. // Prepare the event broadcaster.
  180. if cc.Broadcaster != nil && cc.EventClient != nil {
  181. cc.Broadcaster.StartRecordingToSink(ctx.Done())
  182. }
  183. if cc.CoreBroadcaster != nil && cc.CoreEventClient != nil {
  184. cc.CoreBroadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: cc.CoreEventClient.Events("")})
  185. }
  186. // Setup healthz checks.
  187. var checks []healthz.HealthChecker
  188. if cc.ComponentConfig.LeaderElection.LeaderElect {
  189. checks = append(checks, cc.LeaderElection.WatchDog)
  190. }
  191. // Start up the healthz server.
  192. if cc.InsecureServing != nil {
  193. separateMetrics := cc.InsecureMetricsServing != nil
  194. handler := buildHandlerChain(newHealthzHandler(&cc.ComponentConfig, separateMetrics, checks...), nil, nil)
  195. if err := cc.InsecureServing.Serve(handler, 0, ctx.Done()); err != nil {
  196. return fmt.Errorf("failed to start healthz server: %v", err)
  197. }
  198. }
  199. if cc.InsecureMetricsServing != nil {
  200. handler := buildHandlerChain(newMetricsHandler(&cc.ComponentConfig), nil, nil)
  201. if err := cc.InsecureMetricsServing.Serve(handler, 0, ctx.Done()); err != nil {
  202. return fmt.Errorf("failed to start metrics server: %v", err)
  203. }
  204. }
  205. if cc.SecureServing != nil {
  206. handler := buildHandlerChain(newHealthzHandler(&cc.ComponentConfig, false, checks...), cc.Authentication.Authenticator, cc.Authorization.Authorizer)
  207. // TODO: handle stoppedCh returned by c.SecureServing.Serve
  208. if _, err := cc.SecureServing.Serve(handler, 0, ctx.Done()); err != nil {
  209. // fail early for secure handlers, removing the old error loop from above
  210. return fmt.Errorf("failed to start secure server: %v", err)
  211. }
  212. }
  213. // Start all informers.
  214. go cc.PodInformer.Informer().Run(ctx.Done())
  215. cc.InformerFactory.Start(ctx.Done())
  216. // Wait for all caches to sync before scheduling.
  217. cc.InformerFactory.WaitForCacheSync(ctx.Done())
  218. // If leader election is enabled, runCommand via LeaderElector until done and exit.
  219. if cc.LeaderElection != nil {
  220. cc.LeaderElection.Callbacks = leaderelection.LeaderCallbacks{
  221. OnStartedLeading: sched.Run,
  222. OnStoppedLeading: func() {
  223. klog.Fatalf("leaderelection lost")
  224. },
  225. }
  226. leaderElector, err := leaderelection.NewLeaderElector(*cc.LeaderElection)
  227. if err != nil {
  228. return fmt.Errorf("couldn't create leader elector: %v", err)
  229. }
  230. leaderElector.Run(ctx)
  231. return fmt.Errorf("lost lease")
  232. }
  233. // Leader election is disabled, so runCommand inline until done.
  234. sched.Run(ctx)
  235. return fmt.Errorf("finished without leader elect")
  236. }
  237. // buildHandlerChain wraps the given handler with the standard filters.
  238. func buildHandlerChain(handler http.Handler, authn authenticator.Request, authz authorizer.Authorizer) http.Handler {
  239. requestInfoResolver := &apirequest.RequestInfoFactory{}
  240. failedHandler := genericapifilters.Unauthorized(legacyscheme.Codecs, false)
  241. handler = genericapifilters.WithAuthorization(handler, authz, legacyscheme.Codecs)
  242. handler = genericapifilters.WithAuthentication(handler, authn, failedHandler, nil)
  243. handler = genericapifilters.WithRequestInfo(handler, requestInfoResolver)
  244. handler = genericapifilters.WithCacheControl(handler)
  245. handler = genericfilters.WithPanicRecovery(handler)
  246. return handler
  247. }
  248. func installMetricHandler(pathRecorderMux *mux.PathRecorderMux) {
  249. configz.InstallHandler(pathRecorderMux)
  250. //lint:ignore SA1019 See the Metrics Stability Migration KEP
  251. defaultMetricsHandler := legacyregistry.Handler().ServeHTTP
  252. pathRecorderMux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
  253. if req.Method == "DELETE" {
  254. metrics.Reset()
  255. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  256. w.Header().Set("X-Content-Type-Options", "nosniff")
  257. io.WriteString(w, "metrics reset\n")
  258. return
  259. }
  260. defaultMetricsHandler(w, req)
  261. })
  262. }
  263. // newMetricsHandler builds a metrics server from the config.
  264. func newMetricsHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration) http.Handler {
  265. pathRecorderMux := mux.NewPathRecorderMux("kube-scheduler")
  266. installMetricHandler(pathRecorderMux)
  267. if config.EnableProfiling {
  268. routes.Profiling{}.Install(pathRecorderMux)
  269. if config.EnableContentionProfiling {
  270. goruntime.SetBlockProfileRate(1)
  271. }
  272. routes.DebugFlags{}.Install(pathRecorderMux, "v", routes.StringFlagPutHandler(logs.GlogSetter))
  273. }
  274. return pathRecorderMux
  275. }
  276. // newHealthzHandler creates a healthz server from the config, and will also
  277. // embed the metrics handler if the healthz and metrics address configurations
  278. // are the same.
  279. func newHealthzHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration, separateMetrics bool, checks ...healthz.HealthChecker) http.Handler {
  280. pathRecorderMux := mux.NewPathRecorderMux("kube-scheduler")
  281. healthz.InstallHandler(pathRecorderMux, checks...)
  282. if !separateMetrics {
  283. installMetricHandler(pathRecorderMux)
  284. }
  285. if config.EnableProfiling {
  286. routes.Profiling{}.Install(pathRecorderMux)
  287. if config.EnableContentionProfiling {
  288. goruntime.SetBlockProfileRate(1)
  289. }
  290. routes.DebugFlags{}.Install(pathRecorderMux, "v", routes.StringFlagPutHandler(logs.GlogSetter))
  291. }
  292. return pathRecorderMux
  293. }
  294. // WithPlugin creates an Option based on plugin name and factory. This function is used to register out-of-tree plugins.
  295. func WithPlugin(name string, factory framework.PluginFactory) Option {
  296. return func(registry framework.Registry) error {
  297. return registry.Register(name, factory)
  298. }
  299. }