The Limen Book Playground limen-lang.org
Chapter 16

Kubernetes

A Kubernetes operator is a program that watches resources in a cluster and keeps other resources in step with them: for each Site, a ConfigMap with its page; for each Database, a StatefulSet and a Secret. It runs for months, inside the cluster, with a service account that can change things. That makes it a good fit for capabilities. You want to know exactly what it can reach, and you want the part that decides what to do to be separate from the part that does it.

This chapter uses the kube module, the client for the Kubernetes API that chapter 14 introduced. It covers connecting, reading, writing, watching, and then the shape of a small operator.

A cluster you can run anywhere

The book's build has no cluster, so the listings in this chapter bring their own. Each one starts a tiny fake API server with the http module on 127.0.0.1:0, answering a few paths with the JSON the real API server would send, and points the client at it. The client is the real one; only the server is pretend. When you run the same code against a cluster, only the line that makes the client changes.

Connecting

There are three ways to make a client, one for each place a program runs:

  • kube.in_cluster(fs, env, net) is for a program in a pod. fs is the service account directory the kubelet mounts, where it reads the token, the cluster's certificate authority and the namespace. env gives the API server's address in KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT.
  • kube.from_config(fs, path, context, net) is for a program on your machine. It reads a kubeconfig, the file kubectl uses, from the Fs it's given. context "" means the file's current context.
  • kube.proxy(net, base) talks plain HTTP to a URL that needs no token, such as kubectl proxy's http://127.0.0.1:8001. It's for development and tests, and it's what this chapter's listings use.
use kube

fn main(root: Root) {
    let out = root.stdout
    // root.fs is the kubeconfig's directory, granted read-only
    let kubeconfig = root.fs.read_only()
    for context in ["", "prod", "staging"] {
        let name = if context == "" { "the current context" } else { context }
        match kube.from_config(kubeconfig, "config", context, root.net) {
            Ok(k) => out.print("{name}: namespace {k.namespace()}"),
            Err(e) => out.print("{name}: {e.message()}"),
        }
    }
    // in a pod, this is how the client is made; here the variables are not set
    match kube.in_cluster(kubeconfig, root.env, root.net) {
        Ok(_) => out.print("in a pod"),
        Err(e) => out.print("in_cluster: {e.message()}"),
    }
    // `kubectl proxy`, or a test: plain http, no token
    let k = kube.proxy(root.net, "http://127.0.0.1:8001")
    out.print("proxy: namespace {k.namespace()}")
}
Listing 16-1: Three ways to make a client examples/ch16-01-connect/main.lmn
$ limen run main.lmn --grant fs=kube:ro --grant net=127.0.0.1:6443
the current context: namespace shop
prod: kube: user `aws` gets its token from `aws`; use kube.from_config_exec with an Exec granted for it
staging: kube: the kubeconfig `config` has no context `staging`
in_cluster: kube: KUBERNETES_SERVICE_HOST is not set
proxy: namespace default

The listing's directory holds a small kubeconfig in kube/config, granted read-only with --grant fs=kube:ro. Making a client opens no connection; it reads the file and checks what it needs, so the errors come early and say what to do. The prod context's user gets its token by running aws, and from_config won't run programs, because it holds no Exec. kube.from_config_exec does, given an Exec granted for the plugin and a Clock to know when the token expires. It returns a different type, kube.ExecClient, so code handed a plain kube.Client can never run anything.

Here are the grants for a real cluster. In a pod:

$ limen run operator.lmn \
    --grant fs=/var/run/secrets/kubernetes.io/serviceaccount:ro \
    --grant env=KUBERNETES_SERVICE_HOST --grant env=KUBERNETES_SERVICE_PORT \
    --grant net=10.96.0.1:443

On your machine, with the server from kubectl config view --minify:

$ limen run operator.lmn --grant fs=$HOME/.kube:ro --grant net=127.0.0.1:6443

Whichever way it was made, the client holds the Net it was given narrowed with only to the API server's address, and trusting only the cluster's certificate authority. Even with --grant net=*, nothing reached through the client can go anywhere else. A token that rotates, the service account's or a kubeconfig's tokenFile, is read again when the file changes and after a 401, and kept in the client. That's why its request methods take mut self, and why you write let mut k = ....

Reading

k.get(path) reads one object and k.list(path) a collection. A path is the API's own, /api/v1/namespaces/shop/configmaps/web, and may carry a query, such as ?labelSelector=app%3Dweb. Each returns Result[(Int, json.Value), IoError]: the status and the body.

use http
use json
use kube

// A fake API server, so the listing runs anywhere: three answers, shaped
// as the real one gives them.
fn api(r: http.Request) -> http.Response {
    match r.path {
        "/api/v1/namespaces/shop/configmaps" => http.json(200, `{"kind": "ConfigMapList", "metadata": {"resourceVersion": "812"}, "items": [
            {"metadata": {"name": "web", "namespace": "shop", "uid": "u-1"}, "data": {"colour": "green"}},
            {"metadata": {"name": "worker", "namespace": "shop", "uid": "u-2"}}]}`),
        "/api/v1/namespaces/shop/configmaps/web" => http.json(200, `{"kind": "ConfigMap", "metadata": {"name": "web", "namespace": "shop", "uid": "u-1", "resourceVersion": "811"}, "data": {"colour": "green"}}`),
        _ => http.json(404, `{"kind": "Status", "status": "Failure", "reason": "NotFound", "code": 404, "message": "configmaps \"gone\" not found"}`),
    }
}

// The fields we read, under the API's names.
struct ConfigMap {
    metadata: Meta,
    data: Option[Map[Str, Str]],
}

struct Meta {
    name: Str,
    uid: Str,
    resource_version: Option[Str] @key("resourceVersion"),
}

struct ConfigMapList {
    metadata: ListMeta,
    items: List[ConfigMap],
}

struct ListMeta {
    resource_version: Str @key("resourceVersion"),
}

struct Status {
    reason: Str,
    message: Str,
}

fn read(out: Stdout, mut k: kube.Client) -> Result[(), IoError] {
    let path = "/api/v1/namespaces/shop/configmaps"

    let (code, v) = k.list(path)?
    let list: Result[ConfigMapList, Str] = json.from_value(v)
    match list {
        Ok(l) => {
            out.print("list {code}: version {l.metadata.resource_version}")
            for cm in l.items {
                let data = cm.data ?? map()
                out.print("  {cm.metadata.name} ({cm.metadata.uid}): colour {data.get("colour") ?? "unset"}")
            }
        },
        Err(e) => out.print("list {code}: {e}"),
    }

    let (code, v) = k.get("{path}/web")?
    let web: Result[ConfigMap, Str] = json.from_value(v)
    match web {
        Ok(cm) => out.print("get {code}: {cm.metadata.name} at version {cm.metadata.resource_version ?? "?"}"),
        Err(e) => out.print("get {code}: {e}"),
    }

    // a 404 is an answer too: Ok, with the server's Status
    let (code, v) = k.get("{path}/gone")?
    if code == 404 {
        let s: Result[Status, Str] = json.from_value(v)
        match s {
            Ok(s) => out.print("get {code}: {s.reason}, {s.message}"),
            Err(e) => out.print("get {code}: {e}"),
        }
    }
    Ok(())
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let k = kube.proxy(root.net.only("127.0.0.1"), "http://127.0.0.1:{l.port()}")
    let out = root.stdout
    let _ = group g {
        g.go(|| {
            let _ = http.serve(l, 3, api)
        })
        g.go(|| {
            let mut mine = k
            match read(out, mut mine) {
                Ok(()) => (),
                Err(e) => out.print(e.message()),
            }
        })
    }
    Ok(())
}
Listing 16-2: Listing, getting, and a 404 examples/ch16-02-read/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
list 200: version 812
  web (u-1): colour green
  worker (u-2): colour unset
get 200: web at version 811
get 404: NotFound, configmaps "gone" not found

Every answer from the server is Ok, a 404 or a 409 included. The status is part of the answer, and only you know what it means: a missing ConfigMap is an error for one program and a reason to create it for another. The body of an error is the server's kind: Status object, with a reason and a message you can decode like any other. Err is kept for what got no answer: a refused connection, a failed TLS handshake, or a body that isn't JSON.

You don't have to dig through json.Value by hand. Declare structs with the fields you read, give a field its API name with @key where the name isn't a Limen one (resource_version: Str @key("resourceVersion")), and json.from_value fills them in. Fields the struct doesn't have are ignored, and an Option field may be missing, so a struct can be as small as the code that uses it.

Writing

Four methods change things, and each takes the path and a json.Value body:

  • k.create(path, manager, body) sends POST to a collection. The server answers 409 if the name is taken.
  • k.apply(path, manager, body) is server-side apply: you send the object as you want it, and the server merges it in. The fields you send become owned by manager, a name for your program, so a change someone makes to them by hand is put back on your next apply, and fields you never send are left alone. It's the right way for an operator to write, because the same call makes an object or fixes one.
  • k.delete(path, uid: Some(id)) deletes the object at path, but only if its uid is still id. Without the uid, a delete can remove an object that was deleted and made again since you looked at it.
  • k.patch_status(path, body) merges body into the object's status, the part of a custom resource an operator writes back.

The fake server in the next listing says what each request looked like when it arrived, so you can see what the client sends:

use http
use json
use kube

// A fake API server that says what each request was, and answers as the
// real one would. The ConfigMap `web` exists already, with uid u-1.
fn api(r: http.Request) -> http.Response {
    let ct = r.header("Content-Type") ?? "no body"
    let seen = "{r.method} {r.path} ({ct})"
    match r.method {
        "POST" => status(409, "AlreadyExists", seen),
        "DELETE" => {
            let body = json.parse(r.body) ?? json.Null
            let uid = body.get("preconditions")?.get("uid")?.as_str() ?? ""
            if uid == "u-1" { answer(200, seen) } else { status(409, "Conflict", seen) }
        },
        _ => answer(200, seen),
    }
}

fn answer(code: Int, seen: Str) -> http.Response {
    http.json(code, json.stringify(json.Obj([json.field("seen", json.Str(seen))])))
}

fn status(code: Int, reason: Str, seen: Str) -> http.Response {
    let fields = [
        json.field("kind", json.Str("Status")),
        json.field("reason", json.Str(reason)),
        json.field("seen", json.Str(seen)),
    ]
    http.json(code, json.stringify(json.Obj(fields)))
}

fn say(out: Stdout, what: Str, r: Result[(Int, json.Value), IoError]) {
    match r {
        Ok((code, v)) => {
            match v.get("reason")?.as_str() {
                Some(reason) => out.print("{what}: {code} {reason}"),
                None => out.print("{what}: {code}"),
            }
            out.print("  sent {v.get("seen")?.as_str() ?? "?"}")
        },
        Err(e) => out.print("{what}: {e.message()}"),
    }
}

struct ConfigMap {
    api_version: Str @key("apiVersion"),
    kind: Str,
    metadata: Meta,
    data: Map[Str, Str],
}

struct Meta {
    name: Str,
}

fn write(out: Stdout, mut k: kube.Client) {
    let dir = "/api/v1/namespaces/shop/configmaps"
    let mut data = map()
    data["colour"] = "green"
    let web = json.to_value(ConfigMap { api_version: "v1", kind: "ConfigMap", metadata: Meta { name: "web" }, data })
    say(out, "create", k.create(dir, "shop-operator", web))
    say(out, "apply", k.apply("{dir}/web", "shop-operator", web))
    say(out, "delete u-0", k.delete("{dir}/web", uid: Some("u-0")))
    say(out, "delete u-1", k.delete("{dir}/web", uid: Some("u-1")))
    let ready = json.Obj([json.field("status", json.Obj([json.field("ready", json.Bool(true))]))])
    say(out, "patch_status", k.patch_status("/apis/example.com/v1/namespaces/shop/shops/main", ready))
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let k = kube.proxy(root.net.only("127.0.0.1"), "http://127.0.0.1:{l.port()}")
    let out = root.stdout
    let _ = group g {
        g.go(|| {
            let _ = http.serve(l, 5, api)
        })
        g.go(|| {
            let mut mine = k
            write(out, mut mine)
        })
    }
    Ok(())
}
Listing 16-3: Create, apply, delete and patch the status examples/ch16-03-write/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
create: 409 AlreadyExists
  sent POST /api/v1/namespaces/shop/configmaps?fieldManager=shop-operator (application/json)
apply: 200
  sent PATCH /api/v1/namespaces/shop/configmaps/web?fieldManager=shop-operator&force=true (application/apply-patch+yaml)
delete u-0: 409 Conflict
  sent DELETE /api/v1/namespaces/shop/configmaps/web (application/json)
delete u-1: 200
  sent DELETE /api/v1/namespaces/shop/configmaps/web (application/json)
patch_status: 200
  sent PATCH /apis/example.com/v1/namespaces/shop/shops/main/status (application/merge-patch+json)

create fails with 409 because web exists already, and apply on the same object succeeds: that's the difference between them. The client adds fieldManager to every write, and force=true to applies, so your program takes over the fields it sends even if another manager set them first. The first delete names a uid the object doesn't have, so the server refuses it with 409; the second names the right one.

The body is built from a struct with json.to_value. A field that is None is left out, which matters for server-side apply: a field you don't send is a field you don't claim.

Watching

An operator can't list everything every second. It watches instead: k.watch(path, resource_version, f) opens a stream of changes to path and calls f with each event line as it arrives, {"type": "ADDED", "object": {...}}, until f returns false or the server ends the watch. It returns a kube.Watch: the status code, the resource_version of the last event it saw, and a message when the server said something went wrong.

Every object and every list has a resourceVersion. A watch from a version sends each change after it, so the usual loop is:

  1. List the collection, and handle every object in it. Keep the list's resourceVersion.
  2. Watch from that version, handling each event.
  3. When the watch ends (servers end them after a few minutes), watch again from the last version it saw.
  4. When the server says the version is too old, 410 Gone, go back to step 1.
use http
use json
use kube

// A fake API server. A list is at version 100 the first time and 200 the
// second. A watch from 100 or 200 sends some events and ends, as a real
// one does after a few minutes. Any other version is too old: like a real
// server once the watch has started, it says so with an ERROR event.
fn api(r: http.Request, lists: Atomic) -> http.Response {
    let path = r.path
    if !path.contains("watch=1") {
        let version = if lists.add(1) == 1 { "100" } else { "200" }
        return http.json(200, `{"kind": "ConfigMapList", "items": [], "metadata": {"resourceVersion": "` + version + `"}}`)
    }
    if path.contains("resourceVersion=100") {
        let events = [
            `{"type": "ADDED", "object": {"metadata": {"name": "web", "resourceVersion": "101"}}}`,
            `{"type": "MODIFIED", "object": {"metadata": {"name": "web", "resourceVersion": "104"}}}`,
            `{"type": "BOOKMARK", "object": {"metadata": {"resourceVersion": "105"}}}`,
        ]
        return http.json(200, events.join("\n") + "\n")
    }
    if path.contains("resourceVersion=200") {
        return http.json(200, `{"type": "DELETED", "object": {"metadata": {"name": "web", "resourceVersion": "201"}}}` + "\n")
    }
    http.json(200, `{"type": "ERROR", "object": {"kind": "Status", "reason": "Expired", "code": 410, "message": "too old resource version"}}` + "\n")
}

struct Event {
    kind: Str @key("type"),
    object: Object,
}

struct Object {
    metadata: Meta,
}

struct Meta {
    name: Option[Str],
    resource_version: Str @key("resourceVersion"),
}

struct Listing {
    metadata: Meta,
}

// List, then watch from the list's version, and again from the last
// version the watch saw; when the version is too old (410), list again.
fn follow(out: Stdout, mut k: kube.Client, rounds: Int) -> Result[(), IoError] {
    let path = "/api/v1/namespaces/shop/configmaps"
    let mut version = ""
    let mut round = 0
    while round < rounds {
        round = round + 1
        if version == "" {
            let (_, v) = k.list(path)?
            let l: Result[Listing, Str] = json.from_value(v)
            version = (l ?? panic("not a list")).metadata.resource_version
            out.print("list: version {version}")
        }
        let w = k.watch(path, version, |line| {
            let e: Result[Event, Str] = json.decode(line)
            match e {
                Ok(e) => {
                    let m = e.object.metadata
                    out.print("  {e.kind} {m.name ?? "-"} at {m.resource_version}")
                },
                Err(why) => out.print("  {why}"),
            }
            true
        })?
        if w.status == 410 {
            out.print("watch ended: 410, {w.message}")
            version = ""
        } else {
            out.print("watch ended: {w.status}, resume at {w.resource_version}")
            version = w.resource_version
        }
    }
    Ok(())
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let k = kube.proxy(root.net.only("127.0.0.1"), "http://127.0.0.1:{l.port()}")
    let out = root.stdout
    let lists = atomic(0)
    let _ = group g {
        g.go(|| {
            let _ = http.serve(l, 5, |r| api(r, lists))
        })
        g.go(|| {
            let mut mine = k
            match follow(out, mut mine, 3) {
                Ok(()) => (),
                Err(e) => out.print(e.message()),
            }
        })
    }
    Ok(())
}
Listing 16-4: List, then watch, and list again after a 410 examples/ch16-04-watch/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
list: version 100
  ADDED web at 101
  MODIFIED web at 104
  BOOKMARK - at 105
watch ended: 200, resume at 105
watch ended: 410, too old resource version
list: version 200
  DELETED web at 201
watch ended: 200, resume at 201

BOOKMARK events carry no change, only a newer version to resume from; the client asks for them, so a quiet collection still moves its version on. watch keeps track of the version itself, bookmarks included, so the loop only reads w.resource_version when the watch ends. A server says a version is too old in one of two ways: as the status of the request, or, once the watch has started, as an event of type ERROR whose object is a Status with code 410. The fake server here does the second. watch turns both into status 410: an ERROR event never reaches f, and it ends the watch. Either way, drop the version and list again.

A client holds no connection, so several tasks can watch at once, each with its own copy: g.go(|| { let mut mine = k; ... }). Each copy keeps its own credentials.

An operator

A good operator is two pieces. One looks at a resource and what exists, and decides what should change. It needs no capability, so it can only compute, and you can test it with plain values. The other holds the client, asks the first what to do, and does it.

The next listing is a small operator for a custom resource, Site, that keeps a ConfigMap holding each site's page. decide is the first piece and reconcile the second:

use http
use json
use kube

// ---------- the resource and what it should have ----------

// A Site, from the custom resource example.com/v1 Site: a page to serve.
struct Site {
    metadata: Meta,
    spec: SiteSpec,
}

struct SiteSpec {
    page: Str,
}

struct Meta {
    name: Str,
    namespace: Option[Str],
}

// The ConfigMap a Site should have: NAME-page, holding the page.
struct ConfigMap {
    api_version: Str @key("apiVersion"),
    kind: Str,
    metadata: Meta,
    data: Map[Str, Str],
}

enum Action {
    Apply(ConfigMap),  // make it, or put it right
    Leave,             // it is as it should be
    Reject(Str),       // the Site is wrong; say why in its status
}

// What to do for a Site, given its ConfigMap if there is one. No
// capability: it only decides, so it is tested without a cluster.
fn decide(s: Site, current: Option[ConfigMap]) -> Action {
    if s.spec.page.trim() == "" {
        return Reject("spec.page is empty")
    }
    let mut data = map()
    data["index.html"] = s.spec.page
    let want = ConfigMap {
        api_version: "v1",
        kind: "ConfigMap",
        metadata: Meta { name: "{s.metadata.name}-page", namespace: s.metadata.namespace },
        data,
    }
    match current {
        Some(c) if c.data == want.data => Leave,
        _ => Apply(want),
    }
}

test "a new site gets a ConfigMap" {
    let s = Site { metadata: Meta { name: "a", namespace: None }, spec: SiteSpec { page: "hi" } }
    match decide(s, None) {
        Apply(c) => assert_eq(c.metadata.name, "a-page"),
        _ => panic("expected Apply"),
    }
}

// ---------- acting on it, with the client ----------

fn reconcile(out: Stdout, mut k: kube.Client) -> Result[(), IoError] {
    let sites = "/apis/example.com/v1/namespaces/shop/sites"
    let (_, v) = k.list(sites)?
    let items: List[Site] = json.from_value(v.get("items") ?? json.Arr([])) ?? []
    for s in items {
        let path = "/api/v1/namespaces/shop/configmaps/{s.metadata.name}-page"
        let (code, got) = k.get(path)?
        let found: Result[ConfigMap, Str] = json.from_value(got)
        let current = if code == 200 { found.ok() } else { None }
        match decide(s, current) {
            Apply(c) => {
                let (code, _) = k.apply(path, "site-operator", json.to_value(c))?
                out.print("{s.metadata.name}: applied {c.metadata.name}, {code}")
            },
            Leave => out.print("{s.metadata.name}: in sync"),
            Reject(why) => {
                let status = json.Obj([json.field("status", json.Obj([json.field("message", json.Str(why))]))])
                let (code, _) = k.patch_status("{sites}/{s.metadata.name}", status)?
                out.print("{s.metadata.name}: {why}, status {code}")
            },
        }
    }
    Ok(())
}

// ---------- a fake API server, so the listing runs anywhere ----------

fn api(r: http.Request) -> http.Response {
    match (r.method, r.path) {
        ("GET", "/apis/example.com/v1/namespaces/shop/sites") => http.json(200, `{"kind": "SiteList", "items": [
            {"metadata": {"name": "home", "namespace": "shop"}, "spec": {"page": "<h1>Home</h1>"}},
            {"metadata": {"name": "about", "namespace": "shop"}, "spec": {"page": "<h1>About</h1>"}},
            {"metadata": {"name": "draft", "namespace": "shop"}, "spec": {"page": ""}}]}`),
        ("GET", "/api/v1/namespaces/shop/configmaps/about-page") => http.json(200, `{"apiVersion": "v1", "kind": "ConfigMap",
            "metadata": {"name": "about-page", "namespace": "shop"}, "data": {"index.html": "<h1>About</h1>"}}`),
        ("GET", _) => http.json(404, `{"kind": "Status", "reason": "NotFound", "code": 404}`),
        _ => http.json(200, r.body),
    }
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let k = kube.proxy(root.net.only("127.0.0.1"), "http://127.0.0.1:{l.port()}")
    let out = root.stdout
    let _ = group g {
        g.go(|| {
            let _ = http.serve(l, 6, api)
        })
        g.go(|| {
            let mut mine = k
            match reconcile(out, mut mine) {
                Ok(()) => (),
                Err(e) => out.print(e.message()),
            }
        })
    }
    Ok(())
}
Listing 16-5: An operator: deciding, and acting examples/ch16-05-operator/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
home: applied home-page, 200
about: in sync
draft: spec.page is empty, status 200

decide takes a Site and its ConfigMap, if there is one, and returns an Action: apply the ConfigMap, leave it, or reject the site with a message for its status. Everything about what the operator means lives there, and none of it needs a cluster to test:

$ limen test main.lmn
ok    a new site gets a ConfigMap (144ms)
1 test, 0 failed (243ms)

limen caps shows the split:

$ limen caps main.lmn
decide     pure
reconcile  Net (via kube.Client.net), Fs (via kube.Client.token_file.fs), Stdout
api        pure
main       Root

decide is pure. reconcile holds the network and the file system, and limen caps names where they come from: the client's Net, and the Fs it reads a rotating token from. api, the fake server's handler, is pure too, because a handler gets nothing unless you give it something. A real operator puts reconcile in the list-then-watch loop of the last section and calls it again for each event or batch of events.

limen caps says what a dependency could do as well. A package that takes a kube.Client takes Net and Fs, so limen.toml must give it caps = ["net", "fs"]; one that takes a kube.ExecClient also takes Exec and Clock, and must say so. In the cluster, Kubernetes' own role-based access control limits what the service account may do. Limen limits what the process may reach. The two answer different questions, and an operator wants both.

Typed objects and manifests

The listings in this chapter declare the few fields they read. For bigger programs, the k8s package has a struct for every core, apps, batch, networking, RBAC and apiextensions type, generated from the Kubernetes API's own description, with a constructor that takes the required fields and the rest by name, and path() for where the object lives. It's a git dependency:

[dependencies]
k8s = { git = "https://github.com/AlfonsoCampodonico/limen-k8s.git", tag = "v0.1.0" }

Building and applying a Deployment then looks like this:

use json
use k8s
use kube

fn deployment(name: Str, replicas: Int) -> k8s.Deployment {
    let mut labels = map()
    labels["app"] = name
    let web = k8s.container("web", image: Some("nginx:1.27-alpine"), ports: Some([k8s.container_port(80)]))
    k8s.deployment(
        metadata: Some(k8s.object_meta(name: Some(name), namespace: Some("shop"))),
        spec: Some(k8s.deployment_spec(
            k8s.label_selector(match_labels: Some(labels)),
            k8s.pod_template_spec(metadata: Some(k8s.object_meta(labels: Some(labels))), spec: Some(k8s.pod_spec([web]))),
            replicas: Some(replicas),
        )),
    )
}

fn deploy(mut k: kube.Client) -> Result[(), IoError] {
    let d = deployment("web", 3)
    let (code, got) = k.apply(d.path(), "shop-operator", json.to_value(d))?
    let now: Result[k8s.Deployment, Str] = json.from_value(got)
    ...
}

A misspelled field is a compile error rather than a request the server rejects. Every field the API doesn't require is an Option, and None fields aren't sent, so applying a typed object claims only the fields you set. The repository's examples/site_operator.lmn is a whole operator written this way, and limen-sandbox-operator is another.

Sometimes you want the objects as a file rather than sent: to review what an operator would do, or to hand to kubectl apply -f. yaml.encode writes any struct the json module can, with the same @key names:

use yaml

struct ConfigMap {
    api_version: Str @key("apiVersion"),
    kind: Str,
    metadata: Meta,
    data: Map[Str, Str],
}

struct Meta {
    name: Str,
    namespace: Str,
    labels: Option[Map[Str, Str]],
}

fn page(site: Str, html: Str) -> ConfigMap {
    let mut data = map()
    data["index.html"] = html
    let mut labels = map()
    labels["example.com/site"] = site
    ConfigMap {
        api_version: "v1",
        kind: "ConfigMap",
        metadata: Meta { name: "{site}-page", namespace: "shop", labels: Some(labels) },
        data,
    }
}

// What the operator would apply, as a file for `kubectl apply -f -`.
fn main(root: Root) {
    let maps = [page("home", "<h1>Home</h1>\n<p>Welcome.</p>\n"), page("about", "<h1>About</h1>")]
    root.stdout.print(maps.map(|m| yaml.encode(m)).join("---\n"))
}
Listing 16-6: Manifests as YAML examples/ch16-06-manifest/main.lmn
$ limen run main.lmn
apiVersion: v1
kind: ConfigMap
metadata:
  name: home-page
  namespace: shop
  labels:
    example.com/site: home
data:
  index.html: |
    <h1>Home</h1>
    <p>Welcome.</p>
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: about-page
  namespace: shop
  labels:
    example.com/site: about
data:
  index.html: <h1>About</h1>

The page with two lines comes out as a | block, as you'd write it by hand, and the documents are joined with --- into one stream.

Summary

The kube module is a client for the Kubernetes API: in_cluster in a pod, from_config with a kubeconfig, proxy for development and tests. Whichever you use, the client's Net is narrowed to the API server, so the program can reach nothing else through it. get, list, create, apply, delete, patch_status and watch return the status with the body, and an error status is an answer for you to act on, not an Err. Decode answers into your own structs with @key, or use the k8s package's types. An operator lists, then watches from the list's version, and lists again after a 410. Keep the decision in a function that takes no capability, so it's tested with plain values and limen caps shows it can't touch the cluster.

Next, we'll look at gRPC: typed calls between services over HTTP/2.