GithubHelp home page GithubHelp logo

ka1wa / kube-rs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from kube-rs/kube

0.0 0.0 0.0 2.12 MB

rust kubernetes client and controller runtime

Home Page: https://docs.rs/kube/

License: Apache License 2.0

Rust 98.68% Makefile 0.51% Dockerfile 0.03% Shell 0.78%

kube-rs's Introduction

kube-rs

CI Client Capabilities Client Support Level Crates.io Discord chat

Rust client for Kubernetes in the style of a more generic client-go, a runtime abstraction inspired by controller-runtime, and a derive macro for CRDs inspired by kubebuilder.

These crates make certain assumptions about the kubernetes apimachinery + api concepts to enable generic abstractions. These abstractions allow rust reinterpretations of reflectors, informers, controllers, and custom resource interfaces, so that you can write applications easily.

Installation

Select a version of kube along with the generated k8s-openapi types corresponding for your cluster version:

[dependencies]
kube = "0.60.0"
kube-runtime = "0.60.0"
k8s-openapi = { version = "0.13.0", default-features = false, features = ["v1_22"] }

Features are available.

We recommend turning off default-features for k8s-openapi to speed up your compilation.

Upgrading

Please check the CHANGELOG when upgrading. All crates herein are versioned and released together to guarantee compatibility before 1.0.

Usage

See the examples directory for how to use any of these crates.

Official examples:

  • version-rs: super lightweight reflector deployment with actix 2 and prometheus metrics
  • controller-rs: Controller owned by a Manager inside actix

Real world users:

Api

The direct Api type takes a client, and is constructed with either the ::all or ::namespaced functions:

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

let p = pods.get("blog").await?;
println!("Got blog pod with containers: {:?}", p.spec.unwrap().containers);

let patch = json!({"spec": {
    "activeDeadlineSeconds": 5
}});
let pp = PatchParams::apply("my_manager");
let patched = pods.patch("blog", &pp, &Patch::Apply(patch)).await?;
assert_eq!(patched.spec.active_deadline_seconds, Some(5));

pods.delete("blog", &DeleteParams::default()).await?;

See the examples ending in _api examples for more detail.

Custom Resource Definitions

Working with custom resources uses automatic code-generation via proc_macros in kube-derive.

You need to #[derive(CustomResource)] and some #[kube(attrs..)] on a spec struct:

#[derive(CustomResource, Debug, Serialize, Deserialize, Default, Clone, JsonSchema)]
#[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)]
pub struct FooSpec {
    name: String,
    info: String,
}

Then you can use the generated wrapper struct Foo as a kube::Resource:

let foos: Api<Foo> = Api::namespaced(client, "default");
let f = Foo::new("my-foo", FooSpec::default());
println!("foo: {:?}", f);
println!("crd: {:?}", serde_yaml::to_string(&Foo::crd()));

There are a ton of kubebuilder-like instructions that you can annotate with here. See the documentation or the crd_ prefixed examples for more.

NB: #[derive(CustomResource)] requires the derive feature enabled on kube.

Runtime

The kube_runtime crate contains sets of higher level abstractions on top of the Api and Resource types so that you don't have to do all the watch/resourceVersion/storage book-keeping yourself.

Watchers

A low level streaming interface (similar to informers) that presents Applied, Deleted or Restarted events.

let api = Api::<Pod>::namespaced(client, "default");
let watcher = watcher(api, ListParams::default());

This now gives a continual stream of events and you do not need to care about the watch having to restart, or connections dropping.

let mut apply_events = try_flatten_applied(watcher).boxed_local();
while let Some(event) = apply_events.try_next().await? {
    println!("Applied: {}", event.name());
}

NB: the plain stream items a watcher returns are different from WatchEvent. If you are following along to "see what changed", you should flatten it with one of the utilities like try_flatten_applied or try_flatten_touched.

Reflectors

A reflector is a watcher with Store on K. It acts on all the Event<K> exposed by watcher to ensure that the state in the Store is as accurate as possible.

let nodes: Api<Node> = Api::namespaced(client, &namespace);
let lp = ListParams::default()
    .labels("beta.kubernetes.io/instance-type=m4.2xlarge");
let store = reflector::store::Writer::<Node>::default();
let reader = store.as_reader();
let rf = reflector(store, watcher(nodes, lp));

At this point you can listen to the reflector as if it was a watcher, but you can also query the reader at any point.

Controllers

A Controller is a reflector along with an arbitrary number of watchers that schedule events internally to send events through a reconciler:

Controller::new(root_kind_api, ListParams::default())
    .owns(child_kind_api, ListParams::default())
    .run(reconcile, error_policy, context)
    .for_each(|res| async move {
        match res {
            Ok(o) => info!("reconciled {:?}", o),
            Err(e) => warn!("reconcile failed: {}", Report::from(e)),
        }
    })
    .await;

Here reconcile and error_policy refer to functions you define. The first will be called when the root or child elements change, and the second when the reconciler returns an Err.

Rustls

Kube has basic support (with caveats) for rustls as a replacement for the openssl dependency. To use this, turn off default features, and enable rustls-tls:

[dependencies]
kube = { version = "0.60.0", default-features = false, features = ["client", "rustls-tls"] }
kube-runtime = { version = "0.60.0" }
k8s-openapi = { version = "0.13.0", default-features = false, features = ["v1_22"] }

This will pull in rustls and hyper-rustls.

musl-libc

Kube will work with distroless, scratch, and alpine (it's also possible to use alpine as a builder with some caveats).

License

Apache 2.0 licensed. See LICENSE for details.

kube-rs's People

Contributors

clux avatar kazk avatar nightkr avatar mikailbag avatar kitmoog avatar rylev avatar ynqa avatar lfrancke avatar lukemathwalker avatar xrl avatar davidb avatar thomastaylor312 avatar ericmcbride avatar twz123 avatar kflansburg avatar ctron avatar gnunicorn avatar coadler avatar dimbleby avatar jonnywalker81 avatar kppullin-nt avatar olix0r avatar svend avatar praveenperera avatar ragne avatar liberwang1013 avatar github-actions[bot] avatar dylanhart avatar rrichardson avatar technosophos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.