Files
LokiStack/backend/services/host.go
T
Logan.LiandClaude 327e282356 refactor: 前后端目录结构模块化 + v2 优化移植与缺陷修复
前端:
- src/srv/api → src/api,按域分文件夹(auth/cluster/host/storage/deployment/collector)
- 新增 http.ts 引擎(http.get/post/put/delete),域模块改用语义化调用
- index.html 增加 favicon(匹配应用 logo 的 emerald + Activity 脉冲)

后端分层增强(保留包名):
- 新增 repository/:从 models 拆出 JsonDB 持久化层(InitDB/GetDB/Shutdown/RequestSave)
- 新增 dto/:从 controllers 抽出各域请求契约(带 binding 校验)
- 新增 pkg/crypto、pkg/jwt:从 utils 拆出安全原语(外部 jwt 别名 jwtv5 避免冲突)
- models 只留领域实体 + sanitizer;utils 只留 gin/应用相关(response/errors)

v2 优化移植与缺陷修复:
- 移植密钥分离/SSH TOFU/并发写安全/Loki 生产级配置/Docker 加固
- 修复 deployment.go 并发丢更新、Helm values 重复键、EncryptField 哨兵、loki-gateway 端点等审计缺陷
- 实现真正的优雅关停(main.go http.Server + signal + repository.Shutdown)
- 修复登录契约:后端返回 accessToken,前端 auth.ts/Login.tsx 对齐
- 补 crypto/jwt/repository 单元测试(含并发写回归)

验证: go build/vet/test 全绿;npm run build 通过;登录→鉴权→优雅关停冒烟通过

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-30 10:46:26 +08:00

190 lines
4.2 KiB
Go

package services
import (
"context"
"fmt"
"strings"
"time"
"lokideploy/models"
"lokideploy/pkg/crypto"
"lokideploy/repository"
"lokideploy/utils"
)
type HostService struct{}
func NewHostService() *HostService {
return &HostService{}
}
func (s *HostService) Create(name, hostIP string, port int, user, authType, password, privateKey, keyPhrase, os, arch, labels string) (*models.Host, error) {
if port == 0 {
port = 22
}
host := models.Host{
ID: repository.GetDB().NextID("hosts"),
Name: name,
HostIP: hostIP,
Port: port,
User: user,
AuthType: authType,
OS: os,
Arch: arch,
Labels: labels,
Status: "pending",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if password != "" {
enc, err := crypto.EncryptField(password)
if err != nil {
return nil, fmt.Errorf("密码加密失败: %w", err)
}
host.Password = enc
}
if privateKey != "" {
enc, err := crypto.EncryptField(privateKey)
if err != nil {
return nil, fmt.Errorf("私钥加密失败: %w", err)
}
host.PrivateKey = enc
}
if keyPhrase != "" {
enc, err := crypto.EncryptField(keyPhrase)
if err != nil {
return nil, fmt.Errorf("私钥口令加密失败: %w", err)
}
host.KeyPhrase = enc
}
db := repository.GetDB()
db.Lock()
db.Hosts = append(db.Hosts, host)
db.Unlock()
db.RequestSave()
go s.Validate(host.ID)
return &host, nil
}
func (s *HostService) Get(id uint) (*models.Host, error) {
db := repository.GetDB()
db.RLock()
defer db.RUnlock()
for i := range db.Hosts {
if db.Hosts[i].ID == id {
h := db.Hosts[i]
return &h, nil
}
}
return nil, utils.ErrNotFound
}
func (s *HostService) List(page, pageSize int) ([]models.Host, int64, error) {
db := repository.GetDB()
db.RLock()
defer db.RUnlock()
total := int64(len(db.Hosts))
start := (page - 1) * pageSize
if start < 0 || start >= len(db.Hosts) {
return []models.Host{}, total, nil
}
end := start + pageSize
if end > len(db.Hosts) {
end = len(db.Hosts)
}
result := make([]models.Host, end-start)
copy(result, db.Hosts[start:end])
return result, total, nil
}
func (s *HostService) Update(id uint, updates map[string]interface{}) error {
db := repository.GetDB()
db.Lock()
defer db.Unlock()
for i := range db.Hosts {
if db.Hosts[i].ID == id {
if v, ok := updates["name"].(string); ok {
db.Hosts[i].Name = v
}
if v, ok := updates["status"].(string); ok {
db.Hosts[i].Status = v
}
if v, ok := updates["os"].(string); ok {
db.Hosts[i].OS = v
}
if v, ok := updates["arch"].(string); ok {
db.Hosts[i].Arch = v
}
db.Hosts[i].UpdatedAt = time.Now()
db.RequestSave()
return nil
}
}
return utils.ErrNotFound
}
func (s *HostService) Delete(id uint) error {
db := repository.GetDB()
db.Lock()
defer db.Unlock()
for i, h := range db.Hosts {
if h.ID == id {
db.Hosts = append(db.Hosts[:i], db.Hosts[i+1:]...)
db.RequestSave()
return nil
}
}
return utils.ErrNotFound
}
func (s *HostService) Validate(id uint) {
host, err := s.Get(id)
if err != nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
password := host.Password
if strings.HasPrefix(password, "ENC:") {
password, _ = crypto.Decrypt(password[4:])
}
client, err := NewSSHClient(host.HostIP, host.Port, host.User, password)
if err != nil {
s.Update(id, map[string]interface{}{"status": "error"})
return
}
defer client.Close()
if info, err := client.GetHostInfo(ctx); err == nil {
s.Update(id, map[string]interface{}{"status": "active", "os": info.OS, "arch": info.Arch})
} else {
s.Update(id, map[string]interface{}{"status": "active"})
}
}
func (s *HostService) ExecuteCommand(id uint, command string) (string, string, error) {
host, err := s.Get(id)
if err != nil {
return "", "", err
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
password := host.Password
if strings.HasPrefix(password, "ENC:") {
password, _ = crypto.Decrypt(password[4:])
}
client, err := NewSSHClient(host.HostIP, host.Port, host.User, password)
if err != nil {
return "", "", err
}
defer client.Close()
return client.Execute(ctx, command)
}