Skip to content

Commit

Permalink
Deprecate ResourceExt::name in favour of safe name_* alternatives (#945)
Browse files Browse the repository at this point in the history
* Deprecate ResourceExt::name in favour of name_unchecked

Also add name_or_generatename returning an optional.

Long term want to remove name and maybe reintroduce it as an optional
shorthand instead.

Signed-off-by: clux <sszynrae@gmail.com>

* simpler docs

Signed-off-by: clux <sszynrae@gmail.com>

* simpler alternative for loggers; name_any

Signed-off-by: clux <sszynrae@gmail.com>

* 5 versions

Signed-off-by: clux <sszynrae@gmail.com>

* remove name_or_generatename

probably not the greatest use case for it

Signed-off-by: clux <sszynrae@gmail.com>

* docfix

Signed-off-by: clux <sszynrae@gmail.com>

* clippy on boot + core

left the eq/partialeq ones, those felt a bit more unclear if they were
good.

Signed-off-by: clux <sszynrae@gmail.com>

* fix eq-partialeq clippy in admission

Signed-off-by: clux <sszynrae@gmail.com>
  • Loading branch information
clux authored Jul 3, 2022
1 parent 9f1df5e commit 55bea0b
Show file tree
Hide file tree
Showing 31 changed files with 114 additions and 80 deletions.
2 changes: 1 addition & 1 deletion e2e/boot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ async fn main() -> anyhow::Result<()> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::all(client);
for p in pods.list(&Default::default()).await? {
tracing::info!("Found pod {}", p.name());
tracing::info!("Found pod {}", p.name_any());
}
Ok(())
}
5 changes: 3 additions & 2 deletions examples/admission_controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,14 @@ async fn mutate_handler(body: AdmissionReview<DynamicObject>) -> Result<impl Rep
let mut res = AdmissionResponse::from(&req);
// req.Object always exists for us, but could be None if extending to DELETE events
if let Some(obj) = req.object {
let name = obj.name_any(); // apiserver may not have generated a name yet
res = match mutate(res.clone(), &obj) {
Ok(res) => {
info!("accepted: {:?} on Foo {}", req.operation, obj.name());
info!("accepted: {:?} on Foo {}", req.operation, name);
res
}
Err(err) => {
warn!("denied: {:?} on {} ({})", req.operation, obj.name(), err);
warn!("denied: {:?} on {} ({})", req.operation, name, err);
res.deny(err.to_string())
}
};
Expand Down
26 changes: 13 additions & 13 deletions examples/crd_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async fn main() -> Result<()> {
res.map_left(|o| {
info!(
"Deleting {}: ({:?})",
o.name(),
o.name_any(),
o.status.unwrap().conditions.unwrap().last()
);
})
Expand All @@ -68,7 +68,7 @@ async fn main() -> Result<()> {
let patch_params = PatchParams::default();
match crds.create(&pp, &foocrd).await {
Ok(o) => {
info!("Created {} ({:?})", o.name(), o.status.unwrap());
info!("Created {} ({:?})", o.name_any(), o.status.unwrap());
debug!("Created CRD: {:?}", o.spec);
}
Err(kube::Error::Api(ae)) => assert_eq!(ae.code, 409), // if you skipped delete, for instance
Expand All @@ -88,8 +88,8 @@ async fn main() -> Result<()> {
replicas: 1,
});
let o = foos.create(&pp, &f1).await?;
assert_eq!(ResourceExt::name(&f1), ResourceExt::name(&o));
info!("Created {}", o.name());
assert_eq!(ResourceExt::name_any(&f1), ResourceExt::name_any(&o));
info!("Created {}", o.name_any());

// Verify we can get it
info!("Get Foo baz");
Expand Down Expand Up @@ -128,7 +128,7 @@ async fn main() -> Result<()> {
f2.status = Some(FooStatus::default());

let o = foos.create(&pp, &f2).await?;
info!("Created {}", o.name());
info!("Created {}", o.name_any());

// Update status on qux
info!("Replace Status on Foo instance qux");
Expand All @@ -143,7 +143,7 @@ async fn main() -> Result<()> {
"status": FooStatus { is_bad: true, replicas: 0 }
});
let o = foos.replace_status("qux", &pp, serde_json::to_vec(&fs)?).await?;
info!("Replaced status {:?} for {}", o.status, o.name());
info!("Replaced status {:?} for {}", o.status, o.name_any());
assert!(o.status.unwrap().is_bad);

info!("Patch Status on Foo instance qux");
Expand All @@ -153,12 +153,12 @@ async fn main() -> Result<()> {
let o = foos
.patch_status("qux", &patch_params, &Patch::Merge(&fs))
.await?;
info!("Patched status {:?} for {}", o.status, o.name());
info!("Patched status {:?} for {}", o.status, o.name_any());
assert!(!o.status.unwrap().is_bad);

info!("Get Status on Foo instance qux");
let o = foos.get_status("qux").await?;
info!("Got status {:?} for {}", o.status, o.name());
info!("Got status {:?} for {}", o.status, o.name_any());
assert!(!o.status.unwrap().is_bad);

// Check scale subresource:
Expand All @@ -172,7 +172,7 @@ async fn main() -> Result<()> {
"spec": { "replicas": 2 }
});
let o = foos.patch_scale("qux", &patch_params, &Patch::Merge(&fs)).await?;
info!("Patched scale {:?} for {}", o.spec, o.name());
info!("Patched scale {:?} for {}", o.spec, o.name_any());
assert_eq!(o.status.unwrap().replicas, 1);
assert_eq!(o.spec.unwrap().replicas.unwrap(), 2); // we only asked for more

Expand All @@ -182,7 +182,7 @@ async fn main() -> Result<()> {
"spec": { "info": "patched qux" }
});
let o = foos.patch("qux", &patch_params, &Patch::Merge(&patch)).await?;
info!("Patched {} with new name: {}", o.name(), o.spec.name);
info!("Patched {} with new name: {}", o.name_any(), o.spec.name);
assert_eq!(o.spec.info, "patched qux");
assert_eq!(o.spec.name, "qux"); // didn't blat existing params

Expand Down Expand Up @@ -214,12 +214,12 @@ async fn main() -> Result<()> {
Err(e) => bail!("somehow got unexpected error from validation: {:?}", e),
Ok(o) => bail!("somehow created {:?} despite validation", o),
}
info!("Rejected fx for invalid name {}", fx.name());
info!("Rejected fx for invalid name {}", fx.name_any());

// Cleanup the full collection - expect a wait
match foos.delete_collection(&dp, &lp).await? {
Left(list) => {
let deleted: Vec<_> = list.iter().map(ResourceExt::name).collect();
let deleted: Vec<_> = list.iter().map(ResourceExt::name_any).collect();
info!("Deleting collection of foos: {:?}", deleted);
}
Right(status) => {
Expand All @@ -232,7 +232,7 @@ async fn main() -> Result<()> {
Left(o) => {
info!(
"Deleting {} CRD definition: {:?}",
o.name(),
o.name_any(),
o.status.unwrap().conditions.unwrap().last()
);
}
Expand Down
4 changes: 2 additions & 2 deletions examples/crd_apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ async fn main() -> anyhow::Result<()> {
info!("Applying 1: \n{}", serde_yaml::to_string(&foo)?);
let o = foos.patch("baz", &ssapply, &Patch::Apply(&foo)).await?;
// NB: kubernetes < 1.20 will fail to admit scale subresources - see #387
info!("Applied 1 {}: {:?}", o.name(), o.spec);
info!("Applied 1 {}: {:?}", o.name_any(), o.spec);

// 2. Apply from partial json!
let patch = serde_json::json!({
Expand All @@ -75,7 +75,7 @@ async fn main() -> anyhow::Result<()> {

info!("Applying 2: \n{}", serde_yaml::to_string(&patch)?);
let o2 = foos.patch("baz", &ssapply, &Patch::Apply(patch)).await?;
info!("Applied 2 {}: {:?}", o2.name(), o2.spec);
info!("Applied 2 {}: {:?}", o2.name_any(), o2.spec);

Ok(())
}
4 changes: 2 additions & 2 deletions examples/crd_reflector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@ async fn main() -> anyhow::Result<()> {
// Periodically read our state
// while this runs you can kubectl apply -f crd-baz.yaml or crd-qux.yaml and see it works
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
let crds = reader.state().iter().map(|r| r.name()).collect::<Vec<_>>();
let crds = reader.state().iter().map(|r| r.name_any()).collect::<Vec<_>>();
info!("Current crds: {:?}", crds);
}
});
let mut rfa = rf.applied_objects().boxed();
while let Some(event) = rfa.try_next().await? {
info!("saw {}", event.name());
info!("saw {}", event.name_any());
}
Ok(())
}
2 changes: 1 addition & 1 deletion examples/custom_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async fn main() -> anyhow::Result<()> {

let pods: Api<Pod> = Api::default_namespaced(client);
for p in pods.list(&Default::default()).await? {
info!("{}", p.name());
info!("{}", p.name_any());
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/custom_client_tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async fn main() -> anyhow::Result<()> {

let pods: Api<Pod> = Api::default_namespaced(client);
for p in pods.list(&Default::default()).await? {
info!("{}", p.name());
info!("{}", p.name_any());
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/custom_client_trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async fn main() -> anyhow::Result<()> {

let pods: Api<Pod> = Api::default_namespaced(client);
for p in pods.list(&Default::default()).await? {
info!("{}", p.name());
info!("{}", p.name_any());
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/dynamic_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async fn main() -> anyhow::Result<()> {

let list = api.list(&Default::default()).await?;
for item in list.items {
let name = item.name();
let name = item.name_any();
let ns = item.metadata.namespace.map(|s| s + "/").unwrap_or_default();
info!("\t\t{}{}", ns, name);
}
Expand Down
4 changes: 2 additions & 2 deletions examples/dynamic_pod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ async fn main() -> anyhow::Result<()> {
// Here we simply steal the type info from k8s_openapi, but we could create this from scratch.
let ar = ApiResource::erase::<k8s_openapi::api::core::v1::Pod>(&());

let pods: Api<PodSimple> = Api::namespaced_with(client, "default", &ar);
let pods: Api<PodSimple> = Api::default_namespaced_with(client, &ar);
for p in pods.list(&Default::default()).await? {
info!("Found pod {} running: {:?}", p.name(), p.spec.containers);
info!("Pod {} runs: {:?}", p.name_any(), p.spec.containers);
}

Ok(())
Expand Down
4 changes: 2 additions & 2 deletions examples/dynamic_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ async fn main() -> anyhow::Result<()> {
let mut items = watcher(api, ListParams::default()).applied_objects().boxed();
while let Some(p) = items.try_next().await? {
if caps.scope == Scope::Cluster {
info!("saw {}", p.name());
info!("saw {}", p.name_any());
} else {
info!("saw {} in {}", p.name(), p.namespace().unwrap());
info!("saw {} in {}", p.name_any(), p.namespace().unwrap());
}
}
Ok(())
Expand Down
14 changes: 7 additions & 7 deletions examples/kubectl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ impl App {
match self.output {
OutputMode::Yaml => println!("{}", serde_yaml::to_string(&result)?),
OutputMode::Pretty => {
// Display style; size colums according to biggest name
let max_name = result.iter().map(|x| x.name().len() + 2).max().unwrap_or(63);
// Display style; size columns according to longest name
let max_name = result.iter().map(|x| x.name_any().len() + 2).max().unwrap_or(63);
println!("{0:<width$} {1:<20}", "NAME", "AGE", width = max_name);
for inst in result {
let age = format_creation_since(inst.creation_timestamp());
println!("{0:<width$} {1:<20}", inst.name(), age, width = max_name);
println!("{0:<width$} {1:<20}", inst.name_any(), age, width = max_name);
}
}
}
Expand Down Expand Up @@ -122,7 +122,7 @@ impl App {
println!("{0:<width$} {1:<20}", "NAME", "AGE", width = 63);
while let Some(inst) = stream.try_next().await? {
let age = format_creation_since(inst.creation_timestamp());
println!("{0:<width$} {1:<20}", inst.name(), age, width = 63);
println!("{0:<width$} {1:<20}", inst.name_any(), age, width = 63);
}
Ok(())
}
Expand All @@ -132,10 +132,10 @@ impl App {
let mut orig = api.get(n).await?;
orig.managed_fields_mut().clear(); // hide managed fields
let input = serde_yaml::to_string(&orig)?;
debug!("opening {} in {:?}", orig.name(), edit::get_editor());
debug!("opening {} in {:?}", orig.name_any(), edit::get_editor());
let edited = edit::edit(&input)?;
if edited != input {
info!("updating changed object {}", orig.name());
info!("updating changed object {}", orig.name_any());
let data: DynamicObject = serde_yaml::from_str(&edited)?;
// NB: simplified kubectl constructs a merge-patch of differences
api.replace(n, &Default::default(), &data).await?;
Expand All @@ -158,7 +158,7 @@ impl App {
} else {
bail!("cannot apply object without valid TypeMeta {:?}", obj);
};
let name = obj.name();
let name = obj.name_any();
if let Some((ar, caps)) = discovery.resolve_gvk(&gvk) {
let api = dynamic_api(ar, caps, client.clone(), &self.namespace, false);
trace!("Applying {}: \n{}", gvk.kind, serde_yaml::to_string(&obj)?);
Expand Down
6 changes: 3 additions & 3 deletions examples/multi_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ async fn main() -> anyhow::Result<()> {
}
while let Some(o) = combo_stream.try_next().await? {
match o {
Watched::Config(cm) => info!("Got configmap: {}", cm.name()),
Watched::Deploy(d) => info!("Got deployment: {}", d.name()),
Watched::Secret(s) => info!("Got secret: {}", s.name()),
Watched::Config(cm) => info!("Got configmap: {}", cm.name_any()),
Watched::Deploy(d) => info!("Got deployment: {}", d.name_any()),
Watched::Secret(s) => info!("Got secret: {}", s.name_any()),
}
}
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions examples/node_reflector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async fn main() -> anyhow::Result<()> {
// Periodically read our state in the background
tokio::spawn(async move {
loop {
let nodes = reader.state().iter().map(|r| r.name()).collect::<Vec<_>>();
let nodes = reader.state().iter().map(|r| r.name_any()).collect::<Vec<_>>();
info!("Current {} nodes: {:?}", nodes.len(), nodes);
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
Expand All @@ -32,7 +32,7 @@ async fn main() -> anyhow::Result<()> {
// Drain and log applied events from the reflector
let mut rfa = rf.applied_objects().boxed();
while let Some(event) = rfa.try_next().await? {
info!("saw {}", event.name());
info!("saw {}", event.name_any());
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion examples/node_watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async fn main() -> anyhow::Result<()> {

// A simple node problem detector
async fn check_for_node_failures(events: &Api<Event>, o: Node) -> anyhow::Result<()> {
let name = o.name();
let name = o.name_any();
// Nodes often modify a lot - only print broken nodes
if let Some(true) = o.spec.unwrap().unschedulable {
let failed = o
Expand Down
8 changes: 4 additions & 4 deletions examples/pod_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ async fn main() -> anyhow::Result<()> {
let pp = PostParams::default();
match pods.create(&pp, &p).await {
Ok(o) => {
let name = o.name();
assert_eq!(p.name(), name);
let name = o.name_any();
assert_eq!(p.name_any(), name);
info!("Created {}", name);
}
Err(kube::Error::Api(ae)) => assert_eq!(ae.code, 409), // if you skipped delete, for instance
Expand Down Expand Up @@ -69,13 +69,13 @@ async fn main() -> anyhow::Result<()> {

let lp = ListParams::default().fields(&format!("metadata.name={}", "blog")); // only want results for our pod
for p in pods.list(&lp).await? {
info!("Found Pod: {}", p.name());
info!("Found Pod: {}", p.name_any());
}

// Delete it
let dp = DeleteParams::default();
pods.delete("blog", &dp).await?.map_left(|pdel| {
assert_eq!(pdel.name(), "blog");
assert_eq!(pdel.name_any(), "blog");
info!("Deleting blog pod started: {:?}", pdel);
});

Expand Down
6 changes: 3 additions & 3 deletions examples/pod_attach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ async fn main() -> anyhow::Result<()> {
while let Some(status) = stream.try_next().await? {
match status {
WatchEvent::Added(o) => {
info!("Added {}", o.name());
info!("Added {}", o.name_any());
}
WatchEvent::Modified(o) => {
let s = o.status.as_ref().expect("status exists on pod");
if s.phase.clone().unwrap_or_default() == "Running" {
info!("Ready to attach to {}", o.name());
info!("Ready to attach to {}", o.name_any());
break;
}
}
Expand All @@ -65,7 +65,7 @@ async fn main() -> anyhow::Result<()> {
pods.delete("example", &DeleteParams::default())
.await?
.map_left(|pdel| {
assert_eq!(pdel.name(), "example");
assert_eq!(pdel.name_any(), "example");
});

Ok(())
Expand Down
6 changes: 3 additions & 3 deletions examples/pod_cp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ async fn main() -> anyhow::Result<()> {
while let Some(status) = stream.try_next().await? {
match status {
WatchEvent::Added(o) => {
info!("Added {}", o.name());
info!("Added {}", o.name_any());
}
WatchEvent::Modified(o) => {
let s = o.status.as_ref().expect("status exists on pod");
if s.phase.clone().unwrap_or_default() == "Running" {
info!("Ready to attach to {}", o.name());
info!("Ready to attach to {}", o.name_any());
break;
}
}
Expand Down Expand Up @@ -90,7 +90,7 @@ async fn main() -> anyhow::Result<()> {
pods.delete("example", &DeleteParams::default())
.await?
.map_left(|pdel| {
assert_eq!(pdel.name(), "example");
assert_eq!(pdel.name_any(), "example");
});

Ok(())
Expand Down
Loading

0 comments on commit 55bea0b

Please sign in to comment.