common.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 podtopologyspread
  14. import (
  15. v1 "k8s.io/api/core/v1"
  16. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  17. "k8s.io/apimachinery/pkg/labels"
  18. )
  19. type topologyPair struct {
  20. key string
  21. value string
  22. }
  23. // topologySpreadConstraint is an internal version for v1.TopologySpreadConstraint
  24. // and where the selector is parsed.
  25. type topologySpreadConstraint struct {
  26. maxSkew int32
  27. topologyKey string
  28. selector labels.Selector
  29. }
  30. // nodeLabelsMatchSpreadConstraints checks if ALL topology keys in spread constraints are present in node labels.
  31. func nodeLabelsMatchSpreadConstraints(nodeLabels map[string]string, constraints []topologySpreadConstraint) bool {
  32. for _, c := range constraints {
  33. if _, ok := nodeLabels[c.topologyKey]; !ok {
  34. return false
  35. }
  36. }
  37. return true
  38. }
  39. func filterTopologySpreadConstraints(constraints []v1.TopologySpreadConstraint, action v1.UnsatisfiableConstraintAction) ([]topologySpreadConstraint, error) {
  40. var result []topologySpreadConstraint
  41. for _, c := range constraints {
  42. if c.WhenUnsatisfiable == action {
  43. selector, err := metav1.LabelSelectorAsSelector(c.LabelSelector)
  44. if err != nil {
  45. return nil, err
  46. }
  47. result = append(result, topologySpreadConstraint{
  48. maxSkew: c.MaxSkew,
  49. topologyKey: c.TopologyKey,
  50. selector: selector,
  51. })
  52. }
  53. }
  54. return result, nil
  55. }