-
Notifications
You must be signed in to change notification settings - Fork 827
/
mutating.go
68 lines (55 loc) · 2.4 KB
/
mutating.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
package propagationpolicy
import (
"context"
"encoding/json"
"fmt"
"net/http"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
policyv1alpha1 "github.com/karmada-io/karmada/pkg/apis/policy/v1alpha1"
"github.com/karmada-io/karmada/pkg/util/helper"
"github.com/karmada-io/karmada/pkg/util/validation"
)
// MutatingAdmission mutates API request if necessary.
type MutatingAdmission struct {
decoder *admission.Decoder
}
// Check if our MutatingAdmission implements necessary interface
var _ admission.Handler = &MutatingAdmission{}
var _ admission.DecoderInjector = &MutatingAdmission{}
// Handle yields a response to an AdmissionRequest.
func (a *MutatingAdmission) Handle(ctx context.Context, req admission.Request) admission.Response {
policy := &policyv1alpha1.PropagationPolicy{}
err := a.decoder.Decode(req, policy)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
klog.V(2).Infof("Mutating PropagationPolicy(%s/%s) for request: %s", policy.Namespace, policy.Name, req.Operation)
// Set default namespace for all resource selector if not set.
for i := range policy.Spec.ResourceSelectors {
if len(policy.Spec.ResourceSelectors[i].Namespace) == 0 {
klog.Infof("Setting resource selector default namespace for policy: %s/%s", policy.Namespace, policy.Name)
policy.Spec.ResourceSelectors[i].Namespace = policy.Namespace
}
}
if len(policy.Name) > validation.LabelValueMaxLength {
return admission.Errored(http.StatusBadRequest, fmt.Errorf("PropagationPolicy's name should be no more than %d characters", validation.LabelValueMaxLength))
}
// Set default spread constraints if both 'SpreadByField' and 'SpreadByLabel' not set.
helper.SetDefaultSpreadConstraints(policy.Spec.Placement.SpreadConstraints)
addedResourceSelectors := helper.GetFollowedResourceSelectorsWhenMatchServiceImport(policy.Spec.ResourceSelectors)
if addedResourceSelectors != nil {
policy.Spec.ResourceSelectors = append(policy.Spec.ResourceSelectors, addedResourceSelectors...)
}
marshaledBytes, err := json.Marshal(policy)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledBytes)
}
// InjectDecoder implements admission.DecoderInjector interface.
// A decoder will be automatically injected.
func (a *MutatingAdmission) InjectDecoder(d *admission.Decoder) error {
a.decoder = d
return nil
}