krab-api 0.2.0

Kubernetes-compatible API server for krabkube
Documentation
pub struct ResDef {
    pub group: &'static str,
    pub version: &'static str,
    pub plural: &'static str,
    pub singular: &'static str,
    pub kind: &'static str,
    pub namespaced: bool,
    pub verbs: &'static [&'static str],
    pub short: &'static [&'static str],
    pub categories: &'static [&'static str],
    pub subresources: &'static [&'static str],
    pub stored: bool,
}

const RW: &[&str] = &[
    "create",
    "delete",
    "deletecollection",
    "get",
    "list",
    "patch",
    "update",
    "watch",
];
const RO: &[&str] = &["get", "list", "watch"];
const ALL: &[&str] = &["all"];

const fn res(
    group: &'static str,
    version: &'static str,
    plural: &'static str,
    singular: &'static str,
    kind: &'static str,
    namespaced: bool,
) -> ResDef {
    ResDef {
        group,
        version,
        plural,
        singular,
        kind,
        namespaced,
        verbs: RW,
        short: &[],
        categories: &[],
        subresources: &[],
        stored: true,
    }
}

pub static RESOURCES: &[ResDef] = &[
    ResDef {
        short: &["ns"],
        subresources: &["status", "finalize"],
        verbs: &[
            "create", "delete", "get", "list", "patch", "update", "watch",
        ],
        ..res("", "v1", "namespaces", "namespace", "Namespace", false)
    },
    ResDef {
        short: &["no"],
        verbs: RO,
        ..res("", "v1", "nodes", "node", "Node", false)
    },
    ResDef {
        short: &["po"],
        categories: ALL,
        subresources: &["status", "log", "exec", "attach", "portforward"],
        ..res("", "v1", "pods", "pod", "Pod", true)
    },
    ResDef {
        short: &["svc"],
        categories: ALL,
        subresources: &["status"],
        ..res("", "v1", "services", "service", "Service", true)
    },
    ResDef {
        short: &["ep"],
        ..res("", "v1", "endpoints", "endpoints", "Endpoints", true)
    },
    ResDef {
        short: &["cm"],
        ..res("", "v1", "configmaps", "configmap", "ConfigMap", true)
    },
    res("", "v1", "secrets", "secret", "Secret", true),
    ResDef {
        short: &["sa"],
        ..res(
            "",
            "v1",
            "serviceaccounts",
            "serviceaccount",
            "ServiceAccount",
            true,
        )
    },
    ResDef {
        short: &["ev"],
        ..res("", "v1", "events", "event", "Event", true)
    },
    ResDef {
        short: &["deploy"],
        categories: ALL,
        subresources: &["status", "scale"],
        ..res(
            "apps",
            "v1",
            "deployments",
            "deployment",
            "Deployment",
            true,
        )
    },
    ResDef {
        short: &["rs"],
        categories: ALL,
        subresources: &["status", "scale"],
        ..res(
            "apps",
            "v1",
            "replicasets",
            "replicaset",
            "ReplicaSet",
            true,
        )
    },
    ResDef {
        short: &["pvc"],
        subresources: &["status"],
        ..res(
            "",
            "v1",
            "persistentvolumeclaims",
            "persistentvolumeclaim",
            "PersistentVolumeClaim",
            true,
        )
    },
    ResDef {
        short: &["pv"],
        subresources: &["status"],
        ..res(
            "",
            "v1",
            "persistentvolumes",
            "persistentvolume",
            "PersistentVolume",
            false,
        )
    },
    ResDef {
        short: &["sc"],
        ..res(
            "storage.k8s.io",
            "v1",
            "storageclasses",
            "storageclass",
            "StorageClass",
            false,
        )
    },
    res(
        "coordination.k8s.io",
        "v1",
        "leases",
        "lease",
        "Lease",
        true,
    ),
    ResDef {
        verbs: &["create"],
        stored: false,
        ..res(
            "authorization.k8s.io",
            "v1",
            "selfsubjectaccessreviews",
            "selfsubjectaccessreview",
            "SelfSubjectAccessReview",
            false,
        )
    },
    ResDef {
        verbs: &["get", "list"],
        stored: false,
        ..res(
            "metrics.k8s.io",
            "v1beta1",
            "nodes",
            "",
            "NodeMetrics",
            false,
        )
    },
    ResDef {
        verbs: &["get", "list"],
        stored: false,
        ..res("metrics.k8s.io", "v1beta1", "pods", "", "PodMetrics", true)
    },
];

impl ResDef {
    pub fn api_version(&self) -> String {
        if self.group.is_empty() {
            self.version.to_string()
        } else {
            format!("{}/{}", self.group, self.version)
        }
    }

    pub fn can(&self, verb: &str) -> bool {
        self.verbs.contains(&verb)
    }

    pub fn has_sub(&self, sub: &str) -> bool {
        self.subresources.contains(&sub)
    }

    pub fn qualified(&self) -> String {
        if self.group.is_empty() {
            self.plural.to_string()
        } else {
            format!("{}.{}", self.plural, self.group)
        }
    }

    pub fn prefix(&self, ns: Option<&str>) -> String {
        match ns {
            Some(ns) if self.namespaced => format!("{}/{ns}/", self.plural),
            _ => format!("{}/", self.plural),
        }
    }

    pub fn key(&self, ns: Option<&str>, name: &str) -> String {
        format!("{}{name}", self.prefix(ns))
    }

    pub fn sub_kind(&self, sub: &str) -> (&'static str, &'static str, &'static str) {
        match sub {
            "scale" => ("autoscaling", "v1", "Scale"),
            _ => (self.group, self.version, self.kind),
        }
    }

    pub fn sub_verbs(&self, sub: &str) -> &'static [&'static str] {
        match sub {
            "log" => &["get"],
            "finalize" => &["update"],
            "attach" => &["get"],
            "exec" | "portforward" => &["create", "get"],
            _ => &["get", "patch", "update"],
        }
    }
}

pub fn find(group: &str, version: &str, plural: &str) -> Option<&'static ResDef> {
    RESOURCES
        .iter()
        .find(|r| r.group == group && r.version == version && r.plural == plural)
}

pub fn group_versions() -> Vec<(&'static str, &'static str)> {
    let mut out: Vec<(&str, &str)> = Vec::new();
    for r in RESOURCES {
        if !r.group.is_empty() && !out.contains(&(r.group, r.version)) {
            out.push((r.group, r.version));
        }
    }
    out
}

pub fn in_group(group: &str, version: &str) -> impl Iterator<Item = &'static ResDef> {
    let (g, v) = (group.to_string(), version.to_string());
    RESOURCES
        .iter()
        .filter(move |r| r.group == g && r.version == v)
}

pub fn namespaced_stored() -> impl Iterator<Item = &'static ResDef> {
    RESOURCES.iter().filter(|r| r.stored && r.namespaced)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn keys_and_lookup() {
        let d = find("apps", "v1", "deployments").unwrap();
        assert_eq!(d.key(Some("t1"), "web"), "deployments/t1/web");
        assert_eq!(d.qualified(), "deployments.apps");
        let n = find("", "v1", "namespaces").unwrap();
        assert_eq!(n.key(Some("x"), "t1"), "namespaces/t1");
        assert!(!find("", "v1", "nodes").unwrap().can("create"));
        assert_eq!(
            find("", "v1", "persistentvolumeclaims")
                .unwrap()
                .key(Some("t1"), "data"),
            "persistentvolumeclaims/t1/data"
        );
        assert_eq!(
            find("storage.k8s.io", "v1", "storageclasses")
                .unwrap()
                .key(Some("t1"), "local-path"),
            "storageclasses/local-path"
        );
        assert_eq!(group_versions()[0], ("apps", "v1"));
    }
}