k8m Documentation

repository·main·Indexed 21 days ago

https://github.com/weibaohui/k8m

An AI-driven, lightweight Kubernetes dashboard for multi-cluster management. Features include AI-powered log analysis, YAML translation, and resource explanation via Ollama, self-hosted AI, and Model Context Protocol (MCP). The documentation covers cluster management (AWS EKS), security (OIDC SSO, 2FA), a pluggable subsystem architecture for extending functionality via Go and Lua scripts, and specific plugins like Kubeconfig Export.

Tokens
65.8K
Snippets
123
Records
213
Agent score
74%

What's inside k8m

  1. Overview of Built-in Inspection Lua Scripts

    main

    The inspection module in k8m includes a collection of built-in Lua scripts used for Kubernetes cluster inspection and compliance checking. These scripts are used to detect misconfigurations, security risks, and resource usage issues across various Kubernetes resources.

    Note: The script contents are defined by the Go-embedded scripts within the application, and this index is automatically generated.

  2. Overview of K8M AI-Driven Kubernetes Dashboard

    main

    k8m is a lightweight, AI-driven Mini Kubernetes Dashboard designed for simplified cluster management. It is built using Golang (backend) and Baidu AMIS (frontend), and uses kom as its Kubernetes API client.

    Key capabilities include:

    • AI Integration: Provides intelligent support for resource explanation, YAML translation, log diagnosis, and command recommendations using built-in models (like Qwen2.5-Coder-7B) or custom models (via Ollama or private APIs).
    • Multi-Cluster Management: Automatically recognizes clusters via InCluster mode or by scanning kubeconfig files in the same directory. Supports heartbeat detection and automatic reconnection.
    • MCP Integration: Visual management of Model Context Protocol (MCP) tools, allowing large language models to execute Kubernetes operations via 49 built-in multi-cluster MCP tools.
    • Plugin-Based Architecture: Features are modular and enabled on demand to minimize resource consumption.
    • Pod Management: Supports real-time log viewing, file browsing (upload/download/edit/delete), and direct shell command execution within Pods.
    • Security: Integrated multi-cluster permission management (Read-only, Exec, or Admin) and MCP permission integration, ensuring AI-driven operations respect user permissions.
  3. K8M Documentation Overview

    main

    K8M provides a comprehensive suite of documentation for managing Kubernetes clusters, configuring AI models (Ollama, self-hosted, MCP), and extending system functionality via plugins and Lua scripts.

    Key documentation areas include:

    • Cluster Management: AWS EKS integration and multi-instance deployment.
    • AI & LLM Integration: Configuring Ollama, self-hosted AI, and Model Context Protocol (MCP) for tools like GitHub Copilot.
    • Security & Access: OIDC Single Sign-On (SSO), Two-Factor Authentication (2FA), and temporary administrator account setup.
    • Extensibility: Writing Lua inspection rules and developing plugins.
    • System Configuration: Database connections, variable parameters, custom menus, and event forwarding.
  4. Explore K8M API Route Structure

    main

    The K8M API service is organized into several functional routing groups. Understanding these top-level routes is essential for interacting with the system's core capabilities:

    • /auth: Authentication and SSO/OIDC flows.
    • /api: General API service routes.
    • /k8s: Kubernetes resource and workload management.
    • /mgm: System management (users, templates, logs, clusters).
    • /params: Public parameters and configuration options.
    • /ai: AI-driven analysis services (events, logs, resources).
    • /admin: Administrative controls (system config, user management, MCP).
  5. Implement Frontend using AMIS JSON

    main

    The k8m plugin architecture enforces strict constraints on frontend development to ensure stability and security:

    • Format: Plugins are only allowed to use AMIS JSON to describe the UI.
    • Prohibited: You cannot introduce React, Vue, or any other frontend frameworks.
    • Prohibited: You cannot execute arbitrary JavaScript logic within the frontend description.
    • Loading: The frontend fetches AMIS JSON via a unified API. If the plugin is not enabled, the request will return a 404 error.
    • Role: AMIS JSON is used solely to describe the interface structure; it does not participate in permission or authorization decisions.
  6. Use the Plugin Capability API

    main

    The pkg/plugins/api package provides an abstraction for plugin capabilities. This system uses a No-Op pattern: if a capability is called but not registered, the system returns a safe, no-op implementation instead of failing.

    Currently supported capabilities include:

    • AIChatService(): For AI chat functionality.
    • WebhookService(): For sending webhooks.

    Developers can add new capabilities following this pattern.

  7. Plugin development prohibitions (Anti-patterns)

    main

    To maintain system stability and security, the following actions are strictly prohibited for plugin developers:

    • Core Modification: Directly modifying core system code.
    • Routing: Registering global routes privately.
    • Frontend Injection: Returning arbitrary frontend code.
    • Security Bypass: Bypassing RBAC (Role-Based Access Control) authentication.
    • Database Violation: Accessing database tables belonging to other modules or plugins.
  8. Manage Plugin Lifecycle and States

    main

    Plugins transition through several explicit states. Understanding these states is critical for managing background tasks and data persistence:

    StateDescriptionAvailable Actions
    StatusUninstalledRegistered in Go; metadata loaded at startup.Install
    StatusInstalledDB tables created; base data initialized.Enable, Uninstall
    StatusEnabledMenus visible; APIs accessible; AMIS JSON loadable.Start, Disable, Uninstall
    StatusRunningBackground tasks and cron jobs are active.Stop, Disable, Uninstall
    StatusStoppedBackground tasks stopped, but plugin remains enabled.Start, Disable, Uninstall
    StatusDisabledMenus hidden; APIs inaccessible; data/permissions retained.Enable, Uninstall

    Lifecycle Methods

    • Install: Creates DB tables and initializes data. Must be idempotent. (Uninstalled $\rightarrow$ Installed)
    • Upgrade: Performs DB migrations and version compatibility handling. Can be triggered in any state. (No state change)
    • Enable: Registers routes and exposes menus/APIs. Does NOT start background tasks. (Installed/Disabled $\rightarrow$ Enabled)
    • Disable: Hides menus and revokes routes. Automatically stops background tasks. (Enabled/Stopped $\rightarrow$ Disabled)
    • Start: Starts non-blocking background goroutines or event listeners. (Enabled/Stopped $\rightarrow$ Running)
    • Stop: Stops background goroutines and cleans up resources. (Running $\rightarrow$ Stopped)
    • Uninstall: Removes plugin info and optionally deletes DB tables (based on keepData parameter). (Any state $\rightarrow$ Uninstalled)
  9. How the frontend Fetcher works with AMIS

    main

    The K8M frontend uses a custom fetcher (defined in ui/src/components/Amis/fetcher.ts) to wrap all HTTP requests. This fetcher is automatically injected into the AMIS rendering process.

    Key Features

    • Automatic Authentication: Automatically adds Authorization: Bearer ${token} from localStorage to every request.
    • Cluster Context Injection: Automatically handles cluster URL rewriting. It supports specifying a target cluster via the x-k8m-target-cluster header or the __cluster query parameter.
    • Error Handling:
      • 401: Automatically redirects to /#/login.
      • 512: Indicates insufficient cluster permissions; redirects to cluster user management.
      • 403: Indicates insufficient permissions.

    Usage in AMIS Schema

    When defining an AMIS component, the api field will automatically use this fetcher:

    {
      "type": "crud",
      "api": {
        "method": "get",
        "url": "/k8s/cluster/${cluster}/pods"
      }
    }
    renderAmis(schema, initialData, {
        theme: 'cxd',
        fetcher,  // Injected custom fetcher
        isCancel: value => axios.isCancel(value),
    })
  10. How the K8M plugin system works

    main

    K8M is built around a plugin architecture where all features are implemented as plugins with a full lifecycle. Plugins are discovered at compile time via Go registration.

    Plugin Lifecycle

    All lifecycle methods must be idempotent:

    • Install(ctx): Create tables and initialize data.
    • Upgrade(ctx): Migrate schema/data during version changes.
    • Enable(ctx): Register routes and expose menus.
    • Disable(ctx): Hide menus and unregister routes.
    • Start(ctx): Start background goroutines or subscribe to the EventBus.
    • Stop(ctx): Stop goroutines and clean up resources.
    • StartCron(ctx, spec): Execute scheduled tasks.
    • Uninstall(ctx): Delete tables (or retain data if requested).

    Routing Types

    Plugins use specific router types to define their scope:

    • ClusterRouter: /k8s/cluster/{cluster}/plugins/{name}/* (Cluster-specific operations)
    • ManagementRouter: /mgm/plugins/{name}/* (General management operations)
    • PluginAdminRouter: /admin/plugins/{name}/* (Platform administrator operations)
    • RootRouter: Root-level routes (rarely used)

    Plugin Directory Structure

    pkg/plugins/modules/{plugin-name}/
    ├── metadata.go          # Plugin metadata and capability declarations
    ├── lifecycle.go         # Lifecycle interface implementation
    ├── models/
    │   ├── db.go           # Init/Upgrade/DropDB functions
    │   └── *.go            # Model definitions
    ├── route/
    │   ├── cluster_api.go  # Cluster operations
    │   ├── mgm_api.go     # Management operations
    │   └── admin_api.go   # Admin operations
    ├── frontend/
    │   └── *.json          # AMIS JSON files
    ├── controller/          # HTTP handlers (optional)
    └── service/             # Business logic (optional)
  11. Understand the k8m Plugin (Feature Module) Architecture

    main

    In k8m, a plugin is not a simple hook or lightweight extension, but a pluggable subsystem. A plugin is a complete functional unit that can be installed, enabled, disabled, or uninstalled.

    Key characteristics include:

    • Capabilities: A plugin can provide menu entries, frontend pages (via AMIS JSON), backend APIs, RBAC permission definitions, SQL schemas, initialization/cleanup logic, and background tasks (goroutines or cron jobs).
    • Isolation: Plugins should have clear capability boundaries and no implicit dependencies on each other.
    • Implementation: Plugin descriptions are primarily written in Go code for compile-time validation and refactorability, while frontend rendering is strictly handled via AMIS JSON.
    • Lifecycle: Plugins follow a formal state machine from Uninstalled to Running or Disabled.
  12. Understand k8m MCP permissions and scope

    main

    The MCP access link is bound to the permissions of the user who created it. The available permission levels for the k8m MCP Server are:

    • Cluster Read-Only (集群只读): Can only view cluster information; no execution allowed.
    • Exec Command (Exec命令): Can execute commands within the cluster.
    • Cluster Administrator (集群管理员): Full access, including cluster management, deployment management, dynamic resource management, node management, Pod management, YAML management, storage management, and Ingress management.

    Scope: The MCP server manages the same range of clusters that are currently connected and managed within the k8m interface.