fit.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. Copyright 2019 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 noderesources
  14. import (
  15. "context"
  16. "fmt"
  17. "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/runtime"
  19. "k8s.io/apimachinery/pkg/util/sets"
  20. utilfeature "k8s.io/apiserver/pkg/util/feature"
  21. v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
  22. "k8s.io/kubernetes/pkg/features"
  23. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  24. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  25. )
  26. var _ framework.PreFilterPlugin = &Fit{}
  27. var _ framework.FilterPlugin = &Fit{}
  28. const (
  29. // FitName is the name of the plugin used in the plugin registry and configurations.
  30. FitName = "NodeResourcesFit"
  31. // preFilterStateKey is the key in CycleState to NodeResourcesFit pre-computed data.
  32. // Using the name of the plugin will likely help us avoid collisions with other plugins.
  33. preFilterStateKey = "PreFilter" + FitName
  34. )
  35. // Fit is a plugin that checks if a node has sufficient resources.
  36. type Fit struct {
  37. ignoredResources sets.String
  38. }
  39. // FitArgs holds the args that are used to configure the plugin.
  40. type FitArgs struct {
  41. // IgnoredResources is the list of resources that NodeResources fit filter
  42. // should ignore.
  43. IgnoredResources []string `json:"ignoredResources,omitempty"`
  44. }
  45. // preFilterState computed at PreFilter and used at Filter.
  46. type preFilterState struct {
  47. schedulernodeinfo.Resource
  48. }
  49. // Clone the prefilter state.
  50. func (s *preFilterState) Clone() framework.StateData {
  51. return s
  52. }
  53. // Name returns name of the plugin. It is used in logs, etc.
  54. func (f *Fit) Name() string {
  55. return FitName
  56. }
  57. // computePodResourceRequest returns a schedulernodeinfo.Resource that covers the largest
  58. // width in each resource dimension. Because init-containers run sequentially, we collect
  59. // the max in each dimension iteratively. In contrast, we sum the resource vectors for
  60. // regular containers since they run simultaneously.
  61. //
  62. // If Pod Overhead is specified and the feature gate is set, the resources defined for Overhead
  63. // are added to the calculated Resource request sum
  64. //
  65. // Example:
  66. //
  67. // Pod:
  68. // InitContainers
  69. // IC1:
  70. // CPU: 2
  71. // Memory: 1G
  72. // IC2:
  73. // CPU: 2
  74. // Memory: 3G
  75. // Containers
  76. // C1:
  77. // CPU: 2
  78. // Memory: 1G
  79. // C2:
  80. // CPU: 1
  81. // Memory: 1G
  82. //
  83. // Result: CPU: 3, Memory: 3G
  84. func computePodResourceRequest(pod *v1.Pod) *preFilterState {
  85. result := &preFilterState{}
  86. for _, container := range pod.Spec.Containers {
  87. result.Add(container.Resources.Requests)
  88. }
  89. // take max_resource(sum_pod, any_init_container)
  90. for _, container := range pod.Spec.InitContainers {
  91. result.SetMaxResource(container.Resources.Requests)
  92. }
  93. // If Overhead is being utilized, add to the total requests for the pod
  94. if pod.Spec.Overhead != nil && utilfeature.DefaultFeatureGate.Enabled(features.PodOverhead) {
  95. result.Add(pod.Spec.Overhead)
  96. }
  97. return result
  98. }
  99. // PreFilter invoked at the prefilter extension point.
  100. func (f *Fit) PreFilter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod) *framework.Status {
  101. cycleState.Write(preFilterStateKey, computePodResourceRequest(pod))
  102. return nil
  103. }
  104. // PreFilterExtensions returns prefilter extensions, pod add and remove.
  105. func (f *Fit) PreFilterExtensions() framework.PreFilterExtensions {
  106. return nil
  107. }
  108. func getPreFilterState(cycleState *framework.CycleState) (*preFilterState, error) {
  109. c, err := cycleState.Read(preFilterStateKey)
  110. if err != nil {
  111. // preFilterState doesn't exist, likely PreFilter wasn't invoked.
  112. return nil, fmt.Errorf("error reading %q from cycleState: %v", preFilterStateKey, err)
  113. }
  114. s, ok := c.(*preFilterState)
  115. if !ok {
  116. return nil, fmt.Errorf("%+v convert to NodeResourcesFit.preFilterState error", c)
  117. }
  118. return s, nil
  119. }
  120. // Filter invoked at the filter extension point.
  121. // Checks if a node has sufficient resources, such as cpu, memory, gpu, opaque int resources etc to run a pod.
  122. // It returns a list of insufficient resources, if empty, then the node has all the resources requested by the pod.
  123. func (f *Fit) Filter(ctx context.Context, cycleState *framework.CycleState, pod *v1.Pod, nodeInfo *schedulernodeinfo.NodeInfo) *framework.Status {
  124. s, err := getPreFilterState(cycleState)
  125. if err != nil {
  126. return framework.NewStatus(framework.Error, err.Error())
  127. }
  128. insufficientResources := fitsRequest(s, nodeInfo, f.ignoredResources)
  129. if len(insufficientResources) != 0 {
  130. // We will keep all failure reasons.
  131. failureReasons := make([]string, 0, len(insufficientResources))
  132. for _, r := range insufficientResources {
  133. failureReasons = append(failureReasons, r.Reason)
  134. }
  135. return framework.NewStatus(framework.Unschedulable, failureReasons...)
  136. }
  137. return nil
  138. }
  139. // InsufficientResource describes what kind of resource limit is hit and caused the pod to not fit the node.
  140. type InsufficientResource struct {
  141. ResourceName v1.ResourceName
  142. // We explicitly have a parameter for reason to avoid formatting a message on the fly
  143. // for common resources, which is expensive for cluster autoscaler simulations.
  144. Reason string
  145. Requested int64
  146. Used int64
  147. Capacity int64
  148. }
  149. // Fits checks if node have enough resources to host the pod.
  150. func Fits(pod *v1.Pod, nodeInfo *schedulernodeinfo.NodeInfo, ignoredExtendedResources sets.String) []InsufficientResource {
  151. return fitsRequest(computePodResourceRequest(pod), nodeInfo, ignoredExtendedResources)
  152. }
  153. func fitsRequest(podRequest *preFilterState, nodeInfo *schedulernodeinfo.NodeInfo, ignoredExtendedResources sets.String) []InsufficientResource {
  154. insufficientResources := make([]InsufficientResource, 0, 4)
  155. allowedPodNumber := nodeInfo.AllowedPodNumber()
  156. if len(nodeInfo.Pods())+1 > allowedPodNumber {
  157. insufficientResources = append(insufficientResources, InsufficientResource{
  158. v1.ResourcePods,
  159. "Too many pods",
  160. 1,
  161. int64(len(nodeInfo.Pods())),
  162. int64(allowedPodNumber),
  163. })
  164. }
  165. if ignoredExtendedResources == nil {
  166. ignoredExtendedResources = sets.NewString()
  167. }
  168. if podRequest.MilliCPU == 0 &&
  169. podRequest.Memory == 0 &&
  170. podRequest.EphemeralStorage == 0 &&
  171. len(podRequest.ScalarResources) == 0 {
  172. return insufficientResources
  173. }
  174. allocatable := nodeInfo.AllocatableResource()
  175. if allocatable.MilliCPU < podRequest.MilliCPU+nodeInfo.RequestedResource().MilliCPU {
  176. insufficientResources = append(insufficientResources, InsufficientResource{
  177. v1.ResourceCPU,
  178. "Insufficient cpu",
  179. podRequest.MilliCPU,
  180. nodeInfo.RequestedResource().MilliCPU,
  181. allocatable.MilliCPU,
  182. })
  183. }
  184. if allocatable.Memory < podRequest.Memory+nodeInfo.RequestedResource().Memory {
  185. insufficientResources = append(insufficientResources, InsufficientResource{
  186. v1.ResourceMemory,
  187. "Insufficient memory",
  188. podRequest.Memory,
  189. nodeInfo.RequestedResource().Memory,
  190. allocatable.Memory,
  191. })
  192. }
  193. if allocatable.EphemeralStorage < podRequest.EphemeralStorage+nodeInfo.RequestedResource().EphemeralStorage {
  194. insufficientResources = append(insufficientResources, InsufficientResource{
  195. v1.ResourceEphemeralStorage,
  196. "Insufficient ephemeral-storage",
  197. podRequest.EphemeralStorage,
  198. nodeInfo.RequestedResource().EphemeralStorage,
  199. allocatable.EphemeralStorage,
  200. })
  201. }
  202. for rName, rQuant := range podRequest.ScalarResources {
  203. if v1helper.IsExtendedResourceName(rName) {
  204. // If this resource is one of the extended resources that should be
  205. // ignored, we will skip checking it.
  206. if ignoredExtendedResources.Has(string(rName)) {
  207. continue
  208. }
  209. }
  210. if allocatable.ScalarResources[rName] < rQuant+nodeInfo.RequestedResource().ScalarResources[rName] {
  211. insufficientResources = append(insufficientResources, InsufficientResource{
  212. rName,
  213. fmt.Sprintf("Insufficient %v", rName),
  214. podRequest.ScalarResources[rName],
  215. nodeInfo.RequestedResource().ScalarResources[rName],
  216. allocatable.ScalarResources[rName],
  217. })
  218. }
  219. }
  220. return insufficientResources
  221. }
  222. // NewFit initializes a new plugin and returns it.
  223. func NewFit(plArgs *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  224. args := &FitArgs{}
  225. if err := framework.DecodeInto(plArgs, args); err != nil {
  226. return nil, err
  227. }
  228. fit := &Fit{}
  229. fit.ignoredResources = sets.NewString(args.IgnoredResources...)
  230. return fit, nil
  231. }