Skip to content

Commit

Permalink
Fix pod assignment issue when pod already has a node assigned
Browse files Browse the repository at this point in the history
Signed-off-by: chaunceyjiang <[email protected]>
  • Loading branch information
chaunceyjiang committed Oct 22, 2024
1 parent 28f20a6 commit 4fce329
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/scheduler/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ func (h *webhook) Handle(_ context.Context, req admission.Request) admission.Res
} else if len(config.SchedulerName) > 0 {
pod.Spec.SchedulerName = config.SchedulerName
}
if pod.Spec.NodeName != "" {
klog.Infof(template+" - Pod already has node assigned", req.Namespace, req.Name, req.UID)
return admission.Denied("pod has node assigned")
}
marshaledPod, err := json.Marshal(pod)
if err != nil {
klog.Errorf(template+" - Failed to marshal pod, error: %v", req.Namespace, req.Name, req.UID, err)
Expand Down
62 changes: 62 additions & 0 deletions pkg/scheduler/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,65 @@ func TestHandle(t *testing.T) {
}

}



func TestPodHasNodeName(t *testing.T) {
// create a Pod object
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
Namespace: "default",
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "container1",
SecurityContext: &corev1.SecurityContext{
Privileged: nil,
},
Resources: corev1.ResourceRequirements{
Limits: corev1.ResourceList{
"nvidia.com/gpu": resource.MustParse("1"),
},
},
},
},
NodeName: "test-node",
},
}

// encode the Pod object
scheme := runtime.NewScheme()
corev1.AddToScheme(scheme)
codec := serializer.NewCodecFactory(scheme).LegacyCodec(corev1.SchemeGroupVersion)
podBytes, err := runtime.Encode(codec, pod)
if err != nil {
t.Fatalf("Error encoding pod: %v", err)
}

// create an AdmissionRequest object
req := admission.Request{
AdmissionRequest: admissionv1.AdmissionRequest{
UID: "test-uid",
Namespace: "default",
Name: "test-pod",
Object: runtime.RawExtension{
Raw: podBytes,
},
},
}

// create a WebHook object
wh, err := NewWebHook()
if err != nil {
t.Fatalf("Error creating WebHook: %v", err)
}

// call the Handle method
resp := wh.Handle(context.Background(), req)
if resp.Allowed {
t.Errorf("Expected allowed response, but got: %v", resp)
}

}

0 comments on commit 4fce329

Please sign in to comment.