...
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 gcpchaoslog = logf.Log.WithName("gcpchaos-resource")
28
29
30
31 var _ webhook.Defaulter = &GCPChaos{}
32
33
34 func (in *GCPChaos) Default() {
35 gcpchaoslog.Info("default", "name", in.Name)
36 in.Spec.Default()
37 }
38
39 func (in *GCPChaosSpec) Default() {
40 }
41
42
43
44 var _ webhook.Validator = &GCPChaos{}
45
46
47 func (in *GCPChaos) ValidateCreate() error {
48 gcpchaoslog.Info("validate create", "name", in.Name)
49 return in.Validate()
50 }
51
52
53 func (in *GCPChaos) ValidateUpdate(old runtime.Object) error {
54 gcpchaoslog.Info("validate update", "name", in.Name)
55 if !reflect.DeepEqual(in.Spec, old.(*GCPChaos).Spec) {
56 return ErrCanNotUpdateChaos
57 }
58 return in.Validate()
59 }
60
61
62 func (in *GCPChaos) ValidateDelete() error {
63 gcpchaoslog.Info("validate delete", "name", in.Name)
64
65
66 return nil
67 }
68
69
70 func (in *GCPChaos) Validate() error {
71 allErrs := in.Spec.Validate()
72
73 if len(allErrs) > 0 {
74 return fmt.Errorf(allErrs.ToAggregate().Error())
75 }
76 return nil
77 }
78
79 func (in *GCPChaosSpec) Validate() field.ErrorList {
80 specField := field.NewPath("spec")
81 allErrs := in.validateDeviceName(specField.Child("deviceName"))
82 allErrs = append(allErrs, validateDuration(in, specField)...)
83 allErrs = append(allErrs, in.validateAction(specField)...)
84 return allErrs
85 }
86
87
88 func (in *GCPChaosSpec) validateAction(spec *field.Path) field.ErrorList {
89 allErrs := field.ErrorList{}
90
91 switch in.Action {
92 case NodeStop, DiskLoss:
93 case NodeReset:
94 default:
95 err := fmt.Errorf("gcpchaos have unknown action type")
96 log.Error(err, "Wrong GCPChaos Action type")
97
98 actionField := spec.Child("action")
99 allErrs = append(allErrs, field.Invalid(actionField, in.Action, err.Error()))
100 }
101 return allErrs
102 }
103
104
105 func (in *GCPChaosSpec) validateDeviceName(containerField *field.Path) field.ErrorList {
106 allErrs := field.ErrorList{}
107 if in.Action == DiskLoss {
108 if in.DeviceNames == nil {
109 err := fmt.Errorf("at least one device name is required on %s action", in.Action)
110 allErrs = append(allErrs, field.Invalid(containerField, in.DeviceNames, err.Error()))
111 }
112 }
113 return allErrs
114 }
115