server.go 13 KB

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