kom
by: weibaohui
kom 是一个用于 Kubernetes 操作的工具,SDK级的kubectl、client-go的使用封装。并且支持作为管理k8s 的 MCP server。 它提供了一系列功能来管理 Kubernetes 资源,包括创建、更新、删除和获取资源,甚至使用SQL查询k8s资源。这个项目支持多种 Kubernetes 资源类型的操作,并能够处理自定义资源定义(CRD)。 通过使用 kom,你可以轻松地进行资源的增删改查和日志获取以及操作POD内文件等动作。
📌Overview
Purpose: kom
is designed to facilitate Kubernetes operations, providing a simplified interface for managing various Kubernetes resources.
Overview: kom
is a tool that encapsulates the functionalities of SDK-level kubectl
and client-go
, allowing users to easily create, update, delete, and retrieve Kubernetes resources, including support for Custom Resource Definitions (CRD). It streamlines resource management within Kubernetes clusters and enables various operational tasks with intuitive methods, including the ability to query resources using SQL statements.
Key Features:
-
Ease of Use: Offers comprehensive functions for managing built-in and CRD resources with straightforward operations for creation, update, deletion, and listing.
-
Multi-Cluster Support: Simplifies management across multiple Kubernetes clusters through the
RegisterCluster
functionality, allowing seamless cluster operations. -
Custom Resource Definition (CRD) Support: Enables users to define and interact with custom resources effortlessly.
-
Callback Mechanism: Facilitates business logic extensions by allowing custom callback registration for various operations, enhancing integration without tight coupling to Kubernetes.
-
File Operations in Pod: Provides functions for seamless file management within Pods, including uploading, downloading, and deleting files.
-
SQL Query Support: Streamlines resource queries using SQL, allowing for advanced filtering and retrieval of Kubernetes resources.
Kom - Kubernetes Operations Manager
简介
kom
是一个用于 Kubernetes 操作的工具,封装了 SDK 级的 kubectl 和 client-go 的使用。支持 Kubernetes 资源的创建、更新、删除、获取,包含内置资源及自定义资源定义(CRD)。提供资源增删改查、日志获取、POD 文件操作,支持使用 SQL 查询 Kubernetes 资源。
特点
- 简单易用,支持多种 Kubernetes 资源操作。
- 多集群支持,通过 RegisterCluster 管理多个集群。
- MCP 支持,支持 stdio 和 SSE 两种模式,内置48种工具。
- 支持跨命名空间查询。
- 链式调用,操作直观简洁。
- 支持 CRD 自定义资源操作。
- 支持回调机制,方便业务扩展。
- 支持 POD 内文件上传、下载、删除。
- 封装高频操作,如 deployment 重启、扩缩容、启停等。
- 支持基于 SQL 的 Kubernetes 资源查询。
- 支持查询缓存,提高高频、批量查询性能。
示例程序
k8m
是基于 kom 和 amis 实现的轻量级 Kubernetes 管理工具,支持多平台架构。
- 从 https://github.com/weibaohui/k8m 下载最新版本。
- 运行
./k8m
后,访问 http://127.0.0.1:3618。
安装示例
import (
"github.com/weibaohui/kom"
"github.com/weibaohui/kom/callbacks"
)
func main() {
callbacks.RegisterInit()
defaultKubeConfig := os.Getenv("KUBECONFIG")
if defaultKubeConfig == "" {
defaultKubeConfig = filepath.Join(homedir.HomeDir(), ".kube", "config")
}
_, _ = kom.Clusters().RegisterInCluster()
_, _ = kom.Clusters().RegisterByPathWithID(defaultKubeConfig, "default")
kom.Clusters().Show()
// 后续逻辑
}
使用示例
1. 多集群管理
注册多集群
kom.Clusters().RegisterInCluster()
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/orb", "orb")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "docker-desktop")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "default")
显示已注册集群
kom.Clusters().Show()
选择默认集群查询 Pod
var pods []corev1.Pod
err := kom.DefaultCluster().Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
选择指定集群查询 Pod
var pods []corev1.Pod
err := kom.Cluster("orb").Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
2. 资源操作示例
创建资源
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)
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
查询资源列表(List)
err := kom.DefaultCluster().Resource(&item).Namespace("default").List(&items).Error
更新资源
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 更新
patchData := `{
"spec": {
"replicas": 5
},
"metadata": {
"labels": {
"new-label": "new-value"
}
}
}`
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Patch(&item, types.StrategicMergePatchType, patchData).Error
删除资源
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Delete().Error
监听资源变化(Watch)
var watcher watch.Interface
var pod corev1.Pod
err := kom.DefaultCluster().Resource(&pod).Namespace("default").Watch(&watcher).Error
go func() {
defer watcher.Stop()
for event := range watcher.ResultChan() {
switch event.Type {
case watch.Added:
fmt.Printf("Added Pod [%s/%s]\n", pod.Namespace, pod.Name)
case watch.Modified:
fmt.Printf("Modified Pod [%s/%s]\n", pod.Namespace, pod.Name)
case watch.Deleted:
fmt.Printf("Deleted Pod [%s/%s]\n", pod.Namespace, pod.Name)
}
}
}()
3. YAML 资源操作
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
`
// 应用 YAML 资源(第一次为创建,第二次为更新)
results := kom.DefaultCluster().Applier().Apply(yaml)
// 删除 YAML 资源
results = kom.DefaultCluster().Applier().Delete(yaml)
4. Pod 操作示例
- 获取日志
- 执行命令及流式命令执行
- 文件操作(列表、上传、下载、删除)
- 获取关联资源(Service、Ingress、PVC、PV、Endpoints、Env、节点等)
5. 自定义资源定义(CRD)操作
- 通过
unstructured.Unstructured
操作 CRD 资源 - 支持创建、查询、更新、删除、Watch
- 示例:创建 CRD 资源及操作 CR 对象
6. 集群状态信息
kom.DefaultCluster().Status().Docs()
kom.DefaultCluster().Status().APIResources()
kom.DefaultCluster().Status().CRDList()
kom.DefaultCluster().Status().ServerVersion()
7. 回调机制
支持自定义回调函数,可用于操作完成后的扩展逻辑。支持的回调包括 get、list、create、update、patch、delete、exec、stream-exec、logs、watch 等。
// 注册回调示例
kom.DefaultCluster().Callback().Get().Register("get", cb)
// 自定义回调函数
func cb(k *kom.Kubectl) error {
stmt := k.Statement
fmt.Printf("Get %s/%s(%s)\n", stmt.Namespace, stmt.Name, stmt.GVR)
return nil
}
8. SQL 查询 Kubernetes 资源
支持使用 SQL 语法查询 Kubernetes 资源,支持内置及 CRD 资源。
sql := "select * from pod where metadata.namespace='kube-system' or metadata.namespace='default' order by metadata.creationTimestamp asc"
var list []v1.Pod
err := kom.DefaultCluster().Sql(sql).List(&list).Error
9. 其他常用操作
- Deployment 重启、扩缩容、停止、恢复、更新镜像标签、升级历史、回滚、暂停、恢复等
- 节点管理:污点添加/移除,cordon/uncordon/drain,IP资源及Pod统计,资源用量统计
- 给资源添加/删除标签及注解
- 创建 NodeShell 与 kubectl Shell
- StorageClass 的 PV、PVC 统计、设为默认
- IngressClass 设为默认
- 获取 Deployment/StatefulSet/DaemonSet 管理的 Pod 列表
- 查询所有节点标签
- 查看 Pod 资源占用率
k8s版本兼容性测试
k8s版本 | 测试结果 |
---|---|
V1.31.3 | ✅ |
V1.31.2 | ✅ |
V1.31.1 | ✅ |
V1.31.0 | ✅ |
V1.30.7 | ✅ |
V1.29.0 | ✅ |
V1.27.7 | ✅ |
V1.24.7 | ✅ |
V1.23.7 | ✅ |
V1.22.3 | ✅ |
V1.22.2 | ✅ |
V1.21.0 | ✅ |
V1.25.7 | ✅ |
其他版本 | 未测 |
联系我
微信号(大罗马的太阳):daluomadetaiyang,备注 kom。