fit.go 8.8 KB

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