前言
上一篇我们首先初步了解一下开源项目-夜莺的alert告警引擎模块的目录,其次通过查看n9e-alert通过Initialize函数的源码大概了解了告警引擎初始化做了哪些工作,另一个重要原因Initialize函数也是通过调用Start函数来实现启动告警引擎,这个和中心节点的n9e进程接入告警引擎是一致的。本文打算通过Start函数来进一步拆解并分析告警引擎的工作原理。
告警引擎启动入口-Start
func Start(alertc aconf.Alert, pushgwc pconf.Pushgw, syncStats *memsto.Stats, alertStats *astats.Stats, externalProcessors *process.ExternalProcessorsType, targetCache *memsto.TargetCacheType, busiGroupCache *memsto.BusiGroupCacheType,
alertMuteCache *memsto.AlertMuteCacheType, alertRuleCache *memsto.AlertRuleCacheType, notifyConfigCache *memsto.NotifyConfigCacheType, datasourceCache *memsto.DatasourceCacheType, ctx *ctx.Context, promClients *prom.PromClientMap, isCenter bool) {
userCache := memsto.NewUserCache(ctx, syncStats)//新建UserCacheType类型,查询数据库中user表,设置标签为sync_users的统计指标值,并启用单独协程9s同步一次数据,并返回指针,用户
userGroupCache := memsto.NewUserGroupCache(ctx, syncStats)//同上,查询user_group表,设置标签为sync_user_groups的统计指标值,用户团队
alertSubscribeCache := memsto.NewAlertSubscribeCache(ctx, syncStats)//同上,查询alert_subscribe表,设置标签为sync_alert_subscribes的统计指标值,订阅告警
recordingRuleCache := memsto.NewRecordingRuleCache(ctx, syncStats)//同上,查询recording_rule表,设置标签为sync_recording_rules的统计指标值,记录规则
go models.InitNotifyConfig(ctx, alertc.Alerting.TemplatesDir)//启用单独协程初始化,保证数据库有告警内置告警渠道,渠道机器人和告警模版
naming := naming.NewNaming(ctx, alertc.Heartbeat, isCenter)//获取naming,按心跳配置更新告警引擎中的服务列表,关键参数是上文中Alert.Heartbeat
//----------todo 下篇-----------
writers := writer.NewWriters(pushgwc)
record.NewScheduler(alertc, recordingRuleCache, promClients, writers, alertStats)
eval.NewScheduler(isCenter, alertc, externalProcessors, alertRuleCache, targetCache, busiGroupCache, alertMuteCache, datasourceCache, promClients, naming, ctx, alertStats)
dp := dispatch.NewDispatch(alertRuleCache, userCache, userGroupCache, alertSubscribeCache, targetCache, notifyConfigCache, alertc.Alerting, ctx)
consumer := dispatch.NewConsumer(alertc.Alerting, ctx, dp)
go dp.ReloadTpls()
go consumer.LoopConsume()
go queue.ReportQueueSize(alertStats)
go sender.StartEmailSender(notifyConfigCache.GetSMTP()) // todo
}
memsto.NewUserCache(ctx, syncStats)定义在根目录中memsto/user_cache.go,主要作用如注释所说是查询myql库的user表,并且往时序库写入两个系统的统计指标
//新建UserCacheType类型,查询数据库中user表信息,给统计Stats对象(CronDuration,SyncNumber)指标设置值,标签为sync_users,并启用单独协程9s同步一次数据,并返回指针
func NewUserCache(ctx *ctx.Context, stats *Stats) *UserCacheType {
uc := &UserCacheType{
statTotal: -1,
statLastUpdated: -1,
ctx: ctx,
stats: stats,
users: make(map[int64]*models.User),
}//新建UserCacheType指针
uc.SyncUsers()//同步用户信息并启动单独协程定期9s同步一次
return uc //返回指针
}
//同步用户信息并启动单独协程定期9s同步一次
func (uc *UserCacheType) SyncUsers() {
err := uc.syncUsers()//同步用户数据库信息并记录相关时序数据指标值
if err != nil {
//同步用户异常退出
fmt.Println("failed to sync users:", err)
exit(1)
}
go uc.loopSyncUsers()//启用单独协程,间隔9秒循环去同步一次用户数据
}
//同步用户数据库信息并记录相关时序数据指标值,标签为sync_users的CronDuration,SyncNumber
func (uc *UserCacheType) syncUsers() error {
start := time.Now()
stat, err := models.UserStat