extractor.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. 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. als, err := e.GetAlertFromPanels(panel)
  69. if err != nil {
  70. return nil, err
  71. }
  72. alerts = append(alerts, als...)
  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, fmt.Errorf("panel id is required. err %v", err)
  82. }
  83. // backward compatibility check, can be removed later
  84. enabled, hasEnabled := jsonAlert.CheckGet("enabled")
  85. if hasEnabled && enabled.MustBool() == false {
  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. if datasource, err := e.lookupDatasourceId(dsName); err != nil {
  118. return nil, err
  119. } else {
  120. jsonQuery.SetPath([]string{"datasourceId"}, datasource.Id)
  121. }
  122. if interval, err := panel.Get("interval").String(); err == nil {
  123. panelQuery.Set("interval", interval)
  124. }
  125. jsonQuery.Set("model", panelQuery.Interface())
  126. }
  127. alert.Settings = jsonAlert
  128. // validate
  129. _, err = NewRuleFromDBAlert(alert)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if alert.ValidToSave() {
  134. alerts = append(alerts, alert)
  135. } else {
  136. e.log.Debug("Invalid Alert Data. Dashboard, Org or Panel ID is not correct", "alertName", alert.Name, "panelId", alert.PanelId)
  137. return nil, m.ErrDashboardContainsInvalidAlertData
  138. }
  139. }
  140. return alerts, nil
  141. }
  142. func (e *DashAlertExtractor) GetAlerts() ([]*m.Alert, error) {
  143. e.log.Debug("GetAlerts")
  144. dashboardJson, err := copyJson(e.Dash.Data)
  145. if err != nil {
  146. return nil, err
  147. }
  148. alerts := make([]*m.Alert, 0)
  149. // We extract alerts from rows to be backwards compatible
  150. // with the old dashboard json model.
  151. rows := dashboardJson.Get("rows").MustArray()
  152. if len(rows) > 0 {
  153. for _, rowObj := range rows {
  154. row := simplejson.NewFromAny(rowObj)
  155. a, err := e.GetAlertFromPanels(row)
  156. if err != nil {
  157. return nil, err
  158. }
  159. alerts = append(alerts, a...)
  160. }
  161. } else {
  162. a, err := e.GetAlertFromPanels(dashboardJson)
  163. if err != nil {
  164. return nil, err
  165. }
  166. alerts = append(alerts, a...)
  167. }
  168. e.log.Debug("Extracted alerts from dashboard", "alertCount", len(alerts))
  169. return alerts, nil
  170. }