KubeAdmin Utility
This utility offers centralized control over Kubernetes deployments, facilitating resource lifecycle management like creation, modification, deletion, and querying across several distinct clusters. It naturally incorporates support for custom resource definitions (CRDs). Drawing parallels to cloud computing, which involves networked access to scalable, elastic resource pools, this tool provides self-service administrative functions for container orchestration environments.
Author

weibaohui
Quick Info
Actions
Tags
Introduction
This package functions as a focused operational layer for managing Kubernetes resources, serving as an abstraction over SDK-level interactions like direct client-go calls. It streamlines fundamental Kubernetes tasks such as resource instantiation, updating states, removal, and retrieval operations. The system accommodates various resource types, including user-defined Custom Resource Definitions (CRDs). Users can execute common resource modifications, retrieve logs, and even perform file system operations inside containers. Notably, it enables management of cluster resources using SQL-like queries for enhanced accessibility.
Related Topics
- Cloud Computing: A model for delivering on-demand computing resources over the network.
- Kubernetes (K8s): An open-source system for automating deployment, scaling, and management of containerized applications.
- Custom Resource Definitions (CRDs): Extending Kubernetes' object model with custom schema definitions.
- Resource Abstraction: Simplifying complex infrastructure interactions through higher-level interfaces.
Setup
Integration into a Go project mandates initializing necessary callback structures prior to cluster registration steps.
import (
"github.com/weibaohui/kom"
"github.com/weibaohui/kom/callbacks"
)
func main() {
// Initialize callbacks first, this step is mandatory
callbacks.RegisterInit()
// Register cluster configurations
defaultKubeConfig := os.Getenv("KUBECONFIG")
if defaultKubeConfig == "" {
defaultKubeConfig = filepath.Join(homedir.HomeDir(), ".kube", "config")
}
_, _ = kom.Clusters().RegisterInCluster()
_, _ = kom.Clusters().RegisterByPathWithID(defaultKubeConfig, "default")
kom.Clusters().Show()
// Further application logic follows here
}
MCP Integration and Modes
This tool supports operation across multiple managed compute platforms (MCPs) using either standard input/output (stdio) or Server-Sent Events (SSE) communication protocols. It includes foundational support for 58 integrated management utilities, allowing for private deployments accessible by multiple users. Complex operations exceeding one hundred combinations are supported.
1. Integrate into Application Code
Starting the MCP Server requires a single function call to begin listening for connections.
// Execute this line to initialize the MCP Server
mcp.RunMCPServer("kom mcp server", "0.0.1", 9096)
2. Compilation
After source code development, compile the binary for deployment.
# Initiate build from source files
go build main.go
# The resulting executable is named 'kom'
3. Execution
Operation supports two distinct modes: stdio and SSE, based on execution context. Kubernetes connection details typically load from the KUBECONFIG environment variable.
# Set the KUBECONFIG environment variable
export KUBECONFIG = /Users/xxx/.kube/config
# Run the compiled tool
./kom
# Access the MCP Server via HTTP endpoint
http://IP:9096/sse
When executed directly, the compiled file operates in stdio mode. The HTTP address provides access via the SSE communication method.
4. Integration into Other MCP Tools
Integration methods accommodate both stdio and sse communication styles. This feature benefits integration with tools like Cursor, Claude Desktop (stdio only), and Windsurf, or via their associated user interface configurations.
{
"mcpServers": {
"kom": {
"type": "sse",
"url": "http://IP:9096/sse"
}
}
}
{
"mcpServers": {
"k8m": {
"command": "path/to/kom",
"args": []
}
}
}
MCP Tool Capabilities (59 Functions Listed)
| Category | Method | Summary |
|---|---|---|
| Cluster Administration (1) | list_k8s_clusters |
Retrieve a list of all registered Kubernetes clusters. |
| DaemonSet Administration (1) | restart_k8s_daemonset |
Restart a DaemonSet specified by cluster, namespace, and name. |
| Deployment Management (12) | scale_k8s_deployment |
Modify the replica count for a Deployment across cluster/namespace. |
restart_k8s_deployment |
Initiate a restart for a Deployment using cluster, namespace, and name. | |
stop_k8s_deployment |
Set the replica count of a Deployment to zero. | |
restore_k8s_deployment |
Revert a Deployment's replica count to its previously stored value. | |
update_k8s_deployment_image_tag |
Change the container image tag within a Deployment specification. | |
get_k8s_deployment_rollout_history |
Query the history of rollout operations for a Deployment. | |
undo_k8s_deployment_rollout |
Execute a rollback on a Deployment's rollout process. | |
pause_k8s_deployment_rollout |
Temporarily halt an ongoing Deployment rollout procedure. | |
resume_k8s_deployment_rollout |
Restart a paused Deployment rollout operation. | |
get_k8s_deployment_rollout_status |
Check the current status of a Deployment rollout. | |
get_k8s_deployment_hpa_list |
Retrieve the list of Horizontal Pod Autoscalers linked to a Deployment. | |
list_k8s_deploy_event |
Fetch relevant event records associated with a Deployment resource. | |
| Dynamic Resource Operations (incl. CRD) (8) | get_k8s_resource |
Fetch the details of a Kubernetes resource by cluster, namespace, and name. |
describe_k8s_resource |
Retrieve a detailed description for a specified Kubernetes resource. | |
delete_k8s_resource |
Remove a Kubernetes resource identified by cluster, namespace, and name. | |
list_k8s_resource |
Obtain a list of Kubernetes resources based on cluster and resource type. | |
annotate_k8s_resource |
Add or remove annotations from a specified Kubernetes resource. | |
label_k8s_resource |
Apply or remove labels associated with a Kubernetes resource. | |
patch_k8s_resource |
Apply a patch update to a Kubernetes resource using cluster, namespace, and name. | |
GetDynamicResource |
Retrieve an instance of a dynamically defined resource. | |
| Node Management (11) | taint_k8s_node |
Apply a taint restriction to a specific Kubernetes node. |
untaint_k8s_node |
Remove an existing taint from a designated Kubernetes node. | |
cordon_k8s_node |
Mark a node as unschedulable, preventing new Pod assignments. | |
uncordon_k8s_node |
Mark a node as schedulable, allowing Pod assignment to resume. | |
drain_k8s_node |
Evict Pods from a node and prevent subsequent scheduling actions. | |
get_k8s_node_ip_usage |
Query the IP address resource utilization statistics for a node. | |
list_k8s_node |
Fetch the complete list of available Node objects. | |
get_k8s_top_node |
Retrieve a ranked list of node resource utilization for CPU and memory. | |
get_k8s_pod_count_running_on_node |
Obtain a count of Pods actively running on a specified node. | |
get_k8s_node_resource_usage |
Query detailed statistics on node resource consumption. | |
TaintNodeTool |
Apply scheduling restrictions (taints) to a cluster node. | |
| Event Management (1) | list_k8s_event |
List Kubernetes event records scoped by cluster and namespace. |
| Ingress Management (1) | set_default_k8s_ingressclass |
Designate a specific IngressClass as the cluster default. |
| Pod Management (18) | run_command_in_k8s_pod |
Execute an arbitrary command within the context of a running Pod. |
list_k8s_pod_event |
Retrieve event records associated specifically with a given Pod. | |
list_files_in_k8s_pod |
List the files present in a specified directory path inside a Pod. | |
list_pod_all_files |
Retrieve a recursive list of all files within a designated Pod path. | |
delete_k8s_pod |
Terminate a running Pod instance. | |
delete_pod_file |
Remove a specific file from the filesystem of a Pod. | |
get_k8s_pod_linked_env |
Extract environment variables configured for a running Pod. | |
get_pod_linked_env_from_yaml |
Extract environment variables defined in the Pod's YAML specification. | |
get_k8s_pod_linked_services |
Find all Service resources associated with a particular Pod. | |
get_pod_linked_ingresses |
Discover Ingress resources that route traffic to the specified Pod. | |
get_pod_linked_endpoints |
Identify the associated Endpoints resources for a Pod. | |
list_k8s_pod |
Obtain a comprehensive list of all Pod resources. | |
get_k8s_top_pod |
List Pods ranked by current CPU and memory consumption. | |
ListPodFilesTool |
List files within a specified directory inside a Pod container. | |
ListAllPodFilesTool |
Recursively list all files under a specified directory path in a Pod. | |
DeletePodFileTool |
Delete a file located within a container filesystem of a Pod. | |
UploadPodFileTool |
Transfer a local file into a specified path within a Pod container. | |
GetPodLogsTool |
Retrieve the output logs generated by a Pod. | |
describe_k8s_pod |
Provide a detailed description of a specific Pod container group. | |
| Storage Management (3) | set_k8s_default_storageclass |
Designate a StorageClass as the cluster's default provisioning mechanism. |
get_k8s_storageclass_pvc_count |
Count the PersistentVolumeClaims bound to a specific StorageClass. | |
get_k8s_storageclass_pv_count |
Count the PersistentVolumes provisioned by a given StorageClass. | |
| YAML Operations (2) | apply_k8s_yaml |
Create or update Kubernetes resources using a provided YAML manifest. |
delete_k8s_yaml |
Remove Kubernetes resources based on their definition in a YAML manifest. |
Launch Command
This specific command initiates an SSE server on port 3619.
mcp.RunMCPServer("kom mcp server", "0.0.1", 3619)
AI Tool Interfacing
Instructions for connecting this utility with various AI-powered development assistants.
Claude Desktop
- Access the settings panel within Claude Desktop.
- Input the MCP Server address in the API configuration section.
- Activate the SSE event listening functionality.
- Confirm successful connection status.
{
"mcpServers": {
"k8m": {
"command": "path/to/kom",
"args": []
}
}
}
Cursor
- Navigate to the configuration interface in Cursor.
- Locate the extension service configuration options.
- Support includes both sse and stdio protocols. For sse, specify
http://localhost:9096/sse. For stdio, provide the path to thekomexecutable.
Windsurf
- Open the configuration center within the application.
- Define the API server address.
- Supports sse (
http://localhost:9096/sse) or stdio (executable path).
cherry studio
- Click the settings icon located in the bottom left corner.
- Select the MCP Server option from the menu.
- Choose to add a new server, specifying either the sse endpoint (
http://localhost:9096/sse) or the stdio executable location.
1. Multi-Cluster Administration
This section details how to register and select multiple operational Kubernetes environments.
Registering Multiple Clusters
Registering in-cluster configurations, along with specific file-based external configurations.
// Register the configuration available within the running cluster, named 'InCluster'
kom.Clusters().RegisterInCluster()
// Register two external clusters using specified paths and custom IDs: 'orb' and 'docker-desktop'
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/orb", "orb")
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "docker-desktop")
// Registering a cluster with the ID 'default' makes it the fallback selection.
kom.Clusters().RegisterByPathWithID("/Users/kom/.kube/config", "default")
AWS EKS Cluster Registration
Configuration details required for authenticating and registering an Amazon EKS cluster.
// Define the authentication structure for EKS
config := aws.EKSAuthConfig{
AccessKey: "XXX", // AWS Access Key ID provided for authentication
SecretAccessKey: "yyy", // AWS Secret Access Key for credentials
Region: "us-east-1", // The AWS region where the cluster resides
ClusterName: "k8m", // The specific name of the EKS cluster
}
// Proceed with registering the AWS EKS cluster
_, err := kom.Clusters().RegisterAWSCluster(config)
if err != nil {
fmt.Printf("EKS Cluster registration failed: %v", err)
return
}
// Example usage targeting the newly registered EKS cluster
var pods []corev1.Pod
clusterID := fmt.Sprintf("%s-%s", config.Region, config.ClusterName) // Generated ID format: {Region}-{ClusterName}
err = kom.Cluster(clusterID).Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
AWS EKS Cluster Registration Notes:
- AccessKey: The required AWS Access Key Identifier.
- SecretAccessKey: The corresponding AWS Secret Access Key.
- Region: Specifies the AWS geographic area, like us-east-1 or ap-southeast-1.
- ClusterName: The designated name of the target EKS cluster.
- RoleARN: (Optional) An IAM Role ARN can be specified for assuming roles during cross-account access.
- Upon successful registration, a unique ID is generated, typically formatted as {Region}-{ClusterName}.
- The system supports utilizing IAM roles for accessing clusters in different AWS accounts.
- AWS credential data is held only in memory and is automatically purged upon program termination.
Displaying Registered Clusters
This command outputs a summary of all known and registered clusters.
kom.Clusters().Show()
Selecting the Default Cluster
This code selects the operational context, defaulting to 'InCluster' if available, then 'default', or any existing cluster.
// Query pods within the kube-system namespace using the default context
var pods []corev1.Pod
err = kom.DefaultCluster().Resource(&corev1.Pod{}).Namespace("kube-system").List(&pods).Error
Selecting a Specific Cluster
Targeting operations toward a cluster explicitly identified by its registration ID.
// Target 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 Operations and Watch Examples for Built-in Objects
Define a standard Deployment object structure to demonstrate basic resource lifecycle manipulation via the utility.
var item v1.Deployment
var items []v1.Deployment
Creating a Resource
Instantiate a new resource object in the cluster based on the provided structure.
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 Query for a Specific Resource
Retrieving the current state of a named resource instance.
// Fetch the Deployment named 'nginx' in the 'default' namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Get(&item).Error
// Fetch the resource, enabling a 5-second caching mechanism for performance during frequent, batch operations.
// Filtering criteria are unaffected by this caching mechanism.
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").WithCache(5 * time.Second).Get(&item).Error
LIST Query for Resource Collections
Fetching multiple resources matching specified criteria across namespaces.
// List all Deployments within the 'default' namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").List(&items).Error
// List Deployments across 'default' and 'kube-system' namespaces
err := kom.DefaultCluster().Resource(&item).Namespace("default","kube-system").List(&items).Error
// List Deployments across all namespaces using wildcard specifier
err := kom.DefaultCluster().Resource(&item).Namespace("*").List(&items).Error
err := kom.DefaultCluster().Resource(&item).AllNamespace().List(&items).Error
// Apply a 5-second cache duration, which benefits batch retrieval operations.
err := kom.DefaultCluster().Resource(&item).WithCache(5 * time.Second).List(&nodeList).Error
LIST Query Using Label Selectors
Filtering collections based on associated metadata labels.
// List Deployments in 'default' namespace matching the label app=nginx
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithLabelSelector("app=nginx").List(&items).Error
LIST Query Using Multiple Labels
Combining multiple label criteria to refine the selection.
// List Deployments in 'default' namespace matching both app=nginx AND m=n labels
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithLabelSelector("app=nginx").WithLabelSelector("m=n").List(&items).Error
LIST Query Using Field Selectors
Filtering based on specific resource fields, such as metadata or status attributes.
// List Deployments in 'default' namespace where the metadata.name field equals test-deploy.
// Field selectors support standard K8s field definitions like metadata.name, metadata.namespace, spec.nodeName, status.phase, etc.
err := kom.DefaultCluster().Resource(&item).Namespace("default").WithFieldSelector("metadata.name=test-deploy").List(&items).Error
Paged Resource Listing via SQL
Executing SQL queries to fetch paginated results for cluster 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) // Reports the total count (e.g., 480)
fmt.Printf("Count %d\n", len(list)) // Reports the returned item count, matching the limit (e.g., 5)
Standard Update of Resource Content
Fetching a resource, modifying its specification, and committing the changes back to the cluster.
// Retrieve the Deployment named nginx to modify its annotations
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)
// Submit the full updated object back to the cluster
err = kom.DefaultCluster().Resource(&item).Update(&item).Error
PATCH Update of Resource Fields
Applying a partial, specified modification to a resource using standard patch types.
// Use Patch to set replicas to 5 and add a label to the nginx Deployment
patchData := `{
"spec": {
"replicas": 5
},
"metadata": {
"labels": {
"new-label": "new-value"
}
}
}`
err := kom.DefaultCluster().Resource(&item).Patch(&item, types.StrategicMergePatchType, patchData).Error
Deleting a Resource
Removing a specific resource instance from the cluster context.
// Delete the Deployment named nginx in the default namespace
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Delete().Error
Force Deletion of a Resource
Executing a deletion command that overrides standard protection mechanisms if necessary.
// Forcefully remove the Deployment named nginx
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").ForceDelete().Error
Retrieving Generic Resources (Including CRDs)
Fetching resources using Group-Version-Kind (GVK) definitions, which is essential for dynamic types.
// Specify GVK to retrieve Event resources in the default namespace
var list []corev1.Event
err := kom.DefaultCluster().GVK("events.k8s.io", "v1", "Event").Namespace("default").List(&list).Error
Watching Resource Revisions
Establishing a continuous stream to monitor changes for Pods within a specific namespace.
// Initiate a watch on Pod resources in the 'default' namespace
var watcher watch.Interface
var pod corev1.Pod
err := kom.DefaultCluster().Resource(&pod).Namespace("default").Watch(&watcher).Error
if err != nil {
fmt.Printf("Create Watcher Error %v", err)
return err
}
go func() {
defer watcher.Stop()
for event := range watcher.ResultChan() {
err := kom.DefaultCluster().Tools().ConvertRuntimeObjectToTypedObject(event.Object, &pod)
if err != nil {
fmt.Printf("Cannot convert object to *v1.Pod type: %v", err)
return
}
// Process the event type
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)
}
}
}()
Describing a Specific Resource
Obtaining the detailed output similar to the kubectl describe command.
// Describe the Deployment named nginx in the default namespace
var describeResult []byte
err := kom.DefaultCluster().Resource(&item).Namespace("default").Name("nginx").Describe(&item).Error
fmt.Printf("describeResult: %s", describeResult)
3. YAML Manifest Creation, Update, and Deletion
Apply a combined manifest containing both a ConfigMap and a Deployment for atomic operations.
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
`
// The initial Apply operation creates the resources, returning results for each entry.
results := kom.DefaultCluster().Applier().Apply(yaml)
// A subsequent Apply with the same YAML acts as an update operation.
results = kom.DefaultCluster().Applier().Apply(yaml)
// Execute deletion based on the provided YAML structure.
results = kom.DefaultCluster().Applier().Delete(yaml)
4. Container (Pod) Operations
Advanced interaction capabilities focusing on containerized workloads.
Retrieving Container Logs
Accessing the output stream from a specific container within a Pod.
// Obtain the log stream for the specified container in the Pod
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)
Executing Commands Non-Interactively
Running a static command inside a Pod container; this triggers the Exec callback mechanism.
// Execute the 'ps -ef' command inside the specified container
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)
Port Forwarding
Establishing a local tunnel to forward traffic to a container port.
err := kom.DefaultCluster().Resource(&v1.Pod{}).
Namespace("default").
Name("nginx-deployment-f576985cc-7czqr").
Ctl().Pod().
ContainerName("nginx").
PortForward("20088", "80", stopCh).Error
// This forwards traffic from local port 20088 to the Pod's port 80.
Streaming Command Execution
Executing commands that produce continuous output, triggering the StreamExec callback mechanism suitable for tools like ping.
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
// Example Output:
//Data PING 127.0.0.1 (127.0.0.1): 56 data bytes
//Data 64 bytes from 127.0.0.1: seq=0 ttl=42 time=0.023 ms
//Data 64 bytes from 127.0.0.1: seq=1 ttl=42 time=0.011 ms
//Data 64 bytes from 127.0.0.1: seq=2 ttl=42 time=0.012 ms
//Data 64 bytes from 127.0.0.1: seq=3 ttl=42 time=0.016 ms
Listing Container Files
Obtaining a file listing for a specified directory path within a container.
// List contents of the /etc directory in the nginx container
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").ListFiles("/etc")
Listing All Container Files Recursively
Retrieving a complete, recursive inventory of files starting from a specified directory.
// Recursively list all files under the /etc directory in the nginx container
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").ListAllFiles("/etc")
Downloading a File
Copying a file from the Pod filesystem to the local machine.
// Download the /etc/hosts file from the specified Pod
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").DownloadFile("/etc/hosts")
Downloading a File as a Tar Archive
Retrieving a file by packaging it into a tar archive during the transfer.
// Download the /etc/hosts file, compressed as a tar stream
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").DownloadTarFile("/etc/hosts")
Uploading a File
Transferring content from the local system into a container's filesystem.
// Save the string content 'txt-context' to /etc/demo.txt inside the Pod
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").SaveFile("/etc/demo.txt", "txt-context")
// Upload a file object from the local OS path to the /etc/ directory of the Pod
file, _ := os.Open(tempFilePath)
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").UploadFile("/etc/", file)
Deleting a Container File
Removing a file from the remote Pod filesystem.
// Remove the file /etc/xyz from the specified Pod container
kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().ContainerName("nginx").DeleteFile("/etc/xyz")
Retrieving Related Service Resources
Finding Service resources that reference the target Pod.
// Get Services linked to the specified Pod
svcs, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedService()
for _, svc := range svcs {
fmt.Printf("service name %v\n", svc.Name)
}
Retrieving Related Ingress Resources
Discovering Ingress objects routing traffic to the target Pod.
// Get Ingress resources linked to the specified Pod
ingresses, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedIngress()
for _, ingress := range ingresses {
fmt.Printf("ingress name %v\n", ingress.Name)
}
Retrieving Related PVC Resources
Identifying PersistentVolumeClaims attached to the target Pod.
// Get PVC resources linked to the specified Pod
pvcs, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedPVC()
for _, pvc := range pvcs {
fmt.Printf("pvc name %v\n", pvc.Name)
}
Retrieving Related PV Resources
Identifying PersistentVolumes utilized by the Pod's PVCs.
// Get PV resources linked to the specified Pod's PVCs
pvs, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedPV()
for _, pv := range pvs {
fmt.Printf("pv name %v\n", pv.Name)
}
Retrieving Related Endpoints
Finding the associated Endpoints objects that map Service selectors to Pod network addresses.
// Get Endpoints resources linked to the specified Pod
endpoints, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedEndpoints()
for _, endpoint := range endpoints {
fmt.Printf("endpoint name %v\n", endpoint.Name)
}
Retrieving Runtime Environment Variables
Extracting active environment configuration from the running Pod processes.
// Obtain environment variables derived from runtime execution in the Pod
envs, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedEnv()
for _, env := range envs {
fmt.Printf("env %s %s=%s\n", env.ContainerName, env.EnvName, env.EnvValue)
}
Retrieving Definition Environment Variables
Extracting environment configuration directly from the Pod specification YAML.
// Obtain environment variables declared in the Pod definition manifest
envs, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedEnvFromPod()
for _, env := range envs {
fmt.Printf("env %s %s=%s\n", env.ContainerName, env.EnvName, env.EnvValue)
}
Retrieving Potentially Schedulable Nodes
Identifying nodes compatible with the Pod based on NodeSelectors, affinity rules, and taints, excluding runtime scheduling factors like resource pressure.
// Determine nodes suitable for scheduling the specified Pod
nodes, err := kom.DefaultCluster().Namespace("default").Name("nginx").Ctl().Pod().LinkedNode()
for _, node := range nodes {
fmt.Printf("reason:%s\t node name %s\n", node.Reason, node.Name)
}
5. Custom Resource Definition (CRD) Operations
This section details CRUD and Watch operations for resources defined via CRDs, utilizing unstructured data types when schema details are unknown ahead of time.
Operations mirror built-in resource handling. To interact with CRDs without pre-defined Go structs, use unstructured.Unstructured and specify the Group, Version, and Kind via GVK or the simplified CRD method.
Define a generic object structure to capture the dynamic results from CRD interactions.
var item unstructured.Unstructured
Creating a Custom Resource Definition (CRD)
Applying the definition manifest that establishes the new resource type within the cluster.
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)
Creating an Instance of a CRD Object
Instantiating a custom resource based on the previously defined schema.
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
GET Retrieval of a Single CR Object
Fetching the current state of a specific custom resource instance.
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Name(item.GetName()).Namespace(item.GetNamespace()).Get(&item).Error
LIST Retrieval of CR Objects
Collecting a collection of custom resources based on scope.
var crontabList []unstructured.Unstructured
// Query CronTab resources within the 'default' namespace
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace(crontab.GetNamespace()).List(&crontabList).Error
// Query CronTab resources across all namespaces
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").AllNamespace().List(&crontabList).Error
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace("*").List(&crontabList).Error
Updating a CR Object
Applying incremental changes to a custom resource instance.
patchData := `{
"spec": {
"image": "patch-image"
},
"metadata": {
"labels": {
"new-label": "new-value"
}
}
}`
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Name(crontab.GetName()).Namespace(crontab.GetNamespace()).Patch(&crontab, types.StrategicMergePatchType, patchData).Error
Deleting a CR Object
Removing a custom resource instance from the cluster.
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Name(crontab.GetName()).Namespace(crontab.GetNamespace()).Delete().Error
Force Deletion of a CR Object
Forcibly removing the custom resource instance.
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Name(crontab.GetName()).Namespace(crontab.GetNamespace()).ForceDelete().Error
Watching CR Objects
Monitoring real-time events associated with a specific type of custom resource.
var watcher watch.Interface
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace("default").Watch(&watcher).Error
if err != nil {
fmt.Printf("Create Watcher Error %v", err)
}
go func() {
defer watcher.Stop()
for event := range watcher.ResultChan() {
var item *unstructured.Unstructured
item, err := kom.DefaultCluster().Tools().ConvertRuntimeObjectToUnstructuredObject(event.Object)
if err != nil {
fmt.Printf("Cannot convert object to Unstructured type: %v", err)
return
}
// Process the event type
switch event.Type {
case watch.Added:
fmt.Printf("Added Unstructured [ %s/%s ]\n", item.GetNamespace(), item.GetName())
case watch.Modified:
fmt.Printf("Modified Unstructured [ %s/%s ]\n", item.GetNamespace(), item.GetName())
case watch.Deleted:
fmt.Printf("Deleted Unstructured [ %s/%s ]\n", item.GetNamespace(), item.GetName())
}
}
}()
Describe Query for a CRD Resource
Generating a descriptive output for a custom resource instance.
// Describe the CronTab resource named item in the default namespace
var describeResult []byte
err := kom.DefaultCluster().CRD("stable.example.com", "v1", "CronTab").Namespace("default").Name(item.GetName()).Describe(&item).Error
fmt.Printf("describeResult: %s", describeResult)
Retrieving Pods Managed by a CRD
Finding Pod resources directly controlled by a specified custom controller instance, like a StatefulSet.
pods, err := kom.DefaultCluster().CRD("apps.kruise.io", "v1beta1", "StatefulSet").
Namespace("default").Name("sample").Ctl().CRD().ManagedPods()
for _, pod := range pods {
fmt.Printf("Get pods: %v", pod.GetName())
}
6. Cluster Parameter Information Retrieval
Accessing metadata and configuration details about the connected Kubernetes cluster.
// Retrieve documentation pertaining to the current cluster context
kom.DefaultCluster().Status().Docs()
// Fetch available API resources registered on the cluster server
kom.DefaultCluster().Status().APIResources()
// Get a list of all Custom Resource Definitions known to the cluster
kom.DefaultCluster().Status().CRDList()
// Query the version information of the connected Kubernetes API server
kom.DefaultCluster().Status().ServerVersion()
// Get aggregated counts for various resource types present in the cluster, limited to the top 10 most populous types.
kom.DefaultCluster().Status().GetResourceCountSummary(10)
7. Callback Mechanism Customization
An extensible architecture allows defining custom functions that execute before or after core operations. Execution order is usually based on registration sequence by default.
- The built-in callback hooks support operations: get, list, create, update, patch, delete, exec, stream-exec, logs, watch, and doc.
- Internal callback names include standardized prefixes:
kom:get,kom:list,kom:create, etc. - Sequence adjustment is possible using
.After("kom:get")or.Before("kom:get")methods relative to internal hooks. - Specific handlers can be deleted using
.Delete("kom:get"). - Handlers can be completely replaced using
.Replace("kom:get", cb).
// Register a custom callback function for the GET resource retrieval operation
kom.DefaultCluster().Callback().Get().Register("get", cb)
// Register callback for Listing operations
kom.DefaultCluster().Callback().List().Register("list", cb)
// Register callback for Create operations
kom.DefaultCluster().Callback().Create().Register("create", cb)
// Register callback for Update operations
kom.DefaultCluster().Callback().Update().Register("update", cb)
// Register callback for Patch operations
kom.DefaultCluster().Callback().Patch().Register("patch", cb)
// Register callback for Delete operations
kom.DefaultCluster().Callback().Delete().Register("delete", cb)
// Register callback for Watch operations
kom.DefaultCluster().Callback().Watch().Register("watch",cb)
// Register callback for Exec Pod command execution
kom.DefaultCluster().Callback().Exec().Register("exec", cb)
// Register callback for retrieving Pod logs
kom.DefaultCluster().Callback().Logs().Register("logs", cb)
// Remove the previously registered 'get' handler
kom.DefaultCluster().Callback().Get().Delete("get")
// Replace the existing 'get' handler with a new function definition
kom.DefaultCluster().Callback().Get().Replace("get", cb)
// Execute this custom callback after the built-in 'kom:get' handler has completed its execution
kom.DefaultCluster().Callback().After("kom:get").Register("get", cb)
// Execute this custom callback before the built-in 'kom:create' handler runs.
// Example 1: Perform authorization checks before creation; return error to halt creation.
// Example 2: Filter the retrieved list (Statement.Dest) after a LIST operation, removing undesired resources before they reach the user.
kom.DefaultCluster().Callback().Before("kom:create").Register("create", cb)
// Definition of a sample custom callback function
func cb(k *kom.Kubectl) error {
stmt := k.Statement
gvr := stmt.GVR
ns := stmt.Namespace
name := stmt.Name
// Output relevant operation context information
fmt.Printf("Get %s/%s(%s)\n", ns, name, gvr)
fmt.Printf("Command %s/%s(%s %s)\n", ns, name, stmt.Command, stmt.Args)
return nil
// Returning an error here will prevent subsequent callbacks and the primary operation from executing.
}
8. SQL Querying of Kubernetes Resources
Simplified data retrieval using SQL syntax directly against cluster resources.
- The
Sql()method facilitates these queries. Tables are recognized by the full names or short aliases of all registered resources, including CRDs accessible within the current cluster context. - Common table names include: pod, deployment, service, ingress, pvc, pv, node, namespace, secret, configmap, and many others.
- Currently, only the asterisk (
*) is supported for selecting all fields (select *). - Supported conditional operators include:
=,!=,>=,<=,<>,like,in,not in,and,or, andbetween. - Sorting is limited to a single field; the default order, if unspecified, is descending by creation timestamp.
Querying Built-in Kubernetes Resources
Fetching Deployments based on namespace criteria.
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())
}
Querying CRD Resources
Executing SQL against a custom resource type registered in the cluster (e.g., Kubevirt VM).
// 'vm' refers to a Kubevirt CRD resource type
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())
}
Chained Query Construction
Building the SQL query step-by-step using dedicated methods.
// Query a list of Pods using chained methods
err := kom.DefaultCluster().From("pod").
Where("metadata.namespace = ? or metadata.namespace= ? ", "kube-system", "default").
Order("metadata.creationTimestamp desc").
List(&list).Error
Support for Nested List Attributes in Queries
SQL syntax allows querying into nested array structures within resource specifications.
// Query pods where any container's port name contains the substring 'k8m'
sql := "select * from pod where spec.containers.ports.name like '%k8m%' "
var list []v1.Pod
err := kom.DefaultCluster().Sql(sql).List(&list).Error
for _, d := range list {
t.Logf("List Items foreach %s,%s\n", d.GetNamespace(), d.GetName())
}
9. Miscellaneous Management Actions
Specific, high-level operations for common resource controllers.
Deployment Restart
Triggers a full restart cycle for a Deployment.
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Restart()
Deployment Scaling
Setting the desired replica count for a Deployment.
// Set the replica count for the Deployment named nginx to 3
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Scale(3)
Deployment Stop
Scaling a Deployment down to zero replicas while preserving the last non-zero count in annotations.
// Set the replica count for the Deployment named nginx to zero
// The active replica count is stored in an annotation for later restoration.
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Stop()
Deployment Restore
Restoring a Deployment's replica count from the value stored in annotations, defaulting to 1 if no annotation exists.
// Revert the Deployment named nginx to its previously recorded replica count
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Scaler().Restore()
Deployment Image Tag Update
Modifying the image tag for a specific container within a Deployment.
// Update the image tag for the container named 'main' in the nginx Deployment to version '20241124'
err = kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Deployment().ReplaceImageTag("main","20241124")
Deployment Rollout History
Fetching the complete record of past rollout revisions for a Deployment.
// Query the upgrade history for the Deployment named nginx
result, err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().History()
Deployment Rollout Undo
Reverting a Deployment to a previous revision state.
// Perform a general rollback on the Deployment named nginx
result, err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Undo()
// Rollback the Deployment named nginx to a specific revision number (e.g., revision '6')
result, err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Undo("6")
Deployment Rollout Pause
Halting any active revision process for the Deployment.
// Suspend the ongoing upgrade process for the Deployment
err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Pause()
Deployment Rollout Resume
Resuming an update process that was previously suspended.
// Restart the suspended upgrade process for the Deployment
err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Resume()
Deployment Rollout Status Check
Determining the current status of the Deployment's active rollout.
// Check the current status of the rollout for the Deployment named nginx
result, err := kom.DefaultCluster().Resource(&Deployment{}).Namespace("default").Name("nginx").Ctl().Rollout().Status()
Deployment HPA Retrieval
Listing associated Horizontal Pod Autoscalers configured for a Deployment.
// Display all HPAs configured for the Deployment named nginx-web in default namespace
list, err := kom.DefaultCluster().Resource(&v1.Deployment{}).Namespace("default").Name("nginx-web").Ctl().Deployment().HPAList()
for _, item := range list {
t.Logf("HPA %s\n", item.Name)
}
Tainting a Node
Applying a scheduling exclusion rule to a node.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Node().Taint("dedicated=special-user:NoSchedule")
Untainting a Node
Removing a previously applied taint restriction from a node.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Node().UnTaint("dedicated=special-user:NoSchedule")
Cordoning a Node
Preventing the scheduler from placing new Pods onto the node.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Node().Cordon()
Uncordoning a Node
Restoring the node's ability to accept new Pods from the scheduler.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Node().UnCordon()
Draining a Node
Safely evacuating all existing Pods from a node prior to maintenance.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Node().Drain()
Querying Node IP Resource Allocation
Checking the total, utilized, and available IP addresses on a node, with optional caching to reduce API load.
nodeName := "lima-rancher-desktop"
total, used, available := kom.DefaultCluster().Resource(&corev1.Node{}).WithCache(5 * time.Second).Name(nodeName).Ctl().Node().IPUsage()
fmt.Printf("Total %d, Used %d, Available %d\n", total, used, available)
//Example Output: Total 256, Used 6, Available 250
Querying Pod Count Per Node
Determining the number of Pods currently scheduled onto a specific node, supporting caching.
nodeName := "lima-rancher-desktop"
total, used, available := kom.DefaultCluster().Resource(&corev1.Node{}).WithCache(5 * time.Second).Name(nodeName).Ctl().Node().PodCount()
fmt.Printf("Total %d, Used %d, Available %d\n", total, used, available)
//Example Output: Total 110, Used 9, Available 101
Querying Node Resource Usage Statistics
Retrieving detailed CPU/Memory requests, limits, and allocatable capacity for a node, supporting caching.
nodeName := "lima-rancher-desktop"
usage := kom.DefaultCluster().Resource(&corev1.Node{}).WithCache(5 * time.Second).Name(nodeName).Ctl().Node().ResourceUsage()
fmt.Printf("Node Usage %s\n", utils.ToJSON(usage))
// Output details include current requests, limits, allocatable amounts, and usage ratios.
Applying Labels to Resources
Attaching metadata labels to a specified resource instance.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Label("name=zhangsan")
Removing Labels from Resources
Removing a specific label key from a resource's metadata.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Label("name-")
Applying Annotations to Resources
Adding metadata annotations to a resource object.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Annotate("name=zhangsan")
Removing Annotations from Resources
Deleting a specified annotation key from a resource's metadata.
err = kom.DefaultCluster().Resource(&Node{}).Name("kind-control-plane").Ctl().Annotate("name-")
Creating a Node Shell Session
Provisioning a temporary Pod for shell access directly related to a Node.
ns, pod, container, err := kom.DefaultCluster().Resource(&v1.Node{}).Name("kind-control-plane").Ctl().Node().CreateNodeShell()
fmt.Printf("Node Shell ns=%s podName=%s containerName=%s", ns, pod, container)
Creating a Kubectl Shell Session
Setting up a temporary Pod environment capable of running kubectl commands, requiring cluster configuration details.
ns, pod, container, err := kom.DefaultCluster().Resource(&v1.Node{}).Name(name).Ctl().Node().CreateKubectlShell(kubeconfig)
fmt.Printf("Kubectl Shell ns=%s podName=%s containerName=%s", ns, pod, container)
Counting PVCs for a StorageClass
Determining how many PersistentVolumeClaims utilize a specific StorageClass.
count, err := kom.DefaultCluster().Resource(&v1.StorageClass{}).Name("hostpath").Ctl().StorageClass().PVCCount()
fmt.Printf("pvc count %d\n", count)
Counting PVs for a StorageClass
Determining how many PersistentVolumes are provisioned by a specific StorageClass.
count, err := kom.DefaultCluster().Resource(&v1.StorageClass{}).Name("hostpath").Ctl().StorageClass().PVCount()
fmt.Printf("pv count %d\n", count)
Setting StorageClass as Default
Designating a StorageClass for automatic provisioning when no explicit class is requested.
err := kom.DefaultCluster().Resource(&v1.StorageClass{}).Name("hostpath").Ctl().StorageClass().SetDefault()
Setting IngressClass as Default
Designating a preferred Ingress controller class for the cluster.
err := kom.DefaultCluster().Resource(&v1.IngressClass{}).Name("nginx").Ctl().IngressClass().SetDefault()
Retrieving Pods Managed by Controllers
Listing all Pods that are currently managed by a specified Deployment, StatefulSet, or DaemonSet.
list, err := kom.DefaultCluster().Namespace("default").Name("managed-pods").Ctl().Deployment().ManagedPods()
for _, pod := range list {
fmt.Printf("ManagedPod: %v", pod.Name)
}
Obtaining All Node Labels Aggregated
Collecting a consolidated map of all labels present across every node in the cluster.
// labels variable will be of type map[string]string
labels, err := kom.DefaultCluster().Resource(&v1.Node{}).Ctl().Node().AllNodeLabels()
fmt.Printf("%s", utils.ToJSON(labels))
Viewing Pod Resource Utilization
Analyzing the CPU/Memory requests, limits, and current consumption for a specific Pod, including fractions.
podName := "coredns-ccb96694c-jprpf"
ns := "kube-system"
usage := kom.DefaultCluster().Resource(&corev1.Pod{}).Name(podName).Namespace(ns).Ctl().Pod().ResourceUsage()
fmt.Printf("Pod Usage %s\n", utils.ToJSON(usage))
// Output includes requested values, limits, allocatable resources, and usage percentages.
Retrieving Field Documentation
Accessing explanatory documentation for specific fields within a resource schema.
var docResult []byte
item := v1.Deployment{}
field := "spec.replicas"
field = "spec.template.spec.containers.name"
field = "spec.template.spec.containers.imagePullPolicy"
field = "spec.template.spec.containers.livenessProbe.successThreshold"
err := kom.DefaultCluster().
Resource(&item).DocField(field).Doc(&docResult).Error
fmt.Printf("Get Deployment Doc [%s] :%s", field, string(docResult))
Extra Details
This utility abstracts the complexity inherent in managing distributed cloud-native resources like Kubernetes clusters. While the original documentation referenced 58 specific integrated tools, the core value lies in providing uniform access methods (CRUD, SQL, Pod control) regardless of the underlying resource type (built-in or custom). The integration patterns—stdio and SSE—align with modern application communication standards for cloud service interaction, allowing external control planes to manage the cluster pool efficiently. The SQL capability significantly lowers the barrier to querying complex state information.
Conclusion
This KubeAdmin Utility delivers a robust, unified interface for administering Kubernetes environments, closely mirroring the cloud computing ethos of providing scalable, self-service resource management. Its capability to handle both native and custom resources via consistent patterns, including powerful SQL querying, makes it an essential component for streamlined operations within complex, multi-cluster cloud infrastructures.
