factory.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. "sort"
  18. "time"
  19. v1 "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/api/errors"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/fields"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/types"
  25. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  26. "k8s.io/apimachinery/pkg/util/sets"
  27. utilfeature "k8s.io/apiserver/pkg/util/feature"
  28. "k8s.io/client-go/informers"
  29. coreinformers "k8s.io/client-go/informers/core/v1"
  30. clientset "k8s.io/client-go/kubernetes"
  31. corelisters "k8s.io/client-go/listers/core/v1"
  32. policylisters "k8s.io/client-go/listers/policy/v1beta1"
  33. "k8s.io/client-go/tools/cache"
  34. "k8s.io/klog"
  35. kubefeatures "k8s.io/kubernetes/pkg/features"
  36. "k8s.io/kubernetes/pkg/scheduler/algorithmprovider"
  37. schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/config"
  38. "k8s.io/kubernetes/pkg/scheduler/apis/config/validation"
  39. "k8s.io/kubernetes/pkg/scheduler/core"
  40. frameworkplugins "k8s.io/kubernetes/pkg/scheduler/framework/plugins"
  41. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/defaultbinder"
  42. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/interpodaffinity"
  43. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/noderesources"
  44. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/queuesort"
  45. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  46. internalcache "k8s.io/kubernetes/pkg/scheduler/internal/cache"
  47. cachedebugger "k8s.io/kubernetes/pkg/scheduler/internal/cache/debugger"
  48. internalqueue "k8s.io/kubernetes/pkg/scheduler/internal/queue"
  49. "k8s.io/kubernetes/pkg/scheduler/volumebinder"
  50. )
  51. const (
  52. initialGetBackoff = 100 * time.Millisecond
  53. maximalGetBackoff = time.Minute
  54. )
  55. // Binder knows how to write a binding.
  56. type Binder interface {
  57. Bind(binding *v1.Binding) error
  58. }
  59. // Configurator defines I/O, caching, and other functionality needed to
  60. // construct a new scheduler.
  61. type Configurator struct {
  62. client clientset.Interface
  63. informerFactory informers.SharedInformerFactory
  64. podInformer coreinformers.PodInformer
  65. // Close this to stop all reflectors
  66. StopEverything <-chan struct{}
  67. schedulerCache internalcache.Cache
  68. // RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule
  69. // corresponding to every RequiredDuringScheduling affinity rule.
  70. // HardPodAffinitySymmetricWeight represents the weight of implicit PreferredDuringScheduling affinity rule, in the range [0-100].
  71. hardPodAffinitySymmetricWeight int32
  72. // Handles volume binding decisions
  73. volumeBinder *volumebinder.VolumeBinder
  74. // Disable pod preemption or not.
  75. disablePreemption bool
  76. // Always check all predicates even if the middle of one predicate fails.
  77. alwaysCheckAllPredicates bool
  78. // percentageOfNodesToScore specifies percentage of all nodes to score in each scheduling cycle.
  79. percentageOfNodesToScore int32
  80. bindTimeoutSeconds int64
  81. podInitialBackoffSeconds int64
  82. podMaxBackoffSeconds int64
  83. enableNonPreempting bool
  84. // framework configuration arguments.
  85. registry framework.Registry
  86. plugins *schedulerapi.Plugins
  87. pluginConfig []schedulerapi.PluginConfig
  88. nodeInfoSnapshot *internalcache.Snapshot
  89. }
  90. // create a scheduler from a set of registered plugins.
  91. func (c *Configurator) create(extenders []core.SchedulerExtender) (*Scheduler, error) {
  92. framework, err := framework.NewFramework(
  93. c.registry,
  94. c.plugins,
  95. c.pluginConfig,
  96. framework.WithClientSet(c.client),
  97. framework.WithInformerFactory(c.informerFactory),
  98. framework.WithSnapshotSharedLister(c.nodeInfoSnapshot),
  99. framework.WithRunAllFilters(c.alwaysCheckAllPredicates),
  100. framework.WithVolumeBinder(c.volumeBinder),
  101. )
  102. if err != nil {
  103. return nil, fmt.Errorf("initializing the scheduling framework: %v", err)
  104. }
  105. podQueue := internalqueue.NewSchedulingQueue(
  106. framework,
  107. internalqueue.WithPodInitialBackoffDuration(time.Duration(c.podInitialBackoffSeconds)*time.Second),
  108. internalqueue.WithPodMaxBackoffDuration(time.Duration(c.podMaxBackoffSeconds)*time.Second),
  109. )
  110. // Setup cache debugger.
  111. debugger := cachedebugger.New(
  112. c.informerFactory.Core().V1().Nodes().Lister(),
  113. c.podInformer.Lister(),
  114. c.schedulerCache,
  115. podQueue,
  116. )
  117. debugger.ListenForSignal(c.StopEverything)
  118. algo := core.NewGenericScheduler(
  119. c.schedulerCache,
  120. podQueue,
  121. c.nodeInfoSnapshot,
  122. framework,
  123. extenders,
  124. c.volumeBinder,
  125. c.informerFactory.Core().V1().PersistentVolumeClaims().Lister(),
  126. GetPodDisruptionBudgetLister(c.informerFactory),
  127. c.disablePreemption,
  128. c.percentageOfNodesToScore,
  129. c.enableNonPreempting,
  130. )
  131. return &Scheduler{
  132. SchedulerCache: c.schedulerCache,
  133. Algorithm: algo,
  134. Framework: framework,
  135. NextPod: internalqueue.MakeNextPodFunc(podQueue),
  136. Error: MakeDefaultErrorFunc(c.client, podQueue, c.schedulerCache),
  137. StopEverything: c.StopEverything,
  138. VolumeBinder: c.volumeBinder,
  139. SchedulingQueue: podQueue,
  140. }, nil
  141. }
  142. // createFromProvider creates a scheduler from the name of a registered algorithm provider.
  143. func (c *Configurator) createFromProvider(providerName string) (*Scheduler, error) {
  144. klog.V(2).Infof("Creating scheduler from algorithm provider '%v'", providerName)
  145. r := algorithmprovider.NewRegistry()
  146. defaultPlugins, exist := r[providerName]
  147. if !exist {
  148. return nil, fmt.Errorf("algorithm provider %q is not registered", providerName)
  149. }
  150. // Combine the provided plugins with the ones from component config.
  151. defaultPlugins.Apply(c.plugins)
  152. c.plugins = defaultPlugins
  153. pluginConfig := []schedulerapi.PluginConfig{c.interPodAffinityPluginConfig()}
  154. pluginConfig = append(pluginConfig, c.pluginConfig...)
  155. c.pluginConfig = pluginConfig
  156. return c.create([]core.SchedulerExtender{})
  157. }
  158. // createFromConfig creates a scheduler from the configuration file
  159. func (c *Configurator) createFromConfig(policy schedulerapi.Policy) (*Scheduler, error) {
  160. lr := frameworkplugins.NewLegacyRegistry()
  161. args := &frameworkplugins.ConfigProducerArgs{}
  162. klog.V(2).Infof("Creating scheduler from configuration: %v", policy)
  163. // validate the policy configuration
  164. if err := validation.ValidatePolicy(policy); err != nil {
  165. return nil, err
  166. }
  167. predicateKeys := sets.NewString()
  168. if policy.Predicates == nil {
  169. klog.V(2).Infof("Using predicates from algorithm provider '%v'", schedulerapi.SchedulerDefaultProviderName)
  170. predicateKeys = lr.DefaultPredicates
  171. } else {
  172. for _, predicate := range policy.Predicates {
  173. klog.V(2).Infof("Registering predicate: %s", predicate.Name)
  174. predicateKeys.Insert(lr.ProcessPredicatePolicy(predicate, args))
  175. }
  176. }
  177. priorityKeys := make(map[string]int64)
  178. if policy.Priorities == nil {
  179. klog.V(2).Infof("Using default priorities")
  180. priorityKeys = lr.DefaultPriorities
  181. } else {
  182. for _, priority := range policy.Priorities {
  183. if priority.Name == frameworkplugins.EqualPriority {
  184. klog.V(2).Infof("Skip registering priority: %s", priority.Name)
  185. continue
  186. }
  187. klog.V(2).Infof("Registering priority: %s", priority.Name)
  188. priorityKeys[lr.ProcessPriorityPolicy(priority, args)] = priority.Weight
  189. }
  190. }
  191. var extenders []core.SchedulerExtender
  192. if len(policy.Extenders) != 0 {
  193. var ignorableExtenders []core.SchedulerExtender
  194. var ignoredExtendedResources []string
  195. for ii := range policy.Extenders {
  196. klog.V(2).Infof("Creating extender with config %+v", policy.Extenders[ii])
  197. extender, err := core.NewHTTPExtender(&policy.Extenders[ii])
  198. if err != nil {
  199. return nil, err
  200. }
  201. if !extender.IsIgnorable() {
  202. extenders = append(extenders, extender)
  203. } else {
  204. ignorableExtenders = append(ignorableExtenders, extender)
  205. }
  206. for _, r := range policy.Extenders[ii].ManagedResources {
  207. if r.IgnoredByScheduler {
  208. ignoredExtendedResources = append(ignoredExtendedResources, r.Name)
  209. }
  210. }
  211. }
  212. args.NodeResourcesFitArgs = &noderesources.FitArgs{
  213. IgnoredResources: ignoredExtendedResources,
  214. }
  215. // place ignorable extenders to the tail of extenders
  216. extenders = append(extenders, ignorableExtenders...)
  217. }
  218. // Providing HardPodAffinitySymmetricWeight in the policy config is the new and preferred way of providing the value.
  219. // Give it higher precedence than scheduler CLI configuration when it is provided.
  220. if policy.HardPodAffinitySymmetricWeight != 0 {
  221. c.hardPodAffinitySymmetricWeight = policy.HardPodAffinitySymmetricWeight
  222. }
  223. // When AlwaysCheckAllPredicates is set to true, scheduler checks all the configured
  224. // predicates even after one or more of them fails.
  225. if policy.AlwaysCheckAllPredicates {
  226. c.alwaysCheckAllPredicates = policy.AlwaysCheckAllPredicates
  227. }
  228. klog.V(2).Infof("Creating scheduler with fit predicates '%v' and priority functions '%v'", predicateKeys, priorityKeys)
  229. args.InterPodAffinityArgs = &interpodaffinity.Args{
  230. HardPodAffinityWeight: &c.hardPodAffinitySymmetricWeight,
  231. }
  232. pluginsForPredicates, pluginConfigForPredicates, err := getPredicateConfigs(predicateKeys, lr, args)
  233. if err != nil {
  234. return nil, err
  235. }
  236. pluginsForPriorities, pluginConfigForPriorities, err := getPriorityConfigs(priorityKeys, lr, args)
  237. if err != nil {
  238. return nil, err
  239. }
  240. // Combine all framework configurations. If this results in any duplication, framework
  241. // instantiation should fail.
  242. var defaultPlugins schedulerapi.Plugins
  243. // "PrioritySort" and "DefaultBinder" were neither predicates nor priorities
  244. // before. We add them by default.
  245. defaultPlugins.Append(&schedulerapi.Plugins{
  246. QueueSort: &schedulerapi.PluginSet{
  247. Enabled: []schedulerapi.Plugin{{Name: queuesort.Name}},
  248. },
  249. Bind: &schedulerapi.PluginSet{
  250. Enabled: []schedulerapi.Plugin{{Name: defaultbinder.Name}},
  251. },
  252. })
  253. defaultPlugins.Append(pluginsForPredicates)
  254. defaultPlugins.Append(pluginsForPriorities)
  255. defaultPlugins.Apply(c.plugins)
  256. c.plugins = &defaultPlugins
  257. var pluginConfig []schedulerapi.PluginConfig
  258. pluginConfig = append(pluginConfig, pluginConfigForPredicates...)
  259. pluginConfig = append(pluginConfig, pluginConfigForPriorities...)
  260. pluginConfig = append(pluginConfig, c.pluginConfig...)
  261. c.pluginConfig = pluginConfig
  262. return c.create(extenders)
  263. }
  264. func (c *Configurator) interPodAffinityPluginConfig() schedulerapi.PluginConfig {
  265. return schedulerapi.PluginConfig{
  266. Name: interpodaffinity.Name,
  267. Args: runtime.Unknown{
  268. Raw: []byte(fmt.Sprintf(`{"hardPodAffinityWeight":%d}`, c.hardPodAffinitySymmetricWeight)),
  269. },
  270. }
  271. }
  272. // getPriorityConfigs returns priorities configuration: ones that will run as priorities and ones that will run
  273. // as framework plugins. Specifically, a priority will run as a framework plugin if a plugin config producer was
  274. // registered for that priority.
  275. func getPriorityConfigs(keys map[string]int64, lr *frameworkplugins.LegacyRegistry, args *frameworkplugins.ConfigProducerArgs) (*schedulerapi.Plugins, []schedulerapi.PluginConfig, error) {
  276. var plugins schedulerapi.Plugins
  277. var pluginConfig []schedulerapi.PluginConfig
  278. // Sort the keys so that it is easier for unit tests to do compare.
  279. var sortedKeys []string
  280. for k := range keys {
  281. sortedKeys = append(sortedKeys, k)
  282. }
  283. sort.Strings(sortedKeys)
  284. for _, priority := range sortedKeys {
  285. weight := keys[priority]
  286. producer, exist := lr.PriorityToConfigProducer[priority]
  287. if !exist {
  288. return nil, nil, fmt.Errorf("no config producer registered for %q", priority)
  289. }
  290. a := *args
  291. a.Weight = int32(weight)
  292. pl, plc := producer(a)
  293. plugins.Append(&pl)
  294. pluginConfig = append(pluginConfig, plc...)
  295. }
  296. return &plugins, pluginConfig, nil
  297. }
  298. // getPredicateConfigs returns predicates configuration: ones that will run as fitPredicates and ones that will run
  299. // as framework plugins. Specifically, a predicate will run as a framework plugin if a plugin config producer was
  300. // registered for that predicate.
  301. // Note that the framework executes plugins according to their order in the Plugins list, and so predicates run as plugins
  302. // are added to the Plugins list according to the order specified in predicates.Ordering().
  303. func getPredicateConfigs(keys sets.String, lr *frameworkplugins.LegacyRegistry, args *frameworkplugins.ConfigProducerArgs) (*schedulerapi.Plugins, []schedulerapi.PluginConfig, error) {
  304. allPredicates := keys.Union(lr.MandatoryPredicates)
  305. // Create the framework plugin configurations, and place them in the order
  306. // that the corresponding predicates were supposed to run.
  307. var plugins schedulerapi.Plugins
  308. var pluginConfig []schedulerapi.PluginConfig
  309. for _, predicateKey := range frameworkplugins.PredicateOrdering() {
  310. if allPredicates.Has(predicateKey) {
  311. producer, exist := lr.PredicateToConfigProducer[predicateKey]
  312. if !exist {
  313. return nil, nil, fmt.Errorf("no framework config producer registered for %q", predicateKey)
  314. }
  315. pl, plc := producer(*args)
  316. plugins.Append(&pl)
  317. pluginConfig = append(pluginConfig, plc...)
  318. allPredicates.Delete(predicateKey)
  319. }
  320. }
  321. // Third, add the rest in no specific order.
  322. for predicateKey := range allPredicates {
  323. producer, exist := lr.PredicateToConfigProducer[predicateKey]
  324. if !exist {
  325. return nil, nil, fmt.Errorf("no framework config producer registered for %q", predicateKey)
  326. }
  327. pl, plc := producer(*args)
  328. plugins.Append(&pl)
  329. pluginConfig = append(pluginConfig, plc...)
  330. }
  331. return &plugins, pluginConfig, nil
  332. }
  333. type podInformer struct {
  334. informer cache.SharedIndexInformer
  335. }
  336. func (i *podInformer) Informer() cache.SharedIndexInformer {
  337. return i.informer
  338. }
  339. func (i *podInformer) Lister() corelisters.PodLister {
  340. return corelisters.NewPodLister(i.informer.GetIndexer())
  341. }
  342. // NewPodInformer creates a shared index informer that returns only non-terminal pods.
  343. func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration) coreinformers.PodInformer {
  344. selector := fields.ParseSelectorOrDie(
  345. "status.phase!=" + string(v1.PodSucceeded) +
  346. ",status.phase!=" + string(v1.PodFailed))
  347. lw := cache.NewListWatchFromClient(client.CoreV1().RESTClient(), string(v1.ResourcePods), metav1.NamespaceAll, selector)
  348. return &podInformer{
  349. informer: cache.NewSharedIndexInformer(lw, &v1.Pod{}, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}),
  350. }
  351. }
  352. // MakeDefaultErrorFunc construct a function to handle pod scheduler error
  353. func MakeDefaultErrorFunc(client clientset.Interface, podQueue internalqueue.SchedulingQueue, schedulerCache internalcache.Cache) func(*framework.PodInfo, error) {
  354. return func(podInfo *framework.PodInfo, err error) {
  355. pod := podInfo.Pod
  356. if err == core.ErrNoNodesAvailable {
  357. klog.V(2).Infof("Unable to schedule %v/%v: no nodes are registered to the cluster; waiting", pod.Namespace, pod.Name)
  358. } else {
  359. if _, ok := err.(*core.FitError); ok {
  360. klog.V(2).Infof("Unable to schedule %v/%v: no fit: %v; waiting", pod.Namespace, pod.Name, err)
  361. } else if errors.IsNotFound(err) {
  362. klog.V(2).Infof("Unable to schedule %v/%v: possibly due to node not found: %v; waiting", pod.Namespace, pod.Name, err)
  363. if errStatus, ok := err.(errors.APIStatus); ok && errStatus.Status().Details.Kind == "node" {
  364. nodeName := errStatus.Status().Details.Name
  365. // when node is not found, We do not remove the node right away. Trying again to get
  366. // the node and if the node is still not found, then remove it from the scheduler cache.
  367. _, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
  368. if err != nil && errors.IsNotFound(err) {
  369. node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName}}
  370. if err := schedulerCache.RemoveNode(&node); err != nil {
  371. klog.V(4).Infof("Node %q is not found; failed to remove it from the cache.", node.Name)
  372. }
  373. }
  374. }
  375. } else {
  376. klog.Errorf("Error scheduling %v/%v: %v; retrying", pod.Namespace, pod.Name, err)
  377. }
  378. }
  379. podSchedulingCycle := podQueue.SchedulingCycle()
  380. // Retry asynchronously.
  381. // Note that this is extremely rudimentary and we need a more real error handling path.
  382. go func() {
  383. defer utilruntime.HandleCrash()
  384. podID := types.NamespacedName{
  385. Namespace: pod.Namespace,
  386. Name: pod.Name,
  387. }
  388. // An unschedulable pod will be placed in the unschedulable queue.
  389. // This ensures that if the pod is nominated to run on a node,
  390. // scheduler takes the pod into account when running predicates for the node.
  391. // Get the pod again; it may have changed/been scheduled already.
  392. getBackoff := initialGetBackoff
  393. for {
  394. pod, err := client.CoreV1().Pods(podID.Namespace).Get(context.TODO(), podID.Name, metav1.GetOptions{})
  395. if err == nil {
  396. if len(pod.Spec.NodeName) == 0 {
  397. podInfo.Pod = pod
  398. if err := podQueue.AddUnschedulableIfNotPresent(podInfo, podSchedulingCycle); err != nil {
  399. klog.Error(err)
  400. }
  401. }
  402. break
  403. }
  404. if errors.IsNotFound(err) {
  405. klog.Warningf("A pod %v no longer exists", podID)
  406. return
  407. }
  408. klog.Errorf("Error getting pod %v for retry: %v; retrying...", podID, err)
  409. if getBackoff = getBackoff * 2; getBackoff > maximalGetBackoff {
  410. getBackoff = maximalGetBackoff
  411. }
  412. time.Sleep(getBackoff)
  413. }
  414. }()
  415. }
  416. }
  417. // GetPodDisruptionBudgetLister returns pdb lister from the given informer factory. Returns nil if PodDisruptionBudget feature is disabled.
  418. func GetPodDisruptionBudgetLister(informerFactory informers.SharedInformerFactory) policylisters.PodDisruptionBudgetLister {
  419. if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.PodDisruptionBudget) {
  420. return informerFactory.Policy().V1beta1().PodDisruptionBudgets().Lister()
  421. }
  422. return nil
  423. }