pub struct Client { /* private fields */ }
client
only.Expand description
Client for connecting with a Kubernetes cluster.
The easiest way to instantiate the client is either by
inferring the configuration from the environment using
Client::try_default
or with an existing Config
using Client::try_from
.
Implementations§
source§impl Client
impl Client
Generic client extensions for the unstable-client
feature
These methods allow users to query across a wide-array of resources without needing
to explicitly create an Api
for each one of them.
§Usage
- Create a
Client
- Specify the
scope
you are querying at viaCluster
orNamespace
as args - Specify the resource type you are using for serialization (e.g. a top level k8s-openapi type)
§Example
let lp = ListParams::default();
// List at Cluster level for Pod resource:
for pod in client.list::<Pod>(&lp, &Cluster).await? {
println!("Found pod {} in {}", pod.name_any(), pod.namespace().unwrap());
}
// Namespaced Get for Service resource:
let svc = client.get::<Service>("kubernetes", &Namespace::from("default")).await?;
assert_eq!(svc.name_unchecked(), "kubernetes");
sourcepub async fn get<K>(&self, name: &str, scope: &impl ObjectUrl<K>) -> Result<K>where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
Available on crate feature unstable-client
only.
pub async fn get<K>(&self, name: &str, scope: &impl ObjectUrl<K>) -> Result<K>where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
unstable-client
only.Get a single instance of a Resource
implementing type K
at the specified scope.
let cr = client.get::<ClusterRole>("cluster-admin", &Cluster).await?;
assert_eq!(cr.name_unchecked(), "cluster-admin");
let svc = client.get::<Service>("kubernetes", &Namespace::from("default")).await?;
assert_eq!(svc.name_unchecked(), "kubernetes");
sourcepub async fn fetch<K>(&self, reference: &impl ObjectRef<K>) -> Result<K>
Available on crate feature unstable-client
only.
pub async fn fetch<K>(&self, reference: &impl ObjectRef<K>) -> Result<K>
unstable-client
only.Fetch a single instance of a Resource
from a provided object reference.
// cluster scoped
let cr: ClusterRole = todo!();
let cr: ClusterRole = client.fetch(&cr.object_ref(&())).await?;
assert_eq!(cr.name_unchecked(), "cluster-admin");
// namespace scoped
let svc: Service = todo!();
let svc: Service = client.fetch(&svc.object_ref(&())).await?;
assert_eq!(svc.name_unchecked(), "kubernetes");
// Fetch an owner of the resource
let pod: Pod = todo!();
let owner = pod
.owner_references()
.to_vec()
.into_iter()
.find(|r| r.kind == Node::kind(&()))
.ok_or("Not Found")?;
let node: Node = client.fetch(&owner).await?;
// Namespace scoped objects require namespace
let pod: Pod = client.fetch(&owner.within("ns".to_string())).await?;
// Fetch dynamic object to resolve type later
let dynamic: DynamicObject = client.fetch(&owner.within("ns".to_string())).await?;
// Fetch using local object reference
let secret_ref = pod
.spec
.unwrap_or_default()
.image_pull_secrets
.unwrap_or_default()
.get(0)
.unwrap_or(&LocalObjectReference{name: "pull_secret".into()});
let secret: Secret = client.fetch(&secret_ref.within(pod.namespace())).await?;
sourcepub async fn list<K>(
&self,
lp: &ListParams,
scope: &impl CollectionUrl<K>,
) -> Result<ObjectList<K>>where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
Available on crate feature unstable-client
only.
pub async fn list<K>(
&self,
lp: &ListParams,
scope: &impl CollectionUrl<K>,
) -> Result<ObjectList<K>>where
K: Resource + Serialize + DeserializeOwned + Clone + Debug,
<K as Resource>::DynamicType: Default,
unstable-client
only.List instances of a Resource
implementing type K
at the specified scope.
let lp = ListParams::default();
for pod in client.list::<Pod>(&lp, &Cluster).await? {
println!("Found pod {} in {}", pod.name_any(), pod.namespace().unwrap());
}
for svc in client.list::<Service>(&lp, &Namespace::from("default")).await? {
println!("Found service {}", svc.name_any());
}
source§impl Client
impl Client
Constructors and low-level api interfaces.
Most users only need Client::try_default
or Client::new
from this block.
The many various lower level interfaces here are for more advanced use-cases with specific requirements.
sourcepub fn new<S, B, T>(service: S, default_namespace: T) -> Self
pub fn new<S, B, T>(service: S, default_namespace: T) -> Self
Create a Client
using a custom Service
stack.
ConfigExt
provides extensions for
building a custom stack.
To create with the default stack with a Config
, use
Client::try_from
.
To create with the default stack with an inferred Config
, use
Client::try_default
.
§Example
use kube::{client::ConfigExt, Client, Config};
use tower::{BoxError, ServiceBuilder};
use hyper_util::rt::TokioExecutor;
let config = Config::infer().await?;
let service = ServiceBuilder::new()
.layer(config.base_uri_layer())
.option_layer(config.auth_layer()?)
.map_err(BoxError::from)
.service(hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build_http());
let client = Client::new(service, config.default_namespace);
sourcepub async fn try_default() -> Result<Self>
pub async fn try_default() -> Result<Self>
Create and initialize a Client
using the inferred configuration.
Will use Config::infer
which attempts to load the local kubeconfig first,
and then if that fails, trying the in-cluster environment variables.
Will fail if neither configuration could be loaded.
let client = Client::try_default().await?;
If you already have a Config
then use Client::try_from
instead.
sourcepub fn default_namespace(&self) -> &str
pub fn default_namespace(&self) -> &str
Get the default namespace for the client
The namespace is either configured on context
in the kubeconfig,
falls back to default
when running locally,
or uses the service account’s namespace when deployed in-cluster.
sourcepub async fn send(&self, request: Request<Body>) -> Result<Response<Body>>
pub async fn send(&self, request: Request<Body>) -> Result<Response<Body>>
Perform a raw HTTP request against the API and return the raw response back. This method can be used to get raw access to the API which may be used to, for example, create a proxy server or application-level gateway between localhost and the API server.
sourcepub async fn connect(
&self,
request: Request<Vec<u8>>,
) -> Result<WebSocketStream<TokioIo<Upgraded>>>
Available on crate feature ws
only.
pub async fn connect( &self, request: Request<Vec<u8>>, ) -> Result<WebSocketStream<TokioIo<Upgraded>>>
ws
only.Make WebSocket connection.
sourcepub async fn request<T>(&self, request: Request<Vec<u8>>) -> Result<T>where
T: DeserializeOwned,
pub async fn request<T>(&self, request: Request<Vec<u8>>) -> Result<T>where
T: DeserializeOwned,
Perform a raw HTTP request against the API and deserialize the response as JSON to some known type.
sourcepub async fn request_text(&self, request: Request<Vec<u8>>) -> Result<String>
pub async fn request_text(&self, request: Request<Vec<u8>>) -> Result<String>
Perform a raw HTTP request against the API and get back the response as a string
sourcepub async fn request_stream(
&self,
request: Request<Vec<u8>>,
) -> Result<impl AsyncBufRead>
pub async fn request_stream( &self, request: Request<Vec<u8>>, ) -> Result<impl AsyncBufRead>
Perform a raw HTTP request against the API and stream the response body.
The response can be processed using AsyncReadExt
and AsyncBufReadExt
.
sourcepub async fn request_status<T>(
&self,
request: Request<Vec<u8>>,
) -> Result<Either<T, Status>>where
T: DeserializeOwned,
pub async fn request_status<T>(
&self,
request: Request<Vec<u8>>,
) -> Result<Either<T, Status>>where
T: DeserializeOwned,
Perform a raw HTTP request against the API and get back either an object
deserialized as JSON or a Status
Object.
sourcepub async fn request_events<T>(
&self,
request: Request<Vec<u8>>,
) -> Result<impl TryStream<Item = Result<WatchEvent<T>>>>where
T: Clone + DeserializeOwned,
pub async fn request_events<T>(
&self,
request: Request<Vec<u8>>,
) -> Result<impl TryStream<Item = Result<WatchEvent<T>>>>where
T: Clone + DeserializeOwned,
Perform a raw request and get back a stream of WatchEvent
objects
source§impl Client
impl Client
Low level discovery methods using k8s_openapi
types.
Consider using the discovery
module for
easier-to-use variants of this functionality.
The following methods might be deprecated to avoid confusion between similarly named types within discovery
.
sourcepub async fn apiserver_version(&self) -> Result<Info>
pub async fn apiserver_version(&self) -> Result<Info>
Returns apiserver version.
sourcepub async fn list_api_groups(&self) -> Result<APIGroupList>
pub async fn list_api_groups(&self) -> Result<APIGroupList>
Lists api groups that apiserver serves.
sourcepub async fn list_api_group_resources(
&self,
apiversion: &str,
) -> Result<APIResourceList>
pub async fn list_api_group_resources( &self, apiversion: &str, ) -> Result<APIResourceList>
Lists resources served in given API group.
§Example usage:
let apigroups = client.list_api_groups().await?;
for g in apigroups.groups {
let ver = g
.preferred_version
.as_ref()
.or_else(|| g.versions.first())
.expect("preferred or versions exists");
let apis = client.list_api_group_resources(&ver.group_version).await?;
dbg!(apis);
}
sourcepub async fn list_core_api_versions(&self) -> Result<APIVersions>
pub async fn list_core_api_versions(&self) -> Result<APIVersions>
Lists versions of core
a.k.a. ""
legacy API group.
sourcepub async fn list_core_api_resources(
&self,
version: &str,
) -> Result<APIResourceList>
pub async fn list_core_api_resources( &self, version: &str, ) -> Result<APIResourceList>
Lists resources served in particular core
group version.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Client
impl !RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl !UnwindSafe for Client
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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