forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
admission.go
90 lines (74 loc) · 2.43 KB
/
admission.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package nodeenv
import (
"fmt"
"io"
"k8s.io/kubernetes/pkg/admission"
kapi "k8s.io/kubernetes/pkg/api"
apierrors "k8s.io/kubernetes/pkg/api/errors"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
oadmission "github.com/openshift/origin/pkg/cmd/server/admission"
"github.com/openshift/origin/pkg/project/cache"
"github.com/openshift/origin/pkg/util/labelselector"
)
func init() {
admission.RegisterPlugin("OriginPodNodeEnvironment", func(client clientset.Interface, config io.Reader) (admission.Interface, error) {
return NewPodNodeEnvironment(client)
})
}
// podNodeEnvironment is an implementation of admission.Interface.
type podNodeEnvironment struct {
*admission.Handler
client clientset.Interface
cache *cache.ProjectCache
}
var _ = oadmission.WantsProjectCache(&podNodeEnvironment{})
var _ = oadmission.Validator(&podNodeEnvironment{})
// Admit enforces that pod and its project node label selectors matches at least a node in the cluster.
func (p *podNodeEnvironment) Admit(a admission.Attributes) (err error) {
resource := a.GetResource()
if resource != kapi.Resource("pods") {
return nil
}
if a.GetSubresource() != "" {
// only run the checks below on pods proper and not subresources
return nil
}
obj := a.GetObject()
pod, ok := obj.(*kapi.Pod)
if !ok {
return nil
}
name := pod.Name
if !p.cache.Running() {
return err
}
namespace, err := p.cache.GetNamespace(a.GetNamespace())
if err != nil {
return apierrors.NewForbidden(resource, name, err)
}
projectNodeSelector, err := p.cache.GetNodeSelectorMap(namespace)
if err != nil {
return err
}
if labelselector.Conflicts(projectNodeSelector, pod.Spec.NodeSelector) {
return apierrors.NewForbidden(resource, name, fmt.Errorf("pod node label selector conflicts with its project node label selector"))
}
// modify pod node selector = project node selector + current pod node selector
pod.Spec.NodeSelector = labelselector.Merge(projectNodeSelector, pod.Spec.NodeSelector)
return nil
}
func (p *podNodeEnvironment) SetProjectCache(c *cache.ProjectCache) {
p.cache = c
}
func (p *podNodeEnvironment) Validate() error {
if p.cache == nil {
return fmt.Errorf("project node environment plugin needs a project cache")
}
return nil
}
func NewPodNodeEnvironment(client clientset.Interface) (admission.Interface, error) {
return &podNodeEnvironment{
Handler: admission.NewHandler(admission.Create),
client: client,
}, nil
}