Kom is a Kubernetes operations manager that simplifies resource management by providing SDK-level abstractions for creating, updating, deleting, and retrieving resources, including CRDs. Kom is a Kubernetes operations manager that

98
9

Kom - Kubernetes Operations Manager

English | 中文
kom

Introduction

kom is a Kubernetes operations tool, functioning as an SDK-level abstraction over kubectl and client-go. It provides functionalities to manage Kubernetes resources, including creating, updating, deleting, and retrieving them. The project supports operations on various Kubernetes resource types and handles Custom Resource Definitions (CRDs).

With kom, you can easily perform CRUD operations, retrieve logs, and manipulate files within Pods. It even allows using SQL queries to manage Kubernetes resources.

Features

  1. Simple and easy to use: kom offers rich functionalities for managing both built-in and CRD resources.
  2. Multi-cluster support: Manage multiple Kubernetes clusters easily via RegisterCluster.
  3. MCP support: Supports multi-cluster MCP management with SSE mode, enabling AI-driven CRUD operations on any resource.
  4. Cross-namespace support: Query resources across namespaces using kom.Namespace("default","kube-system").List(&items).
  5. Chained calls: Simplifies resource operations with intuitive chained calls.
  6. CRD support: Easily define and operate on Custom Resource Definitions.
  7. Callback mechanism: Easily extend business logic without tight coupling with Kubernetes operations.
  8. Pod file operations: Easily upload, download, and delete files within Pods.
  9. High-frequency operation encapsulation: Offers pre-built functions like deployment restart, scaling, and start/stop.
  10. SQL query support: Query k8s resources using SQL.
  11. Query cache support: Improve query performance in high-frequency scenarios by setting cache expiration times.

Example Program

k8m is a lightweight Kubernetes management tool based on kom and amis, single-file, and supports multiple platforms.

  1. Download: Download the latest version from https://github.com/weibaohui/k8m.
  2. Run: Start using the ./k8m command and visit http://127.0.0.1:3618.

Installation

import (
    "github.com/weibaohui/kom"
    "github.com/weibaohui/kom/callbacks"
)
func main() {
    // Register callbacks, must be registered first
    callbacks.RegisterInit()
    // Register cluster
	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
}

Usage Examples

0. Multi-Cluster k8s MCP Support

Supports multiple tools. Includes query, list, delete, describe operations on any resource, and POD log reading operations.

// One-line code to start MCP Server
mcp.RunMCPServer("kom mcp server", "0.0.1", 9096)
# MCP Server access address
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

Startup command

mcp.RunMCPServer("kom mcp server", "0.0.1", 3619)

AI Tool Integration

Claude Desktop
  1. Open the Claude Desktop settings panel
  2. Add the MCP Server address in the API configuration area
  3. Enable SSE event monitoring function
  4. Verify the connection status
Cursor
  1. Enter the Cursor settings interface
  2. Find the extension service configuration option
  3. Add the URL of the MCP Server (e.g.: http://localhost:3619/sse)
  4. Turn on real-time event notification
Windsurf
  1. Visit the configuration center
  2. Set the API server address
  3. Enable real-time event notification
  4. Test the connection

1. Multi-Cluster Management

Register Multiple Clusters

// Register InCluster cluster, named InCluster
kom.Clusters().RegisterInCluster()
// Register two clusters with names, named orb and docker-desktop respectively
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/orb", "orb")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "docker-desktop")
// Register a cluster named default, then kom.DefaultCluster() will return the cluster.
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "default")

Display Registered Clusters

kom.Clusters().Show()

Select Default Cluster

// Use the default cluster to query pods in the kube-system namespace
// First try to return the instance with ID "InCluster", if it does not exist,
// then try to return the instance with ID "default".
// If instances with the above two names do not exist, return any instance in the clusters list.
var pods []corev1.Pod
err = kom.DefaultCluster().Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error

Select Specified Cluster

// 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

2. CRUD and Watch Examples for Built-in Resource Objects

Define a Deployment object and perform resource operations through kom.

var item v1.Deployment
var items []v1.Deployment

Create a Resource

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

Get a Resource

// Query the Deployment named nginx in the default namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
// Query the Deployment named nginx in the default namespace and use the cache for 5 seconds
// Within 5 seconds, no query will be performed again, it is recommended to enable caching for batch operations and high-frequency operations
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").WithCache(5 * time.Second).Get(&item).Error

List Resources

// Query the list of Deployments in the default namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").List(&items).Error
// Query the list of Deployments in the default and kube-system namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("default","kube-system").List(&items).Error
// Query the list of Deployments in all namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("*").List(&items).Error
err := kom.DefaultCluster().Resource(&item).AllNamespace().List(&items).Error
// Set 5 seconds cache, effective for list
err := kom.DefaultCluster().Resource(&item).WithCache(5 * time.Second).List(&nodeList).Error

Query Resource List by Label

// Query the list of Deployments with the label app:nginx in the default namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithLabelSelector("app=nginx").List(&items).Error

Query Resource List by Multiple Labels

// Query the list of Deployments with labels app:nginx m:n in the default namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithLabelSelector("app=nginx").WithLabelSelector("m=n").List(&items).Error

Query Resource List by Field

// Query the list of Deployments with the label metadata.name=test-deploy in the default namespace
// filedSelector generally supports native field definitions. Such as metadata.name,metadata.namespace,metadata.labels,metadata.annotations,metadata.creationTimestamp,spec.nodeName,spec.serviceAccountName,spec.schedulerName,status.phase,status.hostIP,status.podIP,status.qosClass,spec.containers.name and other fields
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithFieldSelector("metadata.name=test-deploy").List(&items).Error

Paging Query Resources

var list []corev1.Pod
var total int64
sql := "select * from pod where metadata.namespace=? or metadata.namespace=?     order by  metadata.creationTimestamp desc "
err := kom.DefaultCluster().Sql(sql, "kube-system", "default").
		FillTotalCount(&total).
		Limit(5).
		Offset(10).
		List(&list).Error
fmt.Printf("total %d\n", total)  //Returns the total number 480
fmt.Printf("Count %d\n", len(list)) //Returns the number of items=limit=5

Update Resource Content

// Update the Deployment named nginx, add 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

PATCH Update Resource

// Use Patch to update the resource, add a label to the Deployment named nginx and set the number of replicas to 5
patchData := `{
    "spec": {
        "replicas": 5
    },
    "metadata": {
        "labels": {
            "new-label": "new-value"
        }
    }
}`
err := kom.DefaultCluster().Resource(&item).Patch(&item, types.MergePatchType, patchData).Error

Delete Resource

// Delete the Deployment named nginx
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Delete().Error

Force Delete Resource

// Delete the Deployment named nginx
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").ForceDelete().Error

Generic Resource Retrieval (Applicable to k8s Built-in Types and CRDs)

// Specify GVK to get resources
var list []corev1.Event
err := kom.DefaultCluster().GVK("events.k8s.io", "v1", "Event").Namespace("default").List(&list).Error

...

Repository

WE
weibaohui

weibaohui/kom

Created

October 21, 2024

Updated

March 28, 2025

Language

Go

Category

System Tools