Skip to content

Commit

Permalink
Merge pull request #530 from clux/kube-core-docs
Browse files Browse the repository at this point in the history
improve docs for kube-core
  • Loading branch information
clux committed May 20, 2021
2 parents 0563628 + 93eacd1 commit 59eb05a
Show file tree
Hide file tree
Showing 17 changed files with 177 additions and 156 deletions.
15 changes: 6 additions & 9 deletions kube-core/src/admission.rs
@@ -1,9 +1,9 @@
//! Contains types for implementing admission controllers.
//!
//! For more information on admission controllers, see:
//! https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/
//! https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/
//! https://github.com/kubernetes/api/blob/master/admission/v1/types.go
//! <https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/>
//! <https://kubernetes.io/blog/2019/03/21/a-guide-to-kubernetes-admission-controllers/>
//! <https://github.com/kubernetes/api/blob/master/admission/v1/types.go>

use crate::{
dynamic::DynamicObject,
Expand Down Expand Up @@ -148,7 +148,7 @@ pub struct AdmissionRequest<T: Resource> {
pub operation: Operation,
/// Information about the requesting user.
pub user_info: UserInfo,
/// The object from the incoming request. It's None for DELETE operations.
/// The object from the incoming request. It's `None` for [`DELETE`](Operation::Delete) operations.
pub object: Option<T>,
/// The existing object. Only populated for DELETE and UPDATE requests.
pub old_object: Option<T>,
Expand All @@ -159,7 +159,7 @@ pub struct AdmissionRequest<T: Resource> {
/// The operation option structure of the operation being performed. e.g.
/// `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This
/// may be different than the options the caller provided. e.g. for a patch
/// request the performed [`Operation`] might be a [`Operation::CREATE`], in
/// request the performed [`Operation`] might be a [`CREATE`](Operation::Create), in
/// which case the Options will a `meta.k8s.io/v1.CreateOptions` even though
/// the caller provided `meta.k8s.io/v1.PatchOptions`.
#[serde(default)]
Expand All @@ -168,18 +168,15 @@ pub struct AdmissionRequest<T: Resource> {

/// The operation specified in an [`AdmissionRequest`].
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Operation {
/// An operation that creates a resource.
#[serde(rename = "CREATE")]
Create,
/// An operation that updates a resource.
#[serde(rename = "UPDATE")]
Update,
/// An operation that deletes a resource.
#[serde(rename = "DELETE")]
Delete,
/// An operation that connects to a resource.
#[serde(rename = "CONNECT")]
Connect,
}

Expand Down
5 changes: 3 additions & 2 deletions kube-core/src/api_resource.rs
@@ -1,8 +1,9 @@
use crate::{gvk::GroupVersionKind, resource::Resource};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::APIResource;

/// Contains information about Kubernetes API resources
/// which is enough for working with it.
/// Information about a Kubernetes API resource
///
/// Enough information to use it as a `Resource`
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct ApiResource {
/// Resource group, empty for core group.
Expand Down
4 changes: 4 additions & 0 deletions kube-core/src/dynamic.rs
@@ -1,3 +1,7 @@
//! Contains types for using resource kinds not known at compile-time.
//!
//! For concrete usage see [examples prefixed with dynamic_](https://github.com/clux/kube-rs/tree/master/examples).

pub use crate::api_resource::ApiResource;
use crate::{metadata::TypeMeta, resource::Resource};
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
Expand Down
1 change: 1 addition & 0 deletions kube-core/src/error.rs
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Core error types.
#[derive(Error, Debug)]
pub enum Error {
/// A request validation failed
Expand Down
1 change: 1 addition & 0 deletions kube-core/src/gvk.rs
@@ -1,3 +1,4 @@
//! Type information structs for dynamic resources.
use serde::{Deserialize, Serialize};

/// Contains enough information to identify API Resource.
Expand Down
23 changes: 18 additions & 5 deletions kube-core/src/lib.rs
@@ -1,7 +1,16 @@
#[cfg(feature = "admission")] pub mod admission;

pub mod api_resource;
pub use api_resource::ApiResource;
//! Crate with types and traits necessary for interacting with the Kubernetes API
//!
//! This crate is available as a minimal alternative to `kube` where a client is not available.
//! The same information here is always re-exported from `kube` under `kube::core`.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]
#![deny(unsafe_code)]

#[cfg_attr(docsrs, doc(cfg(feature = "admission")))]
#[cfg(feature = "admission")]
pub mod admission;

mod api_resource;
pub mod dynamic;
pub use dynamic::DynamicObject;

Expand All @@ -11,7 +20,6 @@ pub use gvk::{GroupVersionKind, GroupVersionResource};
pub mod metadata;

pub mod object;
pub use object::WatchEvent;

pub mod params;

Expand All @@ -25,6 +33,11 @@ pub mod response;

pub mod subresource;

pub mod watch;
pub use watch::WatchEvent;

mod error;
pub use error::{Error, ErrorResponse};

/// Convient alias for `Result<T, Error>`
pub type Result<T, E = Error> = std::result::Result<T, E>;
3 changes: 1 addition & 2 deletions kube-core/src/metadata.rs
@@ -1,8 +1,7 @@
//! Metadata structs used in traits, lists, and dynamic objects.
pub use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ListMeta, ObjectMeta};
use serde::{Deserialize, Serialize};

pub use crate::resource::{Resource, ResourceExt};

/// Type information that is flattened into every kubernetes object
#[derive(Deserialize, Serialize, Clone, Default, Debug, Eq, PartialEq, Hash)]
#[serde(rename_all = "camelCase")]
Expand Down
178 changes: 58 additions & 120 deletions kube-core/src/object.rs
@@ -1,125 +1,7 @@
use crate::{
metadata::{ListMeta, ObjectMeta, TypeMeta},
ErrorResponse,
};
//! Generic object and objectlist wrappers.
use crate::metadata::{ListMeta, ObjectMeta, TypeMeta};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;

/// A raw event returned from a watch query
///
/// Note that a watch query returns many of these as newline separated JSON.
#[derive(Deserialize, Serialize, Clone)]
#[serde(tag = "type", content = "object", rename_all = "UPPERCASE")]
pub enum WatchEvent<K> {
/// Resource was added
Added(K),
/// Resource was modified
Modified(K),
/// Resource was deleted
Deleted(K),
/// Resource bookmark. `Bookmark` is a slimmed down `K` due to [#285](https://github.com/clux/kube-rs/issues/285).
///
/// From [Watch bookmarks](https://kubernetes.io/docs/reference/using-api/api-concepts/#watch-bookmarks).
///
/// NB: This became Beta first in Kubernetes 1.16.
Bookmark(Bookmark),
/// There was some kind of error
Error(ErrorResponse),
}

impl<K> Debug for WatchEvent<K> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self {
WatchEvent::Added(_) => write!(f, "Added event"),
WatchEvent::Modified(_) => write!(f, "Modified event"),
WatchEvent::Deleted(_) => write!(f, "Deleted event"),
WatchEvent::Bookmark(_) => write!(f, "Bookmark event"),
WatchEvent::Error(e) => write!(f, "Error event: {:?}", e),
}
}
}

/// Slimed down K for [`WatchEvent::Bookmark`] due to [#285](https://github.com/clux/kube-rs/issues/285).
///
/// Can only be relied upon to have metadata with resource version.
/// Bookmarks contain apiVersion + kind + basically empty metadata.
#[derive(Serialize, Deserialize, Clone)]
pub struct Bookmark {
/// apiVersion + kind
#[serde(flatten)]
pub types: TypeMeta,

/// Basically empty metadata
pub metadata: BookmarkMeta,
}

/// Slimed down Metadata for WatchEvent::Bookmark
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct BookmarkMeta {
pub resource_version: String,
}

// -------------------------------------------------------

/// A standard Kubernetes object with `.spec` and `.status`.
///
/// This is a convenience struct provided for serialization/deserialization
/// It is not useful within the library anymore, because it can not easily implement
/// the [`k8s_openapi`] traits.
///
/// This is what Kubernetes maintainers tell you the world looks like.
/// It's.. generally true.
#[derive(Deserialize, Serialize, Clone)]
pub struct Object<P, U>
where
P: Clone,
U: Clone,
{
/// The types field of an `Object`
#[serde(flatten)]
pub types: TypeMeta,

/// Resource metadata
///
/// Contains information common to most resources about the Resource,
/// including the object name, annotations, labels and more.
pub metadata: ObjectMeta,

/// The Spec struct of a resource. I.e. `PodSpec`, `DeploymentSpec`, etc.
///
/// This defines the desired state of the Resource as specified by the user.
pub spec: P,

/// The Status of a resource. I.e. `PodStatus`, `DeploymentStatus`, etc.
///
/// This publishes the state of the Resource as observed by the controller.
/// Use `U = NotUsed` when a status does not exist.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<U>,
}

impl<P, U> Object<P, U>
where
P: Clone,
U: Clone,
{
/// A constructor like the one from kube-derive
pub fn new<K: k8s_openapi::Resource>(name: &str, spec: P) -> Self {
Self {
types: TypeMeta {
api_version: <K as k8s_openapi::Resource>::API_VERSION.to_string(),
kind: <K as k8s_openapi::Resource>::KIND.to_string(),
},
metadata: ObjectMeta {
name: Some(name.to_string()),
..Default::default()
},
spec,
status: None,
}
}
}

/// A generic Kubernetes object list
///
Expand Down Expand Up @@ -218,6 +100,62 @@ impl<'a, T: Clone> IntoIterator for &'a mut ObjectList<T> {

// -------------------------------------------------------

/// A standard Kubernetes object with `.spec` and `.status`.
///
/// This is a convenience struct provided for serialization/deserialization
/// It is not useful within the library anymore, because it can not easily implement
/// the [`k8s_openapi`] traits.
#[derive(Deserialize, Serialize, Clone)]
pub struct Object<P, U>
where
P: Clone,
U: Clone,
{
/// The types field of an `Object`
#[serde(flatten)]
pub types: TypeMeta,

/// Resource metadata
///
/// Contains information common to most resources about the Resource,
/// including the object name, annotations, labels and more.
pub metadata: ObjectMeta,

/// The Spec struct of a resource. I.e. `PodSpec`, `DeploymentSpec`, etc.
///
/// This defines the desired state of the Resource as specified by the user.
pub spec: P,

/// The Status of a resource. I.e. `PodStatus`, `DeploymentStatus`, etc.
///
/// This publishes the state of the Resource as observed by the controller.
/// Use `U = NotUsed` when a status does not exist.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub status: Option<U>,
}

impl<P, U> Object<P, U>
where
P: Clone,
U: Clone,
{
/// A constructor like the one from kube-derive
pub fn new<K: k8s_openapi::Resource>(name: &str, spec: P) -> Self {
Self {
types: TypeMeta {
api_version: <K as k8s_openapi::Resource>::API_VERSION.to_string(),
kind: <K as k8s_openapi::Resource>::KIND.to_string(),
},
metadata: ObjectMeta {
name: Some(name.to_string()),
..Default::default()
},
spec,
status: None,
}
}
}

/// Empty struct for when data should be discarded
///
/// Not using [`()`](https://doc.rust-lang.org/stable/std/primitive.unit.html), because serde's
Expand Down
5 changes: 2 additions & 3 deletions kube-core/src/params.rs
@@ -1,10 +1,9 @@
///! A port of *Optionals from apimachinery/types.go
//! A port of request parameter *Optionals from apimachinery/types.go
use crate::{Error, Result};
use serde::Serialize;

/// Common query parameters used in watch/list/delete calls on collections
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct ListParams {
/// A selector to restrict the list of returned objects by their labels.
///
Expand Down Expand Up @@ -169,7 +168,7 @@ impl PostParams {
/// See [kubernetes patch docs](https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) for the older patch types.
///
/// Note that patches have different effects on different fields depending on their merge strategies.
/// These strategies are configurable when deriving your [`CustomResource`](kube_derive::CustomResource#customizing-schemas).
/// These strategies are configurable when deriving your [`CustomResource`](https://docs.rs/kube-derive/*/kube_derive/derive.CustomResource.html#customizing-schemas).
///
/// # Creating a patch via serde_json
/// ```
Expand Down
2 changes: 1 addition & 1 deletion kube-core/src/request.rs
@@ -1,6 +1,6 @@
//! Request builder type for arbitrary api types
use super::params::{DeleteParams, ListParams, Patch, PatchParams, PostParams};
use crate::{Error, Result};

/// A Kubernetes request builder
///
/// Takes a base_path and supplies constructors for common operations
Expand Down
2 changes: 1 addition & 1 deletion kube-core/src/resource.rs
Expand Up @@ -22,7 +22,7 @@ pub trait Resource {
/// Types that require some information at runtime should select `DynamicType`
/// as type of this information.
///
/// See [`DynamicObject`](crate::api::DynamicObject) for a valid implementation of non-k8s-openapi resources.
/// See [`DynamicObject`](crate::dynamic::DynamicObject) for a valid implementation of non-k8s-openapi resources.
type DynamicType: Send + Sync + 'static;

/// Returns kind of this object
Expand Down
2 changes: 1 addition & 1 deletion kube-core/src/response.rs
@@ -1,6 +1,6 @@
//! Generic api response types
use serde::Deserialize;
// TODO: replace with Status in k8s openapi?

/// A Kubernetes status object
#[allow(missing_docs)]
#[derive(Deserialize, Debug)]
Expand Down
7 changes: 4 additions & 3 deletions kube-core/src/subresource.rs
@@ -1,3 +1,4 @@
//! Request builder types and parameters for subresources
use std::fmt::Debug;

use crate::{
Expand Down Expand Up @@ -132,15 +133,15 @@ pub struct AttachParams {
pub container: Option<String>,
/// Attach to the container's standard input. Defaults to `false`.
///
/// Call [`AttachedProcess::stdin`] to obtain a writer.
/// Call [`AttachedProcess::stdin`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stdin) to obtain a writer.
pub stdin: bool,
/// Attach to the container's standard output. Defaults to `true`.
///
/// Call [`AttachedProcess::stdout`] to obtain a reader.
/// Call [`AttachedProcess::stdout`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stdout) to obtain a reader.
pub stdout: bool,
/// Attach to the container's standard error. Defaults to `true`.
///
/// Call [`AttachedProcess::stderr`] to obtain a reader.
/// Call [`AttachedProcess::stderr`](https://docs.rs/kube/*/kube/api/struct.AttachedProcess.html#method.stderr) to obtain a reader.
pub stderr: bool,
/// Allocate TTY. Defaults to `false`.
///
Expand Down

0 comments on commit 59eb05a

Please sign in to comment.