factory.go 17 KB

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