host

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: 15 Imported by: 0

Documentation

Overview

Package host provides host management functionality for the STX Agent system. host 包提供 STX Agent 系统的主机管理功能。

Package host provides host management functionality for the STX Agent system. host 包提供 STX Agent 系统的主机管理功能。

Package host provides host management functionality for the STX Agent system. host 包提供 STX Agent 系统的主机管理功能。

Index

Constants

View Source
const (
	ErrCodeHostNotFound           = 2001
	ErrCodeHostNameDuplicate      = 2002
	ErrCodeHostIPInvalid          = 2003
	ErrCodeHostHasCluster         = 2004
	ErrCodeHostTypeInvalid        = 2005
	ErrCodeDockerAPIURLInvalid    = 2006
	ErrCodeK8sAPIURLInvalid       = 2007
	ErrCodeK8sCredentialsRequired = 2008
	ErrCodeHostIPDuplicate        = 2009
)

Error codes for host management operations. 主机管理操作的错误代码。

View Source
const DefaultHeartbeatTimeout = 30 * time.Second

DefaultHeartbeatTimeout is the default timeout for considering a host offline. DefaultHeartbeatTimeout 是判断主机离线的默认超时时间。

Variables

View Source
var (
	// ErrHostNotFound indicates the requested host does not exist.
	// ErrHostNotFound 表示请求的主机不存在。
	ErrHostNotFound = errors.New("host: host not found")
	// ErrHostNameDuplicate indicates a host with the same name already exists.
	// ErrHostNameDuplicate 表示同名主机已存在。
	ErrHostNameDuplicate = errors.New("host: host name already exists")
	// ErrHostIPInvalid indicates the IP address format is invalid.
	// ErrHostIPInvalid 表示 IP 地址格式无效。
	ErrHostIPInvalid = errors.New("host: invalid IP address format")
	// ErrHostIPDuplicate indicates a host with the same IP already exists.
	// ErrHostIPDuplicate 表示相同 IP 的主机已存在。
	ErrHostIPDuplicate = errors.New("host: host IP address already exists")
	// ErrHostHasCluster indicates the host is associated with one or more clusters.
	// ErrHostHasCluster 表示主机关联了一个或多个集群。
	ErrHostHasCluster = errors.New("host: host is associated with clusters and cannot be deleted")
	// ErrHostNameEmpty indicates the host name is empty.
	// ErrHostNameEmpty 表示主机名为空。
	ErrHostNameEmpty = errors.New("host: host name cannot be empty")
	// ErrHostTypeInvalid indicates the host type is invalid.
	// ErrHostTypeInvalid 表示主机类型无效。
	ErrHostTypeInvalid = errors.New("host: invalid host type, must be bare_metal, docker, or kubernetes")
	// ErrDockerAPIURLInvalid indicates the Docker API URL format is invalid.
	// ErrDockerAPIURLInvalid 表示 Docker API URL 格式无效。
	ErrDockerAPIURLInvalid = errors.New("host: invalid Docker API URL format, must be tcp://host:port or unix:///path")
	// ErrK8sAPIURLInvalid indicates the Kubernetes API URL format is invalid.
	// ErrK8sAPIURLInvalid 表示 Kubernetes API URL 格式无效。
	ErrK8sAPIURLInvalid = errors.New("host: invalid Kubernetes API URL format, must be https://host:port")
	// ErrK8sCredentialsRequired indicates K8s credentials are required.
	// ErrK8sCredentialsRequired 表示需要 K8s 凭证。
	ErrK8sCredentialsRequired = errors.New("host: kubernetes host requires kubeconfig or token")
)

Error definitions for host management operations. 主机管理操作的错误定义。

ValidHostTypes contains all valid host types. ValidHostTypes 包含所有有效的主机类型。

Functions

func ValidateDockerAPIURL

func ValidateDockerAPIURL(apiURL string) bool

ValidateDockerAPIURL validates the Docker API URL format. ValidateDockerAPIURL 验证 Docker API URL 格式。 Valid formats: tcp://host:port, unix:///path/to/socket

func ValidateIPAddress

func ValidateIPAddress(ip string) bool

ValidateIPAddress validates that the IP address is a valid IPv4 or IPv6 address. Returns true if the IP address is valid, false otherwise.

func ValidateK8sAPIURL

func ValidateK8sAPIURL(apiURL string) bool

ValidateK8sAPIURL validates the Kubernetes API URL format. ValidateK8sAPIURL 验证 Kubernetes API URL 格式。 Valid format: https://host:port

Types

type AgentStatus

type AgentStatus string

AgentStatus represents the installation status of an Agent on a host. AgentStatus 表示主机上 Agent 的安装状态。

const (
	// AgentStatusNotInstalled indicates the Agent has not been installed on the host.
	// AgentStatusNotInstalled 表示 Agent 尚未安装在主机上。
	AgentStatusNotInstalled AgentStatus = "not_installed"
	// AgentStatusInstalled indicates the Agent is installed and connected.
	// AgentStatusInstalled 表示 Agent 已安装并已连接。
	AgentStatusInstalled AgentStatus = "installed"
	// AgentStatusOffline indicates the Agent was installed but is currently offline.
	// AgentStatusOffline 表示 Agent 已安装但当前离线。
	AgentStatusOffline AgentStatus = "offline"
)

type CreateHostRequest

type CreateHostRequest struct {
	Name        string   `json:"name" binding:"required,max=100"`
	HostType    HostType `json:"host_type"`
	Description string   `json:"description"`

	// bare_metal fields / 物理机字段
	IPAddress string `json:"ip_address"`
	SSHPort   int    `json:"ssh_port"`

	// docker fields / Docker 字段
	DockerAPIURL     string `json:"docker_api_url"`
	DockerTLSEnabled bool   `json:"docker_tls_enabled"`
	DockerCertPath   string `json:"docker_cert_path"`

	// kubernetes fields / Kubernetes 字段
	K8sAPIURL     string `json:"k8s_api_url"`
	K8sNamespace  string `json:"k8s_namespace"`
	K8sKubeconfig string `json:"k8s_kubeconfig"`
	K8sToken      string `json:"k8s_token"`
}

CreateHostRequest represents a request to create a new host. CreateHostRequest 表示创建新主机的请求。

type CreateHostResponse

type CreateHostResponse struct {
	ErrorMsg string    `json:"error_msg"`
	Data     *HostInfo `json:"data"`
}

CreateHostResponse represents the response for creating a host. CreateHostResponse 表示创建主机的响应。

type DeleteHostResponse

type DeleteHostResponse struct {
	ErrorMsg string `json:"error_msg"`
	Data     any    `json:"data"`
}

DeleteHostResponse represents the response for deleting a host. DeleteHostResponse 表示删除主机的响应。

type GetHostResponse

type GetHostResponse struct {
	ErrorMsg string    `json:"error_msg"`
	Data     *HostInfo `json:"data"`
}

GetHostResponse represents the response for getting a host. GetHostResponse 表示获取主机详情的响应。

type GetInstallCommandResponse

type GetInstallCommandResponse struct {
	ErrorMsg string `json:"error_msg"`
	Data     *struct {
		Command string `json:"command"`
	} `json:"data"`
}

GetInstallCommandResponse represents the response for getting install command. GetInstallCommandResponse 表示获取安装命令的响应。

type Handler

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

Handler provides HTTP handlers for host management operations. Handler 提供主机管理操作的 HTTP 处理器。

func NewHandler

func NewHandler(service *Service, auditRepo *audit.Repository) *Handler

NewHandler creates a new Handler instance. NewHandler 创建一个新的 Handler 实例。 auditRepo may be nil; audit logging is skipped when nil.

func (*Handler) CreateHost

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

CreateHost handles POST /api/v1/hosts - creates a new host. CreateHost 处理 POST /api/v1/hosts - 创建新主机。 @Tags hosts @Accept json @Produce json @Param request body CreateHostRequest true "创建主机请求" @Success 200 {object} CreateHostResponse @Router /api/v1/hosts [post]

func (*Handler) DeleteHost

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

DeleteHost handles DELETE /api/v1/hosts/:id - deletes a host. DeleteHost 处理 DELETE /api/v1/hosts/:id - 删除主机。 @Tags hosts @Produce json @Param id path int true "主机ID" @Success 200 {object} DeleteHostResponse @Router /api/v1/hosts/{id} [delete]

func (*Handler) GetHost

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

GetHost handles GET /api/v1/hosts/:id - gets a host by ID. GetHost 处理 GET /api/v1/hosts/:id - 根据 ID 获取主机详情。 @Tags hosts @Produce json @Param id path int true "主机ID" @Success 200 {object} GetHostResponse @Router /api/v1/hosts/{id} [get]

func (*Handler) GetInstallCommand

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

GetInstallCommand handles GET /api/v1/hosts/:id/install-command - gets the Agent install command. GetInstallCommand 处理 GET /api/v1/hosts/:id/install-command - 获取 Agent 安装命令。 @Tags hosts @Produce json @Param id path int true "主机ID" @Success 200 {object} GetInstallCommandResponse @Router /api/v1/hosts/{id}/install-command [get]

func (*Handler) ListHosts

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

ListHosts handles GET /api/v1/hosts - lists hosts with filtering and pagination. ListHosts 处理 GET /api/v1/hosts - 获取主机列表(支持过滤和分页)。 @Tags hosts @Param request query ListHostsRequest true "查询参数" @Produce json @Success 200 {object} ListHostsResponse @Router /api/v1/hosts [get]

func (*Handler) UpdateHost

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

UpdateHost handles PUT /api/v1/hosts/:id - updates an existing host. UpdateHost 处理 PUT /api/v1/hosts/:id - 更新现有主机。 @Tags hosts @Accept json @Produce json @Param id path int true "主机ID" @Param request body UpdateHostRequest true "更新主机请求" @Success 200 {object} UpdateHostResponse @Router /api/v1/hosts/{id} [put]

type Host

type Host struct {
	ID          uint       `json:"id" gorm:"primaryKey;autoIncrement"`
	Name        string     `json:"name" gorm:"size:100;uniqueIndex;not null"`
	HostType    HostType   `json:"host_type" gorm:"size:20;not null;default:bare_metal;index"`
	Description string     `json:"description" gorm:"type:text"`
	Status      HostStatus `json:"status" gorm:"size:20;default:pending;index"`

	// Common resource usage fields / 通用资源使用率字段
	CPUUsage    float64    `json:"cpu_usage" gorm:"type:decimal(5,2)"`
	MemoryUsage float64    `json:"memory_usage" gorm:"type:decimal(5,2)"`
	DiskUsage   float64    `json:"disk_usage" gorm:"type:decimal(5,2)"`
	LastCheck   *time.Time `json:"last_check"`

	// bare_metal specific fields / 物理机/VM 专用字段
	IPAddress     string      `json:"ip_address" gorm:"size:45"`
	SSHPort       int         `json:"ssh_port" gorm:"default:22"`
	AgentID       string      `json:"agent_id" gorm:"size:100;index"`
	AgentStatus   AgentStatus `json:"agent_status" gorm:"size:20;default:not_installed;index"`
	AgentVersion  string      `json:"agent_version" gorm:"size:20"`
	OSType        string      `json:"os_type" gorm:"size:20"`
	Arch          string      `json:"arch" gorm:"size:20"`
	CPUCores      int         `json:"cpu_cores"`
	TotalMemory   int64       `json:"total_memory"`
	TotalDisk     int64       `json:"total_disk"`
	LastHeartbeat *time.Time  `json:"last_heartbeat"`

	// docker specific fields (Phase 2) / Docker 专用字段(第二阶段)
	DockerAPIURL     string `json:"docker_api_url" gorm:"size:255"`
	DockerTLSEnabled bool   `json:"docker_tls_enabled" gorm:"default:false"`
	DockerCertPath   string `json:"docker_cert_path" gorm:"size:255"`
	DockerVersion    string `json:"docker_version" gorm:"size:20"`

	// kubernetes specific fields (Phase 2) / Kubernetes 专用字段(第二阶段)
	K8sAPIURL     string `json:"k8s_api_url" gorm:"size:255"`
	K8sNamespace  string `json:"k8s_namespace" gorm:"size:100;default:default"`
	K8sKubeconfig string `json:"k8s_kubeconfig" gorm:"type:text"`
	K8sToken      string `json:"k8s_token" gorm:"type:text"`
	K8sVersion    string `json:"k8s_version" gorm:"size:20"`

	CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
	CreatedBy uint      `json:"created_by"`
}

Host represents a physical machine, VM, Docker host, or Kubernetes cluster that runs SeaTunnel services. Host 表示运行 SeaTunnel 服务的物理机、虚拟机、Docker 主机或 Kubernetes 集群。

func (*Host) IsOnline

func (h *Host) IsOnline(timeout time.Duration) bool

IsOnline returns true if the host has received a heartbeat within the timeout period. The default timeout is 30 seconds as per Requirements 3.4. For backward compatibility this uses no "since" cutoff; use IsOnlineWithSince for process-start awareness.

func (*Host) IsOnlineWithSince

func (h *Host) IsOnlineWithSince(timeout time.Duration, since time.Time) bool

IsOnlineWithSince returns true if the host has received a heartbeat within the timeout period and (when since is non-zero) the last heartbeat is after since (e.g. process start time). This avoids showing hosts as online after platform restart before any heartbeat is received.

func (Host) TableName

func (Host) TableName() string

TableName specifies the table name for the Host model.

func (*Host) ToHostInfo

func (h *Host) ToHostInfo(heartbeatTimeout time.Duration, since time.Time) *HostInfo

ToHostInfo converts a Host to HostInfo with online status calculated. ToHostInfo 将 Host 转换为 HostInfo,并计算在线状态。 since: if non-zero, host is considered online only if last_heartbeat is after since (e.g. process start). For bare_metal: when !IsOnline the displayed status is forced to offline for consistency.

type HostFilter

type HostFilter struct {
	Name        string      `json:"name"`
	HostType    HostType    `json:"host_type"`
	IPAddress   string      `json:"ip_address"`
	Status      HostStatus  `json:"status"`
	AgentStatus AgentStatus `json:"agent_status"`
	IsOnline    *bool       `json:"is_online"`
	Page        int         `json:"page"`
	PageSize    int         `json:"page_size"`
}

HostFilter represents filter criteria for querying hosts. HostFilter 表示查询主机的过滤条件。

type HostInfo

type HostInfo struct {
	ID          uint       `json:"id"`
	Name        string     `json:"name"`
	HostType    HostType   `json:"host_type"`
	Description string     `json:"description"`
	Status      HostStatus `json:"status"`

	// Common fields / 通用字段
	CPUUsage    float64    `json:"cpu_usage"`
	MemoryUsage float64    `json:"memory_usage"`
	DiskUsage   float64    `json:"disk_usage"`
	IsOnline    bool       `json:"is_online"`
	LastCheck   *time.Time `json:"last_check"`

	// bare_metal fields / 物理机字段
	IPAddress     string      `json:"ip_address,omitempty"`
	SSHPort       int         `json:"ssh_port,omitempty"`
	AgentID       string      `json:"agent_id,omitempty"`
	AgentStatus   AgentStatus `json:"agent_status,omitempty"`
	AgentVersion  string      `json:"agent_version,omitempty"`
	OSType        string      `json:"os_type,omitempty"`
	Arch          string      `json:"arch,omitempty"`
	CPUCores      int         `json:"cpu_cores,omitempty"`
	TotalMemory   int64       `json:"total_memory,omitempty"`
	TotalDisk     int64       `json:"total_disk,omitempty"`
	LastHeartbeat *time.Time  `json:"last_heartbeat,omitempty"`

	// docker fields / Docker 字段
	DockerAPIURL     string `json:"docker_api_url,omitempty"`
	DockerTLSEnabled bool   `json:"docker_tls_enabled,omitempty"`
	DockerVersion    string `json:"docker_version,omitempty"`

	// kubernetes fields / Kubernetes 字段
	K8sAPIURL    string `json:"k8s_api_url,omitempty"`
	K8sNamespace string `json:"k8s_namespace,omitempty"`
	K8sVersion   string `json:"k8s_version,omitempty"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

HostInfo represents host information for API responses. HostInfo 表示 API 响应的主机信息。

type HostStatus

type HostStatus string

HostStatus represents the connection status of a host. HostStatus 表示主机的连接状态。

const (
	// HostStatusPending indicates the host is waiting for connection.
	// HostStatusPending 表示主机正在等待连接。
	HostStatusPending HostStatus = "pending"
	// HostStatusConnected indicates the host is connected and operational.
	// HostStatusConnected 表示主机已连接并可操作。
	HostStatusConnected HostStatus = "connected"
	// HostStatusOffline indicates the host is offline.
	// HostStatusOffline 表示主机离线。
	HostStatusOffline HostStatus = "offline"
	// HostStatusError indicates the host has an error.
	// HostStatusError 表示主机出现错误。
	HostStatusError HostStatus = "error"
)

type HostType

type HostType string

HostType represents the type of host environment. HostType 表示主机环境类型。

const (
	// HostTypeBareMetal indicates a physical machine or VM managed by Agent.
	// HostTypeBareMetal 表示由 Agent 管理的物理机或虚拟机。
	HostTypeBareMetal HostType = "bare_metal"
	// HostTypeDocker indicates a Docker host managed via Docker API.
	// HostTypeDocker 表示通过 Docker API 管理的 Docker 主机。
	HostTypeDocker HostType = "docker"
	// HostTypeKubernetes indicates a Kubernetes cluster managed via K8s API.
	// HostTypeKubernetes 表示通过 K8s API 管理的 Kubernetes 集群。
	HostTypeKubernetes HostType = "kubernetes"
)

func (HostType) IsValid

func (t HostType) IsValid() bool

IsValid checks if the host type is valid. IsValid 检查主机类型是否有效。

type ListHostsRequest

type ListHostsRequest struct {
	Current     int         `json:"current" form:"current" binding:"min=1"`
	Size        int         `json:"size" form:"size" binding:"min=1,max=100"`
	Name        string      `json:"name" form:"name"`
	HostType    HostType    `json:"host_type" form:"host_type"`
	IPAddress   string      `json:"ip_address" form:"ip_address"`
	Status      HostStatus  `json:"status" form:"status"`
	AgentStatus AgentStatus `json:"agent_status" form:"agent_status"`
	IsOnline    *bool       `json:"is_online" form:"is_online"`
}

ListHostsRequest represents the request for listing hosts. ListHostsRequest 表示获取主机列表的请求。

type ListHostsResponse

type ListHostsResponse struct {
	ErrorMsg string `json:"error_msg"`
	Data     *struct {
		Total int64       `json:"total"`
		Hosts []*HostInfo `json:"hosts"`
	} `json:"data"`
}

ListHostsResponse represents the response for listing hosts. ListHostsResponse 表示获取主机列表的响应。

type Repository

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

Repository provides data access operations for Host entities.

func NewRepository

func NewRepository(db *gorm.DB) *Repository

NewRepository creates a new Repository instance.

func (*Repository) Create

func (r *Repository) Create(ctx context.Context, host *Host) error

Create creates a new host record in the database. Create 在数据库中创建新的主机记录。 Returns ErrHostNameDuplicate if a host with the same name already exists. Returns ErrHostIPDuplicate if a host with the same IP already exists. Returns ErrHostIPInvalid if the IP address format is invalid (for bare_metal).

func (*Repository) Delete

func (r *Repository) Delete(ctx context.Context, id uint) error

Delete removes a host record from the database. Returns ErrHostNotFound if the host does not exist. Note: Cluster association check should be done at the service layer.

func (*Repository) ExistsByName

func (r *Repository) ExistsByName(ctx context.Context, name string) (bool, error)

ExistsByName checks if a host with the given name exists.

func (*Repository) GetByAgentID

func (r *Repository) GetByAgentID(ctx context.Context, agentID string) (*Host, error)

GetByAgentID retrieves a host by its Agent ID. Returns ErrHostNotFound if no host with the given Agent ID exists.

func (*Repository) GetByID

func (r *Repository) GetByID(ctx context.Context, id uint) (*Host, error)

GetByID retrieves a host by its ID. Returns ErrHostNotFound if the host does not exist.

func (*Repository) GetByIP

func (r *Repository) GetByIP(ctx context.Context, ip string) (*Host, error)

GetByIP retrieves a host by its IP address. Returns ErrHostNotFound if no host with the given IP exists.

func (*Repository) GetByName

func (r *Repository) GetByName(ctx context.Context, name string) (*Host, error)

GetByName retrieves a host by its name. Returns ErrHostNotFound if no host with the given name exists.

func (*Repository) List

func (r *Repository) List(ctx context.Context, filter *HostFilter, heartbeatTimeout time.Duration, since time.Time) ([]*Host, int64, error)

List retrieves hosts based on filter criteria with pagination. List 根据过滤条件和分页获取主机列表。 since: when non-zero, IsOnline filter uses heartbeat after since (e.g. process start). Returns the list of hosts and total count.

func (*Repository) MarkOfflineHosts

func (r *Repository) MarkOfflineHosts(ctx context.Context, timeout time.Duration) (int64, error)

MarkOfflineHosts marks all hosts as offline if their last heartbeat exceeds the timeout.

func (*Repository) Update

func (r *Repository) Update(ctx context.Context, host *Host) error

Update updates an existing host record. Returns ErrHostNotFound if the host does not exist. Returns ErrHostNameDuplicate if updating to a name that already exists. Returns ErrHostIPDuplicate if updating to an IP that already exists. Returns ErrHostIPInvalid if the IP address format is invalid.

func (*Repository) UpdateAgentStatus

func (r *Repository) UpdateAgentStatus(ctx context.Context, id uint, status AgentStatus, agentID string, version string) error

UpdateAgentStatus updates the agent status and related fields for a host. Also updates the host status based on agent status: - AgentStatusInstalled -> HostStatusConnected - AgentStatusOffline -> HostStatusOffline

func (*Repository) UpdateHeartbeat

func (r *Repository) UpdateHeartbeat(ctx context.Context, id uint, cpuUsage, memoryUsage, diskUsage float64) error

UpdateHeartbeat updates the heartbeat timestamp and resource usage for a host.

func (*Repository) UpdateSystemInfo

func (r *Repository) UpdateSystemInfo(ctx context.Context, id uint, osType, arch string, cpuCores int, totalMemory, totalDisk int64) error

UpdateSystemInfo updates the system information for a host.

type Service

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

Service provides business logic for host management operations. Service 提供主机管理操作的业务逻辑。

func NewService

func NewService(repo *Repository, clusterRepo *cluster.Repository, cfg *ServiceConfig) *Service

NewService creates a new Service instance. NewService 创建一个新的 Service 实例。

func (*Service) CheckAndMarkOffline

func (s *Service) CheckAndMarkOffline(ctx context.Context, hostID uint) (bool, error)

CheckAndMarkOffline checks a specific host and marks it offline if heartbeat timeout exceeded. CheckAndMarkOffline 检查特定主机,如果心跳超时则标记为离线。

func (*Service) Create

func (s *Service) Create(ctx context.Context, req *CreateHostRequest) (*Host, error)

Create creates a new host with validation. Create 创建一个新主机并进行验证。 Requirements: 3.1 - Validates host name uniqueness and IP address format.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, id uint) error

Delete removes a host after checking cluster associations. Delete 在检查集群关联后删除主机。 Requirements: 3.6 - Checks if host is associated with clusters before deletion.

func (*Service) Get

func (s *Service) Get(ctx context.Context, id uint) (*Host, error)

Get retrieves a host by ID. Get 根据 ID 获取主机。 Requirements: 3.5 - Returns host details including agent status and resource usage.

func (*Service) GetAssociatedClusters

func (s *Service) GetAssociatedClusters(ctx context.Context, hostID uint) ([]*cluster.Cluster, error)

GetAssociatedClusters returns the list of clusters associated with a host. GetAssociatedClusters 返回与主机关联的集群列表。

func (*Service) GetByAgentID

func (s *Service) GetByAgentID(ctx context.Context, agentID string) (*Host, error)

GetByAgentID retrieves a host by Agent ID. GetByAgentID 根据 Agent ID 获取主机。

func (*Service) GetByIP

func (s *Service) GetByIP(ctx context.Context, ip string) (*Host, error)

GetByIP retrieves a host by IP address. GetByIP 根据 IP 地址获取主机。

func (*Service) GetHeartbeatTimeout

func (s *Service) GetHeartbeatTimeout() time.Duration

GetHeartbeatTimeout returns the configured heartbeat timeout. GetHeartbeatTimeout 返回配置的心跳超时时间。

func (*Service) GetHostByID

func (s *Service) GetHostByID(ctx context.Context, id uint) (*cluster.HostInfo, error)

GetHostByID implements cluster.HostProvider interface. GetHostByID 实现 cluster.HostProvider 接口。 This method is used by cluster service to get host information. 此方法由集群服务用于获取主机信息。

func (*Service) GetInstallCommand

func (s *Service) GetInstallCommand(ctx context.Context, hostID uint) (string, error)

GetInstallCommand generates the Agent installation command for a host. GetInstallCommand 为主机生成 Agent 安装命令。 Requirements: 2.1 - Returns shell script with auto-detection logic and Control Plane address.

func (*Service) GetProcessStartedAt

func (s *Service) GetProcessStartedAt() time.Time

GetProcessStartedAt returns the process start time used for "online since start" checks.

func (*Service) IsHostOnline

func (s *Service) IsHostOnline(ctx context.Context, hostID uint) (bool, error)

IsHostOnline checks if a host is currently online based on heartbeat. IsHostOnline 根据心跳检查主机是否当前在线。

func (*Service) List

func (s *Service) List(ctx context.Context, filter *HostFilter) ([]*Host, int64, error)

List retrieves hosts based on filter criteria. List 根据过滤条件获取主机列表。 Requirements: 3.5 - Returns host name, IP, agent status, online status, resource usage, last heartbeat.

func (*Service) ListWithInfo

func (s *Service) ListWithInfo(ctx context.Context, filter *HostFilter) ([]*HostInfo, int64, error)

ListWithInfo retrieves hosts and converts them to HostInfo with online status. ListWithInfo 获取主机列表并转换为包含在线状态的 HostInfo。

func (*Service) MarkOfflineHosts

func (s *Service) MarkOfflineHosts(ctx context.Context) (int64, error)

MarkOfflineHosts marks all hosts as offline if their last heartbeat exceeds the timeout. MarkOfflineHosts 如果主机的最后心跳超过超时时间,则将其标记为离线。 Requirements: 3.4 - Marks hosts as offline if no heartbeat received for 30 seconds.

func (*Service) SetOnHostDeleted added in v1.2.0

func (s *Service) SetOnHostDeleted(fn func(ctx context.Context, hostID uint))

SetOnHostDeleted 设置主机删除后的钩子。/ SetOnHostDeleted sets the hook run after a host is deleted.

func (*Service) Update

func (s *Service) Update(ctx context.Context, id uint, req *UpdateHostRequest) (*Host, error)

Update updates an existing host with validation. Update 更新现有主机并进行验证。

func (*Service) UpdateAgentStatus

func (s *Service) UpdateAgentStatus(ctx context.Context, hostID uint, ipAddress string, agentID string, version string, systemInfo *SystemInfo, hostname string, localIPs []string) (*Host, error)

UpdateAgentStatus updates the agent status when an Agent registers. UpdateAgentStatus 在 Agent 注册时更新 Agent 状态。 Requirements: 3.2 - Matches Agent hostID or IP with registered host and updates status to "installed". If hostID > 0, attempts to find and bind to the specified host first. 若 hostID > 0,则优先查找并绑定指定的主机 ID。 If no host matches, falls back to matching by IP, then by uninstalled host name, or auto-creates a bare_metal host. 若未匹配到主机,则依次回退到按 IP 查找、按未安装主机名匹配或自动创建物理机。 localIPs is the Agent's local address set; when the stored host IP is not among them, it is treated as wrong and corrected. localIPs 为本机地址集合;若主机已存 IP 不在该集合中,视为用户填错并校正为上报主 IP。

func (*Service) UpdateAgentStatusByID

func (s *Service) UpdateAgentStatusByID(ctx context.Context, hostID uint, status AgentStatus, agentID string, version string) error

UpdateAgentStatusByID updates the agent status for a specific host ID. UpdateAgentStatusByID 更新指定主机 ID 的 Agent 状态。

func (*Service) UpdateDockerVersion

func (s *Service) UpdateDockerVersion(ctx context.Context, hostID uint, version string) error

UpdateDockerVersion updates the Docker version for a Docker host. UpdateDockerVersion 更新 Docker 主机的 Docker 版本。

func (*Service) UpdateHeartbeat

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

UpdateHeartbeat updates the heartbeat timestamp and resource usage for a host. UpdateHeartbeat 更新主机的心跳时间戳和资源使用率。 Requirements: 3.3 - Updates last heartbeat time, CPU, memory, and disk usage. If the host was marked offline, it is set back to installed so dashboard and host management show the same state. 若主机此前被标为离线,会恢复为已安装,使首页与主机管理状态一致。

func (*Service) UpdateHeartbeatByID

func (s *Service) UpdateHeartbeatByID(ctx context.Context, hostID uint, cpuUsage, memoryUsage, diskUsage float64) error

UpdateHeartbeatByID updates the heartbeat for a specific host ID. UpdateHeartbeatByID 更新指定主机 ID 的心跳。

func (*Service) UpdateHostStatus

func (s *Service) UpdateHostStatus(ctx context.Context, hostID uint, status HostStatus) error

UpdateHostStatus updates the connection status for a host (used for Docker/K8s hosts). UpdateHostStatus 更新主机的连接状态(用于 Docker/K8s 主机)。 This method is called after API connection test for Docker/K8s hosts. 此方法在 Docker/K8s 主机的 API 连接测试后调用。

func (*Service) UpdateK8sVersion

func (s *Service) UpdateK8sVersion(ctx context.Context, hostID uint, version string) error

UpdateK8sVersion updates the Kubernetes version for a K8s host. UpdateK8sVersion 更新 K8s 主机的 Kubernetes 版本。

func (*Service) UpdateResourceUsage

func (s *Service) UpdateResourceUsage(ctx context.Context, hostID uint, cpuUsage, memoryUsage, diskUsage float64) error

UpdateResourceUsage updates the resource usage for any host type. UpdateResourceUsage 更新任何主机类型的资源使用率。 This is used for Docker/K8s hosts where resource info is obtained via API. 用于通过 API 获取资源信息的 Docker/K8s 主机。

type ServiceConfig

type ServiceConfig struct {
	HeartbeatTimeout time.Duration
	ControlPlaneAddr string
}

ServiceConfig holds configuration for the Host Service. ServiceConfig 保存 Host Service 的配置。

type SystemInfo

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

SystemInfo represents system information reported by an Agent. SystemInfo 表示 Agent 上报的系统信息。

type UpdateHostRequest

type UpdateHostRequest struct {
	Name        *string `json:"name"`
	Description *string `json:"description"`

	// bare_metal fields / 物理机字段
	IPAddress *string `json:"ip_address"`
	SSHPort   *int    `json:"ssh_port"`

	// docker fields / Docker 字段
	DockerAPIURL     *string `json:"docker_api_url"`
	DockerTLSEnabled *bool   `json:"docker_tls_enabled"`
	DockerCertPath   *string `json:"docker_cert_path"`

	// kubernetes fields / Kubernetes 字段
	K8sAPIURL     *string `json:"k8s_api_url"`
	K8sNamespace  *string `json:"k8s_namespace"`
	K8sKubeconfig *string `json:"k8s_kubeconfig"`
	K8sToken      *string `json:"k8s_token"`
}

UpdateHostRequest represents a request to update an existing host. UpdateHostRequest 表示更新现有主机的请求。

type UpdateHostResponse

type UpdateHostResponse struct {
	ErrorMsg string    `json:"error_msg"`
	Data     *HostInfo `json:"data"`
}

UpdateHostResponse represents the response for updating a host. UpdateHostResponse 表示更新主机的响应。

Jump to

Keyboard shortcuts

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