Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions charts/hami/templates/device-plugin/monitorrole.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ rules:
- list
- create
- update
- patch

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emitnodewarningevent has exactly one caller, register.go, which runs under this exact role. this role already had update on events before this pr. so the original update() call was never actually forbidden, rbaccheck flagged it against the scheduler clusterrole instead, which never calls this function at all. does that mean the real bug here was never an rbac violation, just rbaccheck checking the wrong role file?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, correct. Thanks! I've updated #2567 to avoid this kind of false alarm. Closed it.

{{- end -}}


3 changes: 1 addition & 2 deletions pkg/device-plugin/nvidiadevice/nvinternal/plugin/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,7 @@ func (plugin *NvidiaDevicePlugin) RegisterInAnnotation() (bool, error) {
if hasAsymmetry {
util.EmitNodeWarningEvent(node, "AsymmetricGPUP2PLink",
"One or more GPU pairs on this node have asymmetric P2P link data; "+
"affected pairs scored 0 (possible NVLink hardware or driver issue)",
time.Hour)
"affected pairs scored 0 (possible NVLink hardware or driver issue)")
}
data, err = json.Marshal(gpuScore)
if err != nil {
Expand Down
30 changes: 16 additions & 14 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,8 +282,10 @@ func AllContainersCreated(pod *corev1.Pod) bool {
return len(pod.Status.ContainerStatuses) >= len(pod.Spec.Containers)
}

// EmitNodeWarningEvent emits a Warning event on the given Node with deduplication.
func EmitNodeWarningEvent(node *corev1.Node, reason, message string, dedupWindow time.Duration) {
// EmitNodeWarningEvent emits a Warning event on the given Node.
// If an existing event with the same node and reason is found, the
// count is incremented via Patch to avoid creating duplicates.
func EmitNodeWarningEvent(node *corev1.Node, reason, message string) {
c := client.GetClient()
if c == nil {
klog.Warningf("cannot emit node event for %s: Kubernetes client not initialized", node.Name)
Expand All @@ -292,22 +294,21 @@ func EmitNodeWarningEvent(node *corev1.Node, reason, message string, dedupWindow

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

fieldSel := fmt.Sprintf(
"involvedObject.kind=Node,involvedObject.name=%s,involvedObject.uid=%s,reason=%s",
node.Name, string(node.UID), reason,
"involvedObject.kind=Node,involvedObject.name=%s,reason=%s",
node.Name, reason,
)
existing, err := c.CoreV1().Events(corev1.NamespaceDefault).List(ctx, metav1.ListOptions{
FieldSelector: fieldSel,
})
if err != nil {
klog.Warningf("failed to list events for node %s: %v; will attempt create", node.Name, err)
klog.Warningf("failed to list events for node %s: %v", node.Name, err)
}

now := metav1.Now()

if err == nil && len(existing.Items) > 0 {
// Client-side filter: the field selector is a server-side optimization; re-check
// here so the function is correct even against fake clients or non-compliant servers.
if err == nil {
var latest *corev1.Event
for i := range existing.Items {
ev := &existing.Items[i]
Expand All @@ -318,12 +319,13 @@ func EmitNodeWarningEvent(node *corev1.Node, reason, message string, dedupWindow
latest = ev
}
}
if latest != nil && now.Sub(latest.LastTimestamp.Time) <= dedupWindow {
latest.Count++
latest.LastTimestamp = now
latest.Message = message
if _, err := c.CoreV1().Events(corev1.NamespaceDefault).Update(ctx, latest, metav1.UpdateOptions{}); err != nil {
klog.Warningf("failed to update node event for %s: %v", node.Name, err)
if latest != nil {
patch := []byte(fmt.Sprintf(
`{"count":%d,"lastTimestamp":"%s","message":"%s"}`,
latest.Count+1, now.UTC().Format(time.RFC3339), message))
if _, err := c.CoreV1().Events(corev1.NamespaceDefault).Patch(
ctx, latest.Name, k8stypes.MergePatchType, patch, metav1.PatchOptions{}); err != nil {
klog.Warningf("failed to patch node event for %s: %v", node.Name, err)
}
return
}
Expand Down
139 changes: 65 additions & 74 deletions pkg/util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package util
import (
"context"
"testing"
"time"

"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -781,96 +780,88 @@ func TestSchedulerPolicyName_String(t *testing.T) {
}
}

func TestEmitNodeWarningEventNilClient(t *testing.T) {
prevClient := client.KubeClient
t.Cleanup(func() { client.KubeClient = prevClient })

node := &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: "test-node",
UID: types.UID("test-uid"),
},
}
client.KubeClient = nil
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Should not panic when client is nil.
EmitNodeWarningEvent(node, "TestReason", "test message")
}

func TestEmitNodeWarningEvent(t *testing.T) {
prevClient := client.KubeClient
t.Cleanup(func() { client.KubeClient = prevClient })

const (
nodeName = "test-node"
nodeUID = types.UID("test-uid-1234")
reason = "AsymmetricGPUP2PLink"
msg1 = "first message"
msg2 = "updated message"
msg = "test message"
)
node := &corev1.Node{
ObjectMeta: metav1.ObjectMeta{
Name: nodeName,
UID: nodeUID,
},
}
dedupWindow := time.Hour

t.Run("no existing event creates new event", func(t *testing.T) {
client.KubeClient = fake.NewClientset()

EmitNodeWarningEvent(node, reason, msg1, dedupWindow)

events, err := client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).List(
context.TODO(), metav1.ListOptions{})
assert.NilError(t, err)
assert.Equal(t, 1, len(events.Items))
assert.Equal(t, reason, events.Items[0].Reason)
assert.Equal(t, msg1, events.Items[0].Message)
assert.Equal(t, int32(1), events.Items[0].Count)
assert.Equal(t, corev1.EventTypeWarning, events.Items[0].Type)
})
client.KubeClient = fake.NewClientset()

t.Run("existing event within dedupWindow updates count and message", func(t *testing.T) {
past := metav1.NewTime(time.Now().Add(-30 * time.Minute)) // within 1h window
existing := &corev1.Event{
// First call creates a new event.
EmitNodeWarningEvent(node, reason, msg)

events, err := client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).List(
context.TODO(), metav1.ListOptions{})
assert.NilError(t, err)
assert.Equal(t, 1, len(events.Items))
assert.Equal(t, reason, events.Items[0].Reason)
assert.Equal(t, msg, events.Items[0].Message)
assert.Equal(t, int32(1), events.Items[0].Count)
assert.Equal(t, corev1.EventTypeWarning, events.Items[0].Type)

// Inject an event with a different UID — the dedup loop should
// skip it and find the matching event to patch.
decoy, err := client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).Create(
context.TODO(), &corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: nodeName + "-existing",
Name: "decoy-event",
Namespace: corev1.NamespaceDefault,
},
InvolvedObject: corev1.ObjectReference{
Kind: "Node",
Name: nodeName,
UID: nodeUID,
},
Reason: reason,
Message: msg1,
Type: corev1.EventTypeWarning,
Count: 3,
FirstTimestamp: past,
LastTimestamp: past,
Kind: "Node", Name: nodeName, UID: "other-uid",
},
Reason: reason,
Source: corev1.EventSource{Component: "hami-device-plugin"},
}, metav1.CreateOptions{})
assert.NilError(t, err)
assert.Assert(t, decoy != nil)

// Second call patches the matching event, not the decoy.
EmitNodeWarningEvent(node, reason, "updated message")

events, err = client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).List(
context.TODO(), metav1.ListOptions{})
assert.NilError(t, err)
// Fake client returns all events (no field selector filtering), so
// expect 2: the decoy (different UID) plus the matched event.
assert.Equal(t, 2, len(events.Items), "expected 2 events, got %d", len(events.Items))

// Find the event matching our node UID — it should have been patched.
var matched *corev1.Event
for i := range events.Items {
if events.Items[i].InvolvedObject.UID == nodeUID {
matched = &events.Items[i]
break
}
client.KubeClient = fake.NewClientset(existing)

EmitNodeWarningEvent(node, reason, msg2, dedupWindow)

events, err := client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).List(
context.TODO(), metav1.ListOptions{})
assert.NilError(t, err)
// Must still be exactly one event — no new object created.
assert.Equal(t, 1, len(events.Items))
assert.Equal(t, int32(4), events.Items[0].Count)
assert.Equal(t, msg2, events.Items[0].Message)
})

t.Run("existing event outside dedupWindow creates new event", func(t *testing.T) {
old := metav1.NewTime(time.Now().Add(-2 * time.Hour)) // outside 1h window
existing := &corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: nodeName + "-old",
Namespace: corev1.NamespaceDefault,
},
InvolvedObject: corev1.ObjectReference{
Kind: "Node",
Name: nodeName,
UID: nodeUID,
},
Reason: reason,
Message: msg1,
Type: corev1.EventTypeWarning,
Count: 1,
FirstTimestamp: old,
LastTimestamp: old,
}
client.KubeClient = fake.NewClientset(existing)

EmitNodeWarningEvent(node, reason, msg2, dedupWindow)

events, err := client.KubeClient.CoreV1().Events(corev1.NamespaceDefault).List(
context.TODO(), metav1.ListOptions{})
assert.NilError(t, err)
// Old event still present plus one new event.
assert.Equal(t, 2, len(events.Items))
})
}
assert.Assert(t, matched != nil, "expected to find event with matching UID")
assert.Equal(t, int32(2), matched.Count)
assert.Equal(t, "updated message", matched.Message)
}
Loading