2022-01-08 22:54:14 -05:00
|
|
|
package singleton
|
2019-12-08 03:59:58 -05:00
|
|
|
|
|
|
|
import (
|
2022-04-12 01:16:33 -04:00
|
|
|
"gorm.io/driver/sqlite"
|
2022-03-18 11:45:03 -04:00
|
|
|
"time"
|
2019-12-09 05:14:31 -05:00
|
|
|
|
2019-12-08 03:59:58 -05:00
|
|
|
"github.com/patrickmn/go-cache"
|
2020-12-19 10:11:16 -05:00
|
|
|
"gorm.io/gorm"
|
2019-12-08 03:59:58 -05:00
|
|
|
|
2020-11-10 21:07:45 -05:00
|
|
|
"github.com/naiba/nezha/model"
|
2019-12-08 03:59:58 -05:00
|
|
|
)
|
|
|
|
|
2022-04-02 23:23:37 -04:00
|
|
|
var Version = "v0.12.18" // !!记得修改 README 中的 badge 版本!!
|
2020-12-19 23:18:27 -05:00
|
|
|
|
2021-01-23 20:41:35 -05:00
|
|
|
var (
|
|
|
|
Conf *model.Config
|
|
|
|
Cache *cache.Cache
|
|
|
|
DB *gorm.DB
|
2022-03-18 11:45:03 -04:00
|
|
|
Loc *time.Location
|
2021-01-23 20:41:35 -05:00
|
|
|
)
|
2021-01-18 20:59:04 -05:00
|
|
|
|
2022-04-12 01:16:33 -04:00
|
|
|
// Init 初始化singleton
|
2022-03-18 11:57:30 -04:00
|
|
|
func Init() {
|
2022-04-12 01:16:33 -04:00
|
|
|
// 初始化时区至上海 UTF+8
|
2022-03-18 11:45:03 -04:00
|
|
|
var err error
|
|
|
|
Loc, err = time.LoadLocation("Asia/Shanghai")
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-01-08 08:04:50 -05:00
|
|
|
|
2022-04-12 01:16:33 -04:00
|
|
|
Conf = &model.Config{}
|
|
|
|
Cache = cache.New(5*time.Minute, 10*time.Minute)
|
2021-01-08 08:04:50 -05:00
|
|
|
}
|
2021-01-23 20:41:35 -05:00
|
|
|
|
2022-04-12 01:16:33 -04:00
|
|
|
// LoadSingleton 加载子服务并执行
|
|
|
|
func LoadSingleton() {
|
|
|
|
LoadNotifications() // 加载通知服务
|
|
|
|
LoadServers() // 加载服务器列表
|
|
|
|
LoadCronTasks() // 加载定时任务
|
2021-01-23 20:41:35 -05:00
|
|
|
}
|
2021-06-21 09:30:42 -04:00
|
|
|
|
2022-04-12 01:16:33 -04:00
|
|
|
// InitConfigFromPath 从给出的文件路径中加载配置
|
|
|
|
func InitConfigFromPath(path string) {
|
|
|
|
err := Conf.Read(path)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2021-06-21 09:30:42 -04:00
|
|
|
}
|
|
|
|
}
|
2022-02-19 01:29:06 -05:00
|
|
|
|
2022-04-12 01:16:33 -04:00
|
|
|
// InitDBFromPath 从给出的文件路径中加载数据库
|
|
|
|
func InitDBFromPath(path string) {
|
|
|
|
var err error
|
|
|
|
DB, err = gorm.Open(sqlite.Open(path), &gorm.Config{
|
|
|
|
CreateBatchSize: 200,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if Conf.Debug {
|
|
|
|
DB = DB.Debug()
|
|
|
|
}
|
|
|
|
err = DB.AutoMigrate(model.Server{}, model.User{},
|
|
|
|
model.Notification{}, model.AlertRule{}, model.Monitor{},
|
|
|
|
model.MonitorHistory{}, model.Cron{}, model.Transfer{})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
2022-02-19 01:29:06 -05:00
|
|
|
}
|
|
|
|
}
|