@@ -20,6 +20,7 @@ import (
2020 "context"
2121 "encoding/json"
2222 "fmt"
23+ "math/rand"
2324
2425 admissionv1 "k8s.io/api/admission/v1"
2526 corev1 "k8s.io/api/core/v1"
@@ -28,6 +29,7 @@ import (
2829 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2930 "k8s.io/apimachinery/pkg/labels"
3031 "k8s.io/apimachinery/pkg/types"
32+ "k8s.io/apimachinery/pkg/util/intstr"
3133 "k8s.io/apimachinery/pkg/util/strategicpatch"
3234 "k8s.io/klog/v2"
3335 "k8s.io/utils/pointer"
@@ -39,6 +41,10 @@ import (
3941 utilclient "github.com/koordinator-sh/koordinator/pkg/util/client"
4042)
4143
44+ var (
45+ randIntnFn = rand .Intn
46+ )
47+
4248// +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch
4349// +kubebuilder:rbac:groups=config.koordinator.sh,resources=clustercolocationprofiles,verbs=get;list;watch
4450
@@ -79,7 +85,15 @@ func (h *PodMutatingHandler) clusterColocationProfileMutatingPod(ctx context.Con
7985 }
8086
8187 for _ , profile := range matchedProfiles {
82- err := h .doMutateByColocationProfile (ctx , pod , profile )
88+ skip , err := shouldSkipProfile (profile )
89+ if err != nil {
90+ return err
91+ }
92+ if skip {
93+ klog .V (4 ).Infof ("skip mutate Pod %s/%s by clusterColocationProfile %s" , pod .Namespace , pod .Name , profile .Name )
94+ continue
95+ }
96+ err = h .doMutateByColocationProfile (ctx , pod , profile )
8397 if err != nil {
8498 return err
8599 }
@@ -125,6 +139,18 @@ func (h *PodMutatingHandler) matchObjectSelector(pod, oldPod *corev1.Pod, object
125139 return matched , nil
126140}
127141
142+ func shouldSkipProfile (profile * configv1alpha1.ClusterColocationProfile ) (bool , error ) {
143+ percent := 100
144+ if profile .Spec .Probability != nil {
145+ var err error
146+ percent , err = intstr .GetScaledValueFromIntOrPercent (profile .Spec .Probability , 100 , false )
147+ if err != nil {
148+ return false , err
149+ }
150+ }
151+ return percent == 0 || (percent != 100 && randIntnFn (100 ) > percent ), nil
152+ }
153+
128154func (h * PodMutatingHandler ) doMutateByColocationProfile (ctx context.Context , pod * corev1.Pod , profile * configv1alpha1.ClusterColocationProfile ) error {
129155 if len (profile .Spec .Labels ) > 0 {
130156 if pod .Labels == nil {
0 commit comments