Skip to content

Commit

Permalink
Change event watcher example to retry the connection (#1616)
Browse files Browse the repository at this point in the history
* Change event watcher example to retry the connection

Fixes #1615

Signed-off-by: Natalie Klestrup Röijezon <[email protected]>

* Factor out printing to ensure consistency

Signed-off-by: Natalie Klestrup Röijezon <[email protected]>

* Report an error if an invalid --for= argument is supplied, instead of ignoring it

Signed-off-by: Natalie Klestrup Röijezon <[email protected]>

---------

Signed-off-by: Natalie Klestrup Röijezon <[email protected]>
  • Loading branch information
nightkr authored Oct 25, 2024
1 parent 140c9bd commit 4a63e81
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions examples/event_watcher.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::pin::pin;

use futures::TryStreamExt;
use futures::StreamExt;
use k8s_openapi::{
api::{core::v1::ObjectReference, events::v1::Event},
apimachinery::pkg::apis::meta::v1::Time,
Expand Down Expand Up @@ -36,21 +36,28 @@ async fn main() -> anyhow::Result<()> {
if let Some(forval) = app.r#for {
if let Some((kind, name)) = forval.split_once('/') {
conf = conf.fields(&format!("regarding.kind={kind},regarding.name={name}"));
} else {
return Err(anyhow::Error::msg("Usage: --for=<KIND>/<NAME>"));
}
}
let event_stream = watcher(events, conf).default_backoff().applied_objects();
let mut event_stream = pin!(event_stream);

#[allow(clippy::print_literal)] // for consistency
{
println!("{0:<6} {1:<15} {2:<55} {3}", "AGE", "REASON", "OBJECT", "MESSAGE");
fn print_event(age: &str, reason: &str, obj: &str, note: &str) {
println!("{age:<6} {reason:<15} {obj:<55} {note}");
}
while let Some(ev) = event_stream.try_next().await? {
let age = ev.creation_timestamp().map(format_creation).unwrap_or_default();
let reason = ev.reason.unwrap_or_default();
let obj = ev.regarding.and_then(format_objref).unwrap_or_default();
let note = ev.note.unwrap_or_default();
println!("{0:<6} {1:<15} {2:<55} {3}", age, reason, obj, note);
print_event("AGE", "REASON", "OBJECT", "MESSAGE");
while let Some(ev) = event_stream.next().await {
match ev {
Ok(ev) => {
let age = ev.creation_timestamp().map(format_creation).unwrap_or_default();
let reason = ev.reason.unwrap_or_default();
let obj = ev.regarding.and_then(format_objref).unwrap_or_default();
let note = ev.note.unwrap_or_default();
print_event(&age, &reason, &obj, &note);
}
Err(err) => eprintln!("{:?}", anyhow::Error::new(err)),
}
}
Ok(())
}
Expand Down

0 comments on commit 4a63e81

Please sign in to comment.