db.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package monitor
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/pkg/errors"
  6. "go-common/app/job/main/aegis/model/monitor"
  7. xsql "go-common/library/database/sql"
  8. "go-common/library/log"
  9. "time"
  10. )
  11. const (
  12. _rulesByBid = "SELECT id,type,bid,name,state,stime,etime,rule,uid,ctime,mtime FROM monitor_rule WHERE bid = ? AND state = 1 AND stime < ? AND etime > ?"
  13. _allValidRules = "SELECT id,type,bid,name,state,stime,etime,rule,uid,ctime,mtime FROM monitor_rule WHERE state = 1 AND stime < ? AND etime > ?"
  14. )
  15. // RulesByBid 获取某业务的监控
  16. func (d *Dao) RulesByBid(c context.Context, bid int64) (rules []*monitor.Rule, err error) {
  17. var (
  18. rows *xsql.Rows
  19. now = time.Now()
  20. )
  21. if rows, err = d.db.Query(c, _rulesByBid, bid, now, now); err != nil {
  22. log.Error("d.db.Exec error(%v)", errors.WithStack(err))
  23. return
  24. }
  25. defer rows.Close()
  26. for rows.Next() {
  27. rule := &monitor.Rule{}
  28. var confStr string
  29. if err = rows.Scan(&rule.ID, &rule.Type, &rule.BID, &rule.Name, &rule.State, &rule.STime, &rule.ETime, &confStr, &rule.UID, &rule.CTime, &rule.MTime); err != nil {
  30. log.Error("rows.Scan error(%v)", err)
  31. return
  32. }
  33. conf := &monitor.RuleConf{}
  34. if err = json.Unmarshal([]byte(confStr), conf); err != nil {
  35. log.Error("json.Unmarshal(%s) error(%v)", confStr, err)
  36. return
  37. }
  38. rule.RuleConf = conf
  39. rules = append(rules, rule)
  40. }
  41. return
  42. }
  43. // ValidRules 获取有效的监控
  44. func (d *Dao) ValidRules(c context.Context) (rules []*monitor.Rule, err error) {
  45. var (
  46. rows *xsql.Rows
  47. now = time.Now()
  48. )
  49. if rows, err = d.db.Query(c, _allValidRules, now, now); err != nil {
  50. log.Error("d.db.Exec error(%v)", errors.WithStack(err))
  51. return
  52. }
  53. defer rows.Close()
  54. for rows.Next() {
  55. rule := &monitor.Rule{}
  56. var confStr string
  57. if err = rows.Scan(&rule.ID, &rule.Type, &rule.BID, &rule.Name, &rule.State, &rule.STime, &rule.ETime, &confStr, &rule.UID, &rule.CTime, &rule.MTime); err != nil {
  58. log.Error("rows.Scan error(%v)", err)
  59. return
  60. }
  61. conf := &monitor.RuleConf{}
  62. if err = json.Unmarshal([]byte(confStr), conf); err != nil {
  63. log.Error("json.Unmarshal(%s) error(%v)", confStr, err)
  64. return
  65. }
  66. rule.RuleConf = conf
  67. rules = append(rules, rule)
  68. }
  69. return
  70. }