Compare commits

..
5 Commits
Author SHA1 Message Date
Akizon77 f0cc0fba38 fix: pin 1.5.1 frontend release source 2026-09-24 23:21:05 +08:00
Akizon77 1d972c42dc fix: pin 1.5.1-rc1 frontend version 2026-09-24 17:25:06 +08:00
Akizon f089b08b3a 裁剪1下 2026-09-24 17:21:44 +08:00
Akizon 6e70263c50 重定向旧版本的主题接口? 2026-09-24 17:21:37 +08:00
Akizon77 0ca87aafd1 移除流量通知 2026-09-14 21:13:26 +08:00
16 changed files with 33 additions and 620 deletions

No files matched your search

+5 -1
View File
@@ -98,7 +98,11 @@ jobs:
fi
VERSION="${{ github.sha }}"
VERSION_HASH="${{ github.sha }}"
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o $BINARY_NAME
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
if [ "${{ matrix.goos }}" = "linux" ]; then
LDFLAGS="$LDFLAGS -extldflags=-Wl,--strip-all"
fi
go build -trimpath -ldflags="$LDFLAGS" -o "$BINARY_NAME"
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
GOARCH: amd64
run: |
VERSION_SHA="${{ github.sha }}"
go build -ldflags "-X github.com/komari-monitor/komari/utils.CurrentVersion=dev -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_SHA}" -o komari .
go build -ldflags "-s -w -extldflags=-Wl,--strip-all -X github.com/komari-monitor/komari/utils.CurrentVersion=dev -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_SHA}" -o komari .
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
+1 -1
View File
@@ -50,7 +50,7 @@ jobs:
run: |
VERSION="${{ github.ref_name }}"
VERSION_HASH="${{ github.sha }}"
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
LDFLAGS="-s -w -extldflags=-Wl,--strip-all -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
echo "Building for linux/amd64..."
GOARCH=amd64 CC="zig cc -target x86_64-linux-musl" go build -trimpath -ldflags="$LDFLAGS" -o komari-linux-amd64
+5 -1
View File
@@ -102,7 +102,11 @@ jobs:
run: |
BINARY_NAME=komari-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.binary_extension }}
VERSION_HASH="$(git rev-parse HEAD)"
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${RELEASE_TAG} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o "$BINARY_NAME"
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${RELEASE_TAG} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
if [ "${{ matrix.goos }}" = "linux" ]; then
LDFLAGS="$LDFLAGS -extldflags=-Wl,--strip-all"
fi
go build -trimpath -ldflags="$LDFLAGS" -o "$BINARY_NAME"
- name: Upload binary to release
env:
+1 -1
View File
@@ -56,7 +56,7 @@ jobs:
VERSION: ${{ github.event.inputs.version }}
run: |
VERSION_HASH="${{ github.sha }}"
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
LDFLAGS="-s -w -extldflags=-Wl,--strip-all -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
echo "Building for linux/amd64..."
GOARCH=amd64 CC="zig cc -target x86_64-linux-musl" go build -trimpath -ldflags="$LDFLAGS" -o komari-linux-amd64
+8 -2
View File
@@ -24,7 +24,9 @@ jobs:
TAG: ${{ github.event.release.tag_name }}
run: |
frontend_ref=""
if [[ "$TAG" =~ ^(.+)-fix[0-9]+$ ]]; then
if [[ "$TAG" == "1.5.1" || "$TAG" == "1.5.1-rc1" ]]; then
frontend_ref="1.5.0-fix1"
elif [[ "$TAG" =~ ^(.+)-fix[0-9]+$ ]]; then
frontend_ref="${BASH_REMATCH[1]}"
fi
echo "frontend_ref=$frontend_ref" >> "$GITHUB_OUTPUT"
@@ -121,7 +123,11 @@ jobs:
fi
VERSION="${{ github.event.release.tag_name }}"
VERSION_HASH="${{ github.sha }}" # Use commit SHA for hash
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o $BINARY_NAME
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
if [ "${{ matrix.goos }}" = "linux" ]; then
LDFLAGS="$LDFLAGS -extldflags=-Wl,--strip-all"
fi
go build -trimpath -ldflags="$LDFLAGS" -o "$BINARY_NAME"
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
+5 -1
View File
@@ -150,7 +150,11 @@ jobs:
fi
VERSION="${{ needs.prepare.outputs.version }}"
VERSION_HASH="${{ github.sha }}" # Use commit SHA for hash
go build -trimpath -ldflags="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}" -o $BINARY_NAME
LDFLAGS="-s -w -X github.com/komari-monitor/komari/utils.CurrentVersion=${VERSION} -X github.com/komari-monitor/komari/utils.VersionHash=${VERSION_HASH}"
if [ "${{ matrix.goos }}" = "linux" ]; then
LDFLAGS="$LDFLAGS -extldflags=-Wl,--strip-all"
fi
go build -trimpath -ldflags="$LDFLAGS" -o "$BINARY_NAME"
- name: Upload binary as artifact
uses: actions/upload-artifact@v4
+1 -1
View File
@@ -444,6 +444,7 @@ func doInitialize() error {
// 若升级时旧表仍存在,管理员可通过升级向导显式导入并清理。
// models.Record / models.PingRecord / models.GPURecord 结构体仍作为
// metric store 的读写 DTO 和旧表导入 DTO 保留在 models 包中。
// models.TrafficReportNotification 同样仅为旧数据库兼容保留,不再建表。
err = instance.AutoMigrate(
&models.User{},
@@ -452,7 +453,6 @@ func doInitialize() error {
&models.Clipboard{},
&models.LoadNotification{},
&models.OfflineNotification{},
&models.TrafficReportNotification{},
&models.PingTask{},
&models.OidcProvider{},
&models.MessageSenderProvider{},
@@ -8,7 +8,4 @@ const (
Login = "Login"
Alert = "Alert"
Traffic = "Traffic"
DReport = "DReport" // 日报
WReport = "WReport" // 周报
MReport = "MReport" // 月报
)
-128
View File
@@ -1,128 +0,0 @@
package notification
import (
"fmt"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
"gorm.io/gorm/clause"
)
func validateTrafficReportNotification(notification models.TrafficReportNotification) error {
if notification.Client == "" {
return fmt.Errorf("client UUID cannot be empty")
}
if notification.Enable && !notification.Daily && !notification.Weekly && !notification.Monthly {
return fmt.Errorf("at least one cadence must be selected when enabling traffic reports")
}
return nil
}
func ValidateTrafficReportNotifications(notifications []models.TrafficReportNotification) error {
for _, notification := range notifications {
if err := validateTrafficReportNotification(notification); err != nil {
return err
}
}
return nil
}
func buildEnabledTrafficReportNotifications(uuids []string, existing []models.TrafficReportNotification) ([]models.TrafficReportNotification, error) {
if len(uuids) == 0 {
return nil, fmt.Errorf("at least one client UUID is required")
}
existingByClient := make(map[string]models.TrafficReportNotification, len(existing))
for _, notification := range existing {
existingByClient[notification.Client] = notification
}
notifications := make([]models.TrafficReportNotification, 0, len(uuids))
for _, uuid := range uuids {
if uuid == "" {
return nil, fmt.Errorf("client UUID cannot be empty")
}
existingNotification, ok := existingByClient[uuid]
if !ok || (!existingNotification.Daily && !existingNotification.Weekly && !existingNotification.Monthly) {
return nil, fmt.Errorf("at least one cadence must be selected when enabling traffic reports")
}
notifications = append(notifications, models.TrafficReportNotification{
Client: uuid,
Enable: true,
})
}
return notifications, nil
}
// ListTrafficReportNotifications 获取所有流量定时报告配置(关联客户端信息)
func ListTrafficReportNotifications() ([]models.TrafficReportNotification, error) {
db := dbcore.GetDBInstance()
var notifications []models.TrafficReportNotification
err := db.Model(&models.TrafficReportNotification{}).Preload("ClientInfo").Find(&notifications).Error
return notifications, err
}
// EditTrafficReportNotifications 批量更新流量定时报告配置
func EditTrafficReportNotifications(notifications []models.TrafficReportNotification) error {
if err := ValidateTrafficReportNotifications(notifications); err != nil {
return err
}
db := dbcore.GetDBInstance()
return db.Model(&models.TrafficReportNotification{}).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "client"}},
DoUpdates: clause.AssignmentColumns([]string{"enable", "daily", "weekly", "monthly"}),
}).
Select("client", "enable", "daily", "weekly", "monthly").
Create(notifications).Error
}
// EnableTrafficReportNotifications 批量启用(仅更新 enable 字段)
func EnableTrafficReportNotifications(uuids []string) error {
if len(uuids) == 0 {
return fmt.Errorf("at least one client UUID is required")
}
db := dbcore.GetDBInstance()
var existing []models.TrafficReportNotification
if err := db.Where("client IN ?", uuids).Find(&existing).Error; err != nil {
return err
}
notifications, err := buildEnabledTrafficReportNotifications(uuids, existing)
if err != nil {
return err
}
return db.Model(&models.TrafficReportNotification{}).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "client"}},
DoUpdates: clause.AssignmentColumns([]string{"enable"}),
}).
Select("client", "enable").
Create(notifications).Error
}
// DisableTrafficReportNotifications 批量禁用
func DisableTrafficReportNotifications(uuids []string) error {
if len(uuids) == 0 {
return fmt.Errorf("at least one client UUID is required")
}
db := dbcore.GetDBInstance()
var notifications []models.TrafficReportNotification
for _, uuid := range uuids {
if uuid == "" {
return fmt.Errorf("client UUID cannot be empty")
}
notifications = append(notifications, models.TrafficReportNotification{
Client: uuid,
Enable: false,
})
}
return db.Model(&models.TrafficReportNotification{}).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "client"}},
DoUpdates: clause.AssignmentColumns([]string{"enable"}),
}).
Select("client", "enable").
Create(notifications).Error
}
@@ -1,36 +0,0 @@
package notification
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/komari-monitor/komari/database/models"
)
func TestValidateTrafficReportNotificationsRejectsEnabledWithoutCadence(t *testing.T) {
err := ValidateTrafficReportNotifications([]models.TrafficReportNotification{{
Client: "client-a",
Enable: true,
}})
assert.Error(t, err)
}
func TestBuildEnabledTrafficReportNotificationsRequiresExistingCadence(t *testing.T) {
_, err := buildEnabledTrafficReportNotifications([]string{"client-a"}, nil)
assert.Error(t, err)
_, err = buildEnabledTrafficReportNotifications([]string{"client-a"}, []models.TrafficReportNotification{{Client: "client-a"}})
assert.Error(t, err)
notifications, err := buildEnabledTrafficReportNotifications([]string{"client-a"}, []models.TrafficReportNotification{{
Client: "client-a",
Daily: true,
}})
require.NoError(t, err)
require.Len(t, notifications, 1)
assert.Equal(t, "client-a", notifications[0].Client)
assert.True(t, notifications[0].Enable)
}
-1
View File
@@ -206,7 +206,6 @@ func registerScheduledWork() {
if err := scheduler.AddFunc("notifier:expire", "0 0 9 * * *", notifier.CheckExpireScheduledWork); err != nil {
logger.ErrorArgs("server", "Failed to add expire notification task:", err)
}
notifier.InitTrafficReportSchedule()
}
const taskResultRetentionDays = 30
-258
View File
@@ -1,258 +0,0 @@
package notifier
import (
"fmt"
"sort"
"strings"
"time"
logger "github.com/komari-monitor/komari/utils/log"
"context"
"github.com/komari-monitor/komari/database/dbcore"
"github.com/komari-monitor/komari/database/models"
messageevent "github.com/komari-monitor/komari/database/models/messageEvent"
"github.com/komari-monitor/komari/internal/config"
"github.com/komari-monitor/komari/internal/metricstore"
"github.com/komari-monitor/komari/internal/scheduler"
"github.com/komari-monitor/komari/utils/messageSender"
)
// InitTrafficReportSchedule 注册三个定时任务:日报、周报、月报
func InitTrafficReportSchedule() {
// 日报:每天凌晨 0 点
if err := scheduler.AddFunc("traffic-report-daily", "0 0 0 * * *", func() {
sendTrafficReport(true, false, false)
}); err != nil {
logger.ErrorArgs("notifier", "Failed to register daily traffic report job:", err)
}
// 周报:每周一凌晨 0 点 (dow=1)
if err := scheduler.AddFunc("traffic-report-weekly", "0 0 0 * * 1", func() {
sendTrafficReport(false, true, false)
}); err != nil {
logger.ErrorArgs("notifier", "Failed to register weekly traffic report job:", err)
}
// 月报:每月 1 日凌晨 0 点
if err := scheduler.AddFunc("traffic-report-monthly", "0 0 0 1 * *", func() {
sendTrafficReport(false, false, true)
}); err != nil {
logger.ErrorArgs("notifier", "Failed to register monthly traffic report job:", err)
}
}
// sendTrafficReport 汇聚所有启用了指定报告类型的服务器流量,合并成一条通知发送
func sendTrafficReport(daily, weekly, monthly bool) {
// 检查全局通知开关
enabled, err := config.GetAs[bool](config.NotificationEnabledKey, false)
if err != nil || !enabled {
return
}
db := dbcore.GetDBInstance()
now := time.Now().UTC()
var eventType, label, suffix string
switch {
case daily:
eventType = messageevent.DReport
label = "daily"
suffix = "昨日流量"
case weekly:
eventType = messageevent.WReport
label = "weekly"
suffix = "上周流量"
case monthly:
eventType = messageevent.MReport
label = "monthly"
suffix = "上个月流量"
default:
return
}
start, end := previousTrafficReportRange(now, label)
// 查询所有启用该类型报告的服务器配置
var notifications []models.TrafficReportNotification
query := db.Model(&models.TrafficReportNotification{}).Where("enable = ?", true)
if daily {
query = query.Where("daily = ?", true)
} else if weekly {
query = query.Where("weekly = ?", true)
} else if monthly {
query = query.Where("monthly = ?", true)
}
if err := query.Find(&notifications).Error; err != nil {
logger.Errorf("notifier", "Failed to query traffic report notifications (%s): %v", label, err)
return
}
if len(notifications) == 0 {
return
}
// 获取客户端信息
clientUUIDs := make([]string, 0, len(notifications))
for _, n := range notifications {
clientUUIDs = append(clientUUIDs, n.Client)
}
var clientList []models.Client
if err := db.Where("uuid IN ?", clientUUIDs).Find(&clientList).Error; err != nil {
logger.Errorf("notifier", "Failed to query clients for traffic report (%s): %v", label, err)
return
}
clientMap := make(map[string]models.Client, len(clientList))
for _, c := range clientList {
clientMap[c.UUID] = c
}
// 为每个服务器统计流量并拼接消息
var lines []string
eventClients := make([]models.Client, 0, len(notifications))
for _, n := range notifications {
c, ok := clientMap[n.Client]
if !ok {
continue
}
used, err := getClientTrafficInRange(n.Client, c.TrafficLimitType, start, end)
if err != nil {
logger.Errorf("notifier", "Failed to compute traffic for client %s (%s): %v", n.Client, label, err)
continue
}
lines = append(lines, fmt.Sprintf("%s%s:%s", c.Name, suffix, humanBytes(used)))
eventClients = append(eventClients, c)
}
if len(lines) == 0 {
return
}
message := strings.Join(lines, "\nKomari 内置的流量报告即将在 1.5.0 版本移除,请尽快迁移至插件“流量定期报告”。\nKomari's built-in traffic reports will be removed in version 1.5.0. Please migrate to the Scheduled Traffic Reports plugin as soon as possible.")
var emoji string
switch {
case daily:
emoji = "📊"
case weekly:
emoji = "📈"
case monthly:
emoji = "📅"
}
if err := messageSender.SendNotification(models.EventMessage{
Event: eventType,
Clients: eventClients,
Time: now,
Emoji: emoji,
Message: message,
}); err != nil {
logger.Errorf("notifier", "Failed to send %s traffic report: %v", label, err)
}
}
func previousTrafficReportRange(now time.Time, period string) (time.Time, time.Time) {
localNow := now.In(time.Local)
var startLocal, endLocal time.Time
switch period {
case "daily":
yesterday := localNow.AddDate(0, 0, -1)
startLocal = time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.Local)
endLocal = startLocal.AddDate(0, 0, 1)
case "weekly":
weekday := int(localNow.Weekday())
if weekday == 0 {
weekday = 7
}
lastMonday := localNow.AddDate(0, 0, -(weekday-1)-7)
startLocal = time.Date(lastMonday.Year(), lastMonday.Month(), lastMonday.Day(), 0, 0, 0, 0, time.Local)
endLocal = startLocal.AddDate(0, 0, 7)
case "monthly":
endLocal = time.Date(localNow.Year(), localNow.Month(), 1, 0, 0, 0, 0, time.Local)
startLocal = endLocal.AddDate(0, -1, 0)
default:
return time.Time{}, time.Time{}
}
return startLocal.UTC(), endLocal.Add(-time.Nanosecond).UTC()
}
// getClientTrafficInRange 查询某客户端在指定时间段内的流量增量。
//
// 历史监控数据已完全迁移到 metric store,这里从 metric store 读取区间内记录并
// 累加精确的流量增量字段计算用量;缺失增量时回退到累计流量差值。
func getClientTrafficInRange(clientUUID string, trafficType string, start, end time.Time) (int64, error) {
ctx := context.Background()
recs, err := metricstore.GetRecordsByClientAndTime(ctx, clientUUID, start, end)
if err != nil {
return 0, err
}
records := make([]trafficDeltaRecord, 0, len(recs))
for _, r := range recs {
records = append(records, trafficDeltaRecord{
Time: r.Time,
NetTotalUp: r.NetTotalUp,
NetTotalDown: r.NetTotalDown,
TrafficUp: r.TrafficUp,
TrafficDown: r.TrafficDown,
})
}
sort.Slice(records, func(i, j int) bool {
return records[i].Time.Before(records[j].Time)
})
// 计算增量基线(区间开始前最后一条累计流量)
var previous *trafficDeltaRecord
baseline, err := metricstore.GetLatestTrafficBefore(ctx, []string{clientUUID}, start)
if err != nil {
return 0, err
}
if base, ok := baseline[clientUUID]; ok {
previous = &trafficDeltaRecord{
Time: base.Time,
NetTotalUp: base.NetTotalUp,
NetTotalDown: base.NetTotalDown,
}
}
totalUp, totalDown := sumTrafficDeltas(records, previous)
return computeUsedByType(strings.ToLower(trafficType), totalUp, totalDown), nil
}
type trafficDeltaRecord struct {
Time time.Time
NetTotalUp int64
NetTotalDown int64
TrafficUp int64
TrafficDown int64
}
func sumTrafficDeltas(records []trafficDeltaRecord, previous *trafficDeltaRecord) (int64, int64) {
var totalUp int64
var totalDown int64
for i := range records {
up := records[i].TrafficUp
down := records[i].TrafficDown
if previous != nil {
up = trafficDeltaOrFallback(up, records[i].NetTotalUp, previous.NetTotalUp)
down = trafficDeltaOrFallback(down, records[i].NetTotalDown, previous.NetTotalDown)
}
totalUp += up
totalDown += down
previous = &records[i]
}
return totalUp, totalDown
}
func trafficDeltaOrFallback(storedDelta, currentTotal, previousTotal int64) int64 {
if storedDelta > 0 {
return storedDelta
}
return metricstore.TrafficCounterDelta(currentTotal, previousTotal)
}
-125
View File
@@ -1,125 +0,0 @@
package notifier
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestPreviousTrafficReportRangesUseSystemTimezone(t *testing.T) {
originalLocal := time.Local
time.Local = time.FixedZone("UTC+8", 8*60*60)
t.Cleanup(func() { time.Local = originalLocal })
now := time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC) // 2026-07-01 00:00 local
tests := []struct {
period string
wantStart time.Time
wantEnd time.Time
}{
{
period: "daily",
wantStart: time.Date(2026, 6, 29, 16, 0, 0, 0, time.UTC),
wantEnd: time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC).Add(-time.Nanosecond),
},
{
period: "weekly",
wantStart: time.Date(2026, 6, 21, 16, 0, 0, 0, time.UTC),
wantEnd: time.Date(2026, 6, 28, 16, 0, 0, 0, time.UTC).Add(-time.Nanosecond),
},
{
period: "monthly",
wantStart: time.Date(2026, 5, 31, 16, 0, 0, 0, time.UTC),
wantEnd: time.Date(2026, 6, 30, 16, 0, 0, 0, time.UTC).Add(-time.Nanosecond),
},
}
for _, test := range tests {
t.Run(test.period, func(t *testing.T) {
start, end := previousTrafficReportRange(now, test.period)
if !start.Equal(test.wantStart) || !end.Equal(test.wantEnd) {
t.Fatalf("range = [%s, %s], want [%s, %s]", start, end, test.wantStart, test.wantEnd)
}
if start.Location() != time.UTC || end.Location() != time.UTC {
t.Fatalf("range locations = [%s, %s], want UTC", start.Location(), end.Location())
}
})
}
}
func TestPreviousDailyTrafficReportRangeHandlesDST(t *testing.T) {
location, err := time.LoadLocation("America/New_York")
if err != nil {
t.Skipf("timezone database unavailable: %v", err)
}
originalLocal := time.Local
time.Local = location
t.Cleanup(func() { time.Local = originalLocal })
now := time.Date(2026, 3, 9, 4, 0, 0, 0, time.UTC) // 2026-03-09 00:00 EDT
start, end := previousTrafficReportRange(now, "daily")
if got := end.Add(time.Nanosecond).Sub(start); got != 23*time.Hour {
t.Fatalf("DST day duration = %s, want 23h", got)
}
}
func TestSumTrafficDeltasUsesStoredDeltas(t *testing.T) {
records := []trafficDeltaRecord{
{TrafficUp: 30, TrafficDown: 40, NetTotalUp: 130, NetTotalDown: 240},
{TrafficUp: 25, TrafficDown: 35, NetTotalUp: 155, NetTotalDown: 275},
}
up, down := sumTrafficDeltas(records, nil)
assert.Equal(t, int64(55), up)
assert.Equal(t, int64(75), down)
}
func TestSumTrafficDeltasFallsBackToCumulativeTotals(t *testing.T) {
previous := &trafficDeltaRecord{NetTotalUp: 100, NetTotalDown: 200}
records := []trafficDeltaRecord{
{TrafficUp: 0, TrafficDown: 0, NetTotalUp: 130, NetTotalDown: 250},
{TrafficUp: 0, TrafficDown: 0, NetTotalUp: 160, NetTotalDown: 310},
}
up, down := sumTrafficDeltas(records, previous)
assert.Equal(t, int64(60), up)
assert.Equal(t, int64(110), down)
}
func TestSumTrafficDeltasHandlesCounterResetInFallback(t *testing.T) {
previous := &trafficDeltaRecord{NetTotalUp: 400, NetTotalDown: 550}
records := []trafficDeltaRecord{
{TrafficUp: 0, TrafficDown: 0, NetTotalUp: 500, NetTotalDown: 600},
{TrafficUp: 0, TrafficDown: 0, NetTotalUp: 100, NetTotalDown: 150},
}
up, down := sumTrafficDeltas(records, previous)
assert.Equal(t, int64(200), up)
assert.Equal(t, int64(200), down)
}
func TestSumTrafficDeltasEmpty(t *testing.T) {
up, down := sumTrafficDeltas(nil, nil)
assert.Equal(t, int64(0), up)
assert.Equal(t, int64(0), down)
}
func TestTrafficDeltaOrFallback(t *testing.T) {
// 存储的增量为正时直接使用
assert.Equal(t, int64(42), trafficDeltaOrFallback(42, 500, 100))
// 增量缺失(<=0)时回退到累计差值
assert.Equal(t, int64(400), trafficDeltaOrFallback(0, 500, 100))
// 回退路径识别计数器重置
assert.Equal(t, int64(50), trafficDeltaOrFallback(0, 50, 500))
}
func TestComputeUsedByType(t *testing.T) {
assert.Equal(t, int64(30), computeUsedByType("up", 30, 70))
assert.Equal(t, int64(70), computeUsedByType("down", 30, 70))
assert.Equal(t, int64(100), computeUsedByType("sum", 30, 70))
assert.Equal(t, int64(30), computeUsedByType("min", 30, 70))
assert.Equal(t, int64(70), computeUsedByType("max", 30, 70))
// 未知类型默认取较大值
assert.Equal(t, int64(70), computeUsedByType("unknown", 30, 70))
}
+5 -7
View File
@@ -1,6 +1,8 @@
package router
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/komari-monitor/komari/web/api"
"github.com/komari-monitor/komari/web/api/admin"
@@ -20,6 +22,9 @@ func Register(r *gin.Engine) {
r.Any("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
r.GET("/admin", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/admin/dashboard")
})
registerPublicRoutes(r)
registerAgentRoutes(r)
@@ -246,13 +251,6 @@ func registerAdminRoutes(r *gin.Engine) {
loadAlert.POST("/delete", jsonRpc.Bind("admin:deleteLoadNotification"))
loadAlert.POST("/edit", jsonRpc.Bind("admin:editLoadNotification"))
}
trafficReport := notificationGroup.Group("/traffic-report")
{
trafficReport.GET("/", jsonRpc.Bind("admin:listTrafficReportNotifications"))
trafficReport.POST("/edit", jsonRpc.Bind("admin:editTrafficReportNotifications"))
trafficReport.POST("/enable", jsonRpc.Bind("admin:enableTrafficReportNotifications"))
trafficReport.POST("/disable", jsonRpc.Bind("admin:disableTrafficReportNotifications"))
}
}
// ping tasks
+1 -53
View File
@@ -13,7 +13,7 @@ import (
)
// admin.notification.go
// 通知相关 RPC2 方法(admin 命名空间):负载告警、离线通知、流量报告。
// 通知相关 RPC2 方法(admin 命名空间):负载告警、离线通知。
func init() {
// load notifications
@@ -26,11 +26,6 @@ func init() {
reg("editOfflineNotification", adminEditOfflineNotification, "Edit offline notifications")
reg("enableOfflineNotification", adminEnableOfflineNotification, "Enable offline notifications for clients")
reg("disableOfflineNotification", adminDisableOfflineNotification, "Disable offline notifications for clients")
// traffic report notifications
reg("listTrafficReportNotifications", adminListTrafficReport, "List traffic report notifications")
reg("editTrafficReportNotifications", adminEditTrafficReport, "Edit traffic report notifications")
reg("enableTrafficReportNotifications", adminEnableTrafficReport, "Enable traffic report notifications")
reg("disableTrafficReportNotifications", adminDisableTrafficReport, "Disable traffic report notifications")
// send notification
reg("sendNotification", adminSendNotification, "Send a notification")
}
@@ -190,50 +185,3 @@ func adminDisableOfflineNotification(_ context.Context, req *rpc.JsonRpcRequest)
}
return nil, nil
}
func adminListTrafficReport(_ context.Context, _ *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) {
list, err := notification.ListTrafficReportNotifications()
if err != nil {
return nil, rpc.MakeError(rpc.InternalError, "Failed to list traffic report notifications: "+err.Error(), nil)
}
return list, nil
}
func adminEditTrafficReport(_ context.Context, req *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) {
var notifications []models.TrafficReportNotification
if err := req.BindParams(&notifications); err != nil {
return nil, rpc.MakeError(rpc.InvalidParams, "Invalid request body: "+err.Error(), nil)
}
if len(notifications) == 0 {
return nil, rpc.MakeError(rpc.InvalidParams, "At least one notification is required", nil)
}
if err := notification.ValidateTrafficReportNotifications(notifications); err != nil {
return nil, rpc.MakeError(rpc.InvalidParams, err.Error(), nil)
}
if err := notification.EditTrafficReportNotifications(notifications); err != nil {
return nil, rpc.MakeError(rpc.InternalError, "Failed to edit traffic report notifications: "+err.Error(), nil)
}
return nil, nil
}
func adminEnableTrafficReport(_ context.Context, req *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) {
var uuids []string
if err := req.BindParams(&uuids); err != nil {
return nil, rpc.MakeError(rpc.InvalidParams, "Invalid request body: "+err.Error(), nil)
}
if err := notification.EnableTrafficReportNotifications(uuids); err != nil {
return nil, rpc.MakeError(rpc.InternalError, "Failed to enable traffic report notifications: "+err.Error(), nil)
}
return nil, nil
}
func adminDisableTrafficReport(_ context.Context, req *rpc.JsonRpcRequest) (any, *rpc.JsonRpcError) {
var uuids []string
if err := req.BindParams(&uuids); err != nil {
return nil, rpc.MakeError(rpc.InvalidParams, "Invalid request body: "+err.Error(), nil)
}
if err := notification.DisableTrafficReportNotifications(uuids); err != nil {
return nil, rpc.MakeError(rpc.InternalError, "Failed to disable traffic report notifications: "+err.Error(), nil)
}
return nil, nil
}