setup

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: GPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

Package setup 系统初始化向导模块

Package setup 系统初始化向导模块

Index

Constants

View Source
const (
	ModuleID      = "setup"
	ModuleName    = "初始化向导"
	ModuleVersion = "1.0.0"
)

Variables

View Source
var (
	ErrSetupAlreadyCompleted = errors.New("setup already completed")
	ErrSetupNotStarted       = errors.New("setup not started")
	ErrInvalidStep           = errors.New("invalid step")
	ErrStepNotCompleted      = errors.New("previous step not completed")
	ErrUserExists            = errors.New("user already exists")
	ErrReservedUsername      = errors.New("reserved username")
	ErrInvalidPassword       = errors.New("invalid password")
	ErrInvalidConfirmText    = errors.New("invalid confirm text, must be 'RESET'")
)

Functions

This section is empty.

Types

type AvailableDisk

type AvailableDisk struct {
	Path      string `json:"path"`      // 设备路径
	Name      string `json:"name"`      // 设备名称
	Model     string `json:"model"`     // 型号
	Serial    string `json:"serial"`    // 序列号
	Size      uint64 `json:"size"`      // 大小
	Type      string `json:"type"`      // 类型: hdd, ssd, nvme
	Transport string `json:"transport"` // 传输协议: sata, nvme, usb
	IsSystem  bool   `json:"is_system"` // 是否为系统盘
	InUse     bool   `json:"in_use"`    // 是否已被使用
}

AvailableDisk 可用于创建存储池的硬盘

type Checker

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

Checker 系统检查器

func NewChecker

func NewChecker(logger *zap.Logger) *Checker

NewChecker 创建系统检查器

func (*Checker) CheckSystem

func (c *Checker) CheckSystem() (*SystemCheckResult, error)

CheckSystem 执行完整的系统检查

func (*Checker) DetectDrives

func (c *Checker) DetectDrives() ([]DetectedDrive, error)

DetectDrives 检测系统中的硬盘

type CompleteResponse

type CompleteResponse struct {
	Success        bool   `json:"success"`
	RedirectURL    string `json:"redirect_url"`
	AutoLoginToken string `json:"auto_login_token,omitempty"`
	RefreshToken   string `json:"refresh_token,omitempty"`
	TokenExpiresAt int64  `json:"token_expires_at,omitempty"`
}

CompleteResponse 完成初始化响应

type ConfigField

type ConfigField struct {
	Key         string      `json:"key"`
	Label       string      `json:"label"`
	Type        string      `json:"type"`
	Default     interface{} `json:"default"`
	Options     []string    `json:"options,omitempty"`
	Description string      `json:"description,omitempty"`
	Required    bool        `json:"required,omitempty"`
}

ConfigField 配置字段定义

type ConfigProvider

type ConfigProvider interface {
	GetString(key string) string
}

ConfigProvider 配置提供者接口

type DependencyCheck

type DependencyCheck struct {
	Name      string `json:"name"`
	Required  bool   `json:"required"`
	Installed bool   `json:"installed"`
	Version   string `json:"version"`
}

DependencyCheck 依赖检查项

type DetectedDrive

type DetectedDrive struct {
	DevicePath string      `json:"device_path"`
	Size       int64       `json:"size"`
	Model      string      `json:"model"`
	Serial     string      `json:"serial"`
	Partitions []Partition `json:"partitions"`
}

DetectedDrive 检测到的硬盘

type DiskSpaceCheck

type DiskSpaceCheck struct {
	Path        string `json:"path"`
	TotalBytes  int64  `json:"total_bytes"`
	AvailBytes  int64  `json:"avail_bytes"`
	MinRequired int64  `json:"min_required"`
	Sufficient  bool   `json:"sufficient"`
}

DiskSpaceCheck 磁盘空间检查

type DriveMount

type DriveMount struct {
	DevicePath string `json:"device_path" binding:"required"`
	MountPoint string `json:"mount_point" binding:"required"`
	Filesystem string `json:"filesystem"`
	Label      string `json:"label"`
	AutoMount  bool   `json:"auto_mount"`
}

DriveMount 硬盘挂载配置

type FactoryResetRequest

type FactoryResetRequest struct {
	Password       string `json:"password" binding:"required"`     // 当前用户密码(二次确认)
	ConfirmText    string `json:"confirm_text" binding:"required"` // 必须输入 "RESET"
	KeepDockerApps bool   `json:"keep_docker_apps"`                // 是否保留 Docker 应用
	KeepUserFiles  bool   `json:"keep_user_files"`                 // 是否保留用户文件
}

FactoryResetRequest 恢复出厂设置请求 用户身份通过 JWT 获取,但需要再次输入密码确认

type FactoryResetResponse

type FactoryResetResponse struct {
	Success     bool   `json:"success"`
	Message     string `json:"message"`
	RedirectURL string `json:"redirect_url"`
}

FactoryResetResponse 恢复出厂设置响应

type FeatureCategory

type FeatureCategory struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Icon        string `json:"icon"`
}

FeatureCategory 功能分类

type FeatureOption

type FeatureOption struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Description  string   `json:"description"`
	Icon         string   `json:"icon,omitempty"`
	Category     string   `json:"category"`     // 分类: container, virtualization, tools
	Dependencies []string `json:"dependencies"` // 依赖的模块
	Recommended  bool     `json:"recommended"`  // 是否推荐启用
	RequiresHW   []string `json:"requires_hw"`  // 需要的硬件: kvm, docker, gpu
}

FeatureOption 可选功能项

type FeatureOptionsResponse

type FeatureOptionsResponse struct {
	Categories []FeatureCategory `json:"categories"`
	Features   []FeatureOption   `json:"features"`
	HWSupport  HardwareSupport   `json:"hw_support"` // 硬件支持情况
}

FeatureOptionsResponse 可选功能列表响应

type FeatureSelection

type FeatureSelection struct {
	EnabledModules []string `json:"enabled_modules" binding:"required"` // 启用的模块 ID 列表
}

FeatureSelection 功能选择请求

type Handler

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

Handler HTTP 处理器

func NewHandler

func NewHandler(service *Service, logger *zap.Logger) *Handler

NewHandler 创建处理器

func (*Handler) CheckSystem

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

CheckSystem 执行系统检查 GET /api/v1/setup/check

func (*Handler) Complete

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

Complete 完成初始化 POST /api/v1/setup/complete

func (*Handler) CompleteStep1

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

CompleteStep1 完成系统检查步骤 POST /api/v1/setup/check/complete

func (*Handler) ConfigureNetwork

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

ConfigureNetwork 配置网络 POST /api/v1/setup/network

func (*Handler) ConfigureSecurity

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

ConfigureSecurity 配置安全选项 POST /api/v1/setup/security

func (*Handler) ConfigureStorage

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

ConfigureStorage 配置存储 POST /api/v1/setup/storage

func (*Handler) CreateAdmin

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

CreateAdmin 创建管理员 POST /api/v1/setup/user

func (*Handler) FactoryReset

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

FactoryReset 恢复出厂设置 POST /api/v1/setup/factory-reset 需要 JWT 认证,且必须是管理员,还需要再次输入密码确认

func (*Handler) GetAvailableDisks

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

GetAvailableDisks 获取可用于创建存储池的硬盘 GET /api/v1/setup/storage/available-disks

func (*Handler) GetDrives

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

GetDrives 获取检测到的硬盘 GET /api/v1/setup/drives

func (*Handler) GetFeatures

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

GetFeatures 获取可选功能列表 GET /api/v1/setup/features

func (*Handler) GetModuleSettings

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

GetModuleSettings 获取所有模块设置 GET /api/v1/settings/modules

func (*Handler) GetStatus

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

GetStatus 获取初始化状态 GET /api/v1/setup/status

func (*Handler) InstallDeps

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

InstallDeps 安装缺失的依赖(SSE 流式响应) POST /api/v1/setup/install-deps

func (*Handler) SaveFeatures

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

SaveFeatures 保存功能选择 POST /api/v1/setup/features

func (*Handler) SetLocale

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

SetLocale 设置语言和时区 POST /api/v1/setup/locale

func (*Handler) SkipFeatures

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

SkipFeatures 跳过功能选择 POST /api/v1/setup/features/skip

func (*Handler) SkipNetwork

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

SkipNetwork 跳过网络配置 POST /api/v1/setup/network/skip

func (*Handler) SkipStorage

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

SkipStorage 跳过存储配置 POST /api/v1/setup/storage/skip

func (*Handler) UpdateModuleSetting

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

UpdateModuleSetting 更新模块设置 PUT /api/v1/settings/modules/:id

func (*Handler) Verify2FA

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

Verify2FA 验证 2FA POST /api/v1/setup/user/verify-2fa

type HardwareSupport

type HardwareSupport struct {
	KVMAvailable    bool   `json:"kvm_available"`
	DockerAvailable bool   `json:"docker_available"`
	GPUAvailable    bool   `json:"gpu_available"`
	GPUType         string `json:"gpu_type,omitempty"` // nvidia, amd, intel
}

HardwareSupport 硬件支持检测结果

type InstallDepsRequest

type InstallDepsRequest struct {
	Packages []string `json:"packages" binding:"required,min=1"`
}

InstallDepsRequest 安装依赖请求

type LocaleSettings

type LocaleSettings struct {
	Language   string `json:"language" binding:"required"`
	Timezone   string `json:"timezone" binding:"required"`
	TimeFormat string `json:"time_format" binding:"required"`
	DateFormat string `json:"date_format" binding:"required"`
}

LocaleSettings 语言和时区设置

type Module

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

Module 初始化向导模块

func NewModule

func NewModule() *Module

NewModule 创建模块实例

func (*Module) Dependencies

func (m *Module) Dependencies() []string

Dependencies 返回依赖的模块

func (*Module) ID

func (m *Module) ID() string

ID 返回模块 ID

func (*Module) Init

func (m *Module) Init(ctx *module.Context) error

Init 初始化模块

func (*Module) IsCompleted

func (m *Module) IsCompleted() bool

IsCompleted 检查初始化是否完成

func (*Module) MarkCompleted

func (m *Module) MarkCompleted() error

MarkCompleted 标记安装为已完成(用于 CLI 初始化)

func (*Module) Name

func (m *Module) Name() string

Name 返回模块名称

func (*Module) NeedsSetup

func (m *Module) NeedsSetup() bool

NeedsSetup 检查是否需要初始化

func (*Module) RegisterRoutes

func (m *Module) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes 注册路由

func (*Module) Service

func (m *Module) Service() *Service

Service 返回服务实例(供其他模块使用)

func (*Module) Start

func (m *Module) Start() error

Start 启动模块

func (*Module) Stop

func (m *Module) Stop() error

Stop 停止模块

func (*Module) Version

func (m *Module) Version() string

Version 返回模块版本

type ModuleSetting

type ModuleSetting struct {
	ModuleID  string                 `json:"module_id" gorm:"primaryKey;size:64"`
	Enabled   bool                   `json:"enabled" gorm:"default:false"`
	Config    map[string]interface{} `json:"config" gorm:"serializer:json;type:text"`
	UpdatedAt time.Time              `json:"updated_at"`
}

ModuleSetting 模块设置(与 model 包中的定义对应)

func (ModuleSetting) TableName

func (ModuleSetting) TableName() string

TableName 返回表名

type ModuleSettingWithMeta

type ModuleSettingWithMeta struct {
	ModuleID      string                 `json:"module_id"`
	Name          string                 `json:"name"`
	Description   string                 `json:"description"`
	Category      string                 `json:"category"`
	Enabled       bool                   `json:"enabled"`
	Dependencies  []string               `json:"dependencies"`
	DepsSatisfied bool                   `json:"deps_satisfied"`
	Config        map[string]interface{} `json:"config"`
	ConfigSchema  []ConfigField          `json:"config_schema"`
	UpdatedAt     time.Time              `json:"updated_at"`
}

ModuleSettingWithMeta 带元信息的模块设置

type NetworkConfig

type NetworkConfig struct {
	Mode      string   `json:"mode,omitempty" binding:"omitempty,oneof=dhcp static"` // dhcp | static,默认 dhcp
	IPAddress string   `json:"ip_address,omitempty"`
	Netmask   string   `json:"netmask,omitempty"`
	Gateway   string   `json:"gateway,omitempty"`
	DNS       []string `json:"dns,omitempty"`
	HTTPPort  int      `json:"http_port,omitempty"`
	HTTPSPort int      `json:"https_port,omitempty"`
}

NetworkConfig 网络配置

type Partition

type Partition struct {
	DevicePath string `json:"device_path"`
	Size       int64  `json:"size"`
	Filesystem string `json:"filesystem"`
	MountPoint string `json:"mount_point"`
	Label      string `json:"label"`
}

Partition 分区信息

type PortCheck

type PortCheck struct {
	Port         int    `json:"port"`
	InUse        bool   `json:"in_use"`
	InUseProcess string `json:"in_use_process"`
}

PortCheck 端口检查项

type SecurityConfig

type SecurityConfig struct {
	UseRandomPort bool `json:"use_random_port"` // 是否使用随机端口
	CustomPort    int  `json:"custom_port"`     // 自定义端口(0 表示不使用)
}

SecurityConfig 安全配置请求

type SecurityConfigResponse

type SecurityConfigResponse struct {
	PortChanged bool   `json:"port_changed"`
	NewPort     int    `json:"new_port,omitempty"`
	Message     string `json:"message"`
}

SecurityConfigResponse 安全配置响应

type Service

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

Service 初始化向导服务

func NewService

func NewService(db *gorm.DB, logger *zap.Logger, dataDir string, config ConfigProvider) *Service

NewService 创建服务实例

func (*Service) CheckSystem

func (s *Service) CheckSystem() (*SystemCheckResult, error)

CheckSystem 执行系统检查

func (*Service) Complete

func (s *Service) Complete() (*CompleteResponse, error)

Complete 完成初始化

func (*Service) CompleteStep1

func (s *Service) CompleteStep1() error

CompleteStep1 完成系统检查步骤

func (*Service) ConfigureNetwork

func (s *Service) ConfigureNetwork(req *NetworkConfig) error

ConfigureNetwork 配置网络

func (*Service) ConfigureSecurity

func (s *Service) ConfigureSecurity(req *SecurityConfig) (*SecurityConfigResponse, error)

ConfigureSecurity 配置安全选项(Setup 中调用) 可选将端口从默认 3080 切换为随机端口

func (*Service) ConfigureStorage

func (s *Service) ConfigureStorage(req *StorageConfig) error

ConfigureStorage 配置存储

func (*Service) CreateAdmin

func (s *Service) CreateAdmin(req *SetupUserRequest) (*TwoFactorSetup, error)

CreateAdmin 创建管理员用户

func (*Service) FactoryReset

func (s *Service) FactoryReset(req *FactoryResetRequest) (*FactoryResetResponse, error)

FactoryReset 恢复出厂设置 用户认证已在 handler 层通过 JWT 验证

func (*Service) GetAllModuleSettings

func (s *Service) GetAllModuleSettings() ([]ModuleSettingWithMeta, error)

GetAllModuleSettings 获取所有模块的设置和元信息

func (*Service) GetAvailableDisks

func (s *Service) GetAvailableDisks() ([]AvailableDisk, error)

GetAvailableDisks 获取可用于创建存储池的硬盘

func (*Service) GetDrives

func (s *Service) GetDrives() ([]DetectedDrive, error)

GetDrives 获取检测到的硬盘

func (*Service) GetFeatureOptions

func (s *Service) GetFeatureOptions() (*FeatureOptionsResponse, error)

GetFeatureOptions 获取可选功能列表

func (*Service) GetModuleSetting

func (s *Service) GetModuleSetting(moduleID string) (*ModuleSetting, error)

GetModuleSetting 获取单个模块的设置

func (*Service) GetStatus

func (s *Service) GetStatus() (*SetupStatus, error)

GetStatus 获取初始化状态

func (*Service) InstallDependencies

func (s *Service) InstallDependencies(packages []string, progressChan chan<- map[string]interface{}) error

InstallDependencies 安装缺失的依赖

func (*Service) IsCompleted

func (s *Service) IsCompleted() bool

IsCompleted 检查初始化是否完成

func (*Service) MarkSetupCompleted

func (s *Service) MarkSetupCompleted() error

MarkSetupCompleted 直接标记初始化完成(用于 CLI 安装)

func (*Service) NeedsSetup

func (s *Service) NeedsSetup() bool

NeedsSetup 检查是否需要初始化

func (*Service) SaveFeatureSelection

func (s *Service) SaveFeatureSelection(req *FeatureSelection) error

SaveFeatureSelection 保存功能选择

func (*Service) SetLocale

func (s *Service) SetLocale(req *LocaleSettings) error

SetLocale 设置语言和时区

func (*Service) SetTokenManager

func (s *Service) SetTokenManager(tm *auth.TokenManager)

SetTokenManager 设置由 bootstrap 注入的共享 TokenManager

func (*Service) SkipFeatureSelection

func (s *Service) SkipFeatureSelection() error

SkipFeatureSelection 跳过功能选择(使用默认配置)

func (*Service) SkipNetworkConfig

func (s *Service) SkipNetworkConfig() error

SkipNetworkConfig 跳过网络配置

func (*Service) SkipStorageConfig

func (s *Service) SkipStorageConfig() error

SkipStorageConfig 跳过存储配置,使用默认路径

func (*Service) UpdateModuleSetting

func (s *Service) UpdateModuleSetting(moduleID string, enabled bool, config map[string]interface{}) (*ModuleSetting, error)

UpdateModuleSetting 更新模块设置

func (*Service) ValidateUserPassword

func (s *Service) ValidateUserPassword(userID string, password string) error

ValidateUserPassword 验证用户密码

func (*Service) Verify2FA

func (s *Service) Verify2FA(userID, code string) error

Verify2FA 验证 2FA 码并启用

type SetupSettings

type SetupSettings struct {
	ID             uint       `json:"id" gorm:"primaryKey"`
	SetupCompleted bool       `json:"setup_completed" gorm:"default:false"`
	CurrentStep    int        `json:"current_step" gorm:"default:1"`
	CompletedSteps string     `json:"completed_steps" gorm:"type:text"` // JSON 数组
	Language       string     `json:"language" gorm:"size:10;default:'zh-CN'"`
	Timezone       string     `json:"timezone" gorm:"size:64;default:'Asia/Shanghai'"`
	TimeFormat     string     `json:"time_format" gorm:"size:10;default:'24h'"`
	DateFormat     string     `json:"date_format" gorm:"size:20;default:'YYYY-MM-DD'"`
	DataPath       string     `json:"data_path" gorm:"size:255"`
	NetworkMode    string     `json:"network_mode" gorm:"size:16;default:'dhcp'"`
	HTTPPort       int        `json:"http_port" gorm:"default:80"`
	HTTPSPort      int        `json:"https_port" gorm:"default:443"`
	StartedAt      *time.Time `json:"started_at"`
	CompletedAt    *time.Time `json:"completed_at"`
	CreatedAt      time.Time  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt      time.Time  `json:"updated_at" gorm:"autoUpdateTime"`
}

SetupSettings 初始化设置(存储在数据库中)

func (SetupSettings) TableName

func (SetupSettings) TableName() string

TableName 指定表名

type SetupStatus

type SetupStatus struct {
	Completed      bool  `json:"completed"`
	CurrentStep    int   `json:"current_step"`
	CompletedSteps []int `json:"completed_steps"`
	CanSkipSetup   bool  `json:"can_skip_setup"`
}

SetupStatus 初始化状态

type SetupUserRequest

type SetupUserRequest struct {
	Username  string `json:"username" binding:"required,min=3,max=32,alphanum"`
	Password  string `json:"password" binding:"required,min=8"`
	Avatar    string `json:"avatar,omitempty"`
	Enable2FA bool   `json:"enable_2fa"`
}

SetupUserRequest 创建管理员请求

type StorageConfig

type StorageConfig struct {
	DataPath       string       `json:"data_path" binding:"required"`
	ExternalDrives []DriveMount `json:"external_drives"`
}

StorageConfig 存储配置(原有的简单配置,保持兼容)

type SystemCheckResult

type SystemCheckResult struct {
	Dependencies []DependencyCheck `json:"dependencies"`
	Ports        []PortCheck       `json:"ports"`
	DiskSpace    DiskSpaceCheck    `json:"disk_space"`
	AllPassed    bool              `json:"all_passed"`
}

SystemCheckResult 系统检查结果

type TwoFactorSetup

type TwoFactorSetup struct {
	Secret      string   `json:"secret"`
	QRCodeURL   string   `json:"qr_code_url"`
	BackupCodes []string `json:"backup_codes"`
}

TwoFactorSetup 2FA 配置响应

type UserAccount

type UserAccount struct {
	ID       string `gorm:"primaryKey"`
	Username string
	Password string
	Role     string
}

UserAccount 用户账户结构(用于密码验证)

func (UserAccount) TableName

func (UserAccount) TableName() string

type Verify2FARequest

type Verify2FARequest struct {
	Code string `json:"code" binding:"required,len=6"`
}

Verify2FARequest 验证 2FA 请求

Jump to

Keyboard shortcuts

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