nezha/service/singleton/nat.go

76 lines
1.4 KiB
Go
Raw Normal View History

2024-07-14 07:41:50 -04:00
package singleton
import (
2024-12-08 07:21:35 -05:00
"cmp"
"slices"
2024-07-14 07:41:50 -04:00
"sync"
2024-11-28 06:38:54 -05:00
"github.com/nezhahq/nezha/model"
2024-07-14 07:41:50 -04:00
)
var (
NATCache = make(map[string]*model.NAT)
NATCacheRwLock sync.RWMutex
NATIDToDomain = make(map[uint64]string)
NATList []*model.NAT
NATListLock sync.RWMutex
)
2024-07-14 07:41:50 -04:00
func initNAT() {
DB.Find(&NATList)
NATCacheRwLock.Lock()
defer NATCacheRwLock.Unlock()
NATCache = make(map[string]*model.NAT)
for i := 0; i < len(NATList); i++ {
NATCache[NATList[i].Domain] = NATList[i]
NATIDToDomain[NATList[i].ID] = NATList[i].Domain
}
2024-07-14 07:41:50 -04:00
}
func OnNATUpdate(n *model.NAT) {
NATCacheRwLock.Lock()
defer NATCacheRwLock.Unlock()
if oldDomain, ok := NATIDToDomain[n.ID]; ok && oldDomain != n.Domain {
delete(NATCache, oldDomain)
}
NATCache[n.Domain] = n
NATIDToDomain[n.ID] = n.Domain
}
func OnNATDelete(id []uint64) {
NATCacheRwLock.Lock()
defer NATCacheRwLock.Unlock()
for _, i := range id {
if domain, ok := NATIDToDomain[i]; ok {
delete(NATCache, domain)
delete(NATIDToDomain, i)
}
}
}
func UpdateNATList() {
NATCacheRwLock.RLock()
defer NATCacheRwLock.RUnlock()
NATListLock.Lock()
defer NATListLock.Unlock()
NATList = make([]*model.NAT, 0, len(NATCache))
for _, n := range NATCache {
NATList = append(NATList, n)
2024-07-14 07:41:50 -04:00
}
slices.SortFunc(NATList, func(a, b *model.NAT) int {
2024-12-08 07:21:35 -05:00
return cmp.Compare(a.ID, b.ID)
})
2024-07-14 07:41:50 -04:00
}
func GetNATConfigByDomain(domain string) *model.NAT {
NATCacheRwLock.RLock()
defer NATCacheRwLock.RUnlock()
return NATCache[domain]
2024-07-14 07:41:50 -04:00
}