File size: 6,845 Bytes
5c24871 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | package singleton
import (
_ "embed"
"iter"
"log"
"maps"
"slices"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"sigs.k8s.io/yaml"
"github.com/nezhahq/nezha/model"
"github.com/nezhahq/nezha/pkg/utils"
)
var Version = "debug"
var (
Cache *cache.Cache
DB *gorm.DB
Loc *time.Location
FrontendTemplates []model.FrontendTemplate
DashboardBootTime = uint64(time.Now().Unix())
ServerShared *ServerClass
ServiceSentinelShared *ServiceSentinel
DDNSShared *DDNSClass
NotificationShared *NotificationClass
NATShared *NATClass
CronShared *CronClass
)
//go:embed frontend-templates.yaml
var frontendTemplatesYAML []byte
func InitTimezoneAndCache() error {
var err error
Loc, err = time.LoadLocation(Conf.Location)
if err != nil {
return err
}
Cache = cache.New(5*time.Minute, 10*time.Minute)
return nil
}
// LoadSingleton 加载子服务并执行
func LoadSingleton(bus chan<- *model.Service) (err error) {
initI18n() // 加载本地化服务
initUser() // 加载用户ID绑定表
NATShared = NewNATClass()
DDNSShared = NewDDNSClass()
NotificationShared = NewNotificationClass()
ServerShared = NewServerClass()
CronShared = NewCronClass()
// 最后初始化 ServiceSentinel
ServiceSentinelShared, err = NewServiceSentinel(bus)
return
}
// InitFrontendTemplates 从内置文件中加载FrontendTemplates
func InitFrontendTemplates() error {
err := yaml.Unmarshal(frontendTemplatesYAML, &FrontendTemplates)
if err != nil {
return err
}
return nil
}
// InitDBFromPath 从给出的文件路径中加载数据库
func InitDBFromPath(path string) error {
var err error
DB, err = gorm.Open(sqlite.Open(path), &gorm.Config{
CreateBatchSize: 200,
})
if err != nil {
return err
}
if Conf.Debug {
DB = DB.Debug()
}
err = DB.AutoMigrate(model.Server{}, model.User{}, model.ServerGroup{}, model.NotificationGroup{},
model.Notification{}, model.AlertRule{}, model.Service{}, model.NotificationGroupNotification{},
model.ServiceHistory{}, model.Cron{}, model.Transfer{}, model.ServerGroupServer{},
model.NAT{}, model.DDNSProfile{}, model.NotificationGroupNotification{},
model.WAF{}, model.Oauth2Bind{})
if err != nil {
return err
}
return nil
}
// RecordTransferHourlyUsage 对流量记录进行打点
func RecordTransferHourlyUsage(servers ...*model.Server) {
now := time.Now()
nowTrimSeconds := time.Date(now.Year(), now.Month(), now.Day(), now.Hour(), 0, 0, 0, now.Location())
var txs []model.Transfer
var slist iter.Seq[*model.Server]
if len(servers) > 0 {
slist = slices.Values(servers)
} else {
slist = utils.Seq2To1(ServerShared.Range)
}
for server := range slist {
tx := model.Transfer{
ServerID: server.ID,
In: utils.SubUintChecked(server.State.NetInTransfer, server.PrevTransferInSnapshot),
Out: utils.SubUintChecked(server.State.NetOutTransfer, server.PrevTransferOutSnapshot),
}
if tx.In == 0 && tx.Out == 0 {
continue
}
server.PrevTransferInSnapshot = server.State.NetInTransfer
server.PrevTransferOutSnapshot = server.State.NetOutTransfer
tx.CreatedAt = nowTrimSeconds
txs = append(txs, tx)
}
if len(txs) == 0 {
return
}
log.Printf("NEZHA>> Saved traffic metrics to database. Affected %d row(s), Error: %v", len(txs), DB.Create(txs).Error)
}
// CleanServiceHistory 清理无效或过时的 监控记录 和 流量记录
func CleanServiceHistory() {
// 清理已被删除的服务器的监控记录与流量记录
DB.Unscoped().Delete(&model.ServiceHistory{}, "created_at < ? OR service_id NOT IN (SELECT `id` FROM services)", time.Now().AddDate(0, 0, -30))
// 由于网络监控记录的数据较多,并且前端仅使用了 1 天的数据
// 考虑到 sqlite 数据量问题,仅保留一天数据,
// server_id = 0 的数据会用于/service页面的可用性展示
DB.Unscoped().Delete(&model.ServiceHistory{}, "(created_at < ? AND server_id != 0) OR service_id NOT IN (SELECT `id` FROM services)", time.Now().AddDate(0, 0, -1))
DB.Unscoped().Delete(&model.Transfer{}, "server_id NOT IN (SELECT `id` FROM servers)")
// 计算可清理流量记录的时长
var allServerKeep time.Time
specialServerKeep := make(map[uint64]time.Time)
var specialServerIDs []uint64
var alerts []model.AlertRule
DB.Find(&alerts)
for _, alert := range alerts {
for _, rule := range alert.Rules {
// 是不是流量记录规则
if !rule.IsTransferDurationRule() {
continue
}
dataCouldRemoveBefore := rule.GetTransferDurationStart().UTC()
// 判断规则影响的机器范围
if rule.Cover == model.RuleCoverAll {
// 更新全局可以清理的数据点
if allServerKeep.IsZero() || allServerKeep.After(dataCouldRemoveBefore) {
allServerKeep = dataCouldRemoveBefore
}
} else {
// 更新特定机器可以清理数据点
for id := range rule.Ignore {
if specialServerKeep[id].IsZero() || specialServerKeep[id].After(dataCouldRemoveBefore) {
specialServerKeep[id] = dataCouldRemoveBefore
specialServerIDs = append(specialServerIDs, id)
}
}
}
}
}
for id, couldRemove := range specialServerKeep {
DB.Unscoped().Delete(&model.Transfer{}, "server_id = ? AND datetime(`created_at`) < datetime(?)", id, couldRemove)
}
if allServerKeep.IsZero() {
DB.Unscoped().Delete(&model.Transfer{}, "server_id NOT IN (?)", specialServerIDs)
} else {
DB.Unscoped().Delete(&model.Transfer{}, "server_id NOT IN (?) AND datetime(`created_at`) < datetime(?)", specialServerIDs, allServerKeep)
}
}
// IPDesensitize 根据设置选择是否对IP进行打码处理 返回处理后的IP(关闭打码则返回原IP)
func IPDesensitize(ip string) string {
if Conf.EnablePlainIPInNotification {
return ip
}
return utils.IPDesensitize(ip)
}
type class[K comparable, V model.CommonInterface] struct {
list map[K]V
listMu sync.RWMutex
sortedList []V
sortedListMu sync.RWMutex
}
func (c *class[K, V]) Get(id K) (s V, ok bool) {
c.listMu.RLock()
defer c.listMu.RUnlock()
s, ok = c.list[id]
return
}
func (c *class[K, V]) GetList() map[K]V {
c.listMu.RLock()
defer c.listMu.RUnlock()
return maps.Clone(c.list)
}
func (c *class[K, V]) GetSortedList() []V {
c.sortedListMu.RLock()
defer c.sortedListMu.RUnlock()
return slices.Clone(c.sortedList)
}
func (c *class[K, V]) Range(fn func(k K, v V) bool) {
c.listMu.RLock()
defer c.listMu.RUnlock()
for k, v := range c.list {
if !fn(k, v) {
break
}
}
}
func (c *class[K, V]) CheckPermission(ctx *gin.Context, idList iter.Seq[K]) bool {
c.listMu.RLock()
defer c.listMu.RUnlock()
for id := range idList {
if s, ok := c.list[id]; ok {
if !s.HasPermission(ctx) {
return false
}
}
}
return true
}
|