scheduler.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 scheduler
  14. import (
  15. "context"
  16. "fmt"
  17. "io/ioutil"
  18. "math/rand"
  19. "os"
  20. "time"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/util/wait"
  25. utilfeature "k8s.io/apiserver/pkg/util/feature"
  26. "k8s.io/client-go/informers"
  27. coreinformers "k8s.io/client-go/informers/core/v1"
  28. clientset "k8s.io/client-go/kubernetes"
  29. "k8s.io/client-go/tools/cache"
  30. "k8s.io/client-go/tools/events"
  31. "k8s.io/klog"
  32. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  33. kubefeatures "k8s.io/kubernetes/pkg/features"
  34. schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/config"
  35. "k8s.io/kubernetes/pkg/scheduler/apis/config/scheme"
  36. "k8s.io/kubernetes/pkg/scheduler/core"
  37. frameworkplugins "k8s.io/kubernetes/pkg/scheduler/framework/plugins"
  38. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  39. internalcache "k8s.io/kubernetes/pkg/scheduler/internal/cache"
  40. internalqueue "k8s.io/kubernetes/pkg/scheduler/internal/queue"
  41. "k8s.io/kubernetes/pkg/scheduler/metrics"
  42. "k8s.io/kubernetes/pkg/scheduler/volumebinder"
  43. )
  44. const (
  45. // BindTimeoutSeconds defines the default bind timeout
  46. BindTimeoutSeconds = 100
  47. // SchedulerError is the reason recorded for events when an error occurs during scheduling a pod.
  48. SchedulerError = "SchedulerError"
  49. // Percentage of plugin metrics to be sampled.
  50. pluginMetricsSamplePercent = 10
  51. )
  52. // podConditionUpdater updates the condition of a pod based on the passed
  53. // PodCondition
  54. // TODO (ahmad-diaa): Remove type and replace it with scheduler methods
  55. type podConditionUpdater interface {
  56. update(pod *v1.Pod, podCondition *v1.PodCondition) error
  57. }
  58. // PodPreemptor has methods needed to delete a pod and to update 'NominatedPod'
  59. // field of the preemptor pod.
  60. // TODO (ahmad-diaa): Remove type and replace it with scheduler methods
  61. type podPreemptor interface {
  62. getUpdatedPod(pod *v1.Pod) (*v1.Pod, error)
  63. deletePod(pod *v1.Pod) error
  64. setNominatedNodeName(pod *v1.Pod, nominatedNode string) error
  65. removeNominatedNodeName(pod *v1.Pod) error
  66. }
  67. // Scheduler watches for new unscheduled pods. It attempts to find
  68. // nodes that they fit on and writes bindings back to the api server.
  69. type Scheduler struct {
  70. // It is expected that changes made via SchedulerCache will be observed
  71. // by NodeLister and Algorithm.
  72. SchedulerCache internalcache.Cache
  73. Algorithm core.ScheduleAlgorithm
  74. // PodConditionUpdater is used only in case of scheduling errors. If we succeed
  75. // with scheduling, PodScheduled condition will be updated in apiserver in /bind
  76. // handler so that binding and setting PodCondition it is atomic.
  77. podConditionUpdater podConditionUpdater
  78. // PodPreemptor is used to evict pods and update 'NominatedNode' field of
  79. // the preemptor pod.
  80. podPreemptor podPreemptor
  81. // Framework runs scheduler plugins at configured extension points.
  82. Framework framework.Framework
  83. // NextPod should be a function that blocks until the next pod
  84. // is available. We don't use a channel for this, because scheduling
  85. // a pod may take some amount of time and we don't want pods to get
  86. // stale while they sit in a channel.
  87. NextPod func() *framework.PodInfo
  88. // Error is called if there is an error. It is passed the pod in
  89. // question, and the error
  90. Error func(*framework.PodInfo, error)
  91. // Recorder is the EventRecorder to use
  92. Recorder events.EventRecorder
  93. // Close this to shut down the scheduler.
  94. StopEverything <-chan struct{}
  95. // VolumeBinder handles PVC/PV binding for the pod.
  96. VolumeBinder *volumebinder.VolumeBinder
  97. // Disable pod preemption or not.
  98. DisablePreemption bool
  99. // SchedulingQueue holds pods to be scheduled
  100. SchedulingQueue internalqueue.SchedulingQueue
  101. scheduledPodsHasSynced func() bool
  102. }
  103. // Cache returns the cache in scheduler for test to check the data in scheduler.
  104. func (sched *Scheduler) Cache() internalcache.Cache {
  105. return sched.SchedulerCache
  106. }
  107. type schedulerOptions struct {
  108. schedulerName string
  109. schedulerAlgorithmSource schedulerapi.SchedulerAlgorithmSource
  110. hardPodAffinitySymmetricWeight int32
  111. disablePreemption bool
  112. percentageOfNodesToScore int32
  113. bindTimeoutSeconds int64
  114. podInitialBackoffSeconds int64
  115. podMaxBackoffSeconds int64
  116. // Contains out-of-tree plugins to be merged with the in-tree registry.
  117. frameworkOutOfTreeRegistry framework.Registry
  118. // Plugins and PluginConfig set from ComponentConfig.
  119. frameworkPlugins *schedulerapi.Plugins
  120. frameworkPluginConfig []schedulerapi.PluginConfig
  121. }
  122. // Option configures a Scheduler
  123. type Option func(*schedulerOptions)
  124. // WithName sets schedulerName for Scheduler, the default schedulerName is default-scheduler
  125. func WithName(schedulerName string) Option {
  126. return func(o *schedulerOptions) {
  127. o.schedulerName = schedulerName
  128. }
  129. }
  130. // WithAlgorithmSource sets schedulerAlgorithmSource for Scheduler, the default is a source with DefaultProvider.
  131. func WithAlgorithmSource(source schedulerapi.SchedulerAlgorithmSource) Option {
  132. return func(o *schedulerOptions) {
  133. o.schedulerAlgorithmSource = source
  134. }
  135. }
  136. // WithHardPodAffinitySymmetricWeight sets hardPodAffinitySymmetricWeight for Scheduler, the default value is 1
  137. func WithHardPodAffinitySymmetricWeight(hardPodAffinitySymmetricWeight int32) Option {
  138. return func(o *schedulerOptions) {
  139. o.hardPodAffinitySymmetricWeight = hardPodAffinitySymmetricWeight
  140. }
  141. }
  142. // WithPreemptionDisabled sets disablePreemption for Scheduler, the default value is false
  143. func WithPreemptionDisabled(disablePreemption bool) Option {
  144. return func(o *schedulerOptions) {
  145. o.disablePreemption = disablePreemption
  146. }
  147. }
  148. // WithPercentageOfNodesToScore sets percentageOfNodesToScore for Scheduler, the default value is 50
  149. func WithPercentageOfNodesToScore(percentageOfNodesToScore int32) Option {
  150. return func(o *schedulerOptions) {
  151. o.percentageOfNodesToScore = percentageOfNodesToScore
  152. }
  153. }
  154. // WithBindTimeoutSeconds sets bindTimeoutSeconds for Scheduler, the default value is 100
  155. func WithBindTimeoutSeconds(bindTimeoutSeconds int64) Option {
  156. return func(o *schedulerOptions) {
  157. o.bindTimeoutSeconds = bindTimeoutSeconds
  158. }
  159. }
  160. // WithFrameworkOutOfTreeRegistry sets the registry for out-of-tree plugins. Those plugins
  161. // will be appended to the default registry.
  162. func WithFrameworkOutOfTreeRegistry(registry framework.Registry) Option {
  163. return func(o *schedulerOptions) {
  164. o.frameworkOutOfTreeRegistry = registry
  165. }
  166. }
  167. // WithFrameworkPlugins sets the plugins that the framework should be configured with.
  168. func WithFrameworkPlugins(plugins *schedulerapi.Plugins) Option {
  169. return func(o *schedulerOptions) {
  170. o.frameworkPlugins = plugins
  171. }
  172. }
  173. // WithFrameworkPluginConfig sets the PluginConfig slice that the framework should be configured with.
  174. func WithFrameworkPluginConfig(pluginConfig []schedulerapi.PluginConfig) Option {
  175. return func(o *schedulerOptions) {
  176. o.frameworkPluginConfig = pluginConfig
  177. }
  178. }
  179. // WithPodInitialBackoffSeconds sets podInitialBackoffSeconds for Scheduler, the default value is 1
  180. func WithPodInitialBackoffSeconds(podInitialBackoffSeconds int64) Option {
  181. return func(o *schedulerOptions) {
  182. o.podInitialBackoffSeconds = podInitialBackoffSeconds
  183. }
  184. }
  185. // WithPodMaxBackoffSeconds sets podMaxBackoffSeconds for Scheduler, the default value is 10
  186. func WithPodMaxBackoffSeconds(podMaxBackoffSeconds int64) Option {
  187. return func(o *schedulerOptions) {
  188. o.podMaxBackoffSeconds = podMaxBackoffSeconds
  189. }
  190. }
  191. var defaultSchedulerOptions = schedulerOptions{
  192. schedulerName: v1.DefaultSchedulerName,
  193. schedulerAlgorithmSource: schedulerapi.SchedulerAlgorithmSource{
  194. Provider: defaultAlgorithmSourceProviderName(),
  195. },
  196. hardPodAffinitySymmetricWeight: v1.DefaultHardPodAffinitySymmetricWeight,
  197. disablePreemption: false,
  198. percentageOfNodesToScore: schedulerapi.DefaultPercentageOfNodesToScore,
  199. bindTimeoutSeconds: BindTimeoutSeconds,
  200. podInitialBackoffSeconds: int64(internalqueue.DefaultPodInitialBackoffDuration.Seconds()),
  201. podMaxBackoffSeconds: int64(internalqueue.DefaultPodMaxBackoffDuration.Seconds()),
  202. }
  203. // New returns a Scheduler
  204. func New(client clientset.Interface,
  205. informerFactory informers.SharedInformerFactory,
  206. podInformer coreinformers.PodInformer,
  207. recorder events.EventRecorder,
  208. stopCh <-chan struct{},
  209. opts ...Option) (*Scheduler, error) {
  210. stopEverything := stopCh
  211. if stopEverything == nil {
  212. stopEverything = wait.NeverStop
  213. }
  214. options := defaultSchedulerOptions
  215. for _, opt := range opts {
  216. opt(&options)
  217. }
  218. schedulerCache := internalcache.New(30*time.Second, stopEverything)
  219. volumeBinder := volumebinder.NewVolumeBinder(
  220. client,
  221. informerFactory.Core().V1().Nodes(),
  222. informerFactory.Storage().V1().CSINodes(),
  223. informerFactory.Core().V1().PersistentVolumeClaims(),
  224. informerFactory.Core().V1().PersistentVolumes(),
  225. informerFactory.Storage().V1().StorageClasses(),
  226. time.Duration(options.bindTimeoutSeconds)*time.Second,
  227. )
  228. registry := frameworkplugins.NewInTreeRegistry()
  229. if err := registry.Merge(options.frameworkOutOfTreeRegistry); err != nil {
  230. return nil, err
  231. }
  232. snapshot := internalcache.NewEmptySnapshot()
  233. configurator := &Configurator{
  234. client: client,
  235. informerFactory: informerFactory,
  236. podInformer: podInformer,
  237. volumeBinder: volumeBinder,
  238. schedulerCache: schedulerCache,
  239. StopEverything: stopEverything,
  240. hardPodAffinitySymmetricWeight: options.hardPodAffinitySymmetricWeight,
  241. disablePreemption: options.disablePreemption,
  242. percentageOfNodesToScore: options.percentageOfNodesToScore,
  243. bindTimeoutSeconds: options.bindTimeoutSeconds,
  244. podInitialBackoffSeconds: options.podInitialBackoffSeconds,
  245. podMaxBackoffSeconds: options.podMaxBackoffSeconds,
  246. enableNonPreempting: utilfeature.DefaultFeatureGate.Enabled(kubefeatures.NonPreemptingPriority),
  247. registry: registry,
  248. plugins: options.frameworkPlugins,
  249. pluginConfig: options.frameworkPluginConfig,
  250. nodeInfoSnapshot: snapshot,
  251. }
  252. metrics.Register()
  253. var sched *Scheduler
  254. source := options.schedulerAlgorithmSource
  255. switch {
  256. case source.Provider != nil:
  257. // Create the config from a named algorithm provider.
  258. sc, err := configurator.createFromProvider(*source.Provider)
  259. if err != nil {
  260. return nil, fmt.Errorf("couldn't create scheduler using provider %q: %v", *source.Provider, err)
  261. }
  262. sched = sc
  263. case source.Policy != nil:
  264. // Create the config from a user specified policy source.
  265. policy := &schedulerapi.Policy{}
  266. switch {
  267. case source.Policy.File != nil:
  268. if err := initPolicyFromFile(source.Policy.File.Path, policy); err != nil {
  269. return nil, err
  270. }
  271. case source.Policy.ConfigMap != nil:
  272. if err := initPolicyFromConfigMap(client, source.Policy.ConfigMap, policy); err != nil {
  273. return nil, err
  274. }
  275. }
  276. sc, err := configurator.createFromConfig(*policy)
  277. if err != nil {
  278. return nil, fmt.Errorf("couldn't create scheduler from policy: %v", err)
  279. }
  280. sched = sc
  281. default:
  282. return nil, fmt.Errorf("unsupported algorithm source: %v", source)
  283. }
  284. // Additional tweaks to the config produced by the configurator.
  285. sched.Recorder = recorder
  286. sched.DisablePreemption = options.disablePreemption
  287. sched.StopEverything = stopEverything
  288. sched.podConditionUpdater = &podConditionUpdaterImpl{client}
  289. sched.podPreemptor = &podPreemptorImpl{client}
  290. sched.scheduledPodsHasSynced = podInformer.Informer().HasSynced
  291. AddAllEventHandlers(sched, options.schedulerName, informerFactory, podInformer)
  292. return sched, nil
  293. }
  294. // initPolicyFromFile initialize policy from file
  295. func initPolicyFromFile(policyFile string, policy *schedulerapi.Policy) error {
  296. // Use a policy serialized in a file.
  297. _, err := os.Stat(policyFile)
  298. if err != nil {
  299. return fmt.Errorf("missing policy config file %s", policyFile)
  300. }
  301. data, err := ioutil.ReadFile(policyFile)
  302. if err != nil {
  303. return fmt.Errorf("couldn't read policy config: %v", err)
  304. }
  305. err = runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), []byte(data), policy)
  306. if err != nil {
  307. return fmt.Errorf("invalid policy: %v", err)
  308. }
  309. return nil
  310. }
  311. // initPolicyFromConfigMap initialize policy from configMap
  312. func initPolicyFromConfigMap(client clientset.Interface, policyRef *schedulerapi.SchedulerPolicyConfigMapSource, policy *schedulerapi.Policy) error {
  313. // Use a policy serialized in a config map value.
  314. policyConfigMap, err := client.CoreV1().ConfigMaps(policyRef.Namespace).Get(context.TODO(), policyRef.Name, metav1.GetOptions{})
  315. if err != nil {
  316. return fmt.Errorf("couldn't get policy config map %s/%s: %v", policyRef.Namespace, policyRef.Name, err)
  317. }
  318. data, found := policyConfigMap.Data[schedulerapi.SchedulerPolicyConfigMapKey]
  319. if !found {
  320. return fmt.Errorf("missing policy config map value at key %q", schedulerapi.SchedulerPolicyConfigMapKey)
  321. }
  322. err = runtime.DecodeInto(scheme.Codecs.UniversalDecoder(), []byte(data), policy)
  323. if err != nil {
  324. return fmt.Errorf("invalid policy: %v", err)
  325. }
  326. return nil
  327. }
  328. // Run begins watching and scheduling. It waits for cache to be synced, then starts scheduling and blocked until the context is done.
  329. func (sched *Scheduler) Run(ctx context.Context) {
  330. if !cache.WaitForCacheSync(ctx.Done(), sched.scheduledPodsHasSynced) {
  331. return
  332. }
  333. sched.SchedulingQueue.Run()
  334. wait.UntilWithContext(ctx, sched.scheduleOne, 0)
  335. sched.SchedulingQueue.Close()
  336. }
  337. // recordFailedSchedulingEvent records an event for the pod that indicates the
  338. // pod has failed to schedule.
  339. // NOTE: This function modifies "pod". "pod" should be copied before being passed.
  340. func (sched *Scheduler) recordSchedulingFailure(podInfo *framework.PodInfo, err error, reason string, message string) {
  341. sched.Error(podInfo, err)
  342. pod := podInfo.Pod
  343. sched.Recorder.Eventf(pod, nil, v1.EventTypeWarning, "FailedScheduling", "Scheduling", message)
  344. if err := sched.podConditionUpdater.update(pod, &v1.PodCondition{
  345. Type: v1.PodScheduled,
  346. Status: v1.ConditionFalse,
  347. Reason: reason,
  348. Message: err.Error(),
  349. }); err != nil {
  350. klog.Errorf("Error updating the condition of the pod %s/%s: %v", pod.Namespace, pod.Name, err)
  351. }
  352. }
  353. // preempt tries to create room for a pod that has failed to schedule, by preempting lower priority pods if possible.
  354. // If it succeeds, it adds the name of the node where preemption has happened to the pod spec.
  355. // It returns the node name and an error if any.
  356. func (sched *Scheduler) preempt(ctx context.Context, state *framework.CycleState, fwk framework.Framework, preemptor *v1.Pod, scheduleErr error) (string, error) {
  357. preemptor, err := sched.podPreemptor.getUpdatedPod(preemptor)
  358. if err != nil {
  359. klog.Errorf("Error getting the updated preemptor pod object: %v", err)
  360. return "", err
  361. }
  362. node, victims, nominatedPodsToClear, err := sched.Algorithm.Preempt(ctx, state, preemptor, scheduleErr)
  363. if err != nil {
  364. klog.Errorf("Error preempting victims to make room for %v/%v: %v", preemptor.Namespace, preemptor.Name, err)
  365. return "", err
  366. }
  367. var nodeName = ""
  368. if node != nil {
  369. nodeName = node.Name
  370. // Update the scheduling queue with the nominated pod information. Without
  371. // this, there would be a race condition between the next scheduling cycle
  372. // and the time the scheduler receives a Pod Update for the nominated pod.
  373. sched.SchedulingQueue.UpdateNominatedPodForNode(preemptor, nodeName)
  374. // Make a call to update nominated node name of the pod on the API server.
  375. err = sched.podPreemptor.setNominatedNodeName(preemptor, nodeName)
  376. if err != nil {
  377. klog.Errorf("Error in preemption process. Cannot set 'NominatedPod' on pod %v/%v: %v", preemptor.Namespace, preemptor.Name, err)
  378. sched.SchedulingQueue.DeleteNominatedPodIfExists(preemptor)
  379. return "", err
  380. }
  381. for _, victim := range victims {
  382. if err := sched.podPreemptor.deletePod(victim); err != nil {
  383. klog.Errorf("Error preempting pod %v/%v: %v", victim.Namespace, victim.Name, err)
  384. return "", err
  385. }
  386. // If the victim is a WaitingPod, send a reject message to the PermitPlugin
  387. if waitingPod := fwk.GetWaitingPod(victim.UID); waitingPod != nil {
  388. waitingPod.Reject("preempted")
  389. }
  390. sched.Recorder.Eventf(victim, preemptor, v1.EventTypeNormal, "Preempted", "Preempting", "Preempted by %v/%v on node %v", preemptor.Namespace, preemptor.Name, nodeName)
  391. }
  392. metrics.PreemptionVictims.Observe(float64(len(victims)))
  393. }
  394. // Clearing nominated pods should happen outside of "if node != nil". Node could
  395. // be nil when a pod with nominated node name is eligible to preempt again,
  396. // but preemption logic does not find any node for it. In that case Preempt()
  397. // function of generic_scheduler.go returns the pod itself for removal of
  398. // the 'NominatedPod' field.
  399. for _, p := range nominatedPodsToClear {
  400. rErr := sched.podPreemptor.removeNominatedNodeName(p)
  401. if rErr != nil {
  402. klog.Errorf("Cannot remove 'NominatedPod' field of pod: %v", rErr)
  403. // We do not return as this error is not critical.
  404. }
  405. }
  406. return nodeName, err
  407. }
  408. // bindVolumes will make the API update with the assumed bindings and wait until
  409. // the PV controller has completely finished the binding operation.
  410. //
  411. // If binding errors, times out or gets undone, then an error will be returned to
  412. // retry scheduling.
  413. func (sched *Scheduler) bindVolumes(assumed *v1.Pod) error {
  414. klog.V(5).Infof("Trying to bind volumes for pod \"%v/%v\"", assumed.Namespace, assumed.Name)
  415. err := sched.VolumeBinder.Binder.BindPodVolumes(assumed)
  416. if err != nil {
  417. klog.V(1).Infof("Failed to bind volumes for pod \"%v/%v\": %v", assumed.Namespace, assumed.Name, err)
  418. // Unassume the Pod and retry scheduling
  419. if forgetErr := sched.SchedulerCache.ForgetPod(assumed); forgetErr != nil {
  420. klog.Errorf("scheduler cache ForgetPod failed: %v", forgetErr)
  421. }
  422. return err
  423. }
  424. klog.V(5).Infof("Success binding volumes for pod \"%v/%v\"", assumed.Namespace, assumed.Name)
  425. return nil
  426. }
  427. // assume signals to the cache that a pod is already in the cache, so that binding can be asynchronous.
  428. // assume modifies `assumed`.
  429. func (sched *Scheduler) assume(assumed *v1.Pod, host string) error {
  430. // Optimistically assume that the binding will succeed and send it to apiserver
  431. // in the background.
  432. // If the binding fails, scheduler will release resources allocated to assumed pod
  433. // immediately.
  434. assumed.Spec.NodeName = host
  435. if err := sched.SchedulerCache.AssumePod(assumed); err != nil {
  436. klog.Errorf("scheduler cache AssumePod failed: %v", err)
  437. return err
  438. }
  439. // if "assumed" is a nominated pod, we should remove it from internal cache
  440. if sched.SchedulingQueue != nil {
  441. sched.SchedulingQueue.DeleteNominatedPodIfExists(assumed)
  442. }
  443. return nil
  444. }
  445. // bind binds a pod to a given node defined in a binding object.
  446. // The precedence for binding is: (1) extenders and (2) framework plugins.
  447. // We expect this to run asynchronously, so we handle binding metrics internally.
  448. func (sched *Scheduler) bind(ctx context.Context, assumed *v1.Pod, targetNode string, state *framework.CycleState) (err error) {
  449. start := time.Now()
  450. defer func() {
  451. sched.finishBinding(assumed, targetNode, start, err)
  452. }()
  453. bound, err := sched.extendersBinding(assumed, targetNode)
  454. if bound {
  455. return err
  456. }
  457. bindStatus := sched.Framework.RunBindPlugins(ctx, state, assumed, targetNode)
  458. if bindStatus.IsSuccess() {
  459. return nil
  460. }
  461. if bindStatus.Code() == framework.Error {
  462. return bindStatus.AsError()
  463. }
  464. return fmt.Errorf("bind status: %s, %v", bindStatus.Code().String(), bindStatus.Message())
  465. }
  466. // TODO(#87159): Move this to a Plugin.
  467. func (sched *Scheduler) extendersBinding(pod *v1.Pod, node string) (bool, error) {
  468. for _, extender := range sched.Algorithm.Extenders() {
  469. if !extender.IsBinder() || !extender.IsInterested(pod) {
  470. continue
  471. }
  472. return true, extender.Bind(&v1.Binding{
  473. ObjectMeta: metav1.ObjectMeta{Namespace: pod.Namespace, Name: pod.Name, UID: pod.UID},
  474. Target: v1.ObjectReference{Kind: "Node", Name: node},
  475. })
  476. }
  477. return false, nil
  478. }
  479. func (sched *Scheduler) finishBinding(assumed *v1.Pod, targetNode string, start time.Time, err error) {
  480. if finErr := sched.SchedulerCache.FinishBinding(assumed); finErr != nil {
  481. klog.Errorf("scheduler cache FinishBinding failed: %v", finErr)
  482. }
  483. if err != nil {
  484. klog.V(1).Infof("Failed to bind pod: %v/%v", assumed.Namespace, assumed.Name)
  485. if err := sched.SchedulerCache.ForgetPod(assumed); err != nil {
  486. klog.Errorf("scheduler cache ForgetPod failed: %v", err)
  487. }
  488. return
  489. }
  490. metrics.BindingLatency.Observe(metrics.SinceInSeconds(start))
  491. metrics.DeprecatedSchedulingDuration.WithLabelValues(metrics.Binding).Observe(metrics.SinceInSeconds(start))
  492. sched.Recorder.Eventf(assumed, nil, v1.EventTypeNormal, "Scheduled", "Binding", "Successfully assigned %v/%v to %v", assumed.Namespace, assumed.Name, targetNode)
  493. }
  494. // scheduleOne does the entire scheduling workflow for a single pod. It is serialized on the scheduling algorithm's host fitting.
  495. func (sched *Scheduler) scheduleOne(ctx context.Context) {
  496. fwk := sched.Framework
  497. podInfo := sched.NextPod()
  498. // pod could be nil when schedulerQueue is closed
  499. if podInfo == nil || podInfo.Pod == nil {
  500. return
  501. }
  502. pod := podInfo.Pod
  503. if sched.skipPodSchedule(pod) {
  504. return
  505. }
  506. klog.V(3).Infof("Attempting to schedule pod: %v/%v", pod.Namespace, pod.Name)
  507. // Synchronously attempt to find a fit for the pod.
  508. start := time.Now()
  509. state := framework.NewCycleState()
  510. state.SetRecordPluginMetrics(rand.Intn(100) < pluginMetricsSamplePercent)
  511. schedulingCycleCtx, cancel := context.WithCancel(ctx)
  512. defer cancel()
  513. scheduleResult, err := sched.Algorithm.Schedule(schedulingCycleCtx, state, pod)
  514. if err != nil {
  515. sched.recordSchedulingFailure(podInfo.DeepCopy(), err, v1.PodReasonUnschedulable, err.Error())
  516. // Schedule() may have failed because the pod would not fit on any host, so we try to
  517. // preempt, with the expectation that the next time the pod is tried for scheduling it
  518. // will fit due to the preemption. It is also possible that a different pod will schedule
  519. // into the resources that were preempted, but this is harmless.
  520. if fitError, ok := err.(*core.FitError); ok {
  521. if sched.DisablePreemption {
  522. klog.V(3).Infof("Pod priority feature is not enabled or preemption is disabled by scheduler configuration." +
  523. " No preemption is performed.")
  524. } else {
  525. preemptionStartTime := time.Now()
  526. sched.preempt(schedulingCycleCtx, state, fwk, pod, fitError)
  527. metrics.PreemptionAttempts.Inc()
  528. metrics.SchedulingAlgorithmPreemptionEvaluationDuration.Observe(metrics.SinceInSeconds(preemptionStartTime))
  529. metrics.DeprecatedSchedulingDuration.WithLabelValues(metrics.PreemptionEvaluation).Observe(metrics.SinceInSeconds(preemptionStartTime))
  530. }
  531. // Pod did not fit anywhere, so it is counted as a failure. If preemption
  532. // succeeds, the pod should get counted as a success the next time we try to
  533. // schedule it. (hopefully)
  534. metrics.PodScheduleFailures.Inc()
  535. } else {
  536. klog.Errorf("error selecting node for pod: %v", err)
  537. metrics.PodScheduleErrors.Inc()
  538. }
  539. return
  540. }
  541. metrics.SchedulingAlgorithmLatency.Observe(metrics.SinceInSeconds(start))
  542. // Tell the cache to assume that a pod now is running on a given node, even though it hasn't been bound yet.
  543. // This allows us to keep scheduling without waiting on binding to occur.
  544. assumedPodInfo := podInfo.DeepCopy()
  545. assumedPod := assumedPodInfo.Pod
  546. // Assume volumes first before assuming the pod.
  547. //
  548. // If all volumes are completely bound, then allBound is true and binding will be skipped.
  549. //
  550. // Otherwise, binding of volumes is started after the pod is assumed, but before pod binding.
  551. //
  552. // This function modifies 'assumedPod' if volume binding is required.
  553. allBound, err := sched.VolumeBinder.Binder.AssumePodVolumes(assumedPod, scheduleResult.SuggestedHost)
  554. if err != nil {
  555. sched.recordSchedulingFailure(assumedPodInfo, err, SchedulerError,
  556. fmt.Sprintf("AssumePodVolumes failed: %v", err))
  557. metrics.PodScheduleErrors.Inc()
  558. return
  559. }
  560. // Run "reserve" plugins.
  561. if sts := fwk.RunReservePlugins(schedulingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost); !sts.IsSuccess() {
  562. sched.recordSchedulingFailure(assumedPodInfo, sts.AsError(), SchedulerError, sts.Message())
  563. metrics.PodScheduleErrors.Inc()
  564. return
  565. }
  566. // assume modifies `assumedPod` by setting NodeName=scheduleResult.SuggestedHost
  567. err = sched.assume(assumedPod, scheduleResult.SuggestedHost)
  568. if err != nil {
  569. // This is most probably result of a BUG in retrying logic.
  570. // We report an error here so that pod scheduling can be retried.
  571. // This relies on the fact that Error will check if the pod has been bound
  572. // to a node and if so will not add it back to the unscheduled pods queue
  573. // (otherwise this would cause an infinite loop).
  574. sched.recordSchedulingFailure(assumedPodInfo, err, SchedulerError, fmt.Sprintf("AssumePod failed: %v", err))
  575. metrics.PodScheduleErrors.Inc()
  576. // trigger un-reserve plugins to clean up state associated with the reserved Pod
  577. fwk.RunUnreservePlugins(schedulingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  578. return
  579. }
  580. // bind the pod to its host asynchronously (we can do this b/c of the assumption step above).
  581. go func() {
  582. bindingCycleCtx, cancel := context.WithCancel(ctx)
  583. defer cancel()
  584. metrics.SchedulerGoroutines.WithLabelValues("binding").Inc()
  585. defer metrics.SchedulerGoroutines.WithLabelValues("binding").Dec()
  586. // Run "permit" plugins.
  587. permitStatus := fwk.RunPermitPlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  588. if !permitStatus.IsSuccess() {
  589. var reason string
  590. if permitStatus.IsUnschedulable() {
  591. metrics.PodScheduleFailures.Inc()
  592. reason = v1.PodReasonUnschedulable
  593. } else {
  594. metrics.PodScheduleErrors.Inc()
  595. reason = SchedulerError
  596. }
  597. if forgetErr := sched.Cache().ForgetPod(assumedPod); forgetErr != nil {
  598. klog.Errorf("scheduler cache ForgetPod failed: %v", forgetErr)
  599. }
  600. // trigger un-reserve plugins to clean up state associated with the reserved Pod
  601. fwk.RunUnreservePlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  602. sched.recordSchedulingFailure(assumedPodInfo, permitStatus.AsError(), reason, permitStatus.Message())
  603. return
  604. }
  605. // Bind volumes first before Pod
  606. if !allBound {
  607. err := sched.bindVolumes(assumedPod)
  608. if err != nil {
  609. sched.recordSchedulingFailure(assumedPodInfo, err, "VolumeBindingFailed", err.Error())
  610. metrics.PodScheduleErrors.Inc()
  611. // trigger un-reserve plugins to clean up state associated with the reserved Pod
  612. fwk.RunUnreservePlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  613. return
  614. }
  615. }
  616. // Run "prebind" plugins.
  617. preBindStatus := fwk.RunPreBindPlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  618. if !preBindStatus.IsSuccess() {
  619. var reason string
  620. metrics.PodScheduleErrors.Inc()
  621. reason = SchedulerError
  622. if forgetErr := sched.Cache().ForgetPod(assumedPod); forgetErr != nil {
  623. klog.Errorf("scheduler cache ForgetPod failed: %v", forgetErr)
  624. }
  625. // trigger un-reserve plugins to clean up state associated with the reserved Pod
  626. fwk.RunUnreservePlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  627. sched.recordSchedulingFailure(assumedPodInfo, preBindStatus.AsError(), reason, preBindStatus.Message())
  628. return
  629. }
  630. err := sched.bind(bindingCycleCtx, assumedPod, scheduleResult.SuggestedHost, state)
  631. metrics.E2eSchedulingLatency.Observe(metrics.SinceInSeconds(start))
  632. if err != nil {
  633. metrics.PodScheduleErrors.Inc()
  634. // trigger un-reserve plugins to clean up state associated with the reserved Pod
  635. fwk.RunUnreservePlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  636. sched.recordSchedulingFailure(assumedPodInfo, err, SchedulerError, fmt.Sprintf("Binding rejected: %v", err))
  637. } else {
  638. // Calculating nodeResourceString can be heavy. Avoid it if klog verbosity is below 2.
  639. if klog.V(2) {
  640. klog.Infof("pod %v/%v is bound successfully on node %q, %d nodes evaluated, %d nodes were found feasible.", assumedPod.Namespace, assumedPod.Name, scheduleResult.SuggestedHost, scheduleResult.EvaluatedNodes, scheduleResult.FeasibleNodes)
  641. }
  642. metrics.PodScheduleSuccesses.Inc()
  643. metrics.PodSchedulingAttempts.Observe(float64(podInfo.Attempts))
  644. metrics.PodSchedulingDuration.Observe(metrics.SinceInSeconds(podInfo.InitialAttemptTimestamp))
  645. // Run "postbind" plugins.
  646. fwk.RunPostBindPlugins(bindingCycleCtx, state, assumedPod, scheduleResult.SuggestedHost)
  647. }
  648. }()
  649. }
  650. // skipPodSchedule returns true if we could skip scheduling the pod for specified cases.
  651. func (sched *Scheduler) skipPodSchedule(pod *v1.Pod) bool {
  652. // Case 1: pod is being deleted.
  653. if pod.DeletionTimestamp != nil {
  654. sched.Recorder.Eventf(pod, nil, v1.EventTypeWarning, "FailedScheduling", "Scheduling", "skip schedule deleting pod: %v/%v", pod.Namespace, pod.Name)
  655. klog.V(3).Infof("Skip schedule deleting pod: %v/%v", pod.Namespace, pod.Name)
  656. return true
  657. }
  658. // Case 2: pod has been assumed and pod updates could be skipped.
  659. // An assumed pod can be added again to the scheduling queue if it got an update event
  660. // during its previous scheduling cycle but before getting assumed.
  661. if sched.skipPodUpdate(pod) {
  662. return true
  663. }
  664. return false
  665. }
  666. type podConditionUpdaterImpl struct {
  667. Client clientset.Interface
  668. }
  669. func (p *podConditionUpdaterImpl) update(pod *v1.Pod, condition *v1.PodCondition) error {
  670. klog.V(3).Infof("Updating pod condition for %s/%s to (%s==%s, Reason=%s)", pod.Namespace, pod.Name, condition.Type, condition.Status, condition.Reason)
  671. if podutil.UpdatePodCondition(&pod.Status, condition) {
  672. _, err := p.Client.CoreV1().Pods(pod.Namespace).UpdateStatus(context.TODO(), pod, metav1.UpdateOptions{})
  673. return err
  674. }
  675. return nil
  676. }
  677. type podPreemptorImpl struct {
  678. Client clientset.Interface
  679. }
  680. func (p *podPreemptorImpl) getUpdatedPod(pod *v1.Pod) (*v1.Pod, error) {
  681. return p.Client.CoreV1().Pods(pod.Namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  682. }
  683. func (p *podPreemptorImpl) deletePod(pod *v1.Pod) error {
  684. return p.Client.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, &metav1.DeleteOptions{})
  685. }
  686. func (p *podPreemptorImpl) setNominatedNodeName(pod *v1.Pod, nominatedNodeName string) error {
  687. podCopy := pod.DeepCopy()
  688. podCopy.Status.NominatedNodeName = nominatedNodeName
  689. _, err := p.Client.CoreV1().Pods(pod.Namespace).UpdateStatus(context.TODO(), podCopy, metav1.UpdateOptions{})
  690. return err
  691. }
  692. func (p *podPreemptorImpl) removeNominatedNodeName(pod *v1.Pod) error {
  693. if len(pod.Status.NominatedNodeName) == 0 {
  694. return nil
  695. }
  696. return p.setNominatedNodeName(pod, "")
  697. }
  698. func defaultAlgorithmSourceProviderName() *string {
  699. provider := schedulerapi.SchedulerDefaultProviderName
  700. return &provider
  701. }