|
| 1 | +/* |
| 2 | +SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and component-operator-runtime contributors |
| 3 | +SPDX-License-Identifier: Apache-2.0 |
| 4 | +*/ |
| 5 | + |
| 6 | +package events |
| 7 | + |
| 8 | +import ( |
| 9 | + "fmt" |
| 10 | + "sync" |
| 11 | + "time" |
| 12 | + |
| 13 | + "k8s.io/client-go/tools/record" |
| 14 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 15 | +) |
| 16 | + |
| 17 | +type DeduplicatingRecorder struct { |
| 18 | + recorder record.EventRecorder |
| 19 | + mutex sync.Mutex |
| 20 | + events map[string]event |
| 21 | +} |
| 22 | + |
| 23 | +type event struct { |
| 24 | + digest string |
| 25 | + timestamp time.Time |
| 26 | +} |
| 27 | + |
| 28 | +func NewDeduplicatingRecorder(recorder record.EventRecorder) *DeduplicatingRecorder { |
| 29 | + return &DeduplicatingRecorder{ |
| 30 | + recorder: recorder, |
| 31 | + events: make(map[string]event), |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func (r *DeduplicatingRecorder) Event(object client.Object, eventType string, reason string, message string) { |
| 36 | + if r.isDuplicate(object, nil, eventType, reason, message) { |
| 37 | + return |
| 38 | + } |
| 39 | + r.recorder.Event(object, eventType, reason, message) |
| 40 | +} |
| 41 | + |
| 42 | +func (r *DeduplicatingRecorder) Eventf(object client.Object, eventType string, reason string, messageFmt string, args ...any) { |
| 43 | + if r.isDuplicate(object, nil, eventType, reason, fmt.Sprintf(messageFmt, args...)) { |
| 44 | + return |
| 45 | + } |
| 46 | + r.recorder.Eventf(object, eventType, reason, messageFmt, args...) |
| 47 | +} |
| 48 | + |
| 49 | +func (r *DeduplicatingRecorder) AnnotatedEventf(object client.Object, annotations map[string]string, eventType string, reason string, messageFmt string, args ...any) { |
| 50 | + if r.isDuplicate(object, annotations, eventType, reason, fmt.Sprintf(messageFmt, args...)) { |
| 51 | + return |
| 52 | + } |
| 53 | + r.recorder.AnnotatedEventf(object, annotations, eventType, reason, messageFmt, args...) |
| 54 | +} |
| 55 | + |
| 56 | +func (r *DeduplicatingRecorder) isDuplicate(object client.Object, annotations map[string]string, eventType, reason, message string) bool { |
| 57 | + uid := string(object.GetUID()) |
| 58 | + digest := calculateDigest(annotations, eventType, reason, message) |
| 59 | + now := time.Now() |
| 60 | + exp := time.Now().Add(-5 * time.Minute) |
| 61 | + |
| 62 | + r.mutex.Lock() |
| 63 | + defer r.mutex.Unlock() |
| 64 | + for uid, event := range r.events { |
| 65 | + if event.timestamp.Before(exp) { |
| 66 | + delete(r.events, uid) |
| 67 | + } |
| 68 | + } |
| 69 | + if r.events[uid].digest == digest { |
| 70 | + return true |
| 71 | + } else { |
| 72 | + r.events[uid] = event{ |
| 73 | + digest: digest, |
| 74 | + timestamp: now, |
| 75 | + } |
| 76 | + return false |
| 77 | + } |
| 78 | +} |
0 commit comments