feat: add notify icon read

This commit is contained in:
engigu
2026-03-09 18:10:23 +08:00
parent e7da316c90
commit 77cf12c9b6
46 changed files with 1347 additions and 252 deletions
+3 -3
View File
@@ -331,8 +331,8 @@ func (s *AgentService) GetTasks(agentID string) []models.AgentTask {
if allEnvs {
envVars = envService.GetAllEnvVars()
} else if task.Envs != "" {
envVars = envService.GetEnvVarsByIDs(task.Envs)
} else if string(task.Envs) != "" {
envVars = envService.GetEnvVarsByIDs(string(task.Envs))
}
envVarsStr := executor.FormatEnvVars(envVars)
@@ -340,7 +340,7 @@ func (s *AgentService) GetTasks(agentID string) []models.AgentTask {
result[i] = models.AgentTask{
ID: task.ID,
Name: task.Name,
Command: task.Command,
Command: string(task.Command),
Schedule: task.Schedule,
Timeout: task.Timeout,
WorkDir: task.WorkDir,
+239
View File
@@ -0,0 +1,239 @@
package services
import (
"encoding/json"
"time"
"fmt"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
"github.com/engigu/baihu-panel/internal/logger"
"github.com/engigu/baihu-panel/internal/models"
"github.com/engigu/baihu-panel/internal/utils"
)
type LogRetentionConfig struct {
Days int `json:"days"`
MaxCount int `json:"max_count"`
}
type AppLogService struct {
settingsService *SettingsService
}
func NewAppLogService() *AppLogService {
return &AppLogService{
settingsService: NewSettingsService(),
}
}
func (s *AppLogService) Add(log *models.AppLog) error {
if log.ID == "" {
log.ID = utils.GenerateID()
}
return database.DB.Create(log).Error
}
func (s *AppLogService) List(category string, status string, level string, page, pageSize int, keyword string) ([]models.AppLog, int64, error) {
var logs []models.AppLog
var total int64
query := database.DB.Model(&models.AppLog{})
if category != "" {
query = query.Where("category = ?", category)
}
if status != "" {
query = query.Where("status = ?", status)
}
if level != "" {
query = query.Where("level = ?", level)
}
if keyword != "" {
query = query.Where("(title LIKE ? OR content LIKE ?)", "%"+keyword+"%", "%"+keyword+"%")
}
query.Count(&total)
offset := (page - 1) * pageSize
err := query.Order("created_at desc").Offset(offset).Limit(pageSize).Find(&logs).Error
return logs, total, err
}
func (s *AppLogService) MarkAsRead(id string) error {
now := models.LocalTime(time.Now())
return database.DB.Model(&models.AppLog{}).Where("id = ?", id).Updates(map[string]interface{}{
"status": constant.LogStatusRead,
"read_at": &now,
}).Error
}
func (s *AppLogService) MarkAllAsRead(category string) error {
now := models.LocalTime(time.Now())
return database.DB.Model(&models.AppLog{}).Where("category = ? AND status = ?", category, constant.LogStatusUnread).Updates(map[string]interface{}{
"status": constant.LogStatusRead,
"read_at": &now,
}).Error
}
func (s *AppLogService) Clear(category string) error {
query := database.DB.Model(&models.AppLog{})
if category != "" {
query = query.Where("category = ?", category)
}
return query.Unscoped().Delete(&models.AppLog{}).Error
}
func (s *AppLogService) GetRetentionConfigs() map[string]LogRetentionConfig {
val := s.settingsService.Get(constant.SectionSystem, "log_retention")
var configs map[string]LogRetentionConfig
if val != "" {
_ = json.Unmarshal([]byte(val), &configs)
}
if configs == nil {
configs = map[string]LogRetentionConfig{
constant.LogCategorySystemNotice: {Days: 30, MaxCount: 500},
constant.LogCategoryPushLog: {Days: 15, MaxCount: 5000},
constant.LogCategoryDefault: {Days: 30, MaxCount: 10000},
}
}
return configs
}
func (s *AppLogService) CleanUp() {
configs := s.GetRetentionConfigs()
categories := []string{constant.LogCategorySystemNotice, constant.LogCategoryPushLog}
for _, cat := range categories {
cfg, ok := configs[cat]
if !ok {
cfg = configs[constant.LogCategoryDefault]
}
if cfg.Days > 0 {
deadline := time.Now().AddDate(0, 0, -cfg.Days)
database.DB.Unscoped().Where("category = ? AND created_at < ?", cat, deadline).Delete(&models.AppLog{})
}
if cfg.MaxCount > 0 {
var total int64
database.DB.Model(&models.AppLog{}).Where("category = ?", cat).Count(&total)
if total > int64(cfg.MaxCount) {
deleteCount := total - int64(cfg.MaxCount)
var ids []string
database.DB.Model(&models.AppLog{}).Where("category = ?", cat).Order("created_at asc").Limit(int(deleteCount)).Pluck("id", &ids)
if len(ids) > 0 {
database.DB.Unscoped().Where("id IN ?", ids).Delete(&models.AppLog{})
}
}
}
}
logger.Debugf("[AppLog] 完成应用日志清理策略")
}
func (s *AppLogService) SubscribeEvents(bus *eventbus.EventBus) {
// 1. [订阅] 系统通知 -> 存储到数据库表现为红点消息
bus.Subscribe(constant.EventSystemNotice, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
title, _ := payload["title"].(string)
content, _ := payload["content"].(string)
level, _ := payload["level"].(string)
if level == "" {
level = constant.LogLevelInfo
}
s.Add(&models.AppLog{
Category: constant.LogCategorySystemNotice,
Title: title,
Content: models.BigText(content),
Level: level,
Status: constant.LogStatusUnread,
})
})
// 2. [订阅] 推送结果 -> 存储到数据库供推送日志查看
bus.Subscribe(constant.EventNotifySent, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
title, _ := payload["title"].(string)
content, _ := payload["content"].(string)
success, _ := payload["success"].(bool)
errorMsg, _ := payload["error_msg"].(string)
channelName, _ := payload["channel_name"].(string)
status := constant.LogStatusSuccess
level := constant.LogLevelInfo
if !success {
status = constant.LogStatusFailed
level = constant.LogLevelError
}
s.Add(&models.AppLog{
Category: constant.LogCategoryPushLog,
Title: fmt.Sprintf("[%s] %s", channelName, title),
Content: models.BigText(content),
Level: level,
Status: status,
ErrorMsg: models.BigText(errorMsg),
})
})
// 3. 将某些业务事件转化为系统内部通知 (自动出现在小铃铛)
bus.Subscribe(constant.EventTaskFailed, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
errMsg, _ := payload["error"].(string)
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行失败", taskName),
"content": fmt.Sprintf("错误详情: %s", errMsg),
"level": constant.LogLevelError,
},
})
})
bus.Subscribe(constant.EventTaskTimeout, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
taskName, _ := payload["task_name"].(string)
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": fmt.Sprintf("任务 [%s] 执行超时", taskName),
"content": "任务已经超过预设的运行时间并被系统强制中止。",
"level": constant.LogLevelWarning,
},
})
})
bus.Subscribe(constant.EventPasswordChanged, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
username, _ := payload["username"].(string)
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": "账户安全提醒",
"content": fmt.Sprintf("用户 %s 的账号密码已被修改。", username),
"level": constant.LogLevelInfo,
},
})
})
}
+5 -1
View File
@@ -57,6 +57,7 @@ func (s *BackupService) getTableConfigs() []tableConfig {
{"deps.json", s.exportTable(&[]models.Dependency{}, true), s.restoreTable(&[]models.Dependency{}, true)},
{"notify_ways.json", s.exportTable(&[]models.NotifyWay{}, true), s.restoreTable(&[]models.NotifyWay{}, true)},
{"notify_bindings.json", s.exportTable(&[]models.NotifyBinding{}, true), s.restoreTable(&[]models.NotifyBinding{}, true)},
{"app_logs.json", s.exportTable(&[]models.AppLog{}, false), s.restoreTable(&[]models.AppLog{}, false)},
}
}
@@ -235,6 +236,7 @@ func (s *BackupService) Restore(zipPath string) error {
tx.Unscoped().Where("1=1").Delete(&models.Dependency{})
tx.Unscoped().Where("1=1").Delete(&models.NotifyWay{})
tx.Unscoped().Where("1=1").Delete(&models.NotifyBinding{})
tx.Unscoped().Where("1=1").Delete(&models.AppLog{})
// 2. 依次恢复每个表
for _, cfg := range configs {
@@ -340,6 +342,8 @@ func (s *BackupService) restoreFromZipFile(tx *gorm.DB, f *zip.File, filename st
return restoreStreamBatch[models.NotifyWay](tx, decoder)
case "notify_bindings.json":
return restoreStreamBatch[models.NotifyBinding](tx, decoder)
case "app_logs.json":
return restoreStreamBatch[models.AppLog](tx, decoder)
default:
return nil
}
@@ -417,7 +421,7 @@ func (s *BackupService) GetBackupFile() string {
if err := database.DB.Where("section = ? AND `key` = ?", BackupSection, BackupFileKey).First(&setting).Error; err != nil {
return ""
}
return setting.Value
return string(setting.Value)
}
func (s *BackupService) ClearBackup() error {
+1 -1
View File
@@ -49,7 +49,7 @@ func (m *BaseManager) Install(dep *models.Dependency) error {
logger.Infof("Installing %s package: %s", m.Language, packageSpec)
output, err := m.runMiseCommand(dep.LangVersion, args)
dep.Log = string(output)
dep.Log = models.BigText(output)
if err != nil {
logger.Errorf("Install failed: %v, output: %s", err, string(output))
+5 -5
View File
@@ -20,7 +20,7 @@ func (es *EnvService) CreateEnvVar(name, value, remark string, hidden bool, user
env := &models.EnvironmentVariable{
ID: utils.GenerateID(),
Name: name,
Value: value,
Value: models.BigText(value),
Remark: remark,
Hidden: hidden,
UserID: userID,
@@ -72,7 +72,7 @@ func (es *EnvService) UpdateEnvVar(id string, name, value, remark string, hidden
}
updates := map[string]interface{}{
"name": name,
"value": value,
"value": models.BigText(value),
"remark": remark,
"hidden": hidden,
}
@@ -98,7 +98,7 @@ func (es *EnvService) DeleteEnvVar(id string, force bool) (bool, []models.Task)
err := database.DB.Transaction(func(tx *gorm.DB) error {
// Update tasks to remove this env ID
for _, task := range associatedTasks {
ids := splitEnvIDs(task.Envs)
ids := splitEnvIDs(string(task.Envs))
var newIDs []string
for _, eid := range ids {
if eid != id {
@@ -166,12 +166,12 @@ func (es *EnvService) formatEnvVars(envs []models.EnvironmentVariable) []string
for _, env := range envs {
if idx, ok := nameToIndex[env.Name]; ok {
mergedList[idx].values = append(mergedList[idx].values, env.Value)
mergedList[idx].values = append(mergedList[idx].values, string(env.Value))
} else {
nameToIndex[env.Name] = len(mergedList)
mergedList = append(mergedList, mergedEnv{
name: env.Name,
values: []string{env.Value},
values: []string{string(env.Value)},
})
}
}
+58
View File
@@ -1,7 +1,10 @@
package services
import (
"fmt"
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
"github.com/engigu/baihu-panel/internal/models"
"github.com/engigu/baihu-panel/internal/utils"
)
@@ -25,6 +28,61 @@ func (s *LoginLogService) Create(username, ip, userAgent, status, message string
return database.DB.Create(log).Error
}
// SubscribeEvents 注册订阅事件
func (s *LoginLogService) SubscribeEvents(bus *eventbus.EventBus) {
// 用户登录事件
bus.Subscribe(constant.EventUserLogin, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
username, _ := payload["username"].(string)
ip, _ := payload["ip"].(string)
userAgent, _ := payload["userAgent"].(string)
status, _ := payload["status"].(string)
message, _ := payload["message"].(string)
s.Create(username, ip, userAgent, status, message)
// 如果登录成功,触发系统通知
if status == "success" {
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": "登录提醒",
"content": fmt.Sprintf("用户 %s 已从 IP %s 登录系统", username, ip),
"level": constant.LogLevelWarning,
},
})
}
})
// 暴力破解防御触发事件
bus.Subscribe(constant.EventBruteForceLogin, func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
username, _ := payload["username"].(string)
ip, _ := payload["ip"].(string)
userAgent, _ := payload["userAgent"].(string)
s.Create(username, ip, userAgent, "failed", "尝试次数过多,由于暴力破解防御机制已锁定")
// 触发系统通知
bus.Publish(eventbus.Event{
Type: constant.EventSystemNotice,
Payload: map[string]interface{}{
"title": "系统安全警告",
"content": fmt.Sprintf("检测到 IP %s 正在尝试暴力破解用户 %s", ip, username),
"level": constant.LogLevelError,
},
})
})
}
// List 获取登录日志列表
func (s *LoginLogService) List(page, pageSize int, username string) ([]models.LoginLog, int64, error) {
var logs []models.LoginLog
+110 -53
View File
@@ -7,6 +7,7 @@ import (
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
"github.com/engigu/baihu-panel/internal/logger"
"github.com/engigu/baihu-panel/internal/models"
"github.com/engigu/baihu-panel/internal/utils"
@@ -98,7 +99,7 @@ func (s *NotificationService) SaveChannel(channel NotifyChannel) error {
ID: channel.ID,
Name: channel.Name,
Type: channel.Type,
Config: string(configJSON),
Config: models.BigText(configJSON),
Enabled: channel.Enabled,
}
return database.DB.Create(notifyWay).Error
@@ -108,7 +109,7 @@ func (s *NotificationService) SaveChannel(channel NotifyChannel) error {
updates := map[string]interface{}{
"name": channel.Name,
"type": channel.Type,
"config": string(configJSON),
"config": models.BigText(configJSON),
"enabled": channel.Enabled,
}
return database.DB.Model(&models.NotifyWay{}).Where("id = ?", channel.ID).Updates(updates).Error
@@ -202,12 +203,39 @@ func (s *NotificationService) SendToChannel(channel NotifyChannel, msg *NotifyMe
Title: msg.Title,
Text: msg.Text,
})
payload := map[string]interface{}{
"title": msg.Title,
"content": msg.Text,
"channel_name": channel.Name,
"success": false,
"error_msg": "",
}
if err != nil {
payload["error_msg"] = err.Error()
eventbus.DefaultBus.Publish(eventbus.Event{
Type: constant.EventNotifySent,
Payload: payload,
})
return &NotifyResult{Success: false, Error: err.Error()}
}
if !result.Success {
payload["error_msg"] = result.Error
eventbus.DefaultBus.Publish(eventbus.Event{
Type: constant.EventNotifySent,
Payload: payload,
})
return &NotifyResult{Success: false, Error: result.Error}
}
payload["success"] = true
eventbus.DefaultBus.Publish(eventbus.Event{
Type: constant.EventNotifySent,
Payload: payload,
})
return &NotifyResult{Success: true}
}
@@ -240,62 +268,91 @@ func (s *NotificationService) SendByChannelID(channelID string, msg *NotifyMessa
return s.SendToChannel(ch, msg)
}
// TriggerEvent 触发事件通知(实现 tasks.Notifier 接口)
func (s *NotificationService) TriggerEvent(bindingType string, eventType string, dataID string, templateData map[string]interface{}) {
var title, text string
// SubscribeEvents 注册通知服务自身为事件流的订阅者
func (s *NotificationService) SubscribeEvents(bus *eventbus.EventBus) {
// 系统事件
systemEvents := []string{constant.EventUserLogin, constant.EventBruteForceLogin, constant.EventPasswordChanged}
for _, evt := range systemEvents {
bus.Subscribe(evt, s.handleEvent(constant.BindingTypeSystem))
}
switch eventType {
case constant.EventUserLogin:
title = "用户登录通知"
text = fmt.Sprintf("用户 %v 在 IP %v 登录成功", templateData["username"], templateData["ip"])
case constant.EventBruteForceLogin:
title = "系统安全警告"
text = fmt.Sprintf("检测到 IP %v 正在尝试暴力破解用户 %v", templateData["ip"], templateData["username"])
case constant.EventPasswordChanged:
title = "账户安全通知"
text = fmt.Sprintf("用户 %v 刚刚修改了密码", templateData["username"])
case constant.EventTaskSuccess:
title = fmt.Sprintf("任务[%v] 成功", templateData["task_name"])
text = fmt.Sprintf("任务 #%v %v\n状态: 成功\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["duration"])
case constant.EventTaskFailed:
title = fmt.Sprintf("任务[%v] 失败", templateData["task_name"])
if errStr, ok := templateData["error"]; ok {
text = fmt.Sprintf("任务 #%v %v\n执行失败\n错误: %v", templateData["task_id"], templateData["task_name"], errStr)
} else {
text = fmt.Sprintf("任务 #%v %v\n执行失败\n状态: %v\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["status"], templateData["duration"])
// 任务事件
taskEvents := []string{constant.EventTaskSuccess, constant.EventTaskFailed, constant.EventTaskTimeout}
for _, evt := range taskEvents {
bus.Subscribe(evt, s.handleEvent(constant.BindingTypeTask))
}
// 通用系统通知
bus.Subscribe(constant.EventSystemNotice, s.handleEvent(constant.BindingTypeSystem))
}
func (s *NotificationService) handleEvent(bindingType string) eventbus.Handler {
return func(e eventbus.Event) {
payload, ok := e.Payload.(map[string]interface{})
if !ok {
return
}
case constant.EventTaskTimeout:
title = fmt.Sprintf("任务[%v] 超时", templateData["task_name"])
text = fmt.Sprintf("任务 #%v %v\n执行超时\n耗时: %vms", templateData["task_id"], templateData["task_name"], templateData["duration"])
default:
title = "系统通知"
text = "收到未知事件"
}
msg := &NotifyMessage{Title: title, Text: text}
bindings := s.GetBindingsByEvent(bindingType, eventType, dataID)
if len(bindings) == 0 {
return
}
channels := s.GetChannels()
channelMap := make(map[string]NotifyChannel)
for _, ch := range channels {
channelMap[ch.ID] = ch
}
for _, binding := range bindings {
ch, ok := channelMap[binding.WayID]
if !ok || !ch.Enabled {
continue
var dataID string
if id, ok := payload["task_id"].(string); ok {
dataID = id
}
go func(channel NotifyChannel) {
result := s.SendToChannel(channel, msg)
if !result.Success {
logger.Warnf("[Notify] 发送事件 %s 到渠道 %s(%s) 失败: %s", eventType, channel.Name, channel.Type, result.Error)
var title, text string
switch e.Type {
case constant.EventUserLogin:
title = "用户登录通知"
text = fmt.Sprintf("用户 %v 在 IP %v 登录成功", payload["username"], payload["ip"])
case constant.EventBruteForceLogin:
title = "系统安全警告"
text = fmt.Sprintf("检测到 IP %v 正在尝试暴力破解用户 %v", payload["ip"], payload["username"])
case constant.EventPasswordChanged:
title = "账户安全通知"
text = fmt.Sprintf("用户 %v 刚刚修改了密码", payload["username"])
case constant.EventTaskSuccess:
title = fmt.Sprintf("任务[%v] 成功", payload["task_name"])
text = fmt.Sprintf("任务 #%v %v\n状态: 成功\n耗时: %vms", payload["task_id"], payload["task_name"], payload["duration"])
case constant.EventTaskFailed:
title = fmt.Sprintf("任务[%v] 失败", payload["task_name"])
if errStr, ok := payload["error"]; ok {
text = fmt.Sprintf("任务 #%v %v\n执行失败\n错误: %v", payload["task_id"], payload["task_name"], errStr)
} else {
text = fmt.Sprintf("任务 #%v %v\n执行失败\n状态: %v\n耗时: %vms", payload["task_id"], payload["task_name"], payload["status"], payload["duration"])
}
}(ch)
case constant.EventTaskTimeout:
title = fmt.Sprintf("任务[%v] 超时", payload["task_name"])
text = fmt.Sprintf("任务 #%v %v\n执行超时\n耗时: %vms", payload["task_id"], payload["task_name"], payload["duration"])
case constant.EventSystemNotice:
title, _ = payload["title"].(string)
text, _ = payload["content"].(string)
default:
return
}
msg := &NotifyMessage{Title: title, Text: text}
bindings := s.GetBindingsByEvent(bindingType, e.Type, dataID)
if len(bindings) == 0 {
return
}
channels := s.GetChannels()
channelMap := make(map[string]NotifyChannel)
for _, ch := range channels {
channelMap[ch.ID] = ch
}
for _, binding := range bindings {
ch, ok := channelMap[binding.WayID]
if !ok || !ch.Enabled {
continue
}
go func(channel NotifyChannel) {
result := s.SendToChannel(channel, msg)
if !result.Success {
logger.Warnf("[Notify] 发送事件 %s 到渠道 %s(%s) 失败: %s", e.Type, channel.Name, channel.Type, result.Error)
}
}(ch)
}
}
}
+2 -2
View File
@@ -16,7 +16,7 @@ func (ss *ScriptService) CreateScript(name, content string, userID string) *mode
script := &models.Script{
ID: utils.GenerateID(),
Name: name,
Content: content,
Content: models.BigText(content),
UserID: userID,
}
database.DB.Create(script)
@@ -43,7 +43,7 @@ func (ss *ScriptService) UpdateScript(id string, name, content string) *models.S
return nil
}
script.Name = name
script.Content = content
script.Content = models.BigText(content)
database.DB.Save(&script)
return &script
}
+6 -6
View File
@@ -25,7 +25,7 @@ func (s *SettingsService) InitSettings() error {
ID: utils.GenerateID(),
Section: section,
Key: key,
Value: value,
Value: models.BigText(value),
}).Error; err != nil {
return err
}
@@ -47,7 +47,7 @@ func (s *SettingsService) InitSettings() error {
ID: utils.GenerateID(),
Section: constant.SectionSecurity,
Key: constant.KeySecret,
Value: secretValue,
Value: models.BigText(secretValue),
}).Error; err != nil {
return err
}
@@ -72,7 +72,7 @@ func (s *SettingsService) Get(section, key string) string {
}
return ""
}
return setting.Value
return string(setting.Value)
}
// Set 设置单个值
@@ -83,10 +83,10 @@ func (s *SettingsService) Set(section, key, value string) error {
ID: utils.GenerateID(),
Section: section,
Key: key,
Value: value,
Value: models.BigText(value),
}).Error
}
return database.DB.Model(&setting).Update("value", value).Error
return database.DB.Model(&setting).Update("value", models.BigText(value)).Error
}
// Delete 删除单个设置
@@ -108,7 +108,7 @@ func (s *SettingsService) GetSection(section string) map[string]string {
var settings []models.Setting
database.DB.Where("section = ?", section).Find(&settings)
for _, setting := range settings {
result[setting.Key] = setting.Value
result[setting.Key] = string(setting.Value)
}
return result
}
+52 -56
View File
@@ -13,6 +13,7 @@ import (
"github.com/engigu/baihu-panel/internal/constant"
"github.com/engigu/baihu-panel/internal/database"
"github.com/engigu/baihu-panel/internal/eventbus"
"github.com/engigu/baihu-panel/internal/executor"
"github.com/engigu/baihu-panel/internal/logger"
"github.com/engigu/baihu-panel/internal/models"
@@ -39,19 +40,12 @@ type EnvService interface {
GetAllEnvVars() []string
}
// Notifier 通知服务接口定义(避免循环依赖)
type Notifier interface {
TriggerEvent(bindingType string, eventType string, dataID string, templateData map[string]interface{})
}
// ExecutorService handles task execution and scheduling
type ExecutorService struct {
taskService *TaskService
taskLogService *TaskLogService
agentWSManager AgentWSManager
settingsService SettingsService
envService EnvService
notifier Notifier
scheduler *executor.Scheduler
cronManager *executor.CronManager
results []executor.ExecutionResult
@@ -64,14 +58,12 @@ func (es *ExecutorService) GetScheduler() *executor.Scheduler {
return es.scheduler
}
// NewExecutorService creates a new executor service
func NewExecutorService(
taskService *TaskService,
taskLogService *TaskLogService,
agentWSManager AgentWSManager,
settingsService SettingsService,
envService EnvService,
notifier Notifier,
) *ExecutorService {
es := &ExecutorService{
taskService: taskService,
@@ -79,7 +71,6 @@ func NewExecutorService(
agentWSManager: agentWSManager,
settingsService: settingsService,
envService: envService,
notifier: notifier,
results: make([]executor.ExecutionResult, 0, 100),
stopCh: make(chan struct{}),
}
@@ -143,7 +134,8 @@ func (h *ServerSchedulerHandler) OnTaskExecuting(req *executor.ExecutionRequest)
if err != nil {
// 并发限制,更新日志状态为失败
taskLog.Status = constant.TaskStatusFailed
taskLog.Output, _ = utils.CompressToBase64("任务并发数限制,拒绝执行")
comp, _ := utils.CompressToBase64("任务并发数限制,拒绝执行")
taskLog.Output = models.BigText(comp)
h.es.taskLogService.SaveTaskLog(taskLog)
return nil, nil, fmt.Errorf("任务并发限制: %v", err)
}
@@ -225,9 +217,9 @@ func (h *ServerSchedulerHandler) OnTaskCompleted(req *executor.ExecutionRequest,
taskLog := &models.TaskLog{
ID: req.LogID,
TaskID: task.ID,
Command: req.Command,
Output: output,
Error: result.Error,
Command: models.BigText(req.Command),
Output: models.BigText(output),
Error: models.BigText(result.Error),
Status: result.Status,
Duration: result.Duration,
ExitCode: result.ExitCode,
@@ -256,27 +248,29 @@ func (h *ServerSchedulerHandler) OnTaskCompleted(req *executor.ExecutionRequest,
h.es.HandleTaskRetry(task, req, result.Success, result.Status, result.ExitCode)
// ======= 通知触发 =======
if h.es.notifier != nil {
go func() {
var eventType string
switch result.Status {
case constant.TaskStatusSuccess:
eventType = constant.EventTaskSuccess
case constant.TaskStatusFailed:
eventType = constant.EventTaskFailed
case constant.TaskStatusTimeout:
eventType = constant.EventTaskTimeout
}
if eventType != "" {
h.es.notifier.TriggerEvent(constant.BindingTypeTask, eventType, task.ID, map[string]interface{}{
// ======= 通知触发 =======
go func() {
var eventType string
switch result.Status {
case constant.TaskStatusSuccess:
eventType = constant.EventTaskSuccess
case constant.TaskStatusFailed:
eventType = constant.EventTaskFailed
case constant.TaskStatusTimeout:
eventType = constant.EventTaskTimeout
}
if eventType != "" {
eventbus.DefaultBus.Publish(eventbus.Event{
Type: eventType,
Payload: map[string]interface{}{
"task_id": task.ID,
"task_name": task.Name,
"status": result.Status,
"duration": result.Duration,
})
}
}()
}
},
})
}
}()
}
func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, err error) {
@@ -305,9 +299,9 @@ func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, er
taskLog := &models.TaskLog{
ID: req.LogID,
TaskID: taskID,
Command: req.Command,
Output: output,
Error: err.Error(),
Command: models.BigText(req.Command),
Output: models.BigText(output),
Error: models.BigText(err.Error()),
Status: constant.TaskStatusFailed,
Duration: 0,
ExitCode: 1,
@@ -338,19 +332,21 @@ func (h *ServerSchedulerHandler) OnTaskFailed(req *executor.ExecutionRequest, er
h.es.HandleTaskRetry(task, req, false, constant.TaskStatusFailed, 1)
// ======= 通知触发 =======
if h.es.notifier != nil {
go func() {
taskName := "未知任务"
if task != nil {
taskName = task.Name
}
h.es.notifier.TriggerEvent(constant.BindingTypeTask, constant.EventTaskFailed, taskID, map[string]interface{}{
// ======= 通知触发 =======
go func() {
taskName := "未知任务"
if task != nil {
taskName = task.Name
}
eventbus.DefaultBus.Publish(eventbus.Event{
Type: constant.EventTaskFailed,
Payload: map[string]interface{}{
"task_id": taskID,
"task_name": taskName,
"error": err.Error(),
})
}()
}
},
})
}()
}
// HandleTaskRetry 处理任务失败重试逻辑
@@ -372,11 +368,11 @@ func (es *ExecutorService) HandleTaskRetry(task *models.Task, req *executor.Exec
return nil
}
newEnvs := es.loadEnvVars(latestTask.ID, latestTask.Envs)
newEnvs := es.loadEnvVars(latestTask.ID, string(latestTask.Envs))
return &executor.ExecutionRequest{
TaskID: req.TaskID,
Name: latestTask.Name,
Command: latestTask.Command,
Command: string(latestTask.Command),
WorkDir: latestTask.WorkDir,
Envs: newEnvs,
Timeout: latestTask.Timeout,
@@ -501,7 +497,7 @@ func (es *ExecutorService) AddCronTask(task *models.Task) error {
return nil
}
// 在加入调度器前,预先加载好环境信息
task.RuntimeEnvs = es.loadEnvVars(task.ID, task.Envs)
task.RuntimeEnvs = es.loadEnvVars(task.ID, string(task.Envs))
return es.cronManager.AddTask(task)
}
@@ -582,7 +578,7 @@ func (es *ExecutorService) ExecuteTask(taskID string, extraEnvs []string) *execu
}
}
envs := es.loadEnvVars(task.ID, task.Envs)
envs := es.loadEnvVars(task.ID, string(task.Envs))
if len(extraEnvs) > 0 {
envs = append(envs, extraEnvs...)
}
@@ -590,7 +586,7 @@ func (es *ExecutorService) ExecuteTask(taskID string, extraEnvs []string) *execu
req := &executor.ExecutionRequest{
TaskID: task.ID,
Name: task.Name,
Command: task.Command,
Command: string(task.Command),
WorkDir: task.WorkDir,
Envs: envs,
Timeout: task.Timeout,
@@ -749,13 +745,13 @@ func (es *ExecutorService) CheckConcurrency(taskID string) error {
return err
}
var goids []int64
if task.RunningGo != "" {
_ = json.Unmarshal([]byte(task.RunningGo), &goids)
if string(task.RunningGo) != "" {
_ = json.Unmarshal([]byte(string(task.RunningGo)), &goids)
}
var config models.TaskConfig
if task.Config != "" {
_ = json.Unmarshal([]byte(task.Config), &config)
var config models.TaskConfig
if string(task.Config) != "" {
_ = json.Unmarshal([]byte(string(task.Config)), &config)
}
if config.Concurrency == 0 && len(goids) > 0 {
@@ -792,7 +788,7 @@ func (es *ExecutorService) AddRunningGo(taskID string) (int64, error) {
goids = append(goids, goid)
data, _ := json.Marshal(goids)
return tx.Model(&task).Update("running_go", string(data)).Error
return tx.Model(&task).Update("running_go", models.BigText(data)).Error
})
if lastErr == nil {
return goid, nil
+7 -7
View File
@@ -40,7 +40,7 @@ func (s *TaskLogService) CreateEmptyLog(taskID string, command string) (*models.
taskLog := &models.TaskLog{
ID: utils.GenerateID(),
TaskID: taskID,
Command: command,
Command: models.BigText(command),
Status: "running",
StartTime: &startTime,
CreatedAt: models.Now(),
@@ -162,9 +162,9 @@ func (s *TaskLogService) CreateTaskLogFromAgentResult(result *models.AgentTaskRe
ID: utils.GenerateID(),
TaskID: result.TaskID,
AgentID: &result.AgentID,
Command: result.Command,
Output: compressed,
Error: result.Error,
Command: models.BigText(result.Command),
Output: models.BigText(compressed),
Error: models.BigText(result.Error),
Status: result.Status,
Duration: result.Duration,
ExitCode: result.ExitCode,
@@ -206,9 +206,9 @@ func (s *TaskLogService) CreateTaskLogFromLocalExecution(taskID string, command,
taskLog := &models.TaskLog{
ID: utils.GenerateID(),
TaskID: taskID,
Command: command,
Output: compressed,
Error: systemErr,
Command: models.BigText(command),
Output: models.BigText(compressed),
Error: models.BigText(systemErr),
Status: status,
Duration: duration,
ExitCode: exitCode,
+6 -6
View File
@@ -23,16 +23,16 @@ func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, w
task := &models.Task{
ID: utils.GenerateID(),
Name: name,
Command: command,
Command: models.BigText(command),
Tags: tags,
Type: taskType,
TriggerType: triggerType,
Config: config,
Config: models.BigText(config),
Schedule: schedule,
Timeout: timeout,
WorkDir: workDir,
CleanConfig: cleanConfig,
Envs: envs,
Envs: models.BigText(envs),
Languages: languages,
AgentID: agentID,
Enabled: true,
@@ -94,17 +94,17 @@ func (ts *TaskService) UpdateTask(id string, name, command, schedule string, tim
return nil
}
task.Name = name
task.Command = command
task.Command = models.BigText(command)
task.Tags = tags
task.Schedule = schedule
task.Timeout = timeout
task.WorkDir = workDir
task.CleanConfig = cleanConfig
task.Envs = envs
task.Envs = models.BigText(envs)
task.Enabled = enabled
task.AgentID = agentID
task.Languages = languages
task.Config = config
task.Config = models.BigText(config)
task.RetryCount = retryCount
task.RetryInterval = retryInterval
task.RandomRange = randomRange