blob: b4912976b69a1c3fa77d7accf0dec608ecadca6b [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 apps "k8s.io/api/apps/v1"
23 "k8s.io/api/core/v1"
24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25 "k8s.io/apimachinery/pkg/labels"
26)
27
28// StatefulSetListerExpansion allows custom methods to be added to
29// StatefulSetLister.
30type StatefulSetListerExpansion interface {
31 GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error)
32}
33
34// StatefulSetNamespaceListerExpansion allows custom methods to be added to
35// StatefulSetNamespaceLister.
36type StatefulSetNamespaceListerExpansion interface{}
37
38// GetPodStatefulSets returns a list of StatefulSets 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 StatefulSets are found.
41func (s *statefulSetLister) GetPodStatefulSets(pod *v1.Pod) ([]*apps.StatefulSet, error) {
42 var selector labels.Selector
43 var ps *apps.StatefulSet
44
45 if len(pod.Labels) == 0 {
46 return nil, fmt.Errorf("no StatefulSets found for pod %v because it has no labels", pod.Name)
47 }
48
49 list, err := s.StatefulSets(pod.Namespace).List(labels.Everything())
50 if err != nil {
51 return nil, err
52 }
53
54 var psList []*apps.StatefulSet
55 for i := range list {
56 ps = list[i]
57 if ps.Namespace != pod.Namespace {
58 continue
59 }
60 selector, err = metav1.LabelSelectorAsSelector(ps.Spec.Selector)
61 if err != nil {
62 return nil, fmt.Errorf("invalid selector: %v", err)
63 }
64
65 // If a StatefulSet with a nil or empty selector creeps in, it should match nothing, not everything.
66 if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
67 continue
68 }
69 psList = append(psList, ps)
70 }
71
72 if len(psList) == 0 {
73 return nil, fmt.Errorf("could not find StatefulSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
74 }
75
76 return psList, nil
77}