extractor.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package alerting
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. "github.com/grafana/grafana/pkg/log"
  8. m "github.com/grafana/grafana/pkg/models"
  9. )
  10. type DashAlertExtractor struct {
  11. Dash *m.Dashboard
  12. OrgId int64
  13. log log.Logger
  14. }
  15. func NewDashAlertExtractor(dash *m.Dashboard, orgId int64) *DashAlertExtractor {
  16. return &DashAlertExtractor{
  17. Dash: dash,
  18. OrgId: orgId,
  19. log: log.New("alerting.extractor"),
  20. }
  21. }
  22. func (e *DashAlertExtractor) lookupDatasourceId(dsName string) (*m.DataSource, error) {
  23. if dsName == "" {
  24. query := &m.GetDataSourcesQuery{OrgId: e.OrgId}
  25. if err := bus.Dispatch(query); err != nil {
  26. return nil, err
  27. } else {
  28. for _, ds := range query.Result {
  29. if ds.IsDefault {
  30. return ds, nil
  31. }
  32. }
  33. }
  34. } else {
  35. query := &m.GetDataSourceByNameQuery{Name: dsName, OrgId: e.OrgId}
  36. if err := bus.Dispatch(query); err != nil {
  37. return nil, err
  38. } else {
  39. return query.Result, nil
  40. }
  41. }
  42. return nil, errors.New("Could not find datasource id for " + dsName)
  43. }
  44. func findPanelQueryByRefId(panel *simplejson.Json, refId string) *simplejson.Json {
  45. for _, targetsObj := range panel.Get("targets").MustArray() {
  46. target := simplejson.NewFromAny(targetsObj)
  47. if target.Get("refId").MustString() == refId {
  48. return target
  49. }
  50. }
  51. return nil
  52. }
  53. func copyJson(in *simplejson.Json) (*simplejson.Json, error) {
  54. rawJson, err := in.MarshalJSON()
  55. if err != nil {
  56. return nil, err
  57. }
  58. return simplejson.NewJson(rawJson)
  59. }
  60. func (e *DashAlertExtractor) GetAlertFromPanels(jsonWithPanels *simplejson.Json) ([]*m.Alert, error) {
  61. alerts := make([]*m.Alert, 0)
  62. for _, panelObj := range jsonWithPanels.Get("panels").MustArray() {
  63. panel := simplejson.NewFromAny(panelObj)
  64. jsonAlert, hasAlert := panel.CheckGet("alert")
  65. if !hasAlert {
  66. continue
  67. }
  68. panelId, err := panel.Get("id").Int64()
  69. if err != nil {
  70. return nil, fmt.Errorf("panel id is required. err %v", err)
  71. }
  72. // backward compatibility check, can be removed later
  73. enabled, hasEnabled := jsonAlert.CheckGet("enabled")
  74. if hasEnabled && enabled.MustBool() == false {
  75. continue
  76. }
  77. frequency, err := getTimeDurationStringToSeconds(jsonAlert.Get("frequency").MustString())
  78. if err != nil {
  79. return nil, ValidationError{Reason: "Could not parse frequency"}
  80. }
  81. alert := &m.Alert{
  82. DashboardId: e.Dash.Id,
  83. OrgId: e.OrgId,
  84. PanelId: panelId,
  85. Id: jsonAlert.Get("id").MustInt64(),
  86. Name: jsonAlert.Get("name").MustString(),
  87. Handler: jsonAlert.Get("handler").MustInt64(),
  88. Message: jsonAlert.Get("message").MustString(),
  89. Frequency: frequency,
  90. }
  91. for _, condition := range jsonAlert.Get("conditions").MustArray() {
  92. jsonCondition := simplejson.NewFromAny(condition)
  93. jsonQuery := jsonCondition.Get("query")
  94. queryRefId := jsonQuery.Get("params").MustArray()[0].(string)
  95. panelQuery := findPanelQueryByRefId(panel, queryRefId)
  96. if panelQuery == nil {
  97. reason := fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found", alert.PanelId, queryRefId)
  98. return nil, ValidationError{Reason: reason}
  99. }
  100. dsName := ""
  101. if panelQuery.Get("datasource").MustString() != "" {
  102. dsName = panelQuery.Get("datasource").MustString()
  103. } else if panel.Get("datasource").MustString() != "" {
  104. dsName = panel.Get("datasource").MustString()
  105. }
  106. if datasource, err := e.lookupDatasourceId(dsName); err != nil {
  107. return nil, err
  108. } else {
  109. jsonQuery.SetPath([]string{"datasourceId"}, datasource.Id)
  110. }
  111. if interval, err := panel.Get("interval").String(); err == nil {
  112. panelQuery.Set("interval", interval)
  113. }
  114. jsonQuery.Set("model", panelQuery.Interface())
  115. }
  116. alert.Settings = jsonAlert
  117. // validate
  118. _, err = NewRuleFromDBAlert(alert)
  119. if err == nil && alert.ValidToSave() {
  120. alerts = append(alerts, alert)
  121. } else {
  122. return nil, err
  123. }
  124. }
  125. return alerts, nil
  126. }
  127. func (e *DashAlertExtractor) GetAlerts() ([]*m.Alert, error) {
  128. e.log.Debug("GetAlerts")
  129. dashboardJson, err := copyJson(e.Dash.Data)
  130. if err != nil {
  131. return nil, err
  132. }
  133. alerts := make([]*m.Alert, 0)
  134. // We extract alerts from rows to be backwards compatible
  135. // with the old dashboard json model.
  136. rows := dashboardJson.Get("rows").MustArray()
  137. if len(rows) > 0 {
  138. for _, rowObj := range rows {
  139. row := simplejson.NewFromAny(rowObj)
  140. a, err := e.GetAlertFromPanels(row)
  141. if err != nil {
  142. return nil, err
  143. }
  144. alerts = append(alerts, a...)
  145. }
  146. } else {
  147. a, err := e.GetAlertFromPanels(dashboardJson)
  148. if err != nil {
  149. return nil, err
  150. }
  151. alerts = append(alerts, a...)
  152. }
  153. e.log.Debug("Extracted alerts from dashboard", "alertCount", len(alerts))
  154. return alerts, nil
  155. }