istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/kube/kclient/events.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package kclient
    16  
    17  import (
    18  	corev1 "k8s.io/api/core/v1"
    19  	"k8s.io/apimachinery/pkg/runtime"
    20  	typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
    21  	"k8s.io/client-go/tools/record"
    22  	"k8s.io/klog/v2"
    23  
    24  	"istio.io/istio/pkg/kube"
    25  )
    26  
    27  type EventRecorder struct {
    28  	eventRecorder    record.EventRecorder
    29  	eventBroadcaster record.EventBroadcaster
    30  }
    31  
    32  // NewEventRecorder creates a new EventRecorder.
    33  // This should be shutdown after usage.
    34  func NewEventRecorder(client kube.Client, component string) EventRecorder {
    35  	eventBroadcaster := record.NewBroadcaster()
    36  	eventBroadcaster.StartLogging(klog.V(5).Infof) // Will log at kube:debug level
    37  	eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: client.Kube().CoreV1().Events("")})
    38  	eventRecorder := eventBroadcaster.NewRecorder(kube.IstioScheme, corev1.EventSource{
    39  		Component: component,
    40  	})
    41  	return EventRecorder{
    42  		eventRecorder:    eventRecorder,
    43  		eventBroadcaster: eventBroadcaster,
    44  	}
    45  }
    46  
    47  // Write creates a single event.
    48  func (e *EventRecorder) Write(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
    49  	e.eventRecorder.Eventf(object, eventtype, reason, messageFmt, args...)
    50  }
    51  
    52  // Shutdown terminates the event recorder. This must be called upon completion of writing events, and events should not be
    53  // written once terminated.
    54  func (e *EventRecorder) Shutdown() {
    55  	e.eventBroadcaster.Shutdown()
    56  }