kom
is a powerful tool designed for Kubernetes operations, providing an SDK-level encapsulation of kubectl
and client-go
. It offers a wide range of functionalities to manage Kubernetes resources, including creating, updating, deleting, and retrieving resources. Additionally, it supports SQL queries for Kubernetes resources and can handle Custom Resource Definitions (CRDs). With kom
, you can easily perform CRUD operations, retrieve logs, and manage files within Pods.
kom
provides a rich set of features, including CRUD operations for both built-in and CRD resources.RegisterCluster
.import (
"github.com/weibaohui/kom"
"github.com/weibaohui/kom/callbacks"
)
func main() {
// Register callbacks first
callbacks.RegisterInit()
// Register clusters
defaultKubeConfig := os.Getenv("KUBECONFIG")
if defaultKubeConfig == "" {
defaultKubeConfig = filepath.Join(homedir.HomeDir(), ".kube", "config")
}
_, _ = kom.Clusters().RegisterInCluster()
_, _ = kom.Clusters().RegisterByPathWithID(defaultKubeConfig, "default")
kom.Clusters().Show()
// Other logic
}
// Start MCP Server with one line of code
mcp.RunMCPServer("kom mcp server", "0.0.1", 9096)
# MCP Server access URL
http://IP:9096/sse
delete_k8s_resource
describe_k8s_resource
get_k8s_resource
get_pod_linked_endpoints
get_pod_linked_ingresses
get_pod_linked_pv
get_pod_linked_pvc
get_pod_linked_services
get_pod_logs
list_clusters
list_k8s_event
list_k8s_resource
pod_file_operations
restart_deployment
scale_deployment
http://localhost:3619/sse
).// Register InCluster cluster with the name "InCluster"
kom.Clusters().RegisterInCluster()
// Register two named clusters, "orb" and "docker-desktop"
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/orb", "orb")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "docker-desktop")
// Register a cluster named "default"
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "default")
kom.Clusters().Show()
// Use the default cluster to query Pods in the "kube-system" namespace
var pods []corev1.Pod
err = kom.DefaultCluster().Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
// Select the "orb" cluster to query Pods in the "kube-system" namespace
var pods []corev1.Pod
err = kom.Cluster("orb").Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
item = v1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "nginx",
Namespace: "default",
},
Spec: v1.DeploymentSpec{
Template: corev1.PodTemplateSpec{
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{Name: "test", Image: "nginx:1.14.2"},
},
},
},
},
}
err := kom.DefaultCluster().Resource(&item).Create(&item).Error
// Query the Deployment named "nginx" in the "default" namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
// Query with a 5-second cache
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").WithCache(5 * time.Second).Get(&item).Error
// Query the list of Deployments in the "default" namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").List(&items).Error
// Query Deployments in "default" and "kube-system" namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("default","kube-system").List(&items).Error
// Query Deployments in all namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("*").List(&items).Error
err := kom.DefaultCluster().Resource(&item).AllNamespace().List(&items).Error
// Set a 5-second cache for the list
err := kom.DefaultCluster().Resource(&item).WithCache(5 * time.Second).List(&nodeList).Error
// Update the Deployment named "nginx" by adding an annotation
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
if item.Spec.Template.Annotations == nil {
item.Spec.Template.Annotations = map[string]string{}
}
item.Spec.Template.Annotations["kom.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)
err = kom.DefaultCluster().Resource(&item).Update(&item).Error
// Delete the Deployment named "nginx"
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Delete().Error
// Force delete the Deployment named "nginx"
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").ForceDelete().Error
yaml := `apiVersion: v1
kind: ConfigMap
metadata:
name: example-config
namespace: default
data:
key: value
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: example-deployment
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: example
template:
metadata:
labels:
app: example
spec:
containers:
- name: example-container
image: nginx
`
// First Apply creates the resources, returns the execution result for each resource
results := kom.DefaultCluster().Applier().Apply(yaml)
// Second Apply updates the resources, returns the execution result for each resource
results = kom.DefaultCluster().Applier().Apply(yaml)
// Delete the resources, returns the execution result for each resource
results = kom.DefaultCluster().Applier().Delete(yaml)
// Get Pod logs
var stream io.ReadCloser
err := kom.DefaultCluster().Namespace("default").Name("random-char-pod").Ctl().Pod().ContainerName("container").GetLogs(&stream, &corev1.PodLogOptions{}).Error
reader := bufio.NewReader(stream)
line, _ := reader.ReadString('\n')
fmt.Println(line)
// Execute the `ps -ef` command in the Pod
var execResult string
err := kom.DefaultCluster().Namespace("default").Name("random-char-pod").Ctl().Pod().ContainerName("container").Command("ps", "-ef").ExecuteCommand(&execResult).Error
fmt.Printf("execResult: %s", execResult)
cb := func(data []byte) error {
fmt.Printf("Data %s\n", string(data))
return nil
}
err := kom.DefaultCluster().Namespace("kube-system").Name("traefik-d7c9c5778-p9nf4").Ctl().Pod().ContainerName("traefik").Command("ping", "127.0.0.1").StreamExecute(cb, cb).Error
yaml := `apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: crontabs.stable.example.com
spec:
group: stable.example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
cronSpec:
type: string
image:
type: string
replicas:
type: integer
scope: Namespaced
names:
plural: crontabs
singular: crontab
kind: CronTab
shortNames:
- ct`
result := kom.DefaultCluster().Applier().Apply(yaml)
item = unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "stable.example.com/v1",
"kind": "CronTab",
"metadata": map[string]interface{}{
"name": "test-crontab",
"namespace": "default",
},
"spec": map[string]interface{}{
"cronSpec": "* * * * */8",
"image": "test-crontab-image",
},
},
}
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace(item.GetNamespace()).Name(item.GetName()).Create(&item).Error
// Cluster documentation
kom.DefaultCluster().Status().Docs()
// Cluster resource information
kom.DefaultCluster().Status().APIResources()
// List of registered CRDs
kom.DefaultCluster().Status().CRDList()
// Cluster version information
kom.DefaultCluster().Status().ServerVersion()
// Register a callback for Get operations
kom.DefaultCluster().Callback().Get().Register("get", cb)
// Register a callback for List operations
kom.DefaultCluster().Callback().List().Register("list", cb)
// Register a callback for Create operations
kom.DefaultCluster().Callback().Create().Register("create", cb)
// Register a callback for Update operations
kom.DefaultCluster().Callback().Update().Register("update", cb)
// Register a callback for Patch operations
kom.DefaultCluster().Callback().Patch().Register("patch", cb)
// Register a callback for Delete operations
kom.DefaultCluster().Callback().Delete().Register("delete", cb)
// Register a callback for Watch operations
kom.DefaultCluster().Callback().Watch().Register("watch",cb)
// Register a callback for Exec operations
kom.DefaultCluster().Callback().Exec().Register("exec", cb)
// Register a callback for Logs operations
kom.DefaultCluster().Callback().Logs().Register("logs", cb)
// Delete a callback
kom.DefaultCluster().Callback().Get().Delete("get")
// Replace a callback
kom.DefaultCluster().Callback().Get().Replace("get", cb)
// Specify callback execution order
kom.DefaultCluster().Callback().After("kom:get").Register("get", cb)
kom.DefaultCluster().Callback().Before("kom:create").Register("create", cb)
sql := "select * from deploy where metadata.namespace='kube-system' or metadata.namespace='default' order by metadata.creationTimestamp asc "
var list []v1.Deployment
err := kom.DefaultCluster().Sql(sql).List(&list).Error
for _, d := range list {
fmt.Printf("List Items foreach %s,%s at %s \n", d.GetNamespace(), d.GetName(), d.GetCreationTimestamp())
}
sql := "select * from vm where (metadata.namespace='kube-system' or metadata.namespace='default' ) "
var list []unstructured.Unstructured
err := kom.DefaultCluster().Sql(sql).List(&list).Error
for _, d := range list {
fmt.Printf("List Items foreach %s,%s\n", d.GetNamespace(), d.GetName())
}
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Restart()
// Scale the Deployment named "nginx" to 3 replicas
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Scale(3)
// Scale the Deployment named "nginx" to 0 replicas
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Stop()
// Restore the Deployment named "nginx" to its previous replica count
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Restore()
// Update the image tag of the Deployment named "nginx"
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Deployment().ReplaceImageTag("main","20241124")
Kubernetes Version | Test Result |
---|---|
V1.31.3 | ✅ |
V1.31.2 | ✅ |
V1.31.1 | ✅ |
V1.31.0 | ✅ |
V1.30.7 | ✅ |
V1.29.0 | ✅ |
V1.25.7 | ✅ |
V1.24.7 | ✅ |
V1.23.7 | ✅ |
V1.22.3 | ✅ |
V1.22.2 | ✅ |
V1.21.0 | ✅ |
WeChat (大罗马的太阳) Search ID: daluomadetaiyang
, note: kom
.
No packages published.