Skip to main content

kube_runtime/
events.rs

1//! Publishes events for objects for kubernetes >= 1.19
2use k8s_openapi::{
3    api::{
4        core::v1::ObjectReference,
5        events::v1::{Event as K8sEvent, EventSeries},
6    },
7    apimachinery::pkg::apis::meta::v1::{MicroTime, ObjectMeta},
8    jiff::{SignedDuration, Timestamp},
9};
10use kube_client::{
11    Client, ResourceExt,
12    api::{Api, Patch, PatchParams, PostParams},
13};
14use std::{
15    collections::HashMap,
16    hash::{Hash, Hasher},
17    sync::Arc,
18};
19use tokio::sync::RwLock;
20
21const CACHE_TTL: SignedDuration = SignedDuration::from_mins(6);
22
23/// Minimal event type for publishing through [`Recorder::publish`].
24///
25/// All string fields must be human readable.
26pub struct Event {
27    /// The event severity.
28    ///
29    /// Shows up in `kubectl describe` as `Type`.
30    pub type_: EventType,
31
32    /// The short reason explaining why the `action` was taken.
33    ///
34    /// This must be at most 128 characters, generally in `PascalCase`. Shows up in `kubectl describe` as `Reason`.
35    pub reason: String,
36
37    /// A optional description of the status of the `action`.
38    ///
39    /// This must be at most 1kB in size. Shows up in `kubectl describe` as `Message`.
40    pub note: Option<String>,
41
42    /// The action that was taken (either successfully or unsuccessfully) against main object
43    ///
44    /// This must be at most 128 characters. It does not currently show up in `kubectl describe`.
45    /// A common convention is a short identifier of the action that caused the outcome described in `reason`.
46    /// Usually denoted in `PascalCase`.
47    pub action: String,
48
49    /// Optional secondary object related to the main object
50    ///
51    /// Some events are emitted for actions that affect multiple objects.
52    /// `secondary` can be populated to capture this detail.
53    ///
54    /// For example: the event concerns a `Deployment` and it affects the current `ReplicaSet` underneath it.
55    /// You would therefore populate `events` using the object reference of the `ReplicaSet`.
56    ///
57    /// Set `secondary` to `None`, instead, if the event affects only the object whose reference
58    /// you passed to [`Recorder::new`].
59    ///
60    /// # Naming note
61    ///
62    /// `secondary` is mapped to `related` in
63    /// [`Events API`](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#event-v1-events-k8s-io).
64    ///
65    /// [`Recorder::new`]: crate::events::Recorder::new
66    pub secondary: Option<ObjectReference>,
67}
68
69/// The event severity or type.
70#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
71pub enum EventType {
72    /// An event took place - nothing to worry about.
73    Normal,
74    /// Something is not working as expected - it might be worth to have a look.
75    Warning,
76}
77
78/// [`ObjectReference`] with Hash and Eq implementations
79///
80/// [`ObjectReference`]: k8s_openapi::api::core::v1::ObjectReference
81#[derive(Clone, Debug, PartialEq)]
82pub struct Reference(ObjectReference);
83
84impl Eq for Reference {}
85
86impl Hash for Reference {
87    fn hash<H: Hasher>(&self, state: &mut H) {
88        self.0.api_version.hash(state);
89        self.0.kind.hash(state);
90        self.0.name.hash(state);
91        self.0.namespace.hash(state);
92        self.0.uid.hash(state);
93    }
94}
95
96/// Cache key for event deduplication
97#[derive(Clone, Debug, PartialEq, Eq, Hash)]
98struct EventKey {
99    pub event_type: EventType,
100    pub action: String,
101    pub reason: String,
102    pub reporting_controller: String,
103    pub reporting_instance: Option<String>,
104    pub regarding: Reference,
105    pub related: Option<Reference>,
106}
107
108/// Information about the reporting controller.
109///
110/// ```
111/// use kube::runtime::events::Reporter;
112///
113/// let reporter = Reporter {
114///     controller: "my-awesome-controller".into(),
115///     instance: std::env::var("CONTROLLER_POD_NAME").ok(),
116/// };
117/// ```
118#[derive(Clone, Debug, PartialEq, Eq, Hash)]
119pub struct Reporter {
120    /// The name of the reporting controller that is publishing the event.
121    ///
122    /// This is likely your deployment.metadata.name.
123    pub controller: String,
124
125    /// The id of the controller publishing the event. Likely your pod name.
126    ///
127    /// Useful when running more than one replica on your controller and you need to disambiguate
128    /// where events came from.
129    ///
130    /// The name of the controller pod can be retrieved using Kubernetes' API or
131    /// it can be injected as an environment variable using
132    ///
133    /// ```yaml
134    /// env:
135    ///   - name: CONTROLLER_POD_NAME
136    ///     valueFrom:
137    ///       fieldRef:
138    ///         fieldPath: metadata.name
139    /// ```
140    ///
141    /// in the manifest of your controller.
142    ///
143    /// Note: If `instance` is not provided, the hostname is used. If the hostname is also
144    /// unavailable, `reporting_instance` defaults to `reporting_controller` in the `Event`.
145    pub instance: Option<String>,
146}
147
148// simple conversions for when instance == controller
149impl From<String> for Reporter {
150    fn from(es: String) -> Self {
151        Self {
152            controller: es,
153            instance: None,
154        }
155    }
156}
157
158impl From<&str> for Reporter {
159    fn from(es: &str) -> Self {
160        // The hostname crate only supports [Windows and Unix](https://github.com/djc/hostname#supported-platforms) targets.
161        // This prevents compiling for wasm32-wasip3.
162        #[cfg(any(unix, windows))]
163        let instance = hostname::get().ok().and_then(|h| h.into_string().ok());
164        #[cfg(not(any(unix, windows)))]
165        let instance = None;
166        Self {
167            controller: es.into(),
168            instance,
169        }
170    }
171}
172
173/// A publisher abstraction to emit Kubernetes' events.
174///
175/// All events emitted by an `Recorder` are attached to the [`ObjectReference`]
176/// specified when building the recorder using [`Recorder::new`].
177///
178/// ```
179/// use kube::runtime::events::{Reporter, Recorder, Event, EventType};
180/// use k8s_openapi::api::core::v1::ObjectReference;
181///
182/// # async fn wrapper() -> Result<(), Box<dyn std::error::Error>> {
183/// # let client: kube::Client = todo!();
184/// let reporter = Reporter {
185///     controller: "my-awesome-controller".into(),
186///     instance: std::env::var("CONTROLLER_POD_NAME").ok(),
187/// };
188///
189/// let recorder = Recorder::new(client, reporter);
190///
191/// // references can be made manually using `ObjectMeta` and `ApiResource`/`Resource` info
192/// let reference = ObjectReference {
193///     // [...]
194///     ..Default::default()
195/// };
196/// // or for k8s-openapi / kube-derive types, use Resource::object_ref:
197/// // let reference = myobject.object_ref();
198/// recorder
199///     .publish(
200///         &Event {
201///             action: "Scheduling".into(),
202///             reason: "Pulling".into(),
203///             note: Some("Pulling image `nginx`".into()),
204///             type_: EventType::Normal,
205///             secondary: None,
206///         },
207///         &reference,
208///     ).await?;
209/// # Ok(())
210/// # }
211/// ```
212///
213/// Events attached to an object will be shown in the `Events` section of the output of
214/// of `kubectl describe` for that object.
215///
216/// ## RBAC
217///
218/// Note that usage of the event recorder minimally requires the following RBAC rules:
219///
220/// ```yaml
221/// - apiGroups: ["events.k8s.io"]
222///   resources: ["events"]
223///   verbs: ["create", "patch"]
224/// ```
225#[derive(Clone)]
226pub struct Recorder {
227    client: Client,
228    reporter: Reporter,
229    cache: Arc<RwLock<HashMap<EventKey, K8sEvent>>>,
230}
231
232impl Recorder {
233    /// Create a new recorder that can publish events for one specific object
234    ///
235    /// This is intended to be created at the start of your controller's reconcile fn.
236    ///
237    /// Cluster scoped objects will publish events in the "default" namespace.
238    #[must_use]
239    pub fn new(client: Client, reporter: Reporter) -> Self {
240        let cache = Arc::default();
241        Self {
242            client,
243            reporter,
244            cache,
245        }
246    }
247
248    /// Builds unique event key based on reportingController, reportingInstance, regarding, reason
249    ///  and note
250    fn get_event_key(&self, ev: &Event, regarding: &ObjectReference) -> EventKey {
251        EventKey {
252            event_type: ev.type_,
253            action: ev.action.clone(),
254            reason: ev.reason.clone(),
255            reporting_controller: self.reporter.controller.clone(),
256            reporting_instance: self.reporter.instance.clone(),
257            regarding: Reference(regarding.clone()),
258            related: ev.secondary.clone().map(Reference),
259        }
260    }
261
262    // See https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.35/#event-v1-events-k8s-io
263    // for more detail on the fields
264    // and what's expected: https://kubernetes.io/docs/reference/using-api/deprecation-guide/#event-v125
265    fn generate_event(&self, ev: &Event, reference: &ObjectReference) -> K8sEvent {
266        let now = Timestamp::now();
267        K8sEvent {
268            action: Some(ev.action.clone()),
269            reason: Some(ev.reason.clone()),
270            deprecated_count: None,
271            deprecated_first_timestamp: None,
272            deprecated_last_timestamp: None,
273            deprecated_source: None,
274            event_time: Some(MicroTime(now)),
275            regarding: Some(reference.clone()),
276            note: ev.note.clone(),
277            metadata: ObjectMeta {
278                namespace: reference.namespace.clone(),
279                name: Some(format!(
280                    "{}.{:x}",
281                    reference.name.as_ref().unwrap_or(&self.reporter.controller),
282                    now.as_nanosecond()
283                )),
284                ..Default::default()
285            },
286            reporting_controller: Some(self.reporter.controller.clone()),
287            reporting_instance: Some(
288                self.reporter
289                    .instance
290                    .clone()
291                    .unwrap_or_else(|| self.reporter.controller.clone()),
292            ),
293            series: None,
294            type_: match ev.type_ {
295                EventType::Normal => Some("Normal".into()),
296                EventType::Warning => Some("Warning".into()),
297            },
298            related: ev.secondary.clone(),
299        }
300    }
301
302    /// Publish a new Kubernetes' event.
303    ///
304    /// # Access control
305    ///
306    /// The event object is created in the same namespace of the [`ObjectReference`].
307    /// Make sure that your controller has `create` permissions in the required namespaces
308    /// for the `event` resource in the API group `events.k8s.io`.
309    ///
310    /// # Errors
311    ///
312    /// Returns an [`Error`](`kube_client::Error`) if the event is rejected by Kubernetes.
313    pub async fn publish(&self, ev: &Event, reference: &ObjectReference) -> Result<(), kube_client::Error> {
314        let now = Timestamp::now();
315
316        // gc past events older than now + CACHE_TTL
317        self.cache.write().await.retain(|_, v| {
318            if let Some(series) = v.series.as_ref() {
319                series.last_observed_time.0 + CACHE_TTL > now
320            } else if let Some(event_time) = v.event_time.as_ref() {
321                event_time.0 + CACHE_TTL > now
322            } else {
323                true
324            }
325        });
326
327        let key = self.get_event_key(ev, reference);
328        let event = match self.cache.read().await.get(&key) {
329            Some(e) => {
330                let count = if let Some(s) = &e.series { s.count + 1 } else { 2 };
331                let series = EventSeries {
332                    count,
333                    last_observed_time: MicroTime(now),
334                };
335                let mut event = e.clone();
336                event.series = Some(series);
337                event
338            }
339            None => self.generate_event(ev, reference),
340        };
341
342        let events = Api::namespaced(
343            self.client.clone(),
344            reference.namespace.as_ref().unwrap_or(&"default".to_string()),
345        );
346        if event.series.is_some() {
347            events
348                .patch(&event.name_any(), &PatchParams::default(), &Patch::Merge(&event))
349                .await?;
350        } else {
351            events.create(&PostParams::default(), &event).await?;
352        }
353
354        {
355            let mut cache = self.cache.write().await;
356            cache.insert(key, event);
357        }
358        Ok(())
359    }
360}
361
362#[cfg(test)]
363mod test {
364    use super::{Event, EventKey, EventType, Recorder, Reference, Reporter};
365
366    use k8s_openapi::{
367        api::{
368            core::v1::{ComponentStatus, Namespace, Service},
369            events::v1::Event as K8sEvent,
370        },
371        apimachinery::pkg::apis::meta::v1::MicroTime,
372        jiff::{SignedDuration, Timestamp},
373    };
374    use kube::{Api, Client, Resource};
375
376    #[tokio::test]
377    #[ignore = "needs cluster (creates an event for the default kubernetes service)"]
378    async fn event_recorder_attaches_events() -> Result<(), Box<dyn std::error::Error>> {
379        let client = Client::try_default().await?;
380
381        let svcs: Api<Service> = Api::namespaced(client.clone(), "default");
382        let s = svcs.get("kubernetes").await?; // always a kubernetes service in default
383        let recorder = Recorder::new(client.clone(), "kube".into());
384        recorder
385            .publish(
386                &Event {
387                    type_: EventType::Normal,
388                    reason: "VeryCoolService".into(),
389                    note: Some("Sending kubernetes to detention".into()),
390                    action: "Test event - plz ignore".into(),
391                    secondary: None,
392                },
393                &s.object_ref(&()),
394            )
395            .await?;
396        let events: Api<K8sEvent> = Api::namespaced(client, "default");
397
398        let event_list = events.list(&Default::default()).await?;
399        let found_event = event_list
400            .into_iter()
401            .find(|e| std::matches!(e.reason.as_deref(), Some("VeryCoolService")))
402            .unwrap();
403        assert_eq!(found_event.note.unwrap(), "Sending kubernetes to detention");
404
405        recorder
406            .publish(
407                &Event {
408                    type_: EventType::Normal,
409                    reason: "VeryCoolService".into(),
410                    note: Some("Sending kubernetes to detention twice".into()),
411                    action: "Test event - plz ignore".into(),
412                    secondary: None,
413                },
414                &s.object_ref(&()),
415            )
416            .await?;
417
418        let event_list = events.list(&Default::default()).await?;
419        let found_event = event_list
420            .into_iter()
421            .find(|e| std::matches!(e.reason.as_deref(), Some("VeryCoolService")))
422            .unwrap();
423        assert!(found_event.series.is_some());
424
425        Ok(())
426    }
427
428    #[tokio::test]
429    #[ignore = "needs cluster (creates an event for the default kubernetes service)"]
430    async fn event_recorder_attaches_events_without_namespace() -> Result<(), Box<dyn std::error::Error>> {
431        let client = Client::try_default().await?;
432
433        let component_status_api: Api<ComponentStatus> = Api::all(client.clone());
434        let s = component_status_api.get("scheduler").await?;
435        let recorder = Recorder::new(client.clone(), "kube".into());
436        recorder
437            .publish(
438                &Event {
439                    type_: EventType::Normal,
440                    reason: "VeryCoolServiceNoNamespace".into(),
441                    note: Some("Sending kubernetes to detention without namespace".into()),
442                    action: "Test event - plz ignore".into(),
443                    secondary: None,
444                },
445                &s.object_ref(&()),
446            )
447            .await?;
448        let events: Api<K8sEvent> = Api::namespaced(client, "default");
449
450        let event_list = events.list(&Default::default()).await?;
451        let found_event = event_list
452            .into_iter()
453            .find(|e| std::matches!(e.reason.as_deref(), Some("VeryCoolServiceNoNamespace")))
454            .unwrap();
455        assert_eq!(
456            found_event.note.unwrap(),
457            "Sending kubernetes to detention without namespace"
458        );
459
460        recorder
461            .publish(
462                &Event {
463                    type_: EventType::Normal,
464                    reason: "VeryCoolServiceNoNamespace".into(),
465                    note: Some("Sending kubernetes to detention without namespace twice".into()),
466                    action: "Test event - plz ignore".into(),
467                    secondary: None,
468                },
469                &s.object_ref(&()),
470            )
471            .await?;
472
473        let event_list = events.list(&Default::default()).await?;
474        let found_event = event_list
475            .into_iter()
476            .find(|e| std::matches!(e.reason.as_deref(), Some("VeryCoolServiceNoNamespace")))
477            .unwrap();
478        assert!(found_event.series.is_some());
479        Ok(())
480    }
481
482    #[tokio::test]
483    #[ignore = "needs cluster (creates an event for the default namespace)"]
484    async fn event_recorder_cache_retain() -> Result<(), Box<dyn std::error::Error>> {
485        let client = Client::try_default().await?;
486
487        // Not the kubernetes service: event names are `{name}.{nanos}`, so a parallel test
488        // publishing for the same name can collide (#2122)
489        let nss: Api<Namespace> = Api::all(client.clone());
490        let s = nss.get("default").await?;
491
492        let reference = s.object_ref(&());
493        let reporter: Reporter = "kube".into();
494        let ev = Event {
495            type_: EventType::Normal,
496            reason: "TestCacheTtl".into(),
497            note: Some("Sending kubernetes to detention".into()),
498            action: "Test event - plz ignore".into(),
499            secondary: None,
500        };
501        let key = EventKey {
502            event_type: ev.type_,
503            action: ev.action.clone(),
504            reason: ev.reason.clone(),
505            reporting_controller: reporter.controller.clone(),
506            regarding: Reference(reference.clone()),
507            reporting_instance: None,
508            related: None,
509        };
510
511        let reporter = Reporter {
512            controller: "kube".into(),
513            instance: None,
514        };
515        let recorder = Recorder::new(client.clone(), reporter);
516
517        recorder.publish(&ev, &s.object_ref(&())).await?;
518        let now = Timestamp::now();
519        let past = now - SignedDuration::from_mins(10);
520        recorder.cache.write().await.entry(key).and_modify(|e| {
521            e.event_time = Some(MicroTime(past));
522        });
523
524        recorder.publish(&ev, &s.object_ref(&())).await?;
525
526        let events: Api<K8sEvent> = Api::namespaced(client, "default");
527        let event_list = events.list(&Default::default()).await?;
528        let found_event = event_list
529            .into_iter()
530            .find(|e| std::matches!(e.reason.as_deref(), Some("TestCacheTtl")))
531            .unwrap();
532        assert_eq!(found_event.note.unwrap(), "Sending kubernetes to detention");
533        assert!(found_event.series.is_none());
534
535        Ok(())
536    }
537}