k3s/vendor/k8s.io/kubernetes/cmd/kube-scheduler/app/server.go

343 lines
12 KiB
Go
Raw Normal View History

2019-01-12 04:58:27 +00:00
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package app implements a Server object for running the scheduler.
package app
import (
"context"
"fmt"
"io"
"net/http"
"os"
goruntime "runtime"
2019-09-27 21:51:53 +00:00
"github.com/spf13/cobra"
2019-11-14 18:56:24 +00:00
"k8s.io/api/core/v1"
eventsv1beta1 "k8s.io/api/events/v1beta1"
2019-01-12 04:58:27 +00:00
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authorization/authorizer"
genericapifilters "k8s.io/apiserver/pkg/endpoints/filters"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
genericfilters "k8s.io/apiserver/pkg/server/filters"
"k8s.io/apiserver/pkg/server/healthz"
"k8s.io/apiserver/pkg/server/mux"
"k8s.io/apiserver/pkg/server/routes"
2019-04-07 17:07:55 +00:00
"k8s.io/apiserver/pkg/util/term"
2019-11-14 18:56:24 +00:00
"k8s.io/client-go/kubernetes/scheme"
2019-09-27 21:51:53 +00:00
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
2019-11-14 18:56:24 +00:00
"k8s.io/client-go/tools/events"
2019-01-12 04:58:27 +00:00
"k8s.io/client-go/tools/leaderelection"
2019-11-14 18:56:24 +00:00
"k8s.io/client-go/tools/record"
2019-04-07 17:07:55 +00:00
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/component-base/cli/globalflag"
2019-12-12 01:27:03 +00:00
"k8s.io/component-base/logs"
2019-09-27 21:51:53 +00:00
"k8s.io/component-base/metrics/legacyregistry"
2019-12-12 01:27:03 +00:00
"k8s.io/component-base/version"
"k8s.io/component-base/version/verflag"
2019-09-27 21:51:53 +00:00
"k8s.io/klog"
2019-01-12 04:58:27 +00:00
schedulerserverconfig "k8s.io/kubernetes/cmd/kube-scheduler/app/config"
"k8s.io/kubernetes/cmd/kube-scheduler/app/options"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/scheduler"
kubeschedulerconfig "k8s.io/kubernetes/pkg/scheduler/apis/config"
2019-08-30 18:33:25 +00:00
framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
2019-01-12 04:58:27 +00:00
"k8s.io/kubernetes/pkg/scheduler/metrics"
2020-03-26 21:07:15 +00:00
"k8s.io/kubernetes/pkg/scheduler/profile"
2019-01-12 04:58:27 +00:00
"k8s.io/kubernetes/pkg/util/configz"
utilflag "k8s.io/kubernetes/pkg/util/flag"
)
2019-09-27 21:51:53 +00:00
// Option configures a framework.Registry.
type Option func(framework.Registry) error
// NewSchedulerCommand creates a *cobra.Command object with default parameters and registryOptions
func NewSchedulerCommand(registryOptions ...Option) *cobra.Command {
2019-01-12 04:58:27 +00:00
opts, err := options.NewOptions()
if err != nil {
klog.Fatalf("unable to initialize command options: %v", err)
}
cmd := &cobra.Command{
Use: "kube-scheduler",
Long: `The Kubernetes scheduler is a policy-rich, topology-aware,
workload-specific function that significantly impacts availability, performance,
and capacity. The scheduler needs to take into account individual and collective
resource requirements, quality of service requirements, hardware/software/policy
constraints, affinity and anti-affinity specifications, data locality, inter-workload
interference, deadlines, and so on. Workload-specific requirements will be exposed
2020-03-26 21:07:15 +00:00
through the API as necessary. See [scheduling](https://kubernetes.io/docs/concepts/scheduling/)
for more information about scheduling and the kube-scheduler component.`,
2019-01-12 04:58:27 +00:00
Run: func(cmd *cobra.Command, args []string) {
2019-09-27 21:51:53 +00:00
if err := runCommand(cmd, args, opts, registryOptions...); err != nil {
2019-01-12 04:58:27 +00:00
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
},
}
fs := cmd.Flags()
namedFlagSets := opts.Flags()
verflag.AddFlags(namedFlagSets.FlagSet("global"))
globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name())
for _, f := range namedFlagSets.FlagSets {
fs.AddFlagSet(f)
}
usageFmt := "Usage:\n %s\n"
2019-04-07 17:07:55 +00:00
cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
2019-01-12 04:58:27 +00:00
cmd.SetUsageFunc(func(cmd *cobra.Command) error {
fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
2019-04-07 17:07:55 +00:00
cliflag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)
2019-01-12 04:58:27 +00:00
return nil
})
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
2019-04-07 17:07:55 +00:00
cliflag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)
2019-01-12 04:58:27 +00:00
})
cmd.MarkFlagFilename("config", "yaml", "yml", "json")
return cmd
}
// runCommand runs the scheduler.
2019-09-27 21:51:53 +00:00
func runCommand(cmd *cobra.Command, args []string, opts *options.Options, registryOptions ...Option) error {
2019-01-12 04:58:27 +00:00
verflag.PrintAndExitIfRequested()
utilflag.PrintFlags(cmd.Flags())
if len(args) != 0 {
fmt.Fprint(os.Stderr, "arguments are not supported\n")
}
if errs := opts.Validate(); len(errs) > 0 {
2019-12-12 01:27:03 +00:00
return utilerrors.NewAggregate(errs)
2019-01-12 04:58:27 +00:00
}
if len(opts.WriteConfigTo) > 0 {
2019-12-12 01:27:03 +00:00
c := &schedulerserverconfig.Config{}
if err := opts.ApplyTo(c); err != nil {
return err
}
if err := options.WriteConfigFile(opts.WriteConfigTo, &c.ComponentConfig); err != nil {
return err
2019-01-12 04:58:27 +00:00
}
klog.Infof("Wrote configuration to: %s\n", opts.WriteConfigTo)
2019-12-12 01:27:03 +00:00
return nil
2019-01-12 04:58:27 +00:00
}
c, err := opts.Config()
if err != nil {
2019-12-12 01:27:03 +00:00
return err
2019-01-12 04:58:27 +00:00
}
// Get the completed config
cc := c.Complete()
// Configz registration.
if cz, err := configz.New("componentconfig"); err == nil {
cz.Set(cc.ComponentConfig)
} else {
return fmt.Errorf("unable to register configz: %s", err)
}
2019-12-12 01:27:03 +00:00
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return Run(ctx, cc, registryOptions...)
2019-01-12 04:58:27 +00:00
}
2019-12-12 01:27:03 +00:00
// Run executes the scheduler based on the given configuration. It only returns on error or when context is done.
func Run(ctx context.Context, cc schedulerserverconfig.CompletedConfig, outOfTreeRegistryOptions ...Option) error {
2019-04-07 17:07:55 +00:00
// To help debugging, immediately log version
klog.V(1).Infof("Starting Kubernetes Scheduler version %+v", version.Get())
2019-01-12 04:58:27 +00:00
2019-12-12 01:27:03 +00:00
outOfTreeRegistry := make(framework.Registry)
for _, option := range outOfTreeRegistryOptions {
if err := option(outOfTreeRegistry); err != nil {
2019-09-27 21:51:53 +00:00
return err
}
}
2020-03-26 21:07:15 +00:00
recorderFactory := getRecorderFactory(&cc)
2019-01-12 04:58:27 +00:00
// Create the scheduler.
sched, err := scheduler.New(cc.Client,
2019-12-12 01:27:03 +00:00
cc.InformerFactory,
2019-01-12 04:58:27 +00:00
cc.PodInformer,
2020-03-26 21:07:15 +00:00
recorderFactory,
2019-12-12 01:27:03 +00:00
ctx.Done(),
2020-03-26 21:07:15 +00:00
scheduler.WithProfiles(cc.ComponentConfig.Profiles...),
2019-12-12 01:27:03 +00:00
scheduler.WithAlgorithmSource(cc.ComponentConfig.AlgorithmSource),
2019-01-12 04:58:27 +00:00
scheduler.WithPreemptionDisabled(cc.ComponentConfig.DisablePreemption),
scheduler.WithPercentageOfNodesToScore(cc.ComponentConfig.PercentageOfNodesToScore),
2019-12-12 01:27:03 +00:00
scheduler.WithBindTimeoutSeconds(cc.ComponentConfig.BindTimeoutSeconds),
scheduler.WithFrameworkOutOfTreeRegistry(outOfTreeRegistry),
scheduler.WithPodMaxBackoffSeconds(cc.ComponentConfig.PodMaxBackoffSeconds),
scheduler.WithPodInitialBackoffSeconds(cc.ComponentConfig.PodInitialBackoffSeconds),
2020-03-26 21:07:15 +00:00
scheduler.WithExtenders(cc.ComponentConfig.Extenders...),
2019-12-12 01:27:03 +00:00
)
2019-01-12 04:58:27 +00:00
if err != nil {
return err
}
// Prepare the event broadcaster.
if cc.Broadcaster != nil && cc.EventClient != nil {
2019-12-12 01:27:03 +00:00
cc.Broadcaster.StartRecordingToSink(ctx.Done())
2019-09-27 21:51:53 +00:00
}
2019-11-14 18:56:24 +00:00
if cc.CoreBroadcaster != nil && cc.CoreEventClient != nil {
cc.CoreBroadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: cc.CoreEventClient.Events("")})
2019-01-12 04:58:27 +00:00
}
// Setup healthz checks.
2019-09-27 21:51:53 +00:00
var checks []healthz.HealthChecker
2019-01-12 04:58:27 +00:00
if cc.ComponentConfig.LeaderElection.LeaderElect {
checks = append(checks, cc.LeaderElection.WatchDog)
}
// Start up the healthz server.
if cc.InsecureServing != nil {
separateMetrics := cc.InsecureMetricsServing != nil
handler := buildHandlerChain(newHealthzHandler(&cc.ComponentConfig, separateMetrics, checks...), nil, nil)
2019-12-12 01:27:03 +00:00
if err := cc.InsecureServing.Serve(handler, 0, ctx.Done()); err != nil {
2019-01-12 04:58:27 +00:00
return fmt.Errorf("failed to start healthz server: %v", err)
}
}
if cc.InsecureMetricsServing != nil {
handler := buildHandlerChain(newMetricsHandler(&cc.ComponentConfig), nil, nil)
2019-12-12 01:27:03 +00:00
if err := cc.InsecureMetricsServing.Serve(handler, 0, ctx.Done()); err != nil {
2019-01-12 04:58:27 +00:00
return fmt.Errorf("failed to start metrics server: %v", err)
}
}
if cc.SecureServing != nil {
handler := buildHandlerChain(newHealthzHandler(&cc.ComponentConfig, false, checks...), cc.Authentication.Authenticator, cc.Authorization.Authorizer)
2019-04-07 17:07:55 +00:00
// TODO: handle stoppedCh returned by c.SecureServing.Serve
2019-12-12 01:27:03 +00:00
if _, err := cc.SecureServing.Serve(handler, 0, ctx.Done()); err != nil {
2019-01-12 04:58:27 +00:00
// fail early for secure handlers, removing the old error loop from above
2019-04-07 17:07:55 +00:00
return fmt.Errorf("failed to start secure server: %v", err)
2019-01-12 04:58:27 +00:00
}
}
// Start all informers.
2019-12-12 01:27:03 +00:00
go cc.PodInformer.Informer().Run(ctx.Done())
cc.InformerFactory.Start(ctx.Done())
2019-01-12 04:58:27 +00:00
// Wait for all caches to sync before scheduling.
2019-12-12 01:27:03 +00:00
cc.InformerFactory.WaitForCacheSync(ctx.Done())
2019-01-12 04:58:27 +00:00
// If leader election is enabled, runCommand via LeaderElector until done and exit.
if cc.LeaderElection != nil {
cc.LeaderElection.Callbacks = leaderelection.LeaderCallbacks{
2019-12-12 01:27:03 +00:00
OnStartedLeading: sched.Run,
2019-01-12 04:58:27 +00:00
OnStoppedLeading: func() {
2019-09-27 21:51:53 +00:00
klog.Fatalf("leaderelection lost")
2019-01-12 04:58:27 +00:00
},
}
leaderElector, err := leaderelection.NewLeaderElector(*cc.LeaderElection)
if err != nil {
return fmt.Errorf("couldn't create leader elector: %v", err)
}
leaderElector.Run(ctx)
return fmt.Errorf("lost lease")
}
// Leader election is disabled, so runCommand inline until done.
2019-12-12 01:27:03 +00:00
sched.Run(ctx)
2019-01-12 04:58:27 +00:00
return fmt.Errorf("finished without leader elect")
}
// buildHandlerChain wraps the given handler with the standard filters.
func buildHandlerChain(handler http.Handler, authn authenticator.Request, authz authorizer.Authorizer) http.Handler {
requestInfoResolver := &apirequest.RequestInfoFactory{}
failedHandler := genericapifilters.Unauthorized(legacyscheme.Codecs, false)
handler = genericapifilters.WithAuthorization(handler, authz, legacyscheme.Codecs)
handler = genericapifilters.WithAuthentication(handler, authn, failedHandler, nil)
handler = genericapifilters.WithRequestInfo(handler, requestInfoResolver)
2019-09-27 21:51:53 +00:00
handler = genericapifilters.WithCacheControl(handler)
2019-01-12 04:58:27 +00:00
handler = genericfilters.WithPanicRecovery(handler)
return handler
}
func installMetricHandler(pathRecorderMux *mux.PathRecorderMux) {
configz.InstallHandler(pathRecorderMux)
2019-12-12 01:27:03 +00:00
//lint:ignore SA1019 See the Metrics Stability Migration KEP
2019-09-27 21:51:53 +00:00
defaultMetricsHandler := legacyregistry.Handler().ServeHTTP
2019-01-12 04:58:27 +00:00
pathRecorderMux.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) {
if req.Method == "DELETE" {
metrics.Reset()
2019-12-12 01:27:03 +00:00
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
2019-01-12 04:58:27 +00:00
io.WriteString(w, "metrics reset\n")
return
}
defaultMetricsHandler(w, req)
})
}
// newMetricsHandler builds a metrics server from the config.
func newMetricsHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration) http.Handler {
pathRecorderMux := mux.NewPathRecorderMux("kube-scheduler")
installMetricHandler(pathRecorderMux)
if config.EnableProfiling {
routes.Profiling{}.Install(pathRecorderMux)
if config.EnableContentionProfiling {
goruntime.SetBlockProfileRate(1)
}
2019-12-12 01:27:03 +00:00
routes.DebugFlags{}.Install(pathRecorderMux, "v", routes.StringFlagPutHandler(logs.GlogSetter))
2019-01-12 04:58:27 +00:00
}
return pathRecorderMux
}
2019-04-07 17:07:55 +00:00
// newHealthzHandler creates a healthz server from the config, and will also
2019-01-12 04:58:27 +00:00
// embed the metrics handler if the healthz and metrics address configurations
// are the same.
2019-09-27 21:51:53 +00:00
func newHealthzHandler(config *kubeschedulerconfig.KubeSchedulerConfiguration, separateMetrics bool, checks ...healthz.HealthChecker) http.Handler {
2019-01-12 04:58:27 +00:00
pathRecorderMux := mux.NewPathRecorderMux("kube-scheduler")
healthz.InstallHandler(pathRecorderMux, checks...)
if !separateMetrics {
installMetricHandler(pathRecorderMux)
}
if config.EnableProfiling {
routes.Profiling{}.Install(pathRecorderMux)
if config.EnableContentionProfiling {
goruntime.SetBlockProfileRate(1)
}
2019-12-12 01:27:03 +00:00
routes.DebugFlags{}.Install(pathRecorderMux, "v", routes.StringFlagPutHandler(logs.GlogSetter))
2019-01-12 04:58:27 +00:00
}
return pathRecorderMux
}
2019-09-27 21:51:53 +00:00
2020-03-26 21:07:15 +00:00
func getRecorderFactory(cc *schedulerserverconfig.CompletedConfig) profile.RecorderFactory {
if _, err := cc.Client.Discovery().ServerResourcesForGroupVersion(eventsv1beta1.SchemeGroupVersion.String()); err == nil {
cc.Broadcaster = events.NewBroadcaster(&events.EventSinkImpl{Interface: cc.EventClient.Events("")})
return profile.NewRecorderFactory(cc.Broadcaster)
}
return func(name string) events.EventRecorder {
r := cc.CoreBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: name})
return record.NewEventRecorderAdapter(r)
}
}
// WithPlugin creates an Option based on plugin name and factory. Please don't remove this function: it is used to register out-of-tree plugins,
// hence there are no references to it from the kubernetes scheduler code base.
2019-09-27 21:51:53 +00:00
func WithPlugin(name string, factory framework.PluginFactory) Option {
return func(registry framework.Registry) error {
return registry.Register(name, factory)
}
}