extractor.go 6.8 KB

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