Skip to content

Commit 916f3d5

Browse files
committed
Update.
1 parent d5e50b8 commit 916f3d5

File tree

4 files changed

+60
-94
lines changed

4 files changed

+60
-94
lines changed

model/server.go

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,33 @@ import (
1313
)
1414

1515
type Server struct {
16-
Common
17-
Name string
16+
ID uint64 `json:"id" gorm:"primaryKey"`
17+
Name string `json:"name"`
18+
Secret string `json:"secret"`
19+
Tag string `json:"tag"`
20+
DisplayIndex int `json:"display_index"`
21+
Host *Host `json:"host" gorm:"-"`
22+
State *State `json:"state" gorm:"-"`
23+
LastActive time.Time `json:"last_active"`
24+
Note string `json:"note"`
25+
PublicNote string `json:"public_note"`
26+
EnableDDNS bool `json:"enable_ddns"`
27+
DDNSProfilesRaw string `json:"ddns_profiles_raw"`
28+
HideForGuest bool `json:"hide_for_guest"`
29+
// 累计流量统计
30+
CumulativeNetInTransfer uint64 `json:"cumulative_net_in_transfer" gorm:"default:0"`
31+
CumulativeNetOutTransfer uint64 `json:"cumulative_net_out_transfer" gorm:"default:0"`
32+
LastTrafficReset time.Time `json:"last_traffic_reset"`
33+
1834
Tag string // 分组名
19-
Secret string `gorm:"uniqueIndex" json:"-"`
2035
Note string `json:"-"` // 管理员可见备注
2136
PublicNote string `json:"PublicNote,omitempty"` // 公开备注
2237
DisplayIndex int // 展示排序,越大越靠前
23-
HideForGuest bool // 对游客隐藏
2438
EnableDDNS bool // 启用DDNS
2539
DDNSProfiles []uint64 `gorm:"-" json:"-"` // DDNS配置
2640

2741
DDNSProfilesRaw string `gorm:"default:'[]';column:ddns_profiles_raw" json:"-"`
2842

29-
Host *Host `gorm:"-"`
30-
State *HostState `gorm:"-"`
31-
LastActive time.Time `gorm:"-"`
3243
LastStateBeforeOffline *HostState `gorm:"-" json:"-"` // 离线前最后一次状态
3344
IsOnline bool `gorm:"-" json:"is_online"` // 是否在线
3445

@@ -42,10 +53,6 @@ type Server struct {
4253

4354
PrevTransferInSnapshot int64 `gorm:"-" json:"-"` // 上次数据点时的入站使用量
4455
PrevTransferOutSnapshot int64 `gorm:"-" json:"-"` // 上次数据点时的出站使用量
45-
46-
// 累计流量数据
47-
CumulativeNetInTransfer uint64 `gorm:"default:0" json:"cumulative_net_in_transfer"` // 累计入站使用量
48-
CumulativeNetOutTransfer uint64 `gorm:"default:0" json:"cumulative_net_out_transfer"` // 累计出站使用量
4956
}
5057

5158
func (s *Server) CopyFromRunningServer(old *Server) {

resource/static/main.js

Lines changed: 8 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -722,29 +722,6 @@ $(document).ready(() => {
722722

723723
// ===== 流量数据处理相关函数 =====
724724

725-
/**
726-
* 通过API获取特定服务器的流量数据
727-
* @param {string|number} serverId 服务器ID
728-
* @returns {Promise} API请求Promise
729-
*/
730-
function fetchTrafficData(serverId) {
731-
return $.ajax({
732-
url: `/api/server/${serverId}/traffic`,
733-
type: "GET",
734-
contentType: "application/json",
735-
}).done((resp) => {
736-
if (resp.code == 200) {
737-
return resp.data;
738-
} else {
739-
console.error("获取流量数据失败:", resp.message);
740-
return null;
741-
}
742-
}).fail((err) => {
743-
console.error("获取流量数据网络错误:", err.responseText);
744-
return null;
745-
});
746-
}
747-
748725
/**
749726
* 调试并修复离线服务器的配置显示问题
750727
* 确保即使某些字段为空,前端也能正常显示离线服务器信息
@@ -848,6 +825,7 @@ function initWebSocket() {
848825
};
849826

850827
ws.onclose = function(event) {
828+
console.log('WebSocket连接已关闭,5秒后重试...');
851829
setTimeout(initWebSocket, 5000);
852830
};
853831

@@ -1035,13 +1013,18 @@ class TrafficManager {
10351013

10361014
const serverId = String(item.server_id);
10371015
const maxTraffic = item.max_formatted || '0B';
1038-
const usedTraffic = item.used_formatted || '0B';
1016+
// 使用累计流量作为已使用流量
1017+
const usedTraffic = item.cumulative_net_in_transfer && item.cumulative_net_out_transfer
1018+
? this.formatTrafficSize(item.cumulative_net_in_transfer + item.cumulative_net_out_transfer)
1019+
: '0B';
10391020
const percent = parseFloat(item.used_percent) || 0;
10401021

10411022
const standardMax = TrafficManager.standardizeTrafficUnit(maxTraffic);
10421023
const standardUsed = TrafficManager.standardizeTrafficUnit(usedTraffic);
10431024
const maxBytes = TrafficManager.parseTrafficToBytes(maxTraffic);
1044-
const usedBytes = TrafficManager.parseTrafficToBytes(usedTraffic);
1025+
const usedBytes = item.cumulative_net_in_transfer && item.cumulative_net_out_transfer
1026+
? item.cumulative_net_in_transfer + item.cumulative_net_out_transfer
1027+
: 0;
10451028

10461029
newData[serverId] = {
10471030
max: standardMax,
@@ -1065,7 +1048,6 @@ class TrafficManager {
10651048
window.serverTrafficData = newData;
10661049
window.lastTrafficUpdateTime = this.lastUpdateTime;
10671050

1068-
// console.log(`已更新 ${updatedCount} 个服务器的流量数据`);
10691051
this.notifySubscribers();
10701052
}
10711053

resource/template/theme-default/home.html

Lines changed: 0 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -922,48 +922,6 @@
922922
// 使Vue实例全局可用
923923
window.statusCards = statusCards;
924924

925-
// WebSocket连接
926-
(function() {
927-
const wsProtocol = window.location.protocol == "https:" ? "wss" : "ws";
928-
const wsUrl = wsProtocol + '://' + window.location.host + '/ws';
929-
930-
function initWebSocket() {
931-
const ws = new WebSocket(wsUrl);
932-
933-
ws.onopen = function() {
934-
// console.log('WebSocket连接已建立');
935-
};
936-
937-
ws.onmessage = function(evt) {
938-
try {
939-
const data = JSON.parse(evt.data);
940-
if (data.trafficData) {
941-
window.serverTrafficRawData = data.trafficData;
942-
if (window.trafficManager) {
943-
window.trafficManager.processTrafficData(data.trafficData);
944-
}
945-
}
946-
} catch (e) {
947-
console.error("处理WebSocket消息时出错:", e);
948-
}
949-
};
950-
951-
ws.onclose = function() {
952-
console.log("WebSocket连接已关闭,5秒后重试...");
953-
setTimeout(initWebSocket, 5000);
954-
};
955-
956-
ws.onerror = function(err) {
957-
console.error("WebSocket错误:", err);
958-
};
959-
960-
return ws;
961-
}
962-
963-
// 初始化WebSocket连接
964-
window.ws = initWebSocket();
965-
})();
966-
967925
$(document).ready(function() {
968926
$('.ui.accordion').accordion({
969927
exclusive: false,

service/singleton/traffic_manager.go

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ package singleton
22

33
import (
44
"fmt"
5+
"log"
56
"sync"
67
"time"
78

89
"github.com/patrickmn/go-cache"
910
"github.com/xos/serverstatus/model"
11+
"gorm.io/gorm"
1012
)
1113

1214
// TrafficManager 流量管理器
@@ -135,15 +137,23 @@ func (tm *TrafficManager) GetTrafficStats(serverID uint64) *TrafficStats {
135137
tm.RLock()
136138
defer tm.RUnlock()
137139

138-
// 先尝试从缓存获取
140+
// 先从缓存获取
139141
if cached, found := tm.cache.Get(tm.getCacheKey(serverID)); found {
140-
if stats, ok := cached.(*TrafficStats); ok {
141-
return stats
142-
}
142+
return cached.(*TrafficStats)
143+
}
144+
145+
// 缓存未命中,从内存获取
146+
if stats, exists := tm.trafficStats[serverID]; exists {
147+
// 更新缓存
148+
tm.cache.Set(
149+
tm.getCacheKey(serverID),
150+
stats,
151+
cache.DefaultExpiration,
152+
)
153+
return stats
143154
}
144155

145-
// 缓存未命中,返回实时数据
146-
return tm.trafficStats[serverID]
156+
return nil
147157
}
148158

149159
// getCacheKey 生成缓存键
@@ -165,31 +175,40 @@ func (tm *TrafficManager) batchWriteWorker() {
165175
}
166176
}
167177

168-
// writeBatchToDatabase 批量写入数据库
178+
// writeBatchToDatabase 将批量数据写入数据库
169179
func (tm *TrafficManager) writeBatchToDatabase() {
170180
if len(tm.batchBuffer) == 0 {
171181
return
172182
}
173183

174-
// 创建批量写入的事务
175-
tx := DB.Begin()
184+
// 创建数据库事务
185+
tx := model.DB.Begin()
176186
if tx.Error != nil {
187+
log.Printf("创建事务失败: %v", tx.Error)
177188
return
178189
}
179190

180-
// 批量插入数据
181-
if err := tx.CreateInBatches(tm.batchBuffer, 100).Error; err != nil {
182-
tx.Rollback()
183-
return
191+
// 批量更新服务器累计流量
192+
for _, transfer := range tm.batchBuffer {
193+
if err := tx.Model(&model.Server{}).
194+
Where("id = ?", transfer.ServerID).
195+
Updates(map[string]interface{}{
196+
"cumulative_net_in_transfer": gorm.Expr("cumulative_net_in_transfer + ?", transfer.In),
197+
"cumulative_net_out_transfer": gorm.Expr("cumulative_net_out_transfer + ?", transfer.Out),
198+
}).Error; err != nil {
199+
tx.Rollback()
200+
log.Printf("更新服务器累计流量失败: %v", err)
201+
return
202+
}
184203
}
185204

186205
// 提交事务
187206
if err := tx.Commit().Error; err != nil {
188-
tx.Rollback()
207+
log.Printf("提交事务失败: %v", err)
189208
return
190209
}
191210

192-
// 清空缓冲区并更新最后写入时间
211+
// 清空缓冲区
193212
tm.batchBuffer = tm.batchBuffer[:0]
194213
tm.lastBatchWrite = time.Now()
195214
}

0 commit comments

Comments
 (0)