blob: c0ab9d3ed4ccb1947c958ace2809069d05f37240 [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 v1beta1
18
19import (
20 "fmt"
21
22 "github.com/golang/glog"
23 "k8s.io/api/core/v1"
24 policy "k8s.io/api/policy/v1beta1"
25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26 "k8s.io/apimachinery/pkg/labels"
27)
28
29// PodDisruptionBudgetListerExpansion allows custom methods to be added to
30// PodDisruptionBudgetLister.
31type PodDisruptionBudgetListerExpansion interface {
32 GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error)
33}
34
35// PodDisruptionBudgetNamespaceListerExpansion allows custom methods to be added to
36// PodDisruptionBudgetNamespaceLister.
37type PodDisruptionBudgetNamespaceListerExpansion interface{}
38
39// GetPodPodDisruptionBudgets returns a list of PodDisruptionBudgets matching a pod. Returns an error only if no matching PodDisruptionBudgets are found.
40func (s *podDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *v1.Pod) ([]*policy.PodDisruptionBudget, error) {
41 var selector labels.Selector
42
43 if len(pod.Labels) == 0 {
44 return nil, fmt.Errorf("no PodDisruptionBudgets found for pod %v because it has no labels", pod.Name)
45 }
46
47 list, err := s.PodDisruptionBudgets(pod.Namespace).List(labels.Everything())
48 if err != nil {
49 return nil, err
50 }
51
52 var pdbList []*policy.PodDisruptionBudget
53 for i := range list {
54 pdb := list[i]
55 selector, err = metav1.LabelSelectorAsSelector(pdb.Spec.Selector)
56 if err != nil {
57 glog.Warningf("invalid selector: %v", err)
58 // TODO(mml): add an event to the PDB
59 continue
60 }
61
62 // If a PDB with a nil or empty selector creeps in, it should match nothing, not everything.
63 if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
64 continue
65 }
66 pdbList = append(pdbList, pdb)
67 }
68
69 if len(pdbList) == 0 {
70 return nil, fmt.Errorf("could not find PodDisruptionBudget for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
71 }
72
73 return pdbList, nil
74}