nezha/service/singleton/server.go
2024-11-03 21:12:28 +08:00

71 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package singleton
import (
"sort"
"sync"
"github.com/naiba/nezha/model"
)
var (
ServerList map[uint64]*model.Server // [ServerID] -> model.Server
ServerUUIDToID map[string]uint64 // [ServerUUID] -> ServerID
ServerLock sync.RWMutex
SortedServerList []*model.Server // 用于存储服务器列表的 slice按照服务器 ID 排序
SortedServerListForGuest []*model.Server
SortedServerLock sync.RWMutex
)
func InitServer() {
ServerList = make(map[uint64]*model.Server)
ServerUUIDToID = make(map[string]uint64)
}
// loadServers 加载服务器列表并根据ID排序
func loadServers() {
InitServer()
var servers []model.Server
DB.Find(&servers)
for _, s := range servers {
innerS := s
innerS.Host = &model.Host{}
innerS.State = &model.HostState{}
innerS.TaskCloseLock = new(sync.Mutex)
ServerList[innerS.ID] = &innerS
ServerUUIDToID[innerS.UUID] = innerS.ID
}
ReSortServer()
}
// ReSortServer 根据服务器ID 对服务器列表进行排序ID越大越靠前
func ReSortServer() {
ServerLock.RLock()
defer ServerLock.RUnlock()
SortedServerLock.Lock()
defer SortedServerLock.Unlock()
SortedServerList = make([]*model.Server, 0, len(ServerList))
for _, s := range ServerList {
SortedServerList = append(SortedServerList, s)
if !s.HideForGuest {
SortedServerListForGuest = append(SortedServerListForGuest, s)
}
}
// 按照服务器 ID 排序的具体实现ID越大越靠前
sort.SliceStable(SortedServerList, func(i, j int) bool {
if SortedServerList[i].DisplayIndex == SortedServerList[j].DisplayIndex {
return SortedServerList[i].ID < SortedServerList[j].ID
}
return SortedServerList[i].DisplayIndex > SortedServerList[j].DisplayIndex
})
sort.SliceStable(SortedServerListForGuest, func(i, j int) bool {
if SortedServerListForGuest[i].DisplayIndex == SortedServerListForGuest[j].DisplayIndex {
return SortedServerListForGuest[i].ID < SortedServerListForGuest[j].ID
}
return SortedServerListForGuest[i].DisplayIndex > SortedServerListForGuest[j].DisplayIndex
})
}