fix: Remove code comments (#9297)

This commit is contained in:
ssongliu 2025-06-26 14:39:22 +08:00 committed by GitHub
parent 6850acabae
commit 874717cbcd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 5 additions and 52 deletions

View file

@ -50,8 +50,6 @@ func (h *HostToolService) GetToolStatus(req request.HostToolReq) (*response.Host
func (h *HostToolService) getSupervisorStatus(res *response.HostToolRes) (*response.HostToolRes, error) { func (h *HostToolService) getSupervisorStatus(res *response.HostToolRes) (*response.HostToolRes, error) {
supervisorConfig := &response.Supervisor{} supervisorConfig := &response.Supervisor{}
// 1. 检查supervisord是否安装
if !cmd.Which(constant.Supervisord) { if !cmd.Which(constant.Supervisord) {
supervisorConfig.IsExist = false supervisorConfig.IsExist = false
res.Config = supervisorConfig res.Config = supervisorConfig
@ -59,7 +57,6 @@ func (h *HostToolService) getSupervisorStatus(res *response.HostToolRes) (*respo
} }
supervisorConfig.IsExist = true supervisorConfig.IsExist = true
// 2. 获取服务名称(兼容不同平台)
serviceName, err := h.determineServiceName() serviceName, err := h.determineServiceName()
if err != nil || serviceName == "" { if err != nil || serviceName == "" {
supervisorConfig.IsExist = false supervisorConfig.IsExist = false
@ -68,28 +65,23 @@ func (h *HostToolService) getSupervisorStatus(res *response.HostToolRes) (*respo
} }
supervisorConfig.ServiceName = serviceName supervisorConfig.ServiceName = serviceName
// 3. 从数据库获取自定义服务名
if nameSetting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorServiceName)); nameSetting.Value != "" { if nameSetting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorServiceName)); nameSetting.Value != "" {
supervisorConfig.ServiceName = nameSetting.Value supervisorConfig.ServiceName = nameSetting.Value
} }
// 4. 获取版本信息
if version, err := cmd.Exec("supervisord -v"); err == nil { if version, err := cmd.Exec("supervisord -v"); err == nil {
supervisorConfig.Version = strings.TrimSpace(version) supervisorConfig.Version = strings.TrimSpace(version)
} }
// 5. 检查supervisorctl是否存在
_, errCtl := exec.LookPath("supervisorctl") _, errCtl := exec.LookPath("supervisorctl")
supervisorConfig.CtlExist = errCtl == nil supervisorConfig.CtlExist = errCtl == nil
// 6. 检查服务状态
if active, err := systemctl.IsActive(supervisorConfig.ServiceName); err == nil && active { if active, err := systemctl.IsActive(supervisorConfig.ServiceName); err == nil && active {
supervisorConfig.Status = "running" supervisorConfig.Status = "running"
} else { } else {
supervisorConfig.Status = "stopped" supervisorConfig.Status = "stopped"
} }
// 7. 获取配置文件路径
h.resolveConfigPath(supervisorConfig) h.resolveConfigPath(supervisorConfig)
res.Config = supervisorConfig res.Config = supervisorConfig
@ -97,7 +89,6 @@ func (h *HostToolService) getSupervisorStatus(res *response.HostToolRes) (*respo
} }
func (h *HostToolService) determineServiceName() (string, error) { func (h *HostToolService) determineServiceName() (string, error) {
// 优先级 1: 数据库配置
if setting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorServiceName)); setting.Value != "" { if setting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorServiceName)); setting.Value != "" {
serviceName, err := systemctl.GetServiceName(setting.Value) serviceName, err := systemctl.GetServiceName(setting.Value)
if err != nil { if err != nil {
@ -105,7 +96,6 @@ func (h *HostToolService) determineServiceName() (string, error) {
} }
return serviceName, nil return serviceName, nil
} }
// 优先级 2: 自动检测服务名
if serviceName, err := systemctl.GetServiceName(constant.Supervisord); err == nil { if serviceName, err := systemctl.GetServiceName(constant.Supervisord); err == nil {
return serviceName, nil return serviceName, nil
} }
@ -113,16 +103,13 @@ func (h *HostToolService) determineServiceName() (string, error) {
} }
func (h *HostToolService) resolveConfigPath(config *response.Supervisor) { func (h *HostToolService) resolveConfigPath(config *response.Supervisor) {
// 1. 数据库配置优先
if pathSetting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorConfigPath)); pathSetting.Value != "" { if pathSetting, _ := settingRepo.Get(settingRepo.WithByKey(constant.SupervisorConfigPath)); pathSetting.Value != "" {
config.ConfigPath = pathSetting.Value config.ConfigPath = pathSetting.Value
return return
} }
// 2. 标记需要初始化配置
config.Init = true config.Init = true
// 3. 尝试获取服务文件路径
if servicePath, err := systemctl.GetServicePath(config.ServiceName); err == nil { if servicePath, err := systemctl.GetServicePath(config.ServiceName); err == nil {
if startCmd, _ := ini_conf.GetIniValue(servicePath, "Service", "ExecStart"); startCmd != "" { if startCmd, _ := ini_conf.GetIniValue(servicePath, "Service", "ExecStart"); startCmd != "" {
if path := parseConfigPathFromCommand(startCmd); path != "" { if path := parseConfigPathFromCommand(startCmd); path != "" {
@ -132,7 +119,6 @@ func (h *HostToolService) resolveConfigPath(config *response.Supervisor) {
} }
} }
// 4. 尝试默认路径
defaultPaths := []string{ defaultPaths := []string{
"/etc/supervisord.conf", "/etc/supervisord.conf",
"/etc/supervisor/supervisord.conf", "/etc/supervisor/supervisord.conf",

View file

@ -134,7 +134,6 @@ func smartServiceName(keyword string) (string, error) {
} }
func handleServiceNaming(mgr ServiceManager, keyword string) string { func handleServiceNaming(mgr ServiceManager, keyword string) string {
keyword = strings.ToLower(keyword) keyword = strings.ToLower(keyword)
// 处理 .service.socket 后缀
if strings.HasSuffix(keyword, ".service.socket") { if strings.HasSuffix(keyword, ".service.socket") {
keyword = strings.TrimSuffix(keyword, ".service.socket") + ".socket" keyword = strings.TrimSuffix(keyword, ".service.socket") + ".socket"
} }
@ -142,7 +141,6 @@ func handleServiceNaming(mgr ServiceManager, keyword string) string {
keyword = strings.TrimSuffix(keyword, ".service") keyword = strings.TrimSuffix(keyword, ".service")
return keyword return keyword
} }
// 自动补全 .service 后缀
if !strings.HasSuffix(keyword, ".service") && if !strings.HasSuffix(keyword, ".service") &&
!strings.HasSuffix(keyword, ".socket") { !strings.HasSuffix(keyword, ".socket") {
keyword += ".service" keyword += ".service"
@ -152,18 +150,17 @@ func handleServiceNaming(mgr ServiceManager, keyword string) string {
func validateCandidatesConcurrently(candidates []string) (string, error) { func validateCandidatesConcurrently(candidates []string) (string, error) {
var ( var (
g errgroup.Group g errgroup.Group
found = make(chan string, 1) // 缓冲确保首个结果不阻塞 found = make(chan string, 1)
) )
// 启动并发检查
for _, candidate := range candidates { for _, candidate := range candidates {
cand := candidate // 避免闭包循环引用 cand := candidate
g.Go(func() error { g.Go(func() error {
confirmed, _ := confirmServiceExists(cand) confirmed, _ := confirmServiceExists(cand)
if confirmed { if confirmed {
select { select {
case found <- cand: // 发送首个成功结果 case found <- cand:
default: // 如果已有结果,忽略后续 default:
} }
return nil return nil
} }
@ -171,7 +168,6 @@ func validateCandidatesConcurrently(candidates []string) (string, error) {
}) })
} }
// 处理结果
resultErr := make(chan error, 1) resultErr := make(chan error, 1)
go func() { go func() {
defer close(found) defer close(found)
@ -220,17 +216,15 @@ func selectBestMatch(keyword string, candidates []string) (string, error) {
lowerKeyword := strings.ToLower(keyword) lowerKeyword := strings.ToLower(keyword)
var exactMatch string var exactMatch string
var firstContainMatch string var firstContainMatch string
// 第一轮遍历:严格匹配完全一致的名称(不区分大小写)
for _, name := range candidates { for _, name := range candidates {
if strings.EqualFold(name, keyword) { if strings.EqualFold(name, keyword) {
exactMatch = name exactMatch = name
break // 完全匹配直接终止循环 break
} }
} }
if exactMatch != "" { if exactMatch != "" {
return exactMatch, nil return exactMatch, nil
} }
// 第二轮遍历:寻找首个包含关键字的名称(不区分大小写)
for _, name := range candidates { for _, name := range candidates {
if strings.Contains(strings.ToLower(name), lowerKeyword) { if strings.Contains(strings.ToLower(name), lowerKeyword) {
firstContainMatch = name firstContainMatch = name
@ -241,7 +235,6 @@ func selectBestMatch(keyword string, candidates []string) (string, error) {
if firstContainMatch != "" { if firstContainMatch != "" {
return firstContainMatch, nil return firstContainMatch, nil
} }
// 无任何匹配项时返回明确错误
return "", fmt.Errorf("%w: %q (no exact or partial match)", ErrNoValidService, keyword) return "", fmt.Errorf("%w: %q (no exact or partial match)", ErrNoValidService, keyword)
} }
@ -394,7 +387,6 @@ func ViewConfig(path string, opt ConfigOption) (string, error) {
output, err := executeCommand(ctx, cmd[0], cmd[1:]...) output, err := executeCommand(ctx, cmd[0], cmd[1:]...)
if err != nil { if err != nil {
// global.LOG.Errorf("View config command failed: %v", err)
return "", fmt.Errorf("view config failed: %w", err) return "", fmt.Errorf("view config failed: %w", err)
} }
return string(output), nil return string(output), nil

View file

@ -12,18 +12,15 @@ import (
"github.com/1Panel-dev/1Panel/backend/global" "github.com/1Panel-dev/1Panel/backend/global"
) )
// ServiceConfig 服务配置结构
type ServiceConfig struct { type ServiceConfig struct {
ServiceName map[string]string ServiceName map[string]string
} }
// ServiceHandler 服务操作处理器
type ServiceHandler struct { type ServiceHandler struct {
config *ServiceConfig config *ServiceConfig
manager ServiceManager manager ServiceManager
} }
// NewServiceHandler 创建服务处理器
func NewServiceHandler(serviceNames map[string]string) *ServiceHandler { func NewServiceHandler(serviceNames map[string]string) *ServiceHandler {
mgr := GetGlobalManager() mgr := GetGlobalManager()
if mgr == nil { if mgr == nil {
@ -38,7 +35,6 @@ func NewServiceHandler(serviceNames map[string]string) *ServiceHandler {
} }
} }
// ServiceStatus 服务状态返回结构
type ServiceStatus struct { type ServiceStatus struct {
IsActive bool `json:"isActive"` IsActive bool `json:"isActive"`
IsEnabled bool `json:"isEnabled"` IsEnabled bool `json:"isEnabled"`
@ -55,7 +51,6 @@ type ServiceIsEnabled struct {
Output string `json:"output"` Output string `json:"output"`
} }
// ServiceResult 通用操作结果
type ServiceResult struct { type ServiceResult struct {
Success bool `json:"success"` Success bool `json:"success"`
Message string `json:"message"` Message string `json:"message"`
@ -67,7 +62,6 @@ var (
ErrServiceNotExist = errors.New("service does not exist") ErrServiceNotExist = errors.New("service does not exist")
) )
// 默认服务配置生成器(自动映射服务名到当前管理器)
func defaultServiceConfig(serviceName string) map[string]string { func defaultServiceConfig(serviceName string) map[string]string {
mgr := getManagerName() mgr := getManagerName()
if mgr == "" { if mgr == "" {
@ -97,7 +91,6 @@ func (h *ServiceHandler) GetServiceName() string {
return h.config.ServiceName[manager] return h.config.ServiceName[manager]
} }
// GetServicePath 获取服务路径
func (h *ServiceHandler) GetServicePath() (string, error) { func (h *ServiceHandler) GetServicePath() (string, error) {
manager := h.ManagerName() manager := h.ManagerName()
serviceName := h.config.ServiceName[manager] serviceName := h.config.ServiceName[manager]
@ -155,7 +148,6 @@ func (h *ServiceHandler) ExecuteAction(action string) (ServiceResult, error) {
return h.executeAction(action, successMsg) return h.executeAction(action, successMsg)
} }
// CheckStatus 检查服务状态
func (h *ServiceHandler) CheckStatus() (ServiceStatus, error) { func (h *ServiceHandler) CheckStatus() (ServiceStatus, error) {
manager := GetGlobalManager() manager := GetGlobalManager()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@ -174,7 +166,6 @@ func (h *ServiceHandler) CheckStatus() (ServiceStatus, error) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) wg.Add(2)
// 任务1检查服务是否活跃status
go func() { go func() {
defer wg.Done() defer wg.Done()
res := result{} res := result{}
@ -203,7 +194,6 @@ func (h *ServiceHandler) CheckStatus() (ServiceStatus, error) {
results <- res results <- res
}() }()
// 任务2检查服务是否启用is-enabled
go func() { go func() {
defer wg.Done() defer wg.Done()
res := result{} res := result{}
@ -335,27 +325,22 @@ func (h *ServiceHandler) IsEnabled() (ServiceStatus, error) {
}, nil }, nil
} }
// StartService 启动服务
func (h *ServiceHandler) StartService() (ServiceResult, error) { func (h *ServiceHandler) StartService() (ServiceResult, error) {
return h.ExecuteAction("start") return h.ExecuteAction("start")
} }
// StopService 停止服务
func (h *ServiceHandler) StopService() (ServiceResult, error) { func (h *ServiceHandler) StopService() (ServiceResult, error) {
return h.ExecuteAction("stop") return h.ExecuteAction("stop")
} }
// RestartService 重启服务
func (h *ServiceHandler) RestartService() (ServiceResult, error) { func (h *ServiceHandler) RestartService() (ServiceResult, error) {
return h.ExecuteAction("restart") return h.ExecuteAction("restart")
} }
// EnableService 启用开机启动
func (h *ServiceHandler) EnableService() (ServiceResult, error) { func (h *ServiceHandler) EnableService() (ServiceResult, error) {
return h.ExecuteAction("enable") return h.ExecuteAction("enable")
} }
// DisableService 禁用开机启动
func (h *ServiceHandler) DisableService() (ServiceResult, error) { func (h *ServiceHandler) DisableService() (ServiceResult, error) {
return h.ExecuteAction("disable") return h.ExecuteAction("disable")
} }
@ -394,7 +379,6 @@ func (h *ServiceHandler) executeAction(action, successMsg string) (ServiceResult
}, nil }, nil
} }
// ReloadManager 重新加载服务管理器(仅用于测试/调试)
func (h *ServiceHandler) ReloadManager() error { func (h *ServiceHandler) ReloadManager() error {
if err := ReinitializeManager(); err != nil { if err := ReinitializeManager(); err != nil {
global.LOG.Errorf("Failed to reload service manager: %v", err) global.LOG.Errorf("Failed to reload service manager: %v", err)

View file

@ -60,7 +60,6 @@ func (b *baseManager) commonServiceExists(config *ServiceConfig, checkFn func(st
if name := config.ServiceName[b.name]; name != "" { if name := config.ServiceName[b.name]; name != "" {
exists, checkErr := checkFn(name) exists, checkErr := checkFn(name)
if checkErr != nil { if checkErr != nil {
// global.LOG.Warnf("Service existence check failed %s: %v", b.name, checkErr)
return false, nil return false, nil
} }
return exists, nil return exists, nil
@ -317,10 +316,8 @@ func (m *sysvinitManager) ParseStatus(output string, config *ServiceConfig, stat
if strings.Contains(output, "no such file or directory") { if strings.Contains(output, "no such file or directory") {
return false, nil return false, nil
} }
// 关键逻辑:如果 find 命令有输出(找到符号链接),则服务已启用
return strings.TrimSpace(output) != "", nil return strings.TrimSpace(output) != "", nil
case "active": case "active":
// 关键逻辑:如果输出包含 "running" 或 "active",则服务处于活动状态
if strings.Contains(output, "not found") { if strings.Contains(output, "not found") {
return false, nil return false, nil
} }
@ -444,16 +441,13 @@ func (e CommandError) Error() string {
func (e CommandError) Unwrap() error { return e.Err } func (e CommandError) Unwrap() error { return e.Err }
// ReinitializeManager for test
func ReinitializeManager() error { func ReinitializeManager() error {
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()
// initOnce = sync.Once{}
globalManager = nil globalManager = nil
return InitializeGlobalManager() return InitializeGlobalManager()
} }
// SetManagerPriority for test
func SetManagerPriority(order []string) { func SetManagerPriority(order []string) {
mu.Lock() mu.Lock()
defer mu.Unlock() defer mu.Unlock()

View file

@ -12,7 +12,6 @@ import (
func DefaultHandler(serviceName string) (*ServiceHandler, error) { func DefaultHandler(serviceName string) (*ServiceHandler, error) {
svcName, err := smartServiceName(serviceName) svcName, err := smartServiceName(serviceName)
if err != nil { if err != nil {
// global.LOG.Errorf("SmartServiceName failed for %s: %v", serviceName, err)
return nil, ErrServiceNotFound return nil, ErrServiceNotFound
} }
return NewServiceHandler(defaultServiceConfig(svcName)), nil return NewServiceHandler(defaultServiceConfig(svcName)), nil
@ -21,7 +20,6 @@ func DefaultHandler(serviceName string) (*ServiceHandler, error) {
func GetServiceName(serviceName string) (string, error) { func GetServiceName(serviceName string) (string, error) {
serviceName, err := smartServiceName(serviceName) serviceName, err := smartServiceName(serviceName)
if err != nil { if err != nil {
// global.LOG.Errorf("GetServiceName validation failed: %v", err)
return "", ErrServiceNotFound return "", ErrServiceNotFound
} }
return serviceName, nil return serviceName, nil
@ -30,7 +28,6 @@ func GetServiceName(serviceName string) (string, error) {
func GetServicePath(serviceName string) (string, error) { func GetServicePath(serviceName string) (string, error) {
handler, err := DefaultHandler(serviceName) handler, err := DefaultHandler(serviceName)
if err != nil { if err != nil {
// global.LOG.Errorf("GetServicePath handler init failed: %v", err)
return "", ErrServiceNotFound return "", ErrServiceNotFound
} }
return handler.GetServicePath() return handler.GetServicePath()