...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package v1alpha1
15
16 import (
17 "fmt"
18 "reflect"
19
20 "k8s.io/apimachinery/pkg/runtime"
21 "k8s.io/apimachinery/pkg/util/validation/field"
22 logf "sigs.k8s.io/controller-runtime/pkg/log"
23 "sigs.k8s.io/controller-runtime/pkg/webhook"
24 )
25
26
27 var podchaoslog = logf.Log.WithName("podchaos-resource")
28
29
30
31 var _ webhook.Defaulter = &PodChaos{}
32
33
34 func (in *PodChaos) Default() {
35 podchaoslog.Info("default", "name", in.Name)
36
37 in.Spec.Selector.DefaultNamespace(in.GetNamespace())
38 in.Spec.Default()
39 }
40
41 func (in *PodChaosSpec) Default() {
42
43 }
44
45
46
47 var _ webhook.Validator = &PodChaos{}
48
49
50 func (in *PodChaos) ValidateCreate() error {
51 podchaoslog.Info("validate create", "name", in.Name)
52 return in.Validate()
53 }
54
55
56 func (in *PodChaos) ValidateUpdate(old runtime.Object) error {
57 podchaoslog.Info("validate update", "name", in.Name)
58 if !reflect.DeepEqual(in.Spec, old.(*PodChaos).Spec) {
59 return ErrCanNotUpdateChaos
60 }
61 return in.Validate()
62 }
63
64
65 func (in *PodChaos) ValidateDelete() error {
66 podchaoslog.Info("validate delete", "name", in.Name)
67
68
69 return nil
70 }
71
72
73 func (in *PodChaos) Validate() error {
74 allErrs := in.Spec.Validate()
75
76 if len(allErrs) > 0 {
77 return fmt.Errorf(allErrs.ToAggregate().Error())
78 }
79 return nil
80 }
81
82 func (in *PodChaosSpec) Validate() field.ErrorList {
83 specField := field.NewPath("spec")
84 allErrs := in.validateContainerNames(specField.Child("containerNames"))
85 allErrs = append(allErrs, validateDuration(in, specField)...)
86
87 return allErrs
88 }
89
90
91 func (in *PodChaosSpec) validateContainerNames(containerField *field.Path) field.ErrorList {
92 allErrs := field.ErrorList{}
93 if in.Action == ContainerKillAction {
94 if len(in.ContainerSelector.ContainerNames) == 0 {
95 err := fmt.Errorf("the name of container should not be empty on %s action", in.Action)
96 allErrs = append(allErrs, field.Invalid(containerField, in.ContainerNames, err.Error()))
97 }
98 }
99 return allErrs
100 }
101