topologies.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2016 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 util
  14. import (
  15. "k8s.io/api/core/v1"
  16. "k8s.io/apimachinery/pkg/labels"
  17. "k8s.io/apimachinery/pkg/util/sets"
  18. )
  19. // GetNamespacesFromPodAffinityTerm returns a set of names
  20. // according to the namespaces indicated in podAffinityTerm.
  21. // If namespaces is empty it considers the given pod's namespace.
  22. func GetNamespacesFromPodAffinityTerm(pod *v1.Pod, podAffinityTerm *v1.PodAffinityTerm) sets.String {
  23. names := sets.String{}
  24. if len(podAffinityTerm.Namespaces) == 0 {
  25. names.Insert(pod.Namespace)
  26. } else {
  27. names.Insert(podAffinityTerm.Namespaces...)
  28. }
  29. return names
  30. }
  31. // PodMatchesTermsNamespaceAndSelector returns true if the given <pod>
  32. // matches the namespace and selector defined by <affinityPod>`s <term>.
  33. func PodMatchesTermsNamespaceAndSelector(pod *v1.Pod, namespaces sets.String, selector labels.Selector) bool {
  34. if !namespaces.Has(pod.Namespace) {
  35. return false
  36. }
  37. if !selector.Matches(labels.Set(pod.Labels)) {
  38. return false
  39. }
  40. return true
  41. }
  42. // NodesHaveSameTopologyKey checks if nodeA and nodeB have same label value with given topologyKey as label key.
  43. // Returns false if topologyKey is empty.
  44. func NodesHaveSameTopologyKey(nodeA, nodeB *v1.Node, topologyKey string) bool {
  45. if len(topologyKey) == 0 {
  46. return false
  47. }
  48. if nodeA.Labels == nil || nodeB.Labels == nil {
  49. return false
  50. }
  51. nodeALabel, okA := nodeA.Labels[topologyKey]
  52. nodeBLabel, okB := nodeB.Labels[topologyKey]
  53. // If found label in both nodes, check the label
  54. if okB && okA {
  55. return nodeALabel == nodeBLabel
  56. }
  57. return false
  58. }
  59. // Topologies contains topologies information of nodes.
  60. type Topologies struct {
  61. DefaultKeys []string
  62. }
  63. // NodesHaveSameTopologyKey checks if nodeA and nodeB have same label value with given topologyKey as label key.
  64. func (tps *Topologies) NodesHaveSameTopologyKey(nodeA, nodeB *v1.Node, topologyKey string) bool {
  65. return NodesHaveSameTopologyKey(nodeA, nodeB, topologyKey)
  66. }