node_label.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 nodelabel
  14. import (
  15. "context"
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/labels"
  19. "k8s.io/apimachinery/pkg/runtime"
  20. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  21. "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  22. )
  23. // Name of this plugin.
  24. const Name = "NodeLabel"
  25. const (
  26. // ErrReasonPresenceViolated is used for CheckNodeLabelPresence predicate error.
  27. ErrReasonPresenceViolated = "node(s) didn't have the requested labels"
  28. )
  29. // Args holds the args that are used to configure the plugin.
  30. type Args struct {
  31. // PresentLabels should be present for the node to be considered a fit for hosting the pod
  32. PresentLabels []string `json:"presentLabels,omitempty"`
  33. // AbsentLabels should be absent for the node to be considered a fit for hosting the pod
  34. AbsentLabels []string `json:"absentLabels,omitempty"`
  35. // Nodes that have labels in the list will get a higher score.
  36. PresentLabelsPreference []string `json:"presentLabelsPreference,omitempty"`
  37. // Nodes that don't have labels in the list will get a higher score.
  38. AbsentLabelsPreference []string `json:"absentLabelsPreference,omitempty"`
  39. }
  40. // validateArgs validates that presentLabels and absentLabels do not conflict.
  41. func validateNoConflict(presentLabels []string, absentLabels []string) error {
  42. m := make(map[string]struct{}, len(presentLabels))
  43. for _, l := range presentLabels {
  44. m[l] = struct{}{}
  45. }
  46. for _, l := range absentLabels {
  47. if _, ok := m[l]; ok {
  48. return fmt.Errorf("detecting at least one label (e.g., %q) that exist in both the present(%+v) and absent(%+v) label list", l, presentLabels, absentLabels)
  49. }
  50. }
  51. return nil
  52. }
  53. // New initializes a new plugin and returns it.
  54. func New(plArgs *runtime.Unknown, handle framework.FrameworkHandle) (framework.Plugin, error) {
  55. args := Args{}
  56. if err := framework.DecodeInto(plArgs, &args); err != nil {
  57. return nil, err
  58. }
  59. if err := validateNoConflict(args.PresentLabels, args.AbsentLabels); err != nil {
  60. return nil, err
  61. }
  62. if err := validateNoConflict(args.PresentLabelsPreference, args.AbsentLabelsPreference); err != nil {
  63. return nil, err
  64. }
  65. return &NodeLabel{
  66. handle: handle,
  67. Args: args,
  68. }, nil
  69. }
  70. // NodeLabel checks whether a pod can fit based on the node labels which match a filter that it requests.
  71. type NodeLabel struct {
  72. handle framework.FrameworkHandle
  73. Args
  74. }
  75. var _ framework.FilterPlugin = &NodeLabel{}
  76. var _ framework.ScorePlugin = &NodeLabel{}
  77. // Name returns name of the plugin. It is used in logs, etc.
  78. func (pl *NodeLabel) Name() string {
  79. return Name
  80. }
  81. // Filter invoked at the filter extension point.
  82. // It checks whether all of the specified labels exists on a node or not, regardless of their value
  83. //
  84. // Consider the cases where the nodes are placed in regions/zones/racks and these are identified by labels
  85. // In some cases, it is required that only nodes that are part of ANY of the defined regions/zones/racks be selected
  86. //
  87. // Alternately, eliminating nodes that have a certain label, regardless of value, is also useful
  88. // A node may have a label with "retiring" as key and the date as the value
  89. // and it may be desirable to avoid scheduling new pods on this node.
  90. func (pl *NodeLabel) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  91. node := nodeInfo.Node()
  92. if node == nil {
  93. return framework.NewStatus(framework.Error, "node not found")
  94. }
  95. nodeLabels := labels.Set(node.Labels)
  96. check := func(labels []string, presence bool) bool {
  97. for _, label := range labels {
  98. exists := nodeLabels.Has(label)
  99. if (exists && !presence) || (!exists && presence) {
  100. return false
  101. }
  102. }
  103. return true
  104. }
  105. if check(pl.PresentLabels, true) && check(pl.AbsentLabels, false) {
  106. return nil
  107. }
  108. return framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonPresenceViolated)
  109. }
  110. // Score invoked at the score extension point.
  111. func (pl *NodeLabel) Score(ctx context.Context, state *framework.CycleState, pod *v1.Pod, nodeName string) (int64, *framework.Status) {
  112. nodeInfo, err := pl.handle.SnapshotSharedLister().NodeInfos().Get(nodeName)
  113. if err != nil || nodeInfo.Node() == nil {
  114. return 0, framework.NewStatus(framework.Error, fmt.Sprintf("getting node %q from Snapshot: %v, node is nil: %v", nodeName, err, nodeInfo.Node() == nil))
  115. }
  116. node := nodeInfo.Node()
  117. score := int64(0)
  118. for _, label := range pl.PresentLabelsPreference {
  119. if labels.Set(node.Labels).Has(label) {
  120. score += framework.MaxNodeScore
  121. }
  122. }
  123. for _, label := range pl.AbsentLabelsPreference {
  124. if !labels.Set(node.Labels).Has(label) {
  125. score += framework.MaxNodeScore
  126. }
  127. }
  128. // Take average score for each label to ensure the score doesn't exceed MaxNodeScore.
  129. score /= int64(len(pl.PresentLabelsPreference) + len(pl.AbsentLabelsPreference))
  130. return score, nil
  131. }
  132. // ScoreExtensions of the Score plugin.
  133. func (pl *NodeLabel) ScoreExtensions() framework.ScoreExtensions {
  134. return nil
  135. }