Compare commits

..
16 Commits
Author SHA1 Message Date
Akizon 8d652049af Merge pull request #210 from komari-monitor/copilot/fix-b576a6c5-0ea2-4f16-8483-2eb7767cd8ad
Add PR and manual triggers to binary build workflow
2025-08-22 16:42:44 +08:00
copilot-swe-agent[bot]andAkizon77 7af2a956d2 Add PR and manual triggers to binary build workflow
Co-authored-by: Akizon77 <64686663+Akizon77@users.noreply.github.com>
2025-08-20 14:31:50 +00:00
copilot-swe-agent[bot] 45b23a04c9 Initial plan 2025-08-20 14:26:30 +00:00
github-actions[bot] 1a7c5990ae Merge pull request #209 from komari-monitor/dev
feat: #159 流量提醒
2025-08-20 14:23:53 +00:00
Akizon77 9133dac3d0 feat: #159 流量提醒 2025-08-20 22:09:57 +08:00
Akizon77 2709166a5b feat: 添加流量监控功能,每分钟检查并提醒流量使用情况 2025-08-20 22:01:47 +08:00
github-actions[bot] fcb5284d57 Merge pull request #208 from komari-monitor/dev
feat: 添加登录通知
2025-08-20 11:08:27 +00:00
Akizon77 92d511253f fix: 调整登录通知消息格式 2025-08-20 18:53:55 +08:00
Akizon77 9874c4d339 feat: 添加登录通知 2025-08-20 17:34:28 +08:00
MoGuQAQ 86e97c66b9 Merge pull request #206 from mogumc/main
feat: ws支持请求特定服务器
2025-08-20 16:47:34 +08:00
Akizon f2afed643e ci: Disable auto run 2025-08-18 16:44:06 +08:00
Akizon f502e3df76 Update cleanup-packages.yml 2025-08-18 16:43:10 +08:00
Akizon 7491da96e6 Merge pull request #204 from guodonn01/main
Feat: ws支持快速重连,fix: 精确时间段下发ping task
2025-08-17 20:38:41 +08:00
root 0b887689f0 Feat: ws支持快速重连,fix: 精确时间段下发ping task 2025-08-17 19:59:36 +08:00
Akizon 9cce96c80c Merge pull request #200 from guodonn01/main
Fix: 下发ping task 应该时间更精确得以interval为间隔
2025-08-16 14:49:11 +08:00
gordon 2711d27c03 Fix: 下发ping task 应该时间更精确得以interval为间隔 2025-08-16 13:27:16 +08:00
14 changed files with 373 additions and 121 deletions

No files matched your search

+5 -1
View File
@@ -1,9 +1,13 @@
name: Build Binaries on Main Push
name: Build Binaries on Main Push and PR
on:
push:
branches:
- main
pull_request:
branches:
- main
workflow_dispatch:
jobs:
build-binaries:
+4 -3
View File
@@ -1,8 +1,9 @@
name: Cleanup Old Packages
on:
schedule:
- cron: '0 0 * * 0' # Run every Sunday at midnight
#schedule:
# - cron: '0 0 * * 0' # Run every Sunday at midnight
# 会清理掉正常的镜像
workflow_dispatch: # Allow manual trigger
jobs:
@@ -57,4 +58,4 @@ jobs:
package_version_id: version.id
});
console.log(`Deleted package version ${version.id} with tags: ${version.metadata.container.tags.join(', ') || 'none'}`);
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
name: Publish Docker Image on Main
on:
push:
branches:
- main
#push:
# branches:
# - main
workflow_dispatch:
env:
+4 -1
View File
@@ -66,7 +66,10 @@ func Exec(c *gin.Context) {
payload, _ := json.Marshal(send)
client := ws.GetConnectedClients()[uuid]
if client != nil {
client.WriteMessage(websocket.TextMessage, payload)
if err := client.WriteMessage(websocket.TextMessage, payload); err != nil {
api.RespondError(c, 400, "Client connection is broke: "+uuid)
return
}
} else {
api.RespondError(c, 400, "Client connection is null: "+uuid)
return
+75 -54
View File
@@ -22,6 +22,12 @@ import (
"github.com/patrickmn/go-cache"
)
const (
// 如果超过这个时间没有收到任何消息,则认为连接已死
// 因为目前server没有存agent的信息上报间隔。只有写一个默认的
readWait = 11 * time.Second
)
func UploadReport(c *gin.Context) {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
@@ -51,7 +57,7 @@ func UploadReport(c *gin.Context) {
}
// Update report with method and token
ws.GetLatestReport()[report.UUID] = &report
ws.SetLatestReport(report.UUID, &report)
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // Restore the body for further use
c.JSON(200, gin.H{"status": "success"})
@@ -109,72 +115,87 @@ func WebSocketReport(c *gin.Context) {
return
}
// 只允许一个客户端的连接
if _, exists := ws.GetConnectedClients()[uuid]; exists {
conn.WriteJSON(gin.H{"status": "error", "error": "Token already in use"})
return
// 接受新连接,并处理旧连接
if oldConn, exists := ws.GetConnectedClients()[uuid]; exists {
log.Printf("Client %s is reconnecting. Closing the old connection.", uuid)
// 强制关闭旧连接。这将导致旧连接的 ReadMessage() 循环出错退出。
go oldConn.Close()
}
ws.SetConnectedClients(uuid, conn)
go notifier.OnlineNotification(uuid)
log.Printf("Client %s is reconnect success, connID: %d", uuid, conn.ID)
go notifier.OnlineNotification(uuid, conn.ID)
defer func() {
ws.DeleteConnectedClients(uuid)
notifier.OfflineNotification(uuid)
ws.DeleteClientConditionally(uuid, conn)
notifier.OfflineNotification(uuid, conn.ID)
}()
// 首先处理第一次ws conn收到的消息
processMessage(conn, message, uuid)
for {
conn.SetReadDeadline(time.Now().Add(readWait))
_, message, err := conn.ReadMessage()
if err != nil {
break
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("Client %s connection error: %v", uuid, err)
}
break // 任何读错误(包括超时)都意味着连接已断开,退出循环
}
processMessage(conn, message, uuid)
}
}
type MessageType struct {
Type string `json:"type"`
}
var msgType MessageType
err = json.Unmarshal(message, &msgType)
// 将消息处理逻辑提取到一个函数中,方便复用
func processMessage(conn *ws.SafeConn, message []byte, uuid string) {
type MessageType struct {
Type string `json:"type"`
}
var msgType MessageType
err := json.Unmarshal(message, &msgType)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid JSON"})
return
}
switch msgType.Type {
case "", "report":
report := common.Report{}
err = json.Unmarshal(message, &report)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid JSON"})
continue
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid report format"})
return
}
switch msgType.Type {
case "", "report":
report := common.Report{}
err = json.Unmarshal(message, &report)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid report format"})
continue
}
report.UpdatedAt = time.Now()
err = SaveClientReport(uuid, report)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": fmt.Sprintf("%v", err)})
continue
}
ws.SetLatestReport(uuid, &report)
case "ping_result":
var reqBody struct {
PingTaskID uint `json:"task_id"`
PingResult int `json:"value"`
PingType string `json:"ping_type"`
FinishedAt time.Time `json:"finished_at"`
}
err = json.Unmarshal(message, &reqBody)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid ping result format"})
continue
}
pingResult := models.PingRecord{
Client: uuid,
TaskId: reqBody.PingTaskID,
Value: reqBody.PingResult,
Time: models.FromTime(reqBody.FinishedAt),
}
tasks.SavePingRecord(pingResult)
default:
log.Printf("Unknown message type: %s", msgType.Type)
conn.WriteJSON(gin.H{"status": "error", "error": "Unknown message type"})
report.UpdatedAt = time.Now()
err = SaveClientReport(uuid, report)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": fmt.Sprintf("%v", err)})
return
}
ws.SetLatestReport(uuid, &report)
case "ping_result":
var reqBody struct {
PingTaskID uint `json:"task_id"`
PingResult int `json:"value"`
PingType string `json:"ping_type"`
FinishedAt time.Time `json:"finished_at"`
}
err = json.Unmarshal(message, &reqBody)
if err != nil {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid ping result format"})
return
}
pingResult := models.PingRecord{
Client: uuid,
TaskId: reqBody.PingTaskID,
Value: reqBody.PingResult,
Time: models.FromTime(reqBody.FinishedAt),
}
tasks.SavePingRecord(pingResult)
default:
log.Printf("Unknown message type: %s", msgType.Type)
conn.WriteJSON(gin.H{"status": "error", "error": "Unknown message type"})
}
}
+27 -5
View File
@@ -2,6 +2,7 @@ package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -50,9 +51,14 @@ func GetClients(c *gin.Context) {
}
message := string(data)
if message != "get" {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid message"})
continue
uuID := ""
if message != "get" { // 非请求全部内容
if strings.HasPrefix(message, "get ") {
uuID = strings.TrimSpace(strings.TrimPrefix(message, "get "))
} else {
conn.WriteJSON(gin.H{"status": "error", "error": "Invalid message"})
continue
}
}
// 登录状态检查
@@ -74,8 +80,14 @@ func GetClients(c *gin.Context) {
}
// 已建立连接的客户端uuid列表
for key := range ws.GetConnectedClients() {
if !(!isLogin && hiddenMap[key]) { // 未登录且 Hidden -> 跳过
resp.Online = append(resp.Online, key)
if uuID != "" { // 请求特定服务器信息
if !(!isLogin && hiddenMap[key]) && key == uuID { // 未登录且 Hidden 或 不符合请求的特定服务器 -> 跳过
resp.Online = append(resp.Online, key)
}
} else {
if !(!isLogin && hiddenMap[key]) { // 未登录且 Hidden -> 跳过
resp.Online = append(resp.Online, key)
}
}
}
// 清除UUID,简化报告单
@@ -87,12 +99,22 @@ func GetClients(c *gin.Context) {
}
}
}
if uuID != "" { // 过滤不符合请求的特定服务器
for key := range resp.Data {
if key != uuID {
delete(resp.Data, key)
}
}
}
for _, report := range resp.Data { // 不暴露 uuid
report.UUID = ""
if report.CPU.Usage == 0 {
report.CPU.Usage = 0.01
}
}
err = conn.WriteJSON(gin.H{"status": "success", "data": resp})
if err != nil {
return
+2
View File
@@ -380,6 +380,8 @@ func DoScheduledWork() {
records.DeleteAll()
tasks.DeleteAllPingRecords()
}
// 每分钟检查一次流量提醒
go notifier.CheckTraffic()
}
}
+15
View File
@@ -2,11 +2,16 @@ package accounts
import (
"errors"
"fmt"
"net"
"time"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"github.com/komari-monitor/komari/utils"
"github.com/komari-monitor/komari/utils/geoip"
"github.com/komari-monitor/komari/utils/messageSender"
)
// GetAllSessions 获取所有会话
@@ -33,6 +38,16 @@ func CreateSession(uuid string, expires int, userAgent, ip, login_method string)
LoginMethod: login_method,
LatestOnline: models.FromTime(time.Now()),
}
cfg, _ := config.Get()
if cfg.LoginNotification {
ipAddr := net.ParseIP(ip)
ipinfo, _ := geoip.GetGeoInfo(ipAddr)
loc := "unknown"
if ipinfo != nil {
loc = ipinfo.Name
}
messageSender.SendTextMessage(fmt.Sprintf("From: %s,(%s)\nMethod: %s\nUser Agent: %s\n\n%s", ip, loc, login_method, userAgent, time.Now().Format(time.RFC3339)), "New Login on Komari")
}
err := db.Create(&sessionRecord).Error
if err != nil {
+6 -4
View File
@@ -20,10 +20,12 @@ type Config struct {
CustomHead string `json:"custom_head" gorm:"type:longtext"`
CustomBody string `json:"custom_body" gorm:"type:longtext"`
// 通知
NotificationEnabled bool `json:"notification_enabled" gorm:"default:false"` // 通知总开关
NotificationMethod string `json:"notification_method" gorm:"type:varchar(64);default:'none'"`
ExpireNotificationEnabled bool `json:"expire_notification_enabled" gorm:"default:false"` // 是否启用过期通知
ExpireNotificationLeadDays int `json:"expire_notification_lead_days" gorm:"default:7"` // 过期前多少天通知,默认7天
NotificationEnabled bool `json:"notification_enabled" gorm:"default:false"` // 通知总开关
NotificationMethod string `json:"notification_method" gorm:"type:varchar(64);default:'none'"`
ExpireNotificationEnabled bool `json:"expire_notification_enabled" gorm:"default:false"` // 是否启用过期通知
ExpireNotificationLeadDays int `json:"expire_notification_lead_days" gorm:"default:7"` // 过期前多少天通知,默认7天
LoginNotification bool `json:"login_notification" gorm:"default:false"` // 登录通知
TrafficLimitPercentage float64 `json:"traffic_limit_percentage" gorm:"default:80.00"` // 流量限制百分比,默认80.00%
// Record
RecordEnabled bool `json:"record_enabled" gorm:"default:true"` // 是否启用记录功能
RecordPreserveTime int `json:"record_preserve_time" gorm:"default:720"` // 记录保留时间,单位小时,默认30天
+26 -9
View File
@@ -20,6 +20,8 @@ type notificationState struct {
mu sync.Mutex // 互斥锁,保护该客户端状态
pendingOfflineSince time.Time // 客户端离线的时间。为零值表示客户端在线或已发送离线通知。
isFirstConnection bool // 标记是否为首次上线连接。
isConnExist bool // 标记是否存在连接
connectionID int64 // 连接ID,用于区分不同的连接会话,防止竞态条件
}
// clientStates 使用 sync.Map 实现对客户端状态的并发访问。
@@ -52,7 +54,7 @@ func getOrInitState(clientID string) *notificationState {
}
// OfflineNotification 在启用通知且未在宽限期内发送的情况下,发送客户端离线通知。
func OfflineNotification(clientID string) {
func OfflineNotification(clientID string, endedConnectionID int64) {
client, err := clients.GetClientByUUID(clientID)
if err != nil {
return
@@ -73,7 +75,8 @@ func OfflineNotification(clientID string) {
state.mu.Lock()
// 如果已处于待通知状态,则不做处理。
if !state.pendingOfflineSince.IsZero() {
// 只有当离线事件来自当前的连接会话时,我们才认为它有效。
if !state.pendingOfflineSince.IsZero() || state.connectionID != endedConnectionID {
state.mu.Unlock()
return
}
@@ -82,7 +85,7 @@ func OfflineNotification(clientID string) {
state.mu.Unlock()
// 新建协程,等待宽限期后判断是否需要发送通知。
go func(startTime time.Time) {
go func(startTime time.Time, expectedConnectionID int64) {
time.Sleep(gracePeriod)
state.mu.Lock()
@@ -90,13 +93,16 @@ func OfflineNotification(clientID string) {
// 检查离线状态是否仍为本次协程启动时的状态。
// 若为零值,说明客户端已重连。
// 若时间不同,说明客户端重连后又断开,已启动新计时。
if state.pendingOfflineSince.IsZero() || !state.pendingOfflineSince.Equal(startTime) {
// 当前的 connectionID 是否还是我们触发离线时的那个ID。如果不是,说明客户端重连过,本次离线通知已失效。
if state.pendingOfflineSince.IsZero() || state.connectionID != expectedConnectionID {
log.Println("%s is reconnected new connID: %d, old connID: %d", clientID, state.connectionID, expectedConnectionID)
return
}
// 即将发送通知,重置待通知状态。
// 需要多一个boolean 是因为pendingOfflineSince在offline睡眠后才修改,可能导致online判断不对
state.pendingOfflineSince = time.Time{}
state.isConnExist = false
// Send notification
message := fmt.Sprintf("🔴%s is offline", client.Name)
@@ -111,11 +117,11 @@ func OfflineNotification(clientID string) {
if err := db.Model(&models.OfflineNotification{}).Where("client = ?", clientID).Update("last_notified", now).Error; err != nil {
log.Printf("Failed to update last_notified for client %s: %v", clientID, err)
}
}(now)
}(now, endedConnectionID)
}
// OnlineNotification 在启用通知的情况下,发送客户端上线通知。
func OnlineNotification(clientID string) {
func OnlineNotification(clientID string, connectionID int64) {
client, err := clients.GetClientByUUID(clientID)
if err != nil {
return
@@ -131,12 +137,14 @@ func OnlineNotification(clientID string) {
state.mu.Lock()
defer state.mu.Unlock()
state.connectionID = connectionID
// 规则1:首次连接不通知。
if state.isFirstConnection {
state.isFirstConnection = false
// 同时清除任何待离线状态(如服务器重启时客户端本已离线)
state.pendingOfflineSince = time.Time{}
state.isConnExist = true
return
}
@@ -145,12 +153,21 @@ func OnlineNotification(clientID string) {
// 上线时总是清除待离线状态。
state.pendingOfflineSince = time.Time{}
// 规则4:宽限期内重连,不通知。
// 规则2:宽限期内重连,不通知。
if wasPending {
return
}
// 规则3:客户端离线足够久已通知(或未待离线),现在重新上线,发送上线通知。
// 规则3: 没断开后重连, 不通知
// 为了解决OfflineNotify中不是全程加锁
if state.isConnExist {
log.Println("%s has connection exist: %d", clientID, connectionID)
return
} else {
state.isConnExist = true
}
// 规则4:客户端离线足够久已通知(或未待离线),现在重新上线,发送上线通知。
message := fmt.Sprintf("🟢%s is online", client.Name)
go func(msg string) {
if err := messageSender.SendTextMessage(msg, "Komari Online Notification"); err != nil {
+137
View File
@@ -0,0 +1,137 @@
package notifier
import (
"fmt"
"math"
"strings"
"time"
"github.com/komari-monitor/komari/database/clients"
"github.com/komari-monitor/komari/database/config"
"github.com/komari-monitor/komari/utils/messageSender"
"github.com/komari-monitor/komari/ws"
cache "github.com/patrickmn/go-cache"
)
// trafficCache 用于记录每个客户端已触发的阈值步进,避免重复提醒
// key: "traffic:"+clientUUID, value: int 步进百分比(例如 80, 85, 90 ... 100)
var trafficCache = cache.New(30*24*time.Hour, time.Hour) // 30天缓存,1小时清理
// CheckTraffic 检查各客户端流量使用情况,并在达到阈值和每+5%时提醒一次;100%时额外提醒一次
// 由外部协程每分钟调用一次
func CheckTraffic() {
// 获取最新上报与客户端配置
reports := ws.GetLatestReport()
if len(reports) == 0 {
return
}
cfg, err := config.Get()
if err != nil {
return
}
if cfg.TrafficLimitPercentage <= 0 {
return
}
// 起始阈值:例如 80%,非5的倍数则从上取整到最近的5的倍数,例如 83->85
startThreshold := cfg.TrafficLimitPercentage
if startThreshold < 0 {
startThreshold = 0
}
baseStep := int(math.Ceil(startThreshold/5.0) * 5.0)
if baseStep > 100 {
baseStep = 100
}
allClients, err := clients.GetAllClientBasicInfo()
if err != nil {
return
}
for _, c := range allClients {
if c.TrafficLimit <= 0 {
continue
}
r, ok := reports[c.UUID]
if !ok || r == nil {
continue
}
// 计算不同类型的使用值
used := computeUsedByType(strings.ToLower(c.TrafficLimitType), r.Network.TotalUp, r.Network.TotalDown)
if used <= 0 {
continue
}
pct := float64(used) / float64(c.TrafficLimit) * 100.0
if pct < startThreshold {
continue
}
// 当前所在阈值步进(5%的倍数)
curStep := int(math.Floor(pct/5.0) * 5.0)
if curStep < baseStep {
curStep = baseStep
}
// if curStep > 100 {
// curStep = 100
// }
key := "traffic:" + c.UUID
last, _ := trafficCache.Get(key)
lastStep, _ := last.(int)
if curStep > lastStep { // 只在进入新步进时提醒一次
trafficCache.SetDefault(key, curStep)
title := "Komari Traffic Alert"
msg := fmt.Sprintf("%s traffic used %d%% (%s / %s), type=%s", c.Name, curStep, humanBytes(used), humanBytes(c.TrafficLimit), strings.ToLower(c.TrafficLimitType))
// 发送通知(内部会检查 NotificationEnabled)
_ = messageSender.SendTextMessage(msg, title)
}
}
}
func computeUsedByType(t string, up, down int64) int64 {
switch t {
case "up":
return up
case "down":
return down
case "sum":
return up + down
case "min":
if up < down {
return up
}
return down
case "max":
fallthrough
default:
if up > down {
return up
}
return down
}
}
func humanBytes(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
// KMGTPE
prefixes := []string{"K", "M", "G", "T", "P", "E"}
if exp >= len(prefixes) {
exp = len(prefixes) - 1
}
return fmt.Sprintf("%.2f %sB", float64(b)/float64(div), prefixes[exp])
}
+57 -38
View File
@@ -1,6 +1,7 @@
package utils
import (
"context"
"sync"
"time"
@@ -10,16 +11,13 @@ import (
// PingTaskManager 管理定时器和任务
type PingTaskManager struct {
mu sync.Mutex
tickers map[int]*time.Ticker
tasks map[int][]models.PingTask
stopChan chan struct{}
mu sync.Mutex
cancelFunc context.CancelFunc
tasks map[int][]models.PingTask
}
var manager = &PingTaskManager{
tickers: make(map[int]*time.Ticker),
tasks: make(map[int][]models.PingTask),
stopChan: make(chan struct{}),
tasks: make(map[int][]models.PingTask),
}
// Reload 重载时间表
@@ -27,60 +25,81 @@ func (m *PingTaskManager) Reload(pingTasks []models.PingTask) error {
m.mu.Lock()
defer m.mu.Unlock()
// 停止所有现有定时器
for _, ticker := range m.tickers {
ticker.Stop()
if m.cancelFunc != nil {
m.cancelFunc()
}
m.tickers = make(map[int]*time.Ticker)
ctx, cancel := context.WithCancel(context.Background())
m.cancelFunc = cancel
m.tasks = make(map[int][]models.PingTask)
// 按Interval分组任务
taskGroups := make(map[int][]models.PingTask)
for _, task := range pingTasks {
if task.Interval <= 0 {
continue
}
taskGroups[task.Interval] = append(taskGroups[task.Interval], task)
}
// 为每个唯一的Interval创建定时器
// 为每个唯一的Interval创建协程
for interval, tasks := range taskGroups {
ticker := time.NewTicker(time.Duration(interval) * time.Second)
m.tickers[interval] = ticker
m.tasks[interval] = tasks
go func(ticker *time.Ticker, tasks []models.PingTask) {
for {
select {
case <-ticker.C:
for _, task := range tasks {
go executePingTask(task)
}
case <-m.stopChan:
return
}
}
}(ticker, tasks)
go m.runPreciseLoop(ctx, time.Duration(interval)*time.Second, tasks)
}
return nil
}
func (m *PingTaskManager) runPreciseLoop(ctx context.Context, interval time.Duration, tasks []models.PingTask) {
// Start the first timer.
timer := time.NewTimer(interval)
// This will be the reference point for all future ticks.
// By adding the interval to this time, we avoid accumulating execution delays.
nextTick := time.Now().Add(interval)
defer timer.Stop()
for {
select {
case <-timer.C:
onlineClients := ws.GetConnectedClients()
for _, task := range tasks {
go executePingTask(ctx, task, onlineClients)
}
nextTick = nextTick.Add(interval)
timer.Reset(time.Until(nextTick))
case <-ctx.Done():
return
}
}
}
// executePingTask 执行单个PingTask
func executePingTask(task models.PingTask) {
clients := ws.GetConnectedClients()
func executePingTask(ctx context.Context, task models.PingTask, onlineClients map[string]*ws.SafeConn) {
var message struct {
TaskID uint `json:"ping_task_id"`
Message string `json:"message"`
Type string `json:"ping_type"`
Target string `json:"ping_target"`
}
message.Message = "ping"
message.TaskID = task.Id
message.Type = task.Type
message.Target = task.Target
for _, clientUUID := range task.Clients {
if conn, exists := clients[clientUUID]; exists {
if conn == nil {
continue
}
message.Message = "ping"
message.TaskID = task.Id
message.Type = task.Type
message.Target = task.Target
select {
case <-ctx.Done():
// Context was canceled, stop sending pings.
return
default:
// Context is still active, continue.
}
if conn, exists := onlineClients[clientUUID]; exists && conn != nil {
if err := conn.WriteJSON(message); err != nil {
continue
}
+10 -3
View File
@@ -29,12 +29,19 @@ func SetConnectedClients(uuid string, conn *SafeConn) {
defer mu.Unlock()
connectedClients[uuid] = conn
}
func DeleteClientConditionally(uuid string, connToRemove *SafeConn) {
mu.Lock()
defer mu.Unlock()
// 检查当前 map 里的 conn 是否就是要删除的这一个
if currentConn, exists := connectedClients[uuid]; exists && currentConn == connToRemove {
delete(connectedClients, uuid)
}
}
func DeleteConnectedClients(uuid string) {
mu.Lock()
defer mu.Unlock()
if conn, exists := connectedClients[uuid]; exists {
conn.Close()
}
// 只从 map 中删除,不再负责关闭连接
delete(connectedClients, uuid)
}
func GetLatestReport() map[string]*common.Report {
+2
View File
@@ -10,12 +10,14 @@ import (
type SafeConn struct {
conn *websocket.Conn
mu sync.Mutex
ID int64
}
func NewSafeConn(conn *websocket.Conn) *SafeConn {
return &SafeConn{
conn: conn,
mu: sync.Mutex{},
ID: time.Now().UnixNano(),
}
}