kube_client

Struct Api

Source
pub struct Api<K> { /* private fields */ }
Available on crate feature client only.
Expand description

The generic Api abstraction

This abstracts over a Request and a type K so that we get automatic serialization/deserialization on the api calls implemented by the dynamic Resource.

Implementations§

Source§

impl<K> Api<K>

PUSH/PUT/POST/GET abstractions

Source

pub async fn get(&self, name: &str) -> Result<K>

Get a named resource

use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let p: Pod = pods.get("blog").await?;
§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.

Source

pub async fn get_metadata(&self, name: &str) -> Result<PartialObjectMeta<K>>

Get only the metadata for a named resource as PartialObjectMeta

use kube::{Api, core::PartialObjectMeta};
use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let p: PartialObjectMeta<Pod> = pods.get_metadata("blog").await?;

Note that the type may be converted to ObjectMeta through the usual conversion traits.

§Errors

This function assumes that the object is expected to always exist, and returns Error if it does not. Consider using Api::get_metadata_opt if you need to handle missing objects.

Source

pub async fn get_with(&self, name: &str, gp: &GetParams) -> Result<K>

Get a named resource with an explicit resourceVersion

This function allows the caller to pass in a GetParams type containing a resourceVersion to a Get call. For example

use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let p: Pod = pods.get_with("blog", &GetParams::any()).await?;
§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.

Source

pub async fn get_metadata_with( &self, name: &str, gp: &GetParams, ) -> Result<PartialObjectMeta<K>>

Get the metadata of an object using an explicit resourceVersion

This function allows the caller to pass in a GetParams type containing a resourceVersion to a Get call. For example

use kube::{Api, api::GetParams, core::PartialObjectMeta};
use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let p: PartialObjectMeta<Pod> = pods.get_metadata_with("blog", &GetParams::any()).await?;

Note that the type may be converted to ObjectMeta through the usual conversion traits.

§Errors

This function assumes that the object is expected to always exist, and returns Error if it does not. Consider using Api::get_metadata_opt if you need to handle missing objects.

Source

pub async fn get_opt(&self, name: &str) -> Result<Option<K>>

Get a named resource if it exists, returns None if it doesn’t exist

use k8s_openapi::api::core::v1::Pod;

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
}
Source

pub async fn get_metadata_opt( &self, name: &str, ) -> Result<Option<PartialObjectMeta<K>>>

Get Metadata for a named resource if it exists, returns None if it doesn’t exit

use k8s_openapi::api::core::v1::Pod;
let pods: Api<Pod> = Api::namespaced(client, "apps");
if let Some(pod) = pods.get_metadata_opt("blog").await? {
    // Pod was found
} else {
    // Pod was not found
}

Note that PartialObjectMeta embeds the raw ObjectMeta.

Source

pub async fn list(&self, lp: &ListParams) -> Result<ObjectList<K>>

Get a list of resources

You use this to get everything, or a subset matching fields/labels, say:

use kube::api::{Api, ListParams, ResourceExt};
use k8s_openapi::api::core::v1::Pod;

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_any());
}
Source

pub async fn list_metadata( &self, lp: &ListParams, ) -> Result<ObjectList<PartialObjectMeta<K>>>

Get a list of resources that contains only their metadata as

Similar to list, you use this to get everything, or a subset matching fields/labels. For example

use kube::api::{Api, ListParams, ResourceExt};
use kube::core::{ObjectMeta, ObjectList, PartialObjectMeta};
use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let lp = ListParams::default().labels("app=blog"); // for this app only
let list: ObjectList<PartialObjectMeta<Pod>> = pods.list_metadata(&lp).await?;
for p in list {
    println!("Found Pod: {}", p.name_any());
}
Source

pub async fn create(&self, pp: &PostParams, data: &K) -> Result<K>
where K: Serialize,

Create a resource

This function requires a type that Serializes to K, which can be:

  1. 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)
  1. 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)
  2. 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)

Note that this method cannot write to the status object (when it exists) of a resource. To set status objects please see Api::replace_status or Api::patch_status.

Source

pub async fn delete( &self, name: &str, dp: &DeleteParams, ) -> Result<Either<K, Status>>

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};
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1 as apiexts;
use apiexts::CustomResourceDefinition;
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));
Source

pub async fn delete_collection( &self, dp: &DeleteParams, lp: &ListParams, ) -> Result<Either<ObjectList<K>, Status>>

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};
use k8s_openapi::api::core::v1::Pod;

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_any).collect();
        println!("Deleting collection of pods: {:?}", names);
    },
    either::Right(status) => {
        println!("Deleted collection of pods: status={:?}", status);
    }
}
Source

pub async fn patch<P: Serialize + Debug>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<K>

Patch a subset of a resource’s properties

Takes a Patch along with PatchParams for the call.

use kube::api::{Api, PatchParams, Patch, Resource};
use k8s_openapi::api::core::v1::Pod;

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", &params, &patch).await?;

Note that this method cannot write to the status object (when it exists) of a resource. To set status objects please see Api::replace_status or Api::patch_status.

Source

pub async fn patch_metadata<P: Serialize + Debug>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<PartialObjectMeta<K>>

Patch a metadata subset of a resource’s properties from PartialObjectMeta

Takes a Patch along with PatchParams for the call. Patches can be constructed raw using serde_json::json! or from ObjectMeta via PartialObjectMetaExt.

use kube::api::{Api, PatchParams, Patch, Resource};
use kube::core::{PartialObjectMetaExt, ObjectMeta};
use k8s_openapi::api::core::v1::Pod;

let pods: Api<Pod> = Api::namespaced(client, "apps");
let metadata = ObjectMeta {
    labels: Some([("key".to_string(), "value".to_string())].into()),
    ..Default::default()
}.into_request_partial::<Pod>();

let params = PatchParams::apply("myapp");
let o_patched = pods.patch_metadata("blog", &params, &Patch::Apply(&metadata)).await?;
println!("Patched {}", o_patched.metadata.name.unwrap());
§Warnings

The TypeMeta (apiVersion + kind) of a patch request (required for apply patches) must match the underlying type that is being patched (e.g. “v1” + “Pod”). The returned TypeMeta will always be {“meta.k8s.io/v1”, “PartialObjectMetadata”}. These constraints are encoded into PartialObjectMetaExt.

This method can write to non-metadata fields such as spec if included in the patch.

Source

pub async fn replace(&self, name: &str, pp: &PostParams, data: &K) -> Result<K>
where K: Serialize,

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};
use k8s_openapi::api::batch::v1::Job;

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?;

Consider mutating the result of api.get rather than recreating it.

Note that this method cannot write to the status object (when it exists) of a resource. To set status objects please see Api::replace_status or Api::patch_status.

Source

pub async fn watch( &self, wp: &WatchParams, version: &str, ) -> Result<impl Stream<Item = Result<WatchEvent<K>>>>

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 WatchParams::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, WatchParams, ResourceExt, WatchEvent};
use k8s_openapi::api::batch::v1::Job;
use futures::{StreamExt, TryStreamExt};

let jobs: Api<Job> = Api::namespaced(client, "apps");
let lp = WatchParams::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_any()),
        WatchEvent::Modified(s) => println!("Modified: {}", s.name_any()),
        WatchEvent::Deleted(s) => println!("Deleted {}", s.name_any()),
        WatchEvent::Bookmark(s) => {},
        WatchEvent::Error(s) => println!("{}", s),
    }
}
Source

pub async fn watch_metadata( &self, wp: &WatchParams, version: &str, ) -> Result<impl Stream<Item = Result<WatchEvent<PartialObjectMeta<K>>>>>

Watch a list of metadata for a given resources

This returns a future that awaits the initial response, then you can stream the remaining buffered WatchEvent objects.

Note that a watch_metadata call can terminate for many reasons (even before the specified WatchParams::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 metadata_watcher to deal with automatic re-watches and error cases.

use kube::api::{Api, WatchParams, ResourceExt, WatchEvent};
use k8s_openapi::api::batch::v1::Job;
use futures::{StreamExt, TryStreamExt};

let jobs: Api<Job> = Api::namespaced(client, "apps");

let lp = WatchParams::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.metadata.name.unwrap()),
        WatchEvent::Modified(s) => println!("Modified: {}", s.metadata.name.unwrap()),
        WatchEvent::Deleted(s) => println!("Deleted {}", s.metadata.name.unwrap()),
        WatchEvent::Bookmark(s) => {},
        WatchEvent::Error(s) => println!("{}", s),
    }
}
Source§

impl<K> Api<K>

Methods for scale subresource.

Source

pub async fn get_scale(&self, name: &str) -> Result<Scale>

Fetch the scale subresource

Source

pub async fn patch_scale<P: Serialize + Debug>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<Scale>

Update the scale subresource

Source

pub async fn replace_scale( &self, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<Scale>

Replace the scale subresource

Source§

impl<K> Api<K>

Arbitrary subresources

Source

pub async fn get_subresource( &self, subresource_name: &str, name: &str, ) -> Result<K>

Display one or many sub-resources.

Source

pub async fn create_subresource<T>( &self, subresource_name: &str, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<T>

Create an instance of the subresource

Source

pub async fn patch_subresource<P: Serialize + Debug>( &self, subresource_name: &str, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<K>

Patch an instance of the subresource

Source

pub async fn replace_subresource( &self, subresource_name: &str, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<K>

Replace an instance of the subresource

Source§

impl<K> Api<K>

Source

pub async fn replace_ephemeral_containers( &self, name: &str, pp: &PostParams, data: &K, ) -> Result<K>
where K: Serialize,

Replace the ephemeral containers sub resource entirely.

This functions in the same way as Api::replace except only .spec.ephemeralcontainers is replaced, everything else is ignored.

Note that ephemeral containers may not be changed or removed once attached to a pod.

You way want to patch the underlying resource to gain access to the main container process, see the documentation for sharedProcessNamespace.

See the Kubernetes documentation for more details.

Api::patch_ephemeral_containers may be more ergonomic, as you can will avoid having to first fetch the existing subresources with an approriate merge strategy, see the examples for more details.

Example of using replace_ephemeral_containers:

use k8s_openapi::api::core::v1::Pod;
use kube::{Api, api::PostParams};
let pods: Api<Pod> = Api::namespaced(client, "apps");
let pp = PostParams::default();

// Get pod object with ephemeral containers.
let mut mypod = pods.get_ephemeral_containers("mypod").await?;

// If there were existing ephemeral containers, we would have to append
// new containers to the list before calling replace_ephemeral_containers.
assert_eq!(mypod.spec.as_mut().unwrap().ephemeral_containers, None);

// Add an ephemeral container to the pod object.
mypod.spec.as_mut().unwrap().ephemeral_containers = Some(serde_json::from_value(serde_json::json!([
   {
       "name": "myephemeralcontainer",
       "image": "busybox:1.34.1",
       "command": ["sh", "-c", "sleep 20"],
   },
]))?);

pods.replace_ephemeral_containers("mypod", &pp, &mypod).await?;
Source

pub async fn patch_ephemeral_containers<P: Serialize>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<K>

Patch the ephemeral containers sub resource

Any partial object containing the ephemeral containers sub resource is valid as long as the complete structure for the object is present, as shown below.

You way want to patch the underlying resource to gain access to the main container process, see the docs for sharedProcessNamespace.

Ephemeral containers may not be changed or removed once attached to a pod. Therefore if the chosen merge strategy overwrites the existing ephemeral containers, you will have to fetch the existing ephemeral containers first. In order to append your new ephemeral containers to the existing list before patching. See some examples and discussion related to merge strategies in Kubernetes here. The example below uses a strategic merge patch which does not require

See the Kubernetes documentation for more information about ephemeral containers.

Example of using patch_ephemeral_containers:

use kube::api::{Api, PatchParams, Patch};
use k8s_openapi::api::core::v1::Pod;
let pods: Api<Pod> = Api::namespaced(client, "apps");
let pp = PatchParams::default(); // stratetgic merge patch

// Note that the strategic merge patch will concatenate the
// lists of ephemeral containers so we avoid having to fetch the
// current list and append to it manually.
let patch = serde_json::json!({
   "spec":{
   "ephemeralContainers": [
   {
       "name": "myephemeralcontainer",
       "image": "busybox:1.34.1",
       "command": ["sh", "-c", "sleep 20"],
   },
   ]
}});

pods.patch_ephemeral_containers("mypod", &pp, &Patch::Strategic(patch)).await?;
Source

pub async fn get_ephemeral_containers(&self, name: &str) -> Result<K>

Get the named resource with the ephemeral containers subresource.

This returns the whole K, with metadata and spec.

Source§

impl<K> Api<K>

Methods for status subresource.

Source

pub async fn get_status(&self, name: &str) -> Result<K>

Get the named resource with a status subresource

This actually returns the whole K, with metadata, and spec.

Source

pub async fn patch_status<P: Serialize + Debug>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<K>

Patch fields on the status object

NB: Requires that the resource has a status subresource.

use kube::api::{Api, PatchParams, Patch};
use k8s_openapi::api::batch::v1::Job;
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));
Source

pub async fn replace_status( &self, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<K>

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};
use k8s_openapi::api::batch::v1::{Job, JobStatus};
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?;
Source§

impl<K> Api<K>
where K: DeserializeOwned + Log,

Source

pub async fn logs(&self, name: &str, lp: &LogParams) -> Result<String>

Fetch logs as a string

Source

pub async fn log_stream( &self, name: &str, lp: &LogParams, ) -> Result<impl AsyncBufRead>

Stream the logs via AsyncBufRead.

Log stream can be processsed using AsyncReadExt and AsyncBufReadExt.

§Example
use futures::{AsyncBufReadExt, TryStreamExt};

let pods: Api<Pod> = Api::default_namespaced(client);
let mut logs = pods
    .log_stream("my-pod", &LogParams::default()).await?
    .lines();

while let Some(line) = logs.try_next().await? {
    println!("{}", line);
}
Source§

impl<K> Api<K>

Source

pub async fn evict(&self, name: &str, ep: &EvictParams) -> Result<Status>

Create an eviction

Source§

impl<K> Api<K>

Source

pub async fn attach( &self, name: &str, ap: &AttachParams, ) -> Result<AttachedProcess>

Available on crate feature ws only.

Attach to pod

Source§

impl<K> Api<K>

Source

pub async fn exec<I, T>( &self, name: &str, command: I, ap: &AttachParams, ) -> Result<AttachedProcess>
where I: IntoIterator<Item = T> + Debug, T: Into<String>,

Available on crate feature ws only.

Execute a command in a pod

Source§

impl<K> Api<K>

Source

pub async fn portforward( &self, name: &str, ports: &[u16], ) -> Result<Portforwarder>

Forward ports of a pod

Source§

impl Api<CertificateSigningRequest>

Source

pub async fn patch_approval<P: Serialize>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<CertificateSigningRequest>

Partially update approval of the specified CertificateSigningRequest.

Source

pub async fn get_approval( &self, name: &str, ) -> Result<CertificateSigningRequest>

Get the CertificateSigningRequest. May differ from get(name)

Source§

impl<K> Api<K>

Source

pub async fn restart(&self, name: &str) -> Result<K>

Trigger a restart of a Resource.

Source§

impl Api<Node>

Source

pub async fn cordon(&self, name: &str) -> Result<Node>

Cordon a Node.

Source

pub async fn uncordon(&self, name: &str) -> Result<Node>

Uncordon a Node.

Source§

impl Api<ServiceAccount>

Source

pub async fn create_token_request( &self, name: &str, pp: &PostParams, token_request: &TokenRequest, ) -> Result<TokenRequest>

Create a TokenRequest of a ServiceAccount

Source§

impl<K: Resource + Clone + DeserializeOwned + Debug> Api<K>

Source

pub async fn entry<'a>(&'a self, name: &'a str) -> Result<Entry<'a, K>>

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::commited 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(&kube::api::PostParams::default()).await?;
Source§

impl<K: Resource> Api<K>

Api constructors for Resource implementors with custom DynamicTypes

This generally means resources created via DynamicObject.

Source

pub fn all_with(client: Client, dyntype: &K::DynamicType) -> Self

Cluster level resources, or resources viewed across all namespaces

This function accepts K::DynamicType so it can be used with dynamic resources.

§Warning

This variant can only list and watch namespaced resources and is commonly used with a watcher. If you need to create/patch/replace/get on a namespaced resource, you need a separate Api::namespaced.

Source

pub fn namespaced_with( client: Client, ns: &str, dyntype: &K::DynamicType, ) -> Self
where K: Resource<Scope = DynamicResourceScope>,

Namespaced resource within a given namespace

This function accepts K::DynamicType so it can be used with dynamic resources.

Source

pub fn default_namespaced_with(client: Client, dyntype: &K::DynamicType) -> Self
where K: Resource<Scope = DynamicResourceScope>,

Namespaced resource within the default namespace

This function accepts K::DynamicType so it can be used with dynamic resources.

The namespace is either configured on context in the kubeconfig or falls back to default when running locally, and it’s using the service account’s namespace when deployed in-cluster.

Source

pub fn into_client(self) -> Client

Consume self and return the Client

Source

pub fn resource_url(&self) -> &str

Return a reference to the current resource url path

Source§

impl<K: Resource> Api<K>
where <K as Resource>::DynamicType: Default,

Api constructors for Resource implementors with Default DynamicTypes

This generally means structs implementing k8s_openapi::Resource.

Source

pub fn all(client: Client) -> Self

Cluster level resources, or resources viewed across all namespaces

Namespace scoped resource allowing querying across all namespaces:

use k8s_openapi::api::core::v1::Pod;
let api: Api<Pod> = Api::all(client);

Cluster scoped resources also use this entrypoint:

use k8s_openapi::api::core::v1::Node;
let api: Api<Node> = Api::all(client);
§Warning

This variant can only list and watch namespaced resources and is commonly used with a watcher. If you need to create/patch/replace/get on a namespaced resource, you need a separate Api::namespaced.

Source

pub fn namespaced(client: Client, ns: &str) -> Self
where K: Resource<Scope = NamespaceResourceScope>,

Namespaced resource within a given namespace

use k8s_openapi::api::core::v1::Pod;
let api: Api<Pod> = Api::namespaced(client, "default");

This will ONLY work on namespaced resources as set by Scope:

use k8s_openapi::api::core::v1::Node;
let api: Api<Node> = Api::namespaced(client, "default"); // resource not namespaced!

For dynamic type information, use Api::namespaced_with variants.

Source

pub fn default_namespaced(client: Client) -> Self
where K: Resource<Scope = NamespaceResourceScope>,

Namespaced resource within the default namespace

The namespace is either configured on context in the kubeconfig or falls back to default when running locally, and it’s using the service account’s namespace when deployed in-cluster.

use k8s_openapi::api::core::v1::Pod;
let api: Api<Pod> = Api::default_namespaced(client);

This will ONLY work on namespaced resources as set by Scope:

use k8s_openapi::api::core::v1::Node;
let api: Api<Node> = Api::default_namespaced(client); // resource not namespaced!

Trait Implementations§

Source§

impl<K: Clone> Clone for Api<K>

Source§

fn clone(&self) -> Api<K>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K> Debug for Api<K>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K> From<Api<K>> for Client

Source§

fn from(api: Api<K>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<K> Freeze for Api<K>

§

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§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T