extractor.go 6.5 KB

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