Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame] | 1 | /* |
| 2 | Copyright 2017 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package v1beta1 |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | |
| 22 | "k8s.io/api/core/v1" |
| 23 | extensions "k8s.io/api/extensions/v1beta1" |
| 24 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 25 | "k8s.io/apimachinery/pkg/labels" |
| 26 | ) |
| 27 | |
| 28 | // ReplicaSetListerExpansion allows custom methods to be added to |
| 29 | // ReplicaSetLister. |
| 30 | type ReplicaSetListerExpansion interface { |
| 31 | GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error) |
| 32 | } |
| 33 | |
| 34 | // ReplicaSetNamespaceListerExpansion allows custom methods to be added to |
| 35 | // ReplicaSetNamespaceLister. |
| 36 | type ReplicaSetNamespaceListerExpansion interface{} |
| 37 | |
| 38 | // GetPodReplicaSets returns a list of ReplicaSets that potentially match a pod. |
| 39 | // Only the one specified in the Pod's ControllerRef will actually manage it. |
| 40 | // Returns an error only if no matching ReplicaSets are found. |
| 41 | func (s *replicaSetLister) GetPodReplicaSets(pod *v1.Pod) ([]*extensions.ReplicaSet, error) { |
| 42 | if len(pod.Labels) == 0 { |
| 43 | return nil, fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name) |
| 44 | } |
| 45 | |
| 46 | list, err := s.ReplicaSets(pod.Namespace).List(labels.Everything()) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | |
| 51 | var rss []*extensions.ReplicaSet |
| 52 | for _, rs := range list { |
| 53 | if rs.Namespace != pod.Namespace { |
| 54 | continue |
| 55 | } |
| 56 | selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector) |
| 57 | if err != nil { |
| 58 | return nil, fmt.Errorf("invalid selector: %v", err) |
| 59 | } |
| 60 | |
| 61 | // If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything. |
| 62 | if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { |
| 63 | continue |
| 64 | } |
| 65 | rss = append(rss, rs) |
| 66 | } |
| 67 | |
| 68 | if len(rss) == 0 { |
| 69 | return nil, fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) |
| 70 | } |
| 71 | |
| 72 | return rss, nil |
| 73 | } |