image_locality.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 imagelocality
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. v1 "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  21. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  22. "k8s.io/kubernetes/pkg/util/parsers"
  23. )
  24. // The two thresholds are used as bounds for the image score range. They correspond to a reasonable size range for
  25. // container images compressed and stored in registries; 90%ile of images on dockerhub drops into this range.
  26. const (
  27. mb int64 = 1024 * 1024
  28. minThreshold int64 = 23 * mb
  29. maxThreshold int64 = 1000 * mb
  30. )
  31. // ImageLocality is a score plugin that favors nodes that already have requested pod container's images.
  32. type ImageLocality struct {
  33. handle framework.FrameworkHandle
  34. }
  35. var _ framework.ScorePlugin = &ImageLocality{}
  36. // Name is the name of the plugin used in the plugin registry and configurations.
  37. const Name = "ImageLocality"
  38. // Name returns name of the plugin. It is used in logs, etc.
  39. func (pl *ImageLocality) Name() string {
  40. return Name
  41. }
  42. // Score invoked at the score extension point.
  43. func (pl *ImageLocality) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {
  44. nodeInfo, err := pl.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)
  45. if err != nil {
  46. return 0, framework.NewStatus(framework.Error, fmt.Sprintf("getting node %q from Snapshot: %v", nodeName, err))
  47. }
  48. nodeInfos, err := pl.handle.SnapshotSharedLister().NodeInfos().List()
  49. if err != nil {
  50. return 0, framework.NewStatus(framework.Error, err.Error())
  51. }
  52. totalNumNodes := len(nodeInfos)
  53. score := calculatePriority(sumImageScores(nodeInfo, pod.Spec.Containers, totalNumNodes))
  54. return score, nil
  55. }
  56. // ScoreExtensions of the Score plugin.
  57. func (pl *ImageLocality) ScoreExtensions() framework.ScoreExtensions {
  58. return nil
  59. }
  60. // New initializes a new plugin and returns it.
  61. func New(_ *runtime.Unknown, h framework.FrameworkHandle) (framework.Plugin, error) {
  62. return &ImageLocality{handle: h}, nil
  63. }
  64. // calculatePriority returns the priority of a node. Given the sumScores of requested images on the node, the node's
  65. // priority is obtained by scaling the maximum priority value with a ratio proportional to the sumScores.
  66. func calculatePriority(sumScores int64) int64 {
  67. if sumScores < minThreshold {
  68. sumScores = minThreshold
  69. } else if sumScores > maxThreshold {
  70. sumScores = maxThreshold
  71. }
  72. return int64(framework.MaxNodeScore) * (sumScores - minThreshold) / (maxThreshold - minThreshold)
  73. }
  74. // sumImageScores returns the sum of image scores of all the containers that are already on the node.
  75. // Each image receives a raw score of its size, scaled by scaledImageScore. The raw scores are later used to calculate
  76. // the final score. Note that the init containers are not considered for it's rare for users to deploy huge init containers.
  77. func sumImageScores(nodeInfo *schedulernodeinfo.NodeInfo, containers []v1.Container, totalNumNodes int) int64 {
  78. var sum int64
  79. imageStates := nodeInfo.ImageStates()
  80. for _, container := range containers {
  81. if state, ok := imageStates[normalizedImageName(container.Image)]; ok {
  82. sum += scaledImageScore(state, totalNumNodes)
  83. }
  84. }
  85. return sum
  86. }
  87. // scaledImageScore returns an adaptively scaled score for the given state of an image.
  88. // The size of the image is used as the base score, scaled by a factor which considers how much nodes the image has "spread" to.
  89. // This heuristic aims to mitigate the undesirable "node heating problem", i.e., pods get assigned to the same or
  90. // a few nodes due to image locality.
  91. func scaledImageScore(imageState *schedulernodeinfo.ImageStateSummary, totalNumNodes int) int64 {
  92. spread := float64(imageState.NumNodes) / float64(totalNumNodes)
  93. return int64(float64(imageState.Size) * spread)
  94. }
  95. // normalizedImageName returns the CRI compliant name for a given image.
  96. // TODO: cover the corner cases of missed matches, e.g,
  97. // 1. Using Docker as runtime and docker.io/library/test:tag in pod spec, but only test:tag will present in node status
  98. // 2. Using the implicit registry, i.e., test:tag or library/test:tag in pod spec but only docker.io/library/test:tag
  99. // in node status; note that if users consistently use one registry format, this should not happen.
  100. func normalizedImageName(name string) string {
  101. if strings.LastIndex(name, ":") <= strings.LastIndex(name, "/") {
  102. name = name + ":" + parsers.DefaultImageTag
  103. }
  104. return name
  105. }