-
Notifications
You must be signed in to change notification settings - Fork 7
/
webhook.go
308 lines (262 loc) · 9.26 KB
/
webhook.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package healthcheck
import (
"fmt"
"net/http"
"github.com/flomesh-io/fsm/pkg/utils"
"k8s.io/apimachinery/pkg/util/validation/field"
gwv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
admissionregv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
flomeshadmission "github.com/flomesh-io/fsm/pkg/admission"
gwpav1alpha1 "github.com/flomesh-io/fsm/pkg/apis/policyattachment/v1alpha1"
"github.com/flomesh-io/fsm/pkg/configurator"
"github.com/flomesh-io/fsm/pkg/constants"
"github.com/flomesh-io/fsm/pkg/logger"
"github.com/flomesh-io/fsm/pkg/webhook"
)
var (
log = logger.New("webhook/healthcheck")
)
type register struct {
*webhook.RegisterConfig
}
// NewRegister creates a new HealthCheckPolicy webhook register
func NewRegister(cfg *webhook.RegisterConfig) webhook.Register {
return ®ister{
RegisterConfig: cfg,
}
}
// GetWebhooks returns the webhooks to be registered for HealthCheckPolicy
func (r *register) GetWebhooks() ([]admissionregv1.MutatingWebhook, []admissionregv1.ValidatingWebhook) {
rule := flomeshadmission.NewRule(
[]admissionregv1.OperationType{admissionregv1.Create, admissionregv1.Update},
[]string{constants.FlomeshGatewayAPIGroup},
[]string{"v1alpha1"},
[]string{"healthcheckpolicies"},
)
return []admissionregv1.MutatingWebhook{flomeshadmission.NewMutatingWebhook(
"mhealthcheckpolicy.kb.flomesh.io",
r.WebhookSvcNs,
r.WebhookSvcName,
constants.HealthCheckPolicyMutatingWebhookPath,
r.CaBundle,
nil,
nil,
admissionregv1.Ignore,
[]admissionregv1.RuleWithOperations{rule},
)}, []admissionregv1.ValidatingWebhook{flomeshadmission.NewValidatingWebhook(
"vhealthcheckpolicy.kb.flomesh.io",
r.WebhookSvcNs,
r.WebhookSvcName,
constants.HealthCheckPolicyValidatingWebhookPath,
r.CaBundle,
nil,
nil,
admissionregv1.Ignore,
[]admissionregv1.RuleWithOperations{rule},
)}
}
// GetHandlers returns the handlers to be registered for HealthCheckPolicy
func (r *register) GetHandlers() map[string]http.Handler {
return map[string]http.Handler{
constants.HealthCheckPolicyMutatingWebhookPath: webhook.DefaultingWebhookFor(newDefaulter(r.KubeClient, r.Config)),
constants.HealthCheckPolicyValidatingWebhookPath: webhook.ValidatingWebhookFor(newValidator(r.KubeClient)),
}
}
type defaulter struct {
kubeClient kubernetes.Interface
cfg configurator.Configurator
}
func newDefaulter(kubeClient kubernetes.Interface, cfg configurator.Configurator) *defaulter {
return &defaulter{
kubeClient: kubeClient,
cfg: cfg,
}
}
// RuntimeObject returns the runtime object for the webhook
func (w *defaulter) RuntimeObject() runtime.Object {
return &gwpav1alpha1.HealthCheckPolicy{}
}
// SetDefaults sets the default values for the HealthCheckPolicy
func (w *defaulter) SetDefaults(obj interface{}) {
policy, ok := obj.(*gwpav1alpha1.HealthCheckPolicy)
if !ok {
return
}
log.Debug().Msgf("Default Webhook, name=%s", policy.Name)
log.Debug().Msgf("Before setting default values, spec=%v", policy.Spec)
//targetRef := policy.Spec.TargetRef
//if (targetRef.Group == constants.KubernetesCoreGroup && targetRef.Kind == constants.KubernetesServiceKind) ||
// (targetRef.Group == constants.FlomeshAPIGroup && targetRef.Kind == constants.FlomeshAPIServiceImportKind) {
// if len(policy.Spec.Ports) > 0 {
// for i, p := range policy.Spec.Ports {
// if p.Config != nil {
// policy.Spec.Ports[i].Config = setDefaults(p.Config, policy.Spec.DefaultConfig)
// }
// }
// }
//
// if policy.Spec.DefaultConfig != nil {
// policy.Spec.DefaultConfig = setDefaultValues(policy.Spec.DefaultConfig)
// }
//}
log.Debug().Msgf("After setting default values, spec=%v", policy.Spec)
}
//func setDefaults(config *gwpav1alpha1.HealthCheckConfig, defaultConfig *gwpav1alpha1.HealthCheckConfig) *gwpav1alpha1.HealthCheckConfig {
// switch {
// case config == nil && defaultConfig == nil:
// return nil
// case config == nil && defaultConfig != nil:
// return setDefaultValues(defaultConfig.DeepCopy())
// case config != nil && defaultConfig == nil:
// return setDefaultValues(config.DeepCopy())
// case config != nil && defaultConfig != nil:
// return mergeConfig(config, defaultConfig)
// }
//
// return nil
//}
//
//func mergeConfig(config *gwpav1alpha1.HealthCheckConfig, defaultConfig *gwpav1alpha1.HealthCheckConfig) *gwpav1alpha1.HealthCheckConfig {
// cfgCopy := config.DeepCopy()
//
// if cfgCopy.Path == nil && defaultConfig.Path != nil {
// cfgCopy.Path = defaultConfig.Path
// }
//
// if len(cfgCopy.Matches) == 0 && len(defaultConfig.Matches) > 0 {
// cfgCopy.Matches = make([]gwpav1alpha1.HealthCheckMatch, 0)
// cfgCopy.Matches = append(cfgCopy.Matches, defaultConfig.Matches...)
// }
//
// if cfgCopy.FailTimeout == nil && defaultConfig.FailTimeout != nil {
// cfgCopy.FailTimeout = defaultConfig.FailTimeout
// }
//
// return cfgCopy
//}
//
//func setDefaultValues(config *gwpav1alpha1.HealthCheckConfig) *gwpav1alpha1.HealthCheckConfig {
// cfg := config.DeepCopy()
//
// if cfg.Path != nil && len(cfg.Matches) == 0 {
// cfg.Matches = []gwpav1alpha1.HealthCheckMatch{
// {
// StatusCodes: []int32{200},
// },
// }
// }
//
// return cfg
//}
type validator struct {
kubeClient kubernetes.Interface
}
// RuntimeObject returns the runtime object for the webhook
func (w *validator) RuntimeObject() runtime.Object {
return &gwpav1alpha1.HealthCheckPolicy{}
}
// ValidateCreate validates the creation of the HealthCheckPolicy
func (w *validator) ValidateCreate(obj interface{}) error {
return doValidation(obj)
}
// ValidateUpdate validates the update of the HealthCheckPolicy
func (w *validator) ValidateUpdate(_, obj interface{}) error {
return doValidation(obj)
}
// ValidateDelete validates the deletion of the HealthCheckPolicy
func (w *validator) ValidateDelete(_ interface{}) error {
return nil
}
func newValidator(kubeClient kubernetes.Interface) *validator {
return &validator{
kubeClient: kubeClient,
}
}
func doValidation(obj interface{}) error {
policy, ok := obj.(*gwpav1alpha1.HealthCheckPolicy)
if !ok {
return nil
}
errorList := validateTargetRef(policy.Spec.TargetRef)
if len(errorList) > 0 {
return utils.ErrorListToError(errorList)
}
errorList = append(errorList, validateSpec(policy)...)
if len(errorList) > 0 {
return utils.ErrorListToError(errorList)
}
return nil
}
func validateTargetRef(ref gwv1alpha2.PolicyTargetReference) field.ErrorList {
var errs field.ErrorList
if ref.Group != constants.KubernetesCoreGroup && ref.Group != constants.FlomeshAPIGroup {
path := field.NewPath("spec").Child("targetRef").Child("group")
errs = append(errs, field.Invalid(path, ref.Group, "group must be set to flomesh.io or core"))
}
if (ref.Group == constants.KubernetesCoreGroup && ref.Kind == constants.KubernetesServiceKind) ||
(ref.Group == constants.FlomeshAPIGroup && ref.Kind == constants.FlomeshAPIServiceImportKind) {
// do nothing
} else {
path := field.NewPath("spec").Child("targetRef").Child("kind")
errs = append(errs, field.Invalid(path, ref.Kind, "kind must be set to Service for group core or ServiceImport for group flomesh.io"))
}
// TODO: validate ports exist in the referenced service
//if ref.Group == constants.KubernetesCoreGroup && ref.Kind == constants.KubernetesServiceKind {
//
//}
//
//if ref.Group == constants.FlomeshAPIGroup && ref.Kind == constants.FlomeshAPIServiceImportKind {
//
//}
return errs
}
func validateSpec(policy *gwpav1alpha1.HealthCheckPolicy) field.ErrorList {
var errs field.ErrorList
if len(policy.Spec.Ports) == 0 {
path := field.NewPath("spec").Child("ports")
errs = append(errs, field.Invalid(path, policy.Spec.Ports, "cannot be empty"))
}
if len(policy.Spec.Ports) > 16 {
path := field.NewPath("spec").Child("ports")
errs = append(errs, field.Invalid(path, policy.Spec.Ports, "max port items cannot be greater than 16"))
}
if policy.Spec.DefaultConfig == nil {
path := field.NewPath("spec").Child("ports")
for i, port := range policy.Spec.Ports {
if port.Config == nil {
errs = append(errs, field.Required(path.Index(i).Child("config"), fmt.Sprintf("config must be set for port %d, as there's no default config", port.Port)))
}
}
}
if policy.Spec.DefaultConfig != nil {
errs = validateConfig(field.NewPath("spec").Child("config"), policy.Spec.DefaultConfig)
}
if len(policy.Spec.Ports) > 0 {
path := field.NewPath("spec").Child("ports")
for i, port := range policy.Spec.Ports {
if port.Config != nil {
errs = append(errs, validateConfig(path.Index(i).Child("config"), port.Config)...)
}
}
}
return errs
}
func validateConfig(path *field.Path, config *gwpav1alpha1.HealthCheckConfig) field.ErrorList {
var errs field.ErrorList
if config.Path != nil && len(config.Matches) == 0 {
errs = append(errs, field.Invalid(path.Child("matches"), config.Matches, "must be set if path is set"))
}
if len(config.Matches) != 0 && config.Path == nil {
errs = append(errs, field.Invalid(path.Child("path"), config.Path, "must be set if matches is set"))
}
if len(config.Matches) > 0 {
for i, match := range config.Matches {
if len(match.StatusCodes) == 0 && match.Body == nil && len(match.Headers) == 0 {
errs = append(errs, field.Invalid(path.Child("matches").Index(i), match, "must have at least one of statusCodes, body or headers"))
}
}
}
return errs
}