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 v1 |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | |
| 22 | "k8s.io/api/core/v1" |
| 23 | "k8s.io/apimachinery/pkg/labels" |
| 24 | ) |
| 25 | |
| 26 | // ReplicationControllerListerExpansion allows custom methods to be added to |
| 27 | // ReplicationControllerLister. |
| 28 | type ReplicationControllerListerExpansion interface { |
| 29 | GetPodControllers(pod *v1.Pod) ([]*v1.ReplicationController, error) |
| 30 | } |
| 31 | |
| 32 | // ReplicationControllerNamespaceListerExpansion allows custom methods to be added to |
| 33 | // ReplicationControllerNamespaceLister. |
| 34 | type ReplicationControllerNamespaceListerExpansion interface{} |
| 35 | |
| 36 | // GetPodControllers returns a list of ReplicationControllers that potentially match a pod. |
| 37 | // Only the one specified in the Pod's ControllerRef will actually manage it. |
| 38 | // Returns an error only if no matching ReplicationControllers are found. |
| 39 | func (s *replicationControllerLister) GetPodControllers(pod *v1.Pod) ([]*v1.ReplicationController, error) { |
| 40 | if len(pod.Labels) == 0 { |
| 41 | return nil, fmt.Errorf("no controllers found for pod %v because it has no labels", pod.Name) |
| 42 | } |
| 43 | |
| 44 | items, err := s.ReplicationControllers(pod.Namespace).List(labels.Everything()) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | |
| 49 | var controllers []*v1.ReplicationController |
| 50 | for i := range items { |
| 51 | rc := items[i] |
| 52 | selector := labels.Set(rc.Spec.Selector).AsSelectorPreValidated() |
| 53 | |
| 54 | // If an rc with a nil or empty selector creeps in, it should match nothing, not everything. |
| 55 | if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { |
| 56 | continue |
| 57 | } |
| 58 | controllers = append(controllers, rc) |
| 59 | } |
| 60 | |
| 61 | if len(controllers) == 0 { |
| 62 | return nil, fmt.Errorf("could not find controller for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) |
| 63 | } |
| 64 | |
| 65 | return controllers, nil |
| 66 | } |