agent

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package agent provides Agent connection management for the STX Control Plane. agent 包提供 STX Control Plane 的 Agent 连接管理功能。

Package agent provides Agent distribution and management for the STX Control Plane. agent 包提供 STX Control Plane 的 Agent 分发和管理功能。

Package agent provides Agent connection management for the STX Control Plane. agent 包提供 STX Control Plane 的 Agent 连接管理功能。

Package agent provides Agent distribution and management for the STX Control Plane. agent 包提供 STX Control Plane 的 Agent 分发和管理功能。

Package agent provides Agent connection management for the STX Control Plane. agent 包提供 STX Control Plane 的 Agent 连接管理功能。

Index

Constants

View Source
const (
	// DefaultHeartbeatInterval is the default interval for Agent heartbeats.
	// DefaultHeartbeatInterval 是 Agent 心跳的默认间隔。
	DefaultHeartbeatInterval = 10 * time.Second

	// DefaultHeartbeatTimeout is the default timeout for considering an Agent offline.
	// DefaultHeartbeatTimeout 是判断 Agent 离线的默认超时时间。
	DefaultHeartbeatTimeout = 30 * time.Second

	// DefaultCheckInterval is the default interval for checking heartbeat timeouts.
	// DefaultCheckInterval 是检查心跳超时的默认间隔。
	DefaultCheckInterval = 5 * time.Second
)

Default configuration values 默认配置值

View Source
const (
	// PackageStreamChunkSize is the raw chunk size used by DownloadPackage (256KB).
	// PackageStreamChunkSize 是 DownloadPackage 使用的原始数据块大小(256KB)。
	PackageStreamChunkSize = 256 * 1024

	// DefaultPackageStallTimeout fails a transfer when no bytes are served for this long.
	// DefaultPackageStallTimeout 在该时长内没有任何数据被拉取时判定传输停滞。
	DefaultPackageStallTimeout = 2 * time.Minute

	// DefaultPackageTransferMaxDuration caps the whole transfer.
	// DefaultPackageTransferMaxDuration 是整个传输的最长时长。
	DefaultPackageTransferMaxDuration = 2 * time.Hour
)
View Source
const DefaultAgentBinary = "stx-agent"

DefaultAgentBinary is the default name of the Agent binary. DefaultAgentBinary 是 Agent 二进制文件的默认名称。

View Source
const DefaultAgentCAFile = DefaultConfigDir + "/certs/ca.crt"

DefaultAgentCAFile is the default on-host path for the Control Plane CA certificate. DefaultAgentCAFile 是 Control Plane CA 证书在本机的默认路径。

View Source
const DefaultAgentHomePath = "$HOME/.stx/agent"

DefaultAgentHomePath is the default Agent home shown in one-click install commands. Prefer $HOME form so zsh/bash do not mangle a leading tilde in --install-dir=... DefaultAgentHomePath 是一键安装命令中展示的默认 Agent 主目录。 优先使用 $HOME 形式,避免 zsh/bash 在 --install-dir=... 里误处理开头的 ~。

View Source
const DefaultConfigDir = DefaultInstallDir + "/etc"

DefaultConfigDir is the default configuration directory derived from DefaultInstallDir. DefaultConfigDir 是由 DefaultInstallDir 推导的默认配置目录。

View Source
const DefaultInstallDir = "$HOME/.stx/agent"

DefaultInstallDir is the default Agent home embedded in the install script ($HOME form). DefaultInstallDir 是安装脚本内嵌的默认 Agent 主目录($HOME 形式)。

View Source
const DefaultServiceName = "stx-agent"

DefaultServiceName is the default service name (systemd unit / launchd label suffix). DefaultServiceName 是默认服务名(systemd unit / launchd label 后缀)。

View Source
const DefaultSupportDir = DefaultInstallDir

DefaultSupportDir is the default support-asset root (same as Agent home). DefaultSupportDir 是默认辅助资产根目录(与 Agent 主目录相同)。

Variables

View Source
var (
	// ErrAgentNotFound indicates the Agent was not found.
	// ErrAgentNotFound 表示未找到 Agent。
	ErrAgentNotFound = errors.New("agent: agent not found")
	// ErrAgentNotConnected indicates the Agent is not connected.
	// ErrAgentNotConnected 表示 Agent 未连接。
	ErrAgentNotConnected = errors.New("agent: agent not connected")
	// ErrCommandTimeout indicates the command execution timed out.
	// ErrCommandTimeout 表示命令执行超时。
	ErrCommandTimeout = errors.New("agent: command execution timeout")
	// ErrStreamNotAvailable indicates the command stream is not available.
	// ErrStreamNotAvailable 表示命令流不可用。
	ErrStreamNotAvailable = errors.New("agent: command stream not available")
)

Errors for Agent Manager operations Agent Manager 操作的错误定义

View Source
var (
	// ErrPackageServeNotFound is returned when a transfer id is unknown or expired.
	// ErrPackageServeNotFound 表示传输标识不存在或已过期。
	ErrPackageServeNotFound = errors.New("package transfer not found or expired / 安装包传输不存在或已过期")

	// ErrPackageTransferStalled is returned when the Agent stops pulling data.
	// ErrPackageTransferStalled 表示 Agent 停止拉取数据。
	ErrPackageTransferStalled = errors.New("package transfer stalled / 安装包传输停滞")
)
View Source
var SupportedPlatforms = []SupportedPlatform{
	{OS: "linux", Arch: "amd64", BinaryName: "stx-agent-linux-amd64"},
	{OS: "linux", Arch: "arm64", BinaryName: "stx-agent-linux-arm64"},
	{OS: "darwin", Arch: "amd64", BinaryName: "stx-agent-darwin-amd64"},
	{OS: "darwin", Arch: "arm64", BinaryName: "stx-agent-darwin-arm64"},
}

SupportedPlatforms defines all supported OS and architecture combinations. SupportedPlatforms 定义所有支持的操作系统和架构组合。 Requirements: 2.1, 2.2 - Supports linux-amd64 and linux-arm64.

Functions

func FormatInstallCommand

func FormatInstallCommand(controlPlaneAddr string) string

FormatInstallCommand builds the one-click Agent install command with an explicit --install-dir. FormatInstallCommand 生成带显式 --install-dir 的 Agent 一键安装命令。

func GetBinaryName

func GetBinaryName(os, arch string) (string, bool)

GetBinaryName returns the binary name for a platform. GetBinaryName 返回平台的二进制文件名称。

func IsPlatformSupported

func IsPlatformSupported(os, arch string) bool

IsPlatformSupported checks if a platform is supported. IsPlatformSupported 检查平台是否受支持。

func NormalizeArch

func NormalizeArch(arch string) string

NormalizeArch normalizes architecture names to standard format. NormalizeArch 将架构名称标准化为标准格式。 Requirements: 2.1 - Supports architecture detection (x86_64 -> amd64, aarch64 -> arm64).

func NormalizeOS

func NormalizeOS(os string) string

NormalizeOS normalizes OS names to standard format. NormalizeOS 将操作系统名称标准化为标准格式。

Types

type AgentConnection

type AgentConnection struct {
	// AgentID is the unique identifier of the Agent.
	// AgentID 是 Agent 的唯一标识符。
	AgentID string

	// HostID is the ID of the host this Agent is running on.
	// HostID 是此 Agent 运行所在主机的 ID。
	HostID uint

	// IPAddress is the IP address of the Agent.
	// IPAddress 是 Agent 的 IP 地址。
	IPAddress string

	// Hostname is the hostname of the Agent.
	// Hostname 是 Agent 的主机名。
	Hostname string

	// Version is the Agent version.
	// Version 是 Agent 版本。
	Version string

	// Stream is the bidirectional gRPC stream for commands.
	// Stream 是用于命令的双向 gRPC 流。
	Stream grpc.BidiStreamingServer[pb.CommandResponse, pb.CommandRequest]

	// LastHeartbeat is the timestamp of the last heartbeat received.
	// LastHeartbeat 是收到的最后一次心跳的时间戳。
	LastHeartbeat time.Time

	// Status is the current connection status.
	// Status 是当前连接状态。
	Status AgentStatus

	// ConnectedAt is the timestamp when the Agent connected.
	// ConnectedAt 是 Agent 连接的时间戳。
	ConnectedAt time.Time
	// contains filtered or unexported fields
}

AgentConnection represents an active connection to an Agent. AgentConnection 表示与 Agent 的活跃连接。 Requirements: 1.2 - Manages bidirectional gRPC stream connection.

func (*AgentConnection) GetStatus

func (c *AgentConnection) GetStatus() AgentStatus

GetStatus returns the current connection status. GetStatus 返回当前连接状态。

func (*AgentConnection) GetStream

GetStream returns the command stream. GetStream 返回命令流。

func (*AgentConnection) IsOnline

func (c *AgentConnection) IsOnline(timeout time.Duration) bool

IsOnline checks if the Agent is online based on heartbeat timeout. IsOnline 根据心跳超时检查 Agent 是否在线。

func (*AgentConnection) SetStatus

func (c *AgentConnection) SetStatus(status AgentStatus)

SetStatus sets the connection status. SetStatus 设置连接状态。

func (*AgentConnection) SetStream

SetStream sets the command stream for the connection. SetStream 设置连接的命令流。

func (*AgentConnection) Snapshot added in v1.2.0

Snapshot 返回连接元数据副本。/ Snapshot returns a copy of the connection metadata.

func (*AgentConnection) UpdateHeartbeat

func (c *AgentConnection) UpdateHeartbeat()

UpdateHeartbeat updates the last heartbeat timestamp. UpdateHeartbeat 更新最后心跳时间戳。

type AgentConnectionSnapshot added in v1.2.0

type AgentConnectionSnapshot struct {
	AgentID       string
	HostID        uint
	IPAddress     string
	Hostname      string
	Version       string
	Status        AgentStatus
	ConnectedAt   time.Time
	LastHeartbeat time.Time
}

AgentConnectionSnapshot 是连接元数据的并发安全副本。 AgentConnectionSnapshot is a concurrency-safe copy of connection metadata.

type AgentStatus

type AgentStatus string

AgentStatus represents the connection status of an Agent. AgentStatus 表示 Agent 的连接状态。

const (
	// AgentStatusConnected indicates the Agent is connected and active.
	// AgentStatusConnected 表示 Agent 已连接且活跃。
	AgentStatusConnected AgentStatus = "connected"
	// AgentStatusDisconnected indicates the Agent has disconnected.
	// AgentStatusDisconnected 表示 Agent 已断开连接。
	AgentStatusDisconnected AgentStatus = "disconnected"
	// AgentStatusOffline indicates the Agent is offline (heartbeat timeout).
	// AgentStatusOffline 表示 Agent 离线(心跳超时)。
	AgentStatusOffline AgentStatus = "offline"
)

type CommandContext

type CommandContext struct {
	// CommandID is the unique identifier of the command.
	// CommandID 是命令的唯一标识符。
	CommandID string

	// AgentID is the ID of the Agent executing the command.
	// AgentID 是执行命令的 Agent 的 ID。
	AgentID string

	// Type is the command type.
	// Type 是命令类型。
	Type pb.CommandType

	// Parameters are the command parameters.
	// Parameters 是命令参数。
	Parameters map[string]string

	// Timeout is the command timeout duration.
	// Timeout 是命令超时时间。
	Timeout time.Duration

	// CreatedAt is when the command was created.
	// CreatedAt 是命令创建的时间。
	CreatedAt time.Time

	// ResultChan is the channel for receiving the command result.
	// ResultChan 是接收命令结果的通道。
	ResultChan chan *pb.CommandResponse

	// Done indicates if the command has completed.
	// Done 表示命令是否已完成。
	Done bool

	// LastStatus is the last known status of the command.
	// LastStatus 是命令的最后已知状态。
	LastStatus pb.CommandStatus

	// LastProgress is the last known progress (0-100).
	// LastProgress 是最后已知的进度 (0-100)。
	LastProgress int32

	// LastOutput is the last known output message.
	// LastOutput 是最后已知的输出消息。
	LastOutput string

	// LastError is the last known error message.
	// LastError 是最后已知的错误消息。
	LastError string
	// contains filtered or unexported fields
}

CommandContext represents the context for a pending command. CommandContext 表示待处理命令的上下文。

func (*CommandContext) IsDone

func (c *CommandContext) IsDone() bool

IsDone checks if the command is done. IsDone 检查命令是否已完成。

func (*CommandContext) MarkDone

func (c *CommandContext) MarkDone()

MarkDone marks the command as done. MarkDone 将命令标记为已完成。

type ErrorResponse

type ErrorResponse struct {
	ErrorMsg string `json:"error_msg"`
}

ErrorResponse represents an error response. ErrorResponse 表示错误响应。

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler provides HTTP handlers for Agent distribution operations. Handler 提供 Agent 分发操作的 HTTP 处理器。

func NewHandler

func NewHandler(cfg *HandlerConfig) *Handler

NewHandler creates a new Handler instance. NewHandler 创建一个新的 Handler 实例。

func (*Handler) DownloadAgent

func (h *Handler) DownloadAgent(c *gin.Context)

DownloadAgent handles GET /api/v1/agent/download - downloads the Agent binary. DownloadAgent 处理 GET /api/v1/agent/download - 下载 Agent 二进制文件。 Requirements: 2.2 - Downloads Agent binary for the specified OS and architecture. @Tags agent @Param os query string true "Operating system (linux, darwin)" @Param arch query string true "CPU architecture (amd64, arm64)" @Produce application/octet-stream @Success 200 {file} binary "Agent binary file" @Failure 400 {object} ErrorResponse "Invalid parameters" @Failure 404 {object} ErrorResponse "Binary not found" @Router /api/v1/agent/download [get]

func (*Handler) DownloadCA

func (h *Handler) DownloadCA(c *gin.Context)

DownloadCA handles GET /api/v1/agent/ca.crt - downloads the gRPC TLS CA for Agent install. DownloadCA 处理 GET /api/v1/agent/ca.crt - 下载供 Agent 安装流使用的 gRPC TLS CA。 @Tags agent @Produce application/x-pem-file @Success 200 {file} binary "CA certificate" @Failure 404 {object} ErrorResponse "TLS disabled or CA not found" @Router /api/v1/agent/ca.crt [get]

func (*Handler) DownloadSTXJavaProxyJar

func (h *Handler) DownloadSTXJavaProxyJar(c *gin.Context)

DownloadSTXJavaProxyJar handles GET /api/v1/agent/assets/stx-java-proxy.jar - downloads the stx-java-proxy thin jar. DownloadSTXJavaProxyJar 处理 GET /api/v1/agent/assets/stx-java-proxy.jar - 下载 stx-java-proxy 薄 jar。

func (*Handler) DownloadSTXJavaProxyScript

func (h *Handler) DownloadSTXJavaProxyScript(c *gin.Context)

DownloadSTXJavaProxyScript handles GET /api/v1/agent/assets/stx-java-proxy.sh - downloads the stx-java-proxy launcher script. DownloadSTXJavaProxyScript 处理 GET /api/v1/agent/assets/stx-java-proxy.sh - 下载 stx-java-proxy 启动脚本。

func (*Handler) GetInstallScript

func (h *Handler) GetInstallScript(c *gin.Context)

GetInstallScript handles GET /api/v1/agent/install.sh - returns the Agent install script. GetInstallScript 处理 GET /api/v1/agent/install.sh - 返回 Agent 安装脚本。 Requirements: 2.1 - Returns shell script with auto-detection logic for OS and architecture. @Tags agent @Produce text/x-shellscript @Success 200 {string} string "Install script" @Router /api/v1/agent/install.sh [get]

func (*Handler) GetUninstallScript

func (h *Handler) GetUninstallScript(c *gin.Context)

GetUninstallScript handles GET /api/v1/agent/uninstall.sh - returns the Agent uninstall script. GetUninstallScript 处理 GET /api/v1/agent/uninstall.sh - 返回 Agent 卸载脚本。 @Tags agent @Produce text/x-shellscript @Success 200 {string} string "Uninstall script" @Router /api/v1/agent/uninstall.sh [get]

type HandlerConfig

type HandlerConfig struct {
	// ControlPlaneAddr is the address of the Control Plane.
	// ControlPlaneAddr 是 Control Plane 的地址。
	ControlPlaneAddr string

	// AgentBinaryDir is the directory containing Agent binary files.
	// AgentBinaryDir 是包含 Agent 二进制文件的目录。
	AgentBinaryDir string

	// STXJavaProxyJarPath is the path to the packaged stx-java-proxy thin jar.
	// STXJavaProxyJarPath 是 stx-java-proxy 薄 jar 的打包路径。
	STXJavaProxyJarPath string

	// STXJavaProxyScriptPath is the path to the packaged stx-java-proxy launcher script.
	// STXJavaProxyScriptPath 是 stx-java-proxy 启动脚本的打包路径。
	STXJavaProxyScriptPath string

	// GRPCPort is the gRPC port for Agent connections.
	// GRPCPort 是 Agent 连接的 gRPC 端口。
	GRPCPort string

	// HeartbeatInterval is the heartbeat interval in seconds.
	// HeartbeatInterval 是心跳间隔(秒)。
	HeartbeatInterval int

	// TLSEnabled indicates whether Control Plane gRPC TLS is enabled.
	// TLSEnabled 表示 Control Plane gRPC TLS 是否已启用。
	TLSEnabled bool

	// CAFile is the local path to the CA certificate Agents should trust.
	// CAFile 是 Agent 应信任的 CA 证书本地路径。
	CAFile string
}

HandlerConfig holds configuration for the Agent Handler. HandlerConfig 保存 Agent Handler 的配置。

type HostServiceAdapter

type HostServiceAdapter struct {
	// contains filtered or unexported fields
}

HostServiceAdapter adapts the Host Service to the HostStatusUpdater interface. HostServiceAdapter 将 Host Service 适配到 HostStatusUpdater 接口。 This adapter allows the Agent Manager to update host status without direct dependency. 此适配器允许 Agent Manager 更新主机状态而无需直接依赖。

func NewHostServiceAdapter

func NewHostServiceAdapter(hostService *host.Service) *HostServiceAdapter

NewHostServiceAdapter creates a new HostServiceAdapter. NewHostServiceAdapter 创建一个新的 HostServiceAdapter。

func (*HostServiceAdapter) MarkHostOffline

func (a *HostServiceAdapter) MarkHostOffline(ctx context.Context, agentID string) error

MarkHostOffline marks a host as offline by agent ID. MarkHostOffline 根据 Agent ID 将主机标记为离线。 Requirements: 3.4 - Marks hosts as offline if no heartbeat received for 30 seconds.

func (*HostServiceAdapter) UpdateAgentStatus

func (a *HostServiceAdapter) UpdateAgentStatus(ctx context.Context, hostID uint, ipAddress string, agentID string, version string, sysInfo *SystemInfo, hostname string, localIPs []string) (uint, error)

UpdateAgentStatus updates the agent status for a host by pre-bound host ID or IP address. UpdateAgentStatus 根据预绑定主机 ID 或 IP 地址更新主机的 Agent 状态。 Requirements: 3.2 - Matches Agent hostID or IP with registered host and updates status to "installed".

func (*HostServiceAdapter) UpdateHeartbeat

func (a *HostServiceAdapter) UpdateHeartbeat(ctx context.Context, agentID string, cpuUsage, memoryUsage, diskUsage float64) error

UpdateHeartbeat updates the heartbeat data for a host. UpdateHeartbeat 更新主机的心跳数据。 Requirements: 3.3 - Updates last heartbeat time, CPU, memory, and disk usage.

type HostStatusUpdater

type HostStatusUpdater interface {
	// UpdateAgentStatus updates the agent status for a host by pre-bound host ID or IP address.
	// UpdateAgentStatus 根据预绑定主机 ID 或 IP 地址更新主机的 Agent 状态。
	// hostname is used when auto-creating a host (e.g. no host matches by IP).
	// localIPs is the Agent local address set used to detect wrong user-entered host IPs.
	// localIPs 为本机地址集合,用于识别用户填错的主机 IP。
	UpdateAgentStatus(ctx context.Context, hostID uint, ipAddress string, agentID string, version string, systemInfo *SystemInfo, hostname string, localIPs []string) (hostIDOut uint, err error)

	// UpdateHeartbeat updates the heartbeat data for a host.
	// UpdateHeartbeat 更新主机的心跳数据。
	UpdateHeartbeat(ctx context.Context, agentID string, cpuUsage, memoryUsage, diskUsage float64) error

	// MarkHostOffline marks a host as offline by agent ID.
	// MarkHostOffline 根据 Agent ID 将主机标记为离线。
	MarkHostOffline(ctx context.Context, agentID string) error
}

HostStatusUpdater is an interface for updating host status. HostStatusUpdater 是更新主机状态的接口。 This interface decouples the Agent Manager from the Host Service. 此接口将 Agent Manager 与 Host Service 解耦。

type InstallScriptConfig

type InstallScriptConfig struct {
	// ControlPlaneAddr is the HTTP address of the Control Plane.
	// ControlPlaneAddr 是 Control Plane 的 HTTP 地址。
	ControlPlaneAddr string

	// GRPCAddr is the gRPC address for Agent connection.
	// GRPCAddr 是 Agent 连接的 gRPC 地址。
	GRPCAddr string

	// HeartbeatInterval is the heartbeat interval in seconds from Control Plane config.
	// HeartbeatInterval 是来自 Control Plane 配置的心跳间隔(秒)。
	HeartbeatInterval int

	// TLSEnabled indicates whether Control Plane gRPC TLS is enabled (Agent should fetch CA).
	// TLSEnabled 表示 Control Plane gRPC TLS 是否已启用(Agent 应拉取 CA)。
	TLSEnabled bool

	// HostID is the optional pre-bound host ID.
	// HostID 是可选的预绑定主机 ID。
	HostID uint64
}

InstallScriptConfig holds configuration for the install script generator. InstallScriptConfig 保存安装脚本生成器的配置。

type InstallScriptData

type InstallScriptData struct {
	// ControlPlaneAddr is the HTTP address of the Control Plane.
	// ControlPlaneAddr 是 Control Plane 的 HTTP 地址。
	ControlPlaneAddr string

	// GRPCAddr is the gRPC address for Agent connection.
	// GRPCAddr 是 Agent 连接的 gRPC 地址。
	GRPCAddr string

	// InstallDir is the Agent home root (bin/etc/logs/lib live underneath).
	// InstallDir 是 Agent 主目录(其下包含 bin/etc/logs/lib)。
	InstallDir string

	// ConfigDir is kept for compatibility; the install script always derives etc/ under InstallDir.
	// ConfigDir 为兼容字段保留;安装脚本始终从 InstallDir 推导 etc/。
	ConfigDir string

	// AgentBinary is the name of the Agent binary file.
	// AgentBinary 是 Agent 二进制文件的名称。
	AgentBinary string

	// ServiceName is the service name (systemd unit / launchd label suffix).
	// ServiceName 是服务名(systemd unit / launchd label 后缀)。
	ServiceName string

	// SupportDir is kept for compatibility; the install script always uses InstallDir as support root.
	// SupportDir 为兼容字段保留;安装脚本始终以 InstallDir 作为辅助资产根目录。
	SupportDir string

	// STXJavaProxyVersion is the default packaged stx-java-proxy version.
	// STXJavaProxyVersion 是默认打包的 stx-java-proxy 版本。
	STXJavaProxyVersion string

	// STXJavaProxyEpochs is the space-separated list of proxy epochs to install (e.g. "v2 v3").
	// STXJavaProxyEpochs 是要安装的 proxy 代际列表(空格分隔,如 "v2 v3")。
	STXJavaProxyEpochs string

	// STXJavaProxyJarFileName is the packaged default stx-java-proxy jar file name.
	// STXJavaProxyJarFileName 是默认打包的 stx-java-proxy jar 文件名。
	STXJavaProxyJarFileName string

	// STXJavaProxyScriptFileName is the packaged stx-java-proxy script file name.
	// STXJavaProxyScriptFileName 是打包的 stx-java-proxy 脚本文件名。
	STXJavaProxyScriptFileName string

	// HeartbeatInterval is the heartbeat interval string (e.g., "60s").
	// HeartbeatInterval 是心跳间隔字符串(如 "60s")。
	HeartbeatInterval string

	// TLSEnabled indicates whether Agent should enable gRPC TLS and download CA.
	// TLSEnabled 表示 Agent 是否应启用 gRPC TLS 并下载 CA。
	TLSEnabled bool

	// AgentCAFile is the on-host path where the downloaded CA certificate is stored.
	// AgentCAFile 是本机保存已下载 CA 证书的路径。
	AgentCAFile string

	// HostID is the optional pre-bound host ID.
	// HostID 是可选的预绑定主机 ID。
	HostID uint64
}

InstallScriptData holds data for rendering the install script template. InstallScriptData 保存渲染安装脚本模板的数据。

type InstallScriptGenerator

type InstallScriptGenerator struct {
	// contains filtered or unexported fields
}

InstallScriptGenerator generates Agent installation scripts. InstallScriptGenerator 生成 Agent 安装脚本。 Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 2.6 - Implements one-click Agent installation.

func NewInstallScriptGenerator

func NewInstallScriptGenerator(cfg *InstallScriptConfig) (*InstallScriptGenerator, error)

NewInstallScriptGenerator creates a new InstallScriptGenerator instance. NewInstallScriptGenerator 创建一个新的 InstallScriptGenerator 实例。

func (*InstallScriptGenerator) Generate

func (g *InstallScriptGenerator) Generate() (string, error)

Generate generates the install script with the configured settings. Generate 使用配置的设置生成安装脚本。 Requirements: 2.1 - Returns shell script with auto-detection logic for OS and architecture.

func (*InstallScriptGenerator) GenerateWithData

func (g *InstallScriptGenerator) GenerateWithData(data *InstallScriptData) (string, error)

GenerateWithData generates the install script with custom data. GenerateWithData 使用自定义数据生成安装脚本。

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager manages Agent connections and command dispatching. Manager 管理 Agent 连接和命令分发。 Requirements: 1.2, 1.5 - Implements Agent connection management and command dispatching.

func NewManager

func NewManager(config *ManagerConfig) *Manager

NewManager creates a new Agent Manager instance. NewManager 创建一个新的 Agent Manager 实例。

func (*Manager) GetAgent

func (m *Manager) GetAgent(agentID string) (*AgentConnection, bool)

GetAgent retrieves an Agent connection by ID. GetAgent 根据 ID 获取 Agent 连接。

func (*Manager) GetAgentByIP

func (m *Manager) GetAgentByIP(ipAddress string) (*AgentConnection, bool)

GetAgentByIP retrieves an Agent connection by IP address. GetAgentByIP 根据 IP 地址获取 Agent 连接。

func (*Manager) GetCommand

func (m *Manager) GetCommand(commandID string) (*CommandContext, bool)

GetCommand retrieves a command context by ID. GetCommand 根据 ID 获取命令上下文。

func (*Manager) GetCommandStatus

func (m *Manager) GetCommandStatus(commandID string) (status string, progress int, message string, err error)

GetCommandStatus retrieves the current status of a command. GetCommandStatus 获取命令的当前状态。

func (*Manager) GetConfig

func (m *Manager) GetConfig() *ManagerConfig

GetConfig returns the manager configuration. GetConfig 返回管理器配置。

func (*Manager) GetConnectedCount

func (m *Manager) GetConnectedCount() int

GetConnectedCount returns the number of connected Agents. GetConnectedCount 返回已连接的 Agent 数量。

func (*Manager) HandleCommandResponse

func (m *Manager) HandleCommandResponse(resp *pb.CommandResponse)

HandleCommandResponse processes a command response from an Agent. HandleCommandResponse 处理来自 Agent 的命令响应。 Requirements: 1.5 - Receives and processes command execution results.

func (*Manager) HandleDisconnect

func (m *Manager) HandleDisconnect(agentID string)

HandleDisconnect handles an Agent disconnection. HandleDisconnect 处理 Agent 断开连接。

func (*Manager) HandleHeartbeat

func (m *Manager) HandleHeartbeat(ctx context.Context, req *pb.HeartbeatRequest) error

HandleHeartbeat processes a heartbeat from an Agent. HandleHeartbeat 处理来自 Agent 的心跳。 Requirements: 1.3 - Updates heartbeat timestamp and resource usage.

func (*Manager) IsRunning

func (m *Manager) IsRunning() bool

IsRunning returns whether the manager is running. IsRunning 返回管理器是否正在运行。

func (*Manager) ListAgents

func (m *Manager) ListAgents() []*AgentConnection

ListAgents returns all connected Agents. ListAgents 返回所有已连接的 Agent。

func (*Manager) RegisterAgent

func (m *Manager) RegisterAgent(ctx context.Context, req *pb.RegisterRequest) (*AgentConnection, error)

RegisterAgent registers a new Agent connection. RegisterAgent 注册一个新的 Agent 连接。 Requirements: 1.2 - Handles Agent registration and connection management.

func (*Manager) RegisterPackageServe added in v1.2.0

func (m *Manager) RegisterPackageServe(agentID, localPath, checksum string) (*PackageServe, error)

RegisterPackageServe allows agentID to pull localPath via DownloadPackage. RegisterPackageServe 允许 agentID 通过 DownloadPackage 拉取 localPath。

func (*Manager) ReleasePackageServe added in v1.2.0

func (m *Manager) ReleasePackageServe(id string)

ReleasePackageServe revokes a transfer id. ReleasePackageServe 撤销传输标识。

func (*Manager) RemoveAgentStream added in v1.1.1

func (m *Manager) RemoveAgentStream(agentID string, stream grpc.BidiStreamingServer[pb.CommandResponse, pb.CommandRequest]) bool

RemoveAgentStream removes the command stream if it matches the current stream. RemoveAgentStream 当传入的流与当前连接持有的流相同时才将其置空,避免重连建立新流后旧流退出发生误杀。

func (*Manager) SendCommand

func (m *Manager) SendCommand(ctx context.Context, agentID string, cmdType pb.CommandType, params map[string]string, timeout time.Duration) (*pb.CommandResponse, error)

SendCommand sends a command to an Agent and waits for the result. SendCommand 向 Agent 发送命令并等待结果。 Requirements: 1.5 - Implements command dispatching and result receiving.

func (*Manager) SendCommandAsync

func (m *Manager) SendCommandAsync(agentID string, cmdType pb.CommandType, params map[string]string, timeout time.Duration) (string, error)

SendCommandAsync sends a command to an Agent without waiting for the result. SendCommandAsync 向 Agent 发送命令但不等待结果。

func (*Manager) SendCommandWithID added in v1.0.0

func (m *Manager) SendCommandWithID(ctx context.Context, commandID, agentID string, cmdType pb.CommandType, params map[string]string, timeout time.Duration) (*pb.CommandResponse, error)

SendCommandWithID sends a command with a caller-provided ID so audit records can exist before dispatch. SendCommandWithID 使用调用方提供的命令编号下发命令,使审计记录可以在发送前创建。

func (*Manager) SetAgentStream

func (m *Manager) SetAgentStream(agentID string, stream grpc.BidiStreamingServer[pb.CommandResponse, pb.CommandRequest]) error

SetAgentStream sets the command stream for an Agent. SetAgentStream 设置 Agent 的命令流。 Requirements: 1.5 - Establishes bidirectional stream for command dispatching.

func (*Manager) SetHostUpdater

func (m *Manager) SetHostUpdater(updater HostStatusUpdater)

SetHostUpdater sets the host status updater. SetHostUpdater 设置主机状态更新器。

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start starts the Agent Manager background tasks. Start 启动 Agent Manager 后台任务。 Requirements: 3.4 - Starts heartbeat timeout detection goroutine.

func (*Manager) Stop

func (m *Manager) Stop()

Stop stops the Agent Manager and all background tasks. Stop 停止 Agent Manager 和所有后台任务。

func (*Manager) StreamPackage added in v1.2.0

func (m *Manager) StreamPackage(ctx context.Context, req *pb.DownloadPackageRequest, send func(*pb.PackageChunk) error) error

StreamPackage streams the registered package to the Agent starting at req.Offset. gRPC flow control provides back-pressure, so no per-chunk ack/timeout is needed here. StreamPackage 从 req.Offset 开始向 Agent 流式发送已注册的安装包; gRPC 自带流控提供背压,无需逐块确认。

func (*Manager) TransferPackage added in v1.2.0

func (m *Manager) TransferPackage(ctx context.Context, agentID, version, localPath, checksum string, opts PackagePullOptions) (PackagePullResult, error)

TransferPackage asks the Agent to pull localPath over the dedicated DownloadPackage stream and waits until the Agent reports completion. Returns the package path on the Agent. TransferPackage 让 Agent 通过专用 DownloadPackage 流拉取 localPath,并等待 Agent 报告完成, 返回安装包在 Agent 上的路径。

func (*Manager) UnregisterAgent

func (m *Manager) UnregisterAgent(agentID string)

UnregisterAgent removes an Agent connection. UnregisterAgent 移除一个 Agent 连接。

type ManagerConfig

type ManagerConfig struct {
	// HeartbeatInterval is the expected interval between heartbeats.
	// HeartbeatInterval 是心跳之间的预期间隔。
	HeartbeatInterval time.Duration

	// HeartbeatTimeout is the timeout for considering an Agent offline.
	// HeartbeatTimeout 是判断 Agent 离线的超时时间。
	HeartbeatTimeout time.Duration

	// CheckInterval is the interval for checking heartbeat timeouts.
	// CheckInterval 是检查心跳超时的间隔。
	CheckInterval time.Duration
}

ManagerConfig holds configuration for the Agent Manager. ManagerConfig 保存 Agent Manager 的配置。

type PackagePullOptions added in v1.2.0

type PackagePullOptions struct {
	StallTimeout time.Duration
	MaxDuration  time.Duration
	PollInterval time.Duration
	OnProgress   func(sent, total int64)
	// CachedRemotePath is where the Control Plane believes the Agent already holds this package;
	// the Agent reuses it only if size and SHA256 match.
	// CachedRemotePath 是 CP 认为 Agent 已持有该安装包的路径;仅当大小与 SHA256 一致时 Agent 才复用。
	CachedRemotePath string
}

PackagePullOptions tunes TransferPackage. PackagePullOptions 用于调整 TransferPackage 的行为。

type PackagePullResult added in v1.2.0

type PackagePullResult struct {
	LocalPath string // path on the Agent / Agent 上的路径
	Reused    bool   // Agent already had an identical file / Agent 已有相同文件,未重新下载
}

PackagePullResult is the outcome of TransferPackage. PackagePullResult 是 TransferPackage 的结果。

type PackageServe added in v1.2.0

type PackageServe struct {
	ID       string
	AgentID  string
	Path     string
	Size     int64
	Checksum string
	// contains filtered or unexported fields
}

PackageServe describes one package file an Agent is allowed to pull. PackageServe 描述一个允许 Agent 拉取的安装包文件。

func (*PackageServe) IdleFor added in v1.2.0

func (p *PackageServe) IdleFor() time.Duration

IdleFor returns how long the serve has been idle. IdleFor 返回自最近活动以来的空闲时长。

func (*PackageServe) Served added in v1.2.0

func (p *PackageServe) Served() int64

Served returns the highest byte offset streamed so far. Served 返回目前已流式发送的最大字节偏移量。

type SupportedPlatform

type SupportedPlatform struct {
	// OS is the operating system (linux, darwin).
	// OS 是操作系统(linux, darwin)。
	OS string

	// Arch is the CPU architecture (amd64, arm64).
	// Arch 是 CPU 架构(amd64, arm64)。
	Arch string

	// BinaryName is the name of the binary file for this platform.
	// BinaryName 是此平台的二进制文件名称。
	BinaryName string
}

SupportedPlatform represents a supported OS and architecture combination. SupportedPlatform 表示支持的操作系统和架构组合。

func GetSupportedPlatforms

func GetSupportedPlatforms() []SupportedPlatform

GetSupportedPlatforms returns all supported platforms. GetSupportedPlatforms 返回所有支持的平台。

type SystemInfo

type SystemInfo struct {
	OSType      string
	Arch        string
	CPUCores    int
	TotalMemory int64
	TotalDisk   int64
}

SystemInfo represents system information from an Agent. SystemInfo 表示来自 Agent 的系统信息。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL