123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package model
- import (
- "fmt"
- "sparrow/pkg/models"
- "github.com/jinzhu/gorm"
- )
- // Alert model
- type Alert struct {
- db *gorm.DB
- }
- // Init init Alert
- func (a *Alert) Init(db *gorm.DB) *Alert {
- a.db = db
- return a
- }
- // Create create a alert rule
- func (a *Alert) Create(alert *models.AlarmRule) error {
- err := a.db.Create(alert).Error
- if err == nil {
- cache := getCache()
- key := fmt.Sprintf("Alert:%d", alert.ID)
- cache.Set(key, &alert)
- }
- return err
- }
- // Delete delete a alert rule
- func (a *Alert) Delete(alert *models.AlarmRule) error {
- cache := getCache()
- key := fmt.Sprintf("Alert:%d", alert.ID)
- if _, ok := cache.Get(key); ok {
- cache.Delete(key)
- }
- return a.db.Delete(alert).Error
- }
- // Update 指定厂商ID
- func (a *Alert) Update(vendorid uint, alert *models.AlarmRule) (data models.AlarmRule, err error) {
- cache := getCache()
- key := fmt.Sprintf("Alert:%d", alert.ID)
- if _, ok := cache.Get(key); ok {
- cache.Delete(key)
- }
- err = a.db.Model(&data).Update(alert).Where("vendor_id = ?", vendorid).Error
- if err == nil {
- cache.Set(key, &data)
- }
- return
- }
- // GetRules 获取告警列表
- // vendorid:厂商ID
- // proid:产品ID,可选
- // procalid:协议ID, 可选
- // name: 规则名称,可选,模糊搜索
- func (a *Alert) GetRules(vendorid uint, pi, ps, proid, protocalid int, name string) (datas []models.AlarmRule, total int, err error) {
- tx := a.db.Where("vendor_id = ? and 1=1")
- if proid != 0 {
- tx = tx.Where("product_id = ?")
- }
- if protocalid != 0 {
- tx = tx.Where("protocal_id = ?", protocalid)
- }
- if name != "" {
- tx = tx.Where("alert_name = ?", name)
- }
- err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
- err = tx.Model(&models.AlarmRule{}).Count(&total).Error
- return
- }
- // GetAlarmRule 获取数据内容
- func (a *Alert) GetAlarmRule(vendorid uint, alertid int) (data models.AlarmRule, err error) {
- cache := getCache()
- key := fmt.Sprintf("Alert:%d", alertid)
- if v, ok := cache.Get(key); ok {
- _d := v.(*models.AlarmRule)
- data = *_d
- } else {
- err = a.db.Where("vendor_id = ? and id = ?", vendorid, alertid).First(&data).Error
- if err == nil {
- cache.Set(key, &data)
- }
- }
- return
- }
- // CheckProtocalRuleCount 返回数据点已经添加的告警数量
- func (a *Alert) CheckProtocalRuleCount(vendorid uint, protocalID int) (total int, err error) {
- err = a.db.Model(&models.AlarmRule{}).
- Where("vendor_id = ? and protocal_id = ?", vendorid, protocalID).
- Count(&total).
- Error
- return
- }
|