forked from stackrox/kube-linter
/
template.go
63 lines (59 loc) · 2.18 KB
/
template.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
package mismatchingselector
import (
"fmt"
"github.com/slysunkin/kube-linter/lib/check"
"github.com/slysunkin/kube-linter/lib/diagnostic"
"github.com/slysunkin/kube-linter/lib/extract"
"github.com/slysunkin/kube-linter/lib/lintcontext"
"github.com/slysunkin/kube-linter/lib/objectkinds"
"github.com/slysunkin/kube-linter/lib/templates"
"github.com/slysunkin/kube-linter/lib/templates/mismatchingselector/params"
v1 "k8s.io/api/batch/v1"
"k8s.io/api/batch/v1beta1"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
)
func init() {
templates.Register(check.Template{
HumanName: "Mismatching Selector",
Key: "mismatching-selector",
Description: "Flag deployments where the selector doesn't match the labels in the pod template spec",
SupportedObjectKinds: check.ObjectKindsDesc{
ObjectKinds: []string{objectkinds.DeploymentLike},
},
Parameters: params.ParamDescs,
ParseAndValidateParams: params.ParseAndValidate,
Instantiate: params.WrapInstantiateFunc(func(_ params.Params) (check.Func, error) {
return func(_ *lintcontext.LintContext, object lintcontext.Object) []diagnostic.Diagnostic {
selector, found := extract.Selector(object.K8sObject)
if !found {
return nil
}
if selector == nil || (len(selector.MatchLabels) == 0 && len(selector.MatchExpressions) == 0) {
switch object.K8sObject.(type) {
// It's okay for CronJobs and Jobs not to have selectors.
case *v1beta1.CronJob, *v1.Job:
return nil
}
return []diagnostic.Diagnostic{{
Message: "object has no selector specified",
}}
}
podTemplateSpec, hasPods := extract.PodTemplateSpec(object.K8sObject)
if !hasPods {
return nil
}
labelSelector, err := metaV1.LabelSelectorAsSelector(selector)
if err != nil {
return []diagnostic.Diagnostic{{
Message: fmt.Sprintf("object has invalid label selector: %v", err),
}}
}
if labelSelector.Matches(labels.Set(podTemplateSpec.Labels)) {
return nil
}
return []diagnostic.Diagnostic{{Message: fmt.Sprintf("labels in pod spec (%v) do not match labels in selector (%v)", podTemplateSpec.Labels, selector)}}
}, nil
}),
})
}