pub struct Api<K> { /* private fields */ }
runtime
only.Expand description
Implementations
sourceimpl<K> Api<K> where
K: Clone + DeserializeOwned + Debug,
impl<K> Api<K> where
K: Clone + DeserializeOwned + Debug,
PUSH/PUT/POST/GET abstractions
sourcepub async fn get(&'_ self, name: &'_ str) -> Result<K, Error>
This is supported on crate feature client
only.
pub async fn get(&'_ self, name: &'_ str) -> Result<K, Error>
client
only.Get a named resource
use kube::{Api, Client};
use k8s_openapi::api::core::v1::Pod;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::namespaced(client, "apps");
let p: Pod = pods.get("blog").await?;
Ok(())
}
Errors
This function assumes that the object is expected to always exist, and returns Error
if it does not.
Consider using Api::get_opt
if you need to handle missing objects.
sourcepub async fn get_opt(&'_ self, name: &'_ str) -> Result<Option<K>, Error>
This is supported on crate feature client
only.
pub async fn get_opt(&'_ self, name: &'_ str) -> Result<Option<K>, Error>
client
only.Get a named resource if it exists, returns None
if it doesn’t exist
use kube::{Api, Client};
use k8s_openapi::api::core::v1::Pod;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::namespaced(client, "apps");
if let Some(pod) = pods.get_opt("blog").await? {
// Pod was found
} else {
// Pod was not found
}
Ok(())
}
sourcepub async fn list(&'_ self, lp: &'_ ListParams) -> Result<ObjectList<K>, Error>
This is supported on crate feature client
only.
pub async fn list(&'_ self, lp: &'_ ListParams) -> Result<ObjectList<K>, Error>
client
only.Get a list of resources
You get use this to get everything, or a subset matching fields/labels, say:
use kube::{api::{Api, ListParams, ResourceExt}, Client};
use k8s_openapi::api::core::v1::Pod;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::namespaced(client, "apps");
let lp = ListParams::default().labels("app=blog"); // for this app only
for p in pods.list(&lp).await? {
println!("Found Pod: {}", p.name());
}
Ok(())
}
sourcepub async fn create(
&'_ self,
pp: &'_ PostParams,
data: &'_ K
) -> Result<K, Error> where
K: Serialize,
This is supported on crate feature client
only.
pub async fn create(
&'_ self,
pp: &'_ PostParams,
data: &'_ K
) -> Result<K, Error> where
K: Serialize,
client
only.Create a resource
This function requires a type that Serializes to K
, which can be:
- Raw string YAML
- easy to port from existing files
- error prone (run-time errors on typos due to failed serialize attempts)
- very error prone (can write invalid YAML)
- An instance of the struct itself
- easy to instantiate for CRDs (you define the struct)
- dense to instantiate for
k8s_openapi
types (due to many optionals) - compile-time safety
- but still possible to write invalid native types (validation at apiserver)
- [
serde_json::json!
] macro instantiated [serde_json::Value
]- Tradeoff between the two
- Easy partially filling of native
k8s_openapi
types (most fields optional) - Partial safety against runtime errors (at least you must write valid JSON)
sourcepub async fn delete(
&'_ self,
name: &'_ str,
dp: &'_ DeleteParams
) -> Result<Either<K, Status>, Error>
This is supported on crate feature client
only.
pub async fn delete(
&'_ self,
name: &'_ str,
dp: &'_ DeleteParams
) -> Result<Either<K, Status>, Error>
client
only.Delete a named resource
When you get a K
via Left
, your delete has started.
When you get a Status
via Right
, this should be a a 2XX style
confirmation that the object being gone.
4XX and 5XX status types are returned as an Err(kube_client::Error::Api)
.
use kube::{api::{Api, DeleteParams}, Client};
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1 as apiexts;
use apiexts::CustomResourceDefinition;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let crds: Api<CustomResourceDefinition> = Api::all(client);
crds.delete("foos.clux.dev", &DeleteParams::default()).await?
.map_left(|o| println!("Deleting CRD: {:?}", o.status))
.map_right(|s| println!("Deleted CRD: {:?}", s));
Ok(())
}
sourcepub async fn delete_collection(
&'_ self,
dp: &'_ DeleteParams,
lp: &'_ ListParams
) -> Result<Either<ObjectList<K>, Status>, Error>
This is supported on crate feature client
only.
pub async fn delete_collection(
&'_ self,
dp: &'_ DeleteParams,
lp: &'_ ListParams
) -> Result<Either<ObjectList<K>, Status>, Error>
client
only.Delete a collection of resources
When you get an ObjectList<K>
via Left
, your delete has started.
When you get a Status
via Right
, this should be a a 2XX style
confirmation that the object being gone.
4XX and 5XX status types are returned as an Err(kube_client::Error::Api)
.
use kube::{api::{Api, DeleteParams, ListParams, ResourceExt}, Client};
use k8s_openapi::api::core::v1::Pod;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::namespaced(client, "apps");
match pods.delete_collection(&DeleteParams::default(), &ListParams::default()).await? {
either::Left(list) => {
let names: Vec<_> = list.iter().map(ResourceExt::name).collect();
println!("Deleting collection of pods: {:?}", names);
},
either::Right(status) => {
println!("Deleted collection of pods: status={:?}", status);
}
}
Ok(())
}
sourcepub async fn patch<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
This is supported on crate feature client
only.
pub async fn patch<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
client
only.Patch a subset of a resource’s properties
Takes a Patch
along with PatchParams
for the call.
use kube::{api::{Api, PatchParams, Patch, Resource}, Client};
use k8s_openapi::api::core::v1::Pod;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let pods: Api<Pod> = Api::namespaced(client, "apps");
let patch = serde_json::json!({
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "blog"
},
"spec": {
"activeDeadlineSeconds": 5
}
});
let params = PatchParams::apply("myapp");
let patch = Patch::Apply(&patch);
let o_patched = pods.patch("blog", ¶ms, &patch).await?;
Ok(())
}
sourcepub async fn replace(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: &'_ K
) -> Result<K, Error> where
K: Serialize,
This is supported on crate feature client
only.
pub async fn replace(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: &'_ K
) -> Result<K, Error> where
K: Serialize,
client
only.Replace a resource entirely with a new one
This is used just like Api::create
, but with one additional instruction:
You must set metadata.resourceVersion
in the provided data because k8s
will not accept an update unless you actually knew what the last version was.
Thus, to use this function, you need to do a get
then a replace
with its result.
use kube::{api::{Api, PostParams, ResourceExt}, Client};
use k8s_openapi::api::batch::v1::Job;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let jobs: Api<Job> = Api::namespaced(client, "apps");
let j = jobs.get("baz").await?;
let j_new: Job = serde_json::from_value(serde_json::json!({
"apiVersion": "batch/v1",
"kind": "Job",
"metadata": {
"name": "baz",
"resourceVersion": j.resource_version(),
},
"spec": {
"template": {
"metadata": {
"name": "empty-job-pod"
},
"spec": {
"containers": [{
"name": "empty",
"image": "alpine:latest"
}],
"restartPolicy": "Never",
}
}
}
}))?;
jobs.replace("baz", &PostParams::default(), &j_new).await?;
Ok(())
}
Consider mutating the result of api.get
rather than recreating it.
sourcepub async fn watch(
&'_ self,
lp: &'_ ListParams,
version: &'_ str
) -> Result<impl Stream<Item = Result<WatchEvent<K>, Error>>, Error>
This is supported on crate feature client
only.
pub async fn watch(
&'_ self,
lp: &'_ ListParams,
version: &'_ str
) -> Result<impl Stream<Item = Result<WatchEvent<K>, Error>>, Error>
client
only.Watch a list of resources
This returns a future that awaits the initial response,
then you can stream the remaining buffered WatchEvent
objects.
Note that a watch
call can terminate for many reasons (even before the specified
ListParams::timeout
is triggered), and will have to be re-issued
with the last seen resource version when or if it closes.
Consider using a managed watcher
to deal with automatic re-watches and error cases.
use kube::{api::{Api, ListParams, ResourceExt, WatchEvent}, Client};
use k8s_openapi::api::batch::v1::Job;
use futures::{StreamExt, TryStreamExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let jobs: Api<Job> = Api::namespaced(client, "apps");
let lp = ListParams::default()
.fields("metadata.name=my_job")
.timeout(20); // upper bound of how long we watch for
let mut stream = jobs.watch(&lp, "0").await?.boxed();
while let Some(status) = stream.try_next().await? {
match status {
WatchEvent::Added(s) => println!("Added {}", s.name()),
WatchEvent::Modified(s) => println!("Modified: {}", s.name()),
WatchEvent::Deleted(s) => println!("Deleted {}", s.name()),
WatchEvent::Bookmark(s) => {},
WatchEvent::Error(s) => println!("{}", s),
}
}
Ok(())
}
sourceimpl<K> Api<K> where
K: Clone + DeserializeOwned,
impl<K> Api<K> where
K: Clone + DeserializeOwned,
Methods for scale subresource.
sourcepub async fn get_scale(&'_ self, name: &'_ str) -> Result<Scale, Error>
This is supported on crate feature client
only.
pub async fn get_scale(&'_ self, name: &'_ str) -> Result<Scale, Error>
client
only.Fetch the scale subresource
sourcepub async fn patch_scale<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<Scale, Error> where
P: Serialize + Debug,
This is supported on crate feature client
only.
pub async fn patch_scale<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<Scale, Error> where
P: Serialize + Debug,
client
only.Update the scale subresource
sourcepub async fn replace_scale(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<Scale, Error>
This is supported on crate feature client
only.
pub async fn replace_scale(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<Scale, Error>
client
only.Replace the scale subresource
sourceimpl<K> Api<K> where
K: Clone + DeserializeOwned + Debug,
impl<K> Api<K> where
K: Clone + DeserializeOwned + Debug,
Arbitrary subresources
sourcepub async fn get_subresource(
&'_ self,
subresource_name: &'_ str,
name: &'_ str
) -> Result<K, Error>
This is supported on crate feature client
only.
pub async fn get_subresource(
&'_ self,
subresource_name: &'_ str,
name: &'_ str
) -> Result<K, Error>
client
only.Display one or many sub-resources.
sourcepub async fn patch_subresource<P>(
&'_ self,
subresource_name: &'_ str,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
This is supported on crate feature client
only.
pub async fn patch_subresource<P>(
&'_ self,
subresource_name: &'_ str,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
client
only.Patch an instance of the subresource
sourcepub async fn replace_subresource(
&'_ self,
subresource_name: &'_ str,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<K, Error>
This is supported on crate feature client
only.
pub async fn replace_subresource(
&'_ self,
subresource_name: &'_ str,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<K, Error>
client
only.Replace an instance of the subresource
sourceimpl<K> Api<K> where
K: DeserializeOwned,
impl<K> Api<K> where
K: DeserializeOwned,
Methods for status subresource.
sourcepub async fn get_status(&'_ self, name: &'_ str) -> Result<K, Error>
This is supported on crate feature client
only.
pub async fn get_status(&'_ self, name: &'_ str) -> Result<K, Error>
client
only.Get the named resource with a status subresource
This actually returns the whole K, with metadata, and spec.
sourcepub async fn patch_status<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
This is supported on crate feature client
only.
pub async fn patch_status<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<K, Error> where
P: Serialize + Debug,
client
only.Patch fields on the status object
NB: Requires that the resource has a status subresource.
use kube::{api::{Api, PatchParams, Patch}, Client};
use k8s_openapi::api::batch::v1::Job;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let jobs: Api<Job> = Api::namespaced(client, "apps");
let mut j = jobs.get("baz").await?;
let pp = PatchParams::default(); // json merge patch
let data = serde_json::json!({
"status": {
"succeeded": 2
}
});
let o = jobs.patch_status("baz", &pp, &Patch::Merge(data)).await?;
assert_eq!(o.status.unwrap().succeeded, Some(2));
Ok(())
}
sourcepub async fn replace_status(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<K, Error>
This is supported on crate feature client
only.
pub async fn replace_status(
&'_ self,
name: &'_ str,
pp: &'_ PostParams,
data: Vec<u8, Global>
) -> Result<K, Error>
client
only.Replace every field on the status object
This works similarly to the Api::replace
method, but .spec
is ignored.
You can leave out the .spec
entirely from the serialized output.
use kube::{api::{Api, PostParams}, Client};
use k8s_openapi::api::batch::v1::{Job, JobStatus};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::try_default().await?;
let jobs: Api<Job> = Api::namespaced(client, "apps");
let mut o = jobs.get_status("baz").await?; // retrieve partial object
o.status = Some(JobStatus::default()); // update the job part
let pp = PostParams::default();
let o = jobs.replace_status("baz", &pp, serde_json::to_vec(&o)?).await?;
Ok(())
}
sourceimpl<K> Api<K> where
K: DeserializeOwned + Log,
impl<K> Api<K> where
K: DeserializeOwned + Log,
sourceimpl<K> Api<K> where
K: DeserializeOwned + Evict,
impl<K> Api<K> where
K: DeserializeOwned + Evict,
sourceimpl<K> Api<K> where
K: Restart + Resource + DeserializeOwned,
impl<K> Api<K> where
K: Restart + Resource + DeserializeOwned,
sourceimpl<K> Api<K> where
K: Resource + Clone + DeserializeOwned + Debug,
impl<K> Api<K> where
K: Resource + Clone + DeserializeOwned + Debug,
sourcepub async fn entry(&'a self, name: &'a str) -> Result<Entry<'a, K>, Error>
This is supported on crate feature client
only.
pub async fn entry(&'a self, name: &'a str) -> Result<Entry<'a, K>, Error>
client
only.Gets a given object’s “slot” on the Kubernetes API, designed for “get-or-create” and “get-and-modify” patterns
This is similar to HashMap::entry
, but the Entry
must be OccupiedEntry::commit
ed for changes to be persisted.
Usage
let kube = kube::Client::try_default().await?;
let cms = kube::Api::<ConfigMap>::namespaced(kube, "default");
cms
// Try to get `entry-example` if it exists
.entry("entry-example").await?
// Modify object if it already exists
.and_modify(|cm| {
cm.data
.get_or_insert_with(BTreeMap::default)
.insert("already-exists".to_string(), "true".to_string());
})
// Provide a default object if it does not exist
.or_insert(|| ConfigMap::default())
// Modify the object unconditionally now that we have provided a default value
.and_modify(|cm| {
cm.data
.get_or_insert_with(BTreeMap::default)
.insert("modified".to_string(), "true".to_string());
})
// Save changes
.commit().await?;
sourceimpl<K> Api<K> where
K: Resource,
impl<K> Api<K> where
K: Resource,
Api constructors for Resource implementors with custom DynamicTypes
This generally means resources created via DynamicObject
.
sourcepub fn all_with(
client: Client,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
This is supported on crate feature client
only.
pub fn all_with(
client: Client,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
client
only.Cluster level resources, or resources viewed across all namespaces
This function accepts K::DynamicType
so it can be used with dynamic resources.
sourcepub fn namespaced_with(
client: Client,
ns: &str,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
This is supported on crate feature client
only.
pub fn namespaced_with(
client: Client,
ns: &str,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
client
only.Namespaced resource within a given namespace
This function accepts K::DynamicType
so it can be used with dynamic resources.
sourcepub fn default_namespaced_with(
client: Client,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
This is supported on crate feature client
only.
pub fn default_namespaced_with(
client: Client,
dyntype: &<K as Resource>::DynamicType
) -> Api<K>
client
only.Namespaced resource within the default namespace
This function accepts K::DynamicType
so it can be used with dynamic resources.
Unless configured explicitly, the default namespace is either “default” out of cluster, or the service account’s namespace in cluster.
sourcepub fn into_client(self) -> Client
This is supported on crate feature client
only.
pub fn into_client(self) -> Client
client
only.Consume self and return the Client
sourcepub fn resource_url(&self) -> &str
This is supported on crate feature client
only.
pub fn resource_url(&self) -> &str
client
only.Return a reference to the current resource url path
sourceimpl<K> Api<K> where
K: Resource,
<K as Resource>::DynamicType: Default,
impl<K> Api<K> where
K: Resource,
<K as Resource>::DynamicType: Default,
Api constructors for Resource implementors with Default DynamicTypes
This generally means structs implementing k8s_openapi::Resource
.
sourcepub fn all(client: Client) -> Api<K>
This is supported on crate feature client
only.
pub fn all(client: Client) -> Api<K>
client
only.Cluster level resources, or resources viewed across all namespaces
sourcepub fn namespaced(client: Client, ns: &str) -> Api<K>
This is supported on crate feature client
only.
pub fn namespaced(client: Client, ns: &str) -> Api<K>
client
only.Namespaced resource within a given namespace
sourcepub fn default_namespaced(client: Client) -> Api<K>
This is supported on crate feature client
only.
pub fn default_namespaced(client: Client) -> Api<K>
client
only.Namespaced resource within the default namespace
Unless configured explicitly, the default namespace is either “default” out of cluster, or the service account’s namespace in cluster.
sourceimpl Api<CertificateSigningRequest>
impl Api<CertificateSigningRequest>
sourcepub async fn patch_approval<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<CertificateSigningRequest, Error> where
P: Serialize,
This is supported on crate feature client
only.
pub async fn patch_approval<P>(
&'_ self,
name: &'_ str,
pp: &'_ PatchParams,
patch: &'_ Patch<P>
) -> Result<CertificateSigningRequest, Error> where
P: Serialize,
client
only.Partially update approval of the specified CertificateSigningRequest.
sourcepub async fn get_approval(
&'_ self,
name: &'_ str
) -> Result<CertificateSigningRequest, Error>
This is supported on crate feature client
only.
pub async fn get_approval(
&'_ self,
name: &'_ str
) -> Result<CertificateSigningRequest, Error>
client
only.Get the CertificateSigningRequest. May differ from get(name)
Trait Implementations
Auto Trait Implementations
impl<K> !RefUnwindSafe for Api<K>
impl<K> Send for Api<K>
impl<K> Sync for Api<K>
impl<K> Unpin for Api<K>
impl<K> !UnwindSafe for Api<K>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more