extractor.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. // DashAlertExtractor extracts alerts from the dashboard json
  11. type DashAlertExtractor struct {
  12. Dash *m.Dashboard
  13. OrgID int64
  14. log log.Logger
  15. }
  16. // NewDashAlertExtractor returns a new DashAlertExtractor
  17. func NewDashAlertExtractor(dash *m.Dashboard, orgID int64) *DashAlertExtractor {
  18. return &DashAlertExtractor{
  19. Dash: dash,
  20. OrgID: orgID,
  21. log: log.New("alerting.extractor"),
  22. }
  23. }
  24. func (e *DashAlertExtractor) lookupDatasourceID(dsName string) (*m.DataSource, error) {
  25. if dsName == "" {
  26. query := &m.GetDataSourcesQuery{OrgId: e.OrgID}
  27. if err := bus.Dispatch(query); err != nil {
  28. return nil, err
  29. }
  30. for _, ds := range query.Result {
  31. if ds.IsDefault {
  32. return ds, nil
  33. }
  34. }
  35. } else {
  36. query := &m.GetDataSourceByNameQuery{Name: dsName, OrgId: e.OrgID}
  37. if err := bus.Dispatch(query); err != nil {
  38. return nil, err
  39. }
  40. return query.Result, nil
  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, validateAlertFunc func(*m.Alert) bool) ([]*m.Alert, error) {
  61. alerts := make([]*m.Alert, 0)
  62. for _, panelObj := range jsonWithPanels.Get("panels").MustArray() {
  63. panel := simplejson.NewFromAny(panelObj)
  64. collapsedJSON, collapsed := panel.CheckGet("collapsed")
  65. // check if the panel is collapsed
  66. if collapsed && collapsedJSON.MustBool() {
  67. // extract alerts from sub panels for collapsed panels
  68. alertSlice, err := e.getAlertFromPanels(panel, validateAlertFunc)
  69. if err != nil {
  70. return nil, err
  71. }
  72. alerts = append(alerts, alertSlice...)
  73. continue
  74. }
  75. jsonAlert, hasAlert := panel.CheckGet("alert")
  76. if !hasAlert {
  77. continue
  78. }
  79. panelID, err := panel.Get("id").Int64()
  80. if err != nil {
  81. return nil, ValidationError{Reason: "A numeric panel id property is missing"}
  82. }
  83. // backward compatibility check, can be removed later
  84. enabled, hasEnabled := jsonAlert.CheckGet("enabled")
  85. if hasEnabled && !enabled.MustBool() {
  86. continue
  87. }
  88. frequency, err := getTimeDurationStringToSeconds(jsonAlert.Get("frequency").MustString())
  89. if err != nil {
  90. return nil, ValidationError{Reason: "Could not parse frequency"}
  91. }
  92. alert := &m.Alert{
  93. DashboardId: e.Dash.Id,
  94. OrgId: e.OrgID,
  95. PanelId: panelID,
  96. Id: jsonAlert.Get("id").MustInt64(),
  97. Name: jsonAlert.Get("name").MustString(),
  98. Handler: jsonAlert.Get("handler").MustInt64(),
  99. Message: jsonAlert.Get("message").MustString(),
  100. Frequency: frequency,
  101. }
  102. for _, condition := range jsonAlert.Get("conditions").MustArray() {
  103. jsonCondition := simplejson.NewFromAny(condition)
  104. jsonQuery := jsonCondition.Get("query")
  105. queryRefID := jsonQuery.Get("params").MustArray()[0].(string)
  106. panelQuery := findPanelQueryByRefID(panel, queryRefID)
  107. if panelQuery == nil {
  108. reason := fmt.Sprintf("Alert on PanelId: %v refers to query(%s) that cannot be found", alert.PanelId, queryRefID)
  109. return nil, ValidationError{Reason: reason}
  110. }
  111. dsName := ""
  112. if panelQuery.Get("datasource").MustString() != "" {
  113. dsName = panelQuery.Get("datasource").MustString()
  114. } else if panel.Get("datasource").MustString() != "" {
  115. dsName = panel.Get("datasource").MustString()
  116. }
  117. datasource, err := e.lookupDatasourceID(dsName)
  118. if err != nil {
  119. e.log.Debug("Error looking up datasource", "error", err)
  120. return nil, ValidationError{Reason: fmt.Sprintf("Data source used by alert rule not found, alertName=%v, datasource=%s", alert.Name, dsName)}
  121. }
  122. jsonQuery.SetPath([]string{"datasourceId"}, datasource.Id)
  123. if interval, err := panel.Get("interval").String(); err == nil {
  124. panelQuery.Set("interval", interval)
  125. }
  126. jsonQuery.Set("model", panelQuery.Interface())
  127. }
  128. alert.Settings = jsonAlert
  129. // validate
  130. _, err = NewRuleFromDBAlert(alert)
  131. if err != nil {
  132. return nil, err
  133. }
  134. if !validateAlertFunc(alert) {
  135. return nil, ValidationError{Reason: fmt.Sprintf("Panel id is not correct, alertName=%v, panelId=%v", alert.Name, alert.PanelId)}
  136. }
  137. alerts = append(alerts, alert)
  138. }
  139. return alerts, nil
  140. }
  141. func validateAlertRule(alert *m.Alert) bool {
  142. return alert.ValidToSave()
  143. }
  144. // GetAlerts extracts alerts from the dashboard json and does full validation on the alert json data
  145. func (e *DashAlertExtractor) GetAlerts() ([]*m.Alert, error) {
  146. return e.extractAlerts(validateAlertRule)
  147. }
  148. func (e *DashAlertExtractor) extractAlerts(validateFunc func(alert *m.Alert) bool) ([]*m.Alert, error) {
  149. dashboardJSON, err := copyJSON(e.Dash.Data)
  150. if err != nil {
  151. return nil, err
  152. }
  153. alerts := make([]*m.Alert, 0)
  154. // We extract alerts from rows to be backwards compatible
  155. // with the old dashboard json model.
  156. rows := dashboardJSON.Get("rows").MustArray()
  157. if len(rows) > 0 {
  158. for _, rowObj := range rows {
  159. row := simplejson.NewFromAny(rowObj)
  160. a, err := e.getAlertFromPanels(row, validateFunc)
  161. if err != nil {
  162. return nil, err
  163. }
  164. alerts = append(alerts, a...)
  165. }
  166. } else {
  167. a, err := e.getAlertFromPanels(dashboardJSON, validateFunc)
  168. if err != nil {
  169. return nil, err
  170. }
  171. alerts = append(alerts, a...)
  172. }
  173. e.log.Debug("Extracted alerts from dashboard", "alertCount", len(alerts))
  174. return alerts, nil
  175. }
  176. // ValidateAlerts validates alerts in the dashboard json but does not require a valid dashboard id
  177. // in the first validation pass
  178. func (e *DashAlertExtractor) ValidateAlerts() error {
  179. _, err := e.extractAlerts(func(alert *m.Alert) bool { return alert.OrgId != 0 && alert.PanelId != 0 })
  180. return err
  181. }