...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package v1alpha1
17
18 import (
19 "fmt"
20
21 "github.com/pkg/errors"
22 "k8s.io/apimachinery/pkg/runtime"
23 "k8s.io/apimachinery/pkg/util/validation/field"
24 logf "sigs.k8s.io/controller-runtime/pkg/log"
25 "sigs.k8s.io/controller-runtime/pkg/webhook"
26 "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
27 )
28
29
30 var schedulelog = logf.Log.WithName("schedule-resource")
31
32 var _ webhook.Defaulter = &Schedule{}
33
34
35 func (in *Schedule) Default() {
36 schedulelog.Info("default", "name", in.Name)
37 in.Spec.ConcurrencyPolicy.Default()
38 }
39
40 func (in *ConcurrencyPolicy) Default() {
41 if *in == "" {
42 *in = ForbidConcurrent
43 }
44 }
45
46 var _ webhook.Validator = &Schedule{}
47
48
49 func (in *Schedule) ValidateCreate() (admission.Warnings, error) {
50 schedulelog.Info("validate create", "name", in.Name)
51 return in.Validate()
52 }
53
54
55 func (in *Schedule) ValidateUpdate(old runtime.Object) (admission.Warnings, error) {
56 schedulelog.Info("validate update", "name", in.Name)
57 return in.Validate()
58 }
59
60
61 func (in *Schedule) ValidateDelete() (admission.Warnings, error) {
62 schedulelog.Info("validate delete", "name", in.Name)
63 return nil, nil
64 }
65
66
67 func (in *Schedule) Validate() ([]string, error) {
68 allErrs := in.Spec.Validate()
69 if len(allErrs) > 0 {
70 return nil, errors.New(allErrs.ToAggregate().Error())
71 }
72 return nil, nil
73 }
74
75 func (in *ScheduleSpec) Validate() field.ErrorList {
76 specField := field.NewPath("spec")
77 allErrs := field.ErrorList{}
78 allErrs = append(allErrs, in.validateSchedule(specField.Child("schedule"))...)
79 allErrs = append(allErrs, in.validateChaos(specField)...)
80 return allErrs
81 }
82
83
84 func (in *ScheduleSpec) validateSchedule(schedule *field.Path) field.ErrorList {
85 allErrs := field.ErrorList{}
86 _, err := StandardCronParser.Parse(in.Schedule)
87 if err != nil {
88 allErrs = append(allErrs, field.Invalid(schedule,
89 in.Schedule,
90 fmt.Sprintf("parse schedule field error:%s", err)))
91 }
92
93 return allErrs
94 }
95
96
97 func (in *ScheduleSpec) validateChaos(chaos *field.Path) field.ErrorList {
98 allErrs := field.ErrorList{}
99 if in.Type != ScheduleTypeWorkflow {
100 allErrs = append(allErrs, in.EmbedChaos.Validate(chaos, string(in.Type))...)
101 }
102 return allErrs
103 }
104