blob: b031d52173a0bb2edd2cba8d089d8017aa6b9a8f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package v1
18
19import (
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.
28type ReplicationControllerListerExpansion interface {
29 GetPodControllers(pod *v1.Pod) ([]*v1.ReplicationController, error)
30}
31
32// ReplicationControllerNamespaceListerExpansion allows custom methods to be added to
33// ReplicationControllerNamespaceLister.
34type 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.
39func (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}