grafana/pkg/api/alerting.go

343 lines
8.6 KiB
Go
Raw Normal View History

package api
import (
"fmt"
"strconv"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/search"
)
2018-03-07 10:54:50 -06:00
func ValidateOrgAlert(c *m.ReqContext) {
id := c.ParamsInt64(":alertId")
query := m.GetAlertByIdQuery{Id: id}
if err := bus.Dispatch(&query); err != nil {
c.JsonApiErr(404, "Alert not found", nil)
return
}
if c.OrgId != query.Result.OrgId {
c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
return
}
}
2018-03-07 10:54:50 -06:00
func GetAlertStatesForDashboard(c *m.ReqContext) Response {
2018-03-22 06:37:35 -05:00
dashboardID := c.QueryInt64("dashboardId")
2018-03-22 06:37:35 -05:00
if dashboardID == 0 {
2018-03-22 16:13:46 -05:00
return Error(400, "Missing query parameter dashboardId", nil)
}
query := m.GetAlertStatesForDashboardQuery{
OrgId: c.OrgId,
DashboardId: c.QueryInt64("dashboardId"),
}
if err := bus.Dispatch(&query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to fetch alert states", err)
}
2018-03-22 16:13:46 -05:00
return JSON(200, query.Result)
}
// GET /api/alerts
2018-03-07 10:54:50 -06:00
func GetAlerts(c *m.ReqContext) Response {
dashboardQuery := c.Query("dashboardQuery")
dashboardTags := c.QueryStrings("dashboardTag")
stringDashboardIDs := c.QueryStrings("dashboardId")
stringFolderIDs := c.QueryStrings("folderId")
dashboardIDs := make([]int64, 0)
for _, id := range stringDashboardIDs {
dashboardID, err := strconv.ParseInt(id, 10, 64)
if err == nil {
dashboardIDs = append(dashboardIDs, dashboardID)
}
}
if dashboardQuery != "" || len(dashboardTags) > 0 || len(stringFolderIDs) > 0 {
folderIDs := make([]int64, 0)
for _, id := range stringFolderIDs {
folderID, err := strconv.ParseInt(id, 10, 64)
if err == nil {
folderIDs = append(folderIDs, folderID)
}
}
searchQuery := search.Query{
Title: dashboardQuery,
Tags: dashboardTags,
SignedInUser: c.SignedInUser,
Limit: 1000,
OrgId: c.OrgId,
DashboardIds: dashboardIDs,
Type: string(search.DashHitDB),
FolderIds: folderIDs,
Permission: m.PERMISSION_VIEW,
}
err := bus.Dispatch(&searchQuery)
if err != nil {
return Error(500, "List alerts failed", err)
}
for _, d := range searchQuery.Result {
if d.Type == search.DashHitDB && d.Id > 0 {
dashboardIDs = append(dashboardIDs, d.Id)
}
}
// if we didn't find any dashboards, return empty result
if len(dashboardIDs) == 0 {
return JSON(200, []*m.AlertListItemDTO{})
}
}
query := m.GetAlertsQuery{
OrgId: c.OrgId,
DashboardIDs: dashboardIDs,
PanelId: c.QueryInt64("panelId"),
Limit: c.QueryInt64("limit"),
User: c.SignedInUser,
Query: c.Query("query"),
}
2016-09-14 07:12:19 -05:00
states := c.QueryStrings("state")
if len(states) > 0 {
query.State = states
}
if err := bus.Dispatch(&query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "List alerts failed", err)
}
for _, alert := range query.Result {
alert.Url = m.GetDashboardUrl(alert.DashboardUid, alert.DashboardSlug)
2018-01-31 03:47:31 -06:00
}
2018-03-22 16:13:46 -05:00
return JSON(200, query.Result)
}
// POST /api/alerts/test
2018-03-07 10:54:50 -06:00
func AlertTest(c *m.ReqContext, dto dtos.AlertTestCommand) Response {
if _, idErr := dto.Dashboard.Get("id").Int64(); idErr != nil {
2018-03-22 16:13:46 -05:00
return Error(400, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
}
backendCmd := alerting.AlertTestCommand{
OrgId: c.OrgId,
Dashboard: dto.Dashboard,
PanelId: dto.PanelId,
2018-11-05 07:25:19 -06:00
User: c.SignedInUser,
}
if err := bus.Dispatch(&backendCmd); err != nil {
2016-07-27 09:29:28 -05:00
if validationErr, ok := err.(alerting.ValidationError); ok {
2018-03-22 16:13:46 -05:00
return Error(422, validationErr.Error(), nil)
}
2018-11-05 07:25:19 -06:00
if err == m.ErrDataSourceAccessDenied {
return Error(403, "Access denied to datasource", err)
}
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to test rule", err)
}
res := backendCmd.Result
dtoRes := &dtos.AlertTestResult{
Firing: res.Firing,
ConditionEvals: res.ConditionEvals,
State: res.Rule.State,
}
if res.Error != nil {
dtoRes.Error = res.Error.Error()
}
for _, log := range res.Logs {
dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
}
for _, match := range res.EvalMatches {
dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
}
dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
2018-03-22 16:13:46 -05:00
return JSON(200, dtoRes)
}
// GET /api/alerts/:id
2018-03-07 10:54:50 -06:00
func GetAlert(c *m.ReqContext) Response {
id := c.ParamsInt64(":alertId")
query := m.GetAlertByIdQuery{Id: id}
if err := bus.Dispatch(&query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "List alerts failed", err)
}
2018-03-22 16:13:46 -05:00
return JSON(200, &query.Result)
}
2018-03-07 10:54:50 -06:00
func GetAlertNotifiers(c *m.ReqContext) Response {
2018-03-22 16:13:46 -05:00
return JSON(200, alerting.GetNotifiers())
}
2018-03-07 10:54:50 -06:00
func GetAlertNotifications(c *m.ReqContext) Response {
query := &m.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
if err := bus.Dispatch(query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to get alert notifications", err)
}
2016-11-06 08:40:02 -06:00
result := make([]*dtos.AlertNotification, 0)
for _, notification := range query.Result {
result = append(result, dtos.NewAlertNotification(notification))
}
2018-03-22 16:13:46 -05:00
return JSON(200, result)
}
2018-03-22 06:37:35 -05:00
func GetAlertNotificationByID(c *m.ReqContext) Response {
query := &m.GetAlertNotificationsQuery{
OrgId: c.OrgId,
Id: c.ParamsInt64("notificationId"),
}
if err := bus.Dispatch(query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to get alert notifications", err)
}
if query.Result == nil {
return Error(404, "Alert notification not found", nil)
}
return JSON(200, dtos.NewAlertNotification(query.Result))
}
2018-03-07 10:54:50 -06:00
func CreateAlertNotification(c *m.ReqContext, cmd m.CreateAlertNotificationCommand) Response {
cmd.OrgId = c.OrgId
if err := bus.Dispatch(&cmd); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to create alert notification", err)
}
return JSON(200, dtos.NewAlertNotification(cmd.Result))
}
2018-03-07 10:54:50 -06:00
func UpdateAlertNotification(c *m.ReqContext, cmd m.UpdateAlertNotificationCommand) Response {
cmd.OrgId = c.OrgId
if err := bus.Dispatch(&cmd); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to update alert notification", err)
}
return JSON(200, dtos.NewAlertNotification(cmd.Result))
}
2018-03-07 10:54:50 -06:00
func DeleteAlertNotification(c *m.ReqContext) Response {
cmd := m.DeleteAlertNotificationCommand{
OrgId: c.OrgId,
Id: c.ParamsInt64("notificationId"),
}
if err := bus.Dispatch(&cmd); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to delete alert notification", err)
}
2018-03-22 16:13:46 -05:00
return Success("Notification deleted")
}
//POST /api/alert-notifications/test
2018-03-07 10:54:50 -06:00
func NotificationTest(c *m.ReqContext, dto dtos.NotificationTestCommand) Response {
cmd := &alerting.NotificationTestCommand{
Name: dto.Name,
Type: dto.Type,
Settings: dto.Settings,
}
if err := bus.Dispatch(cmd); err != nil {
if err == m.ErrSmtpNotEnabled {
2018-03-22 16:13:46 -05:00
return Error(412, err.Error(), err)
}
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to send alert notifications", err)
}
2018-03-22 16:13:46 -05:00
return Success("Test notification sent")
}
//POST /api/alerts/:alertId/pause
2018-03-07 10:54:50 -06:00
func PauseAlert(c *m.ReqContext, dto dtos.PauseAlertCommand) Response {
2018-03-22 16:13:46 -05:00
alertID := c.ParamsInt64("alertId")
2018-03-22 16:13:46 -05:00
query := m.GetAlertByIdQuery{Id: alertID}
if err := bus.Dispatch(&query); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Get Alert failed", err)
}
Shouldn't be able to overwrite a dashboard if you don't have permissions (#10900) * dashboards: new command for validating dashboard before update Removes validation logic from saveDashboard and later on use the new command for validating dashboard before saving a dashboard. This due to the fact that we need to validate permissions for overwriting other dashboards by uid and title. * dashboards: use the new command for validating dashboard before saving Had to refactor dashboard provisioning a bit to be able to sidetrack the permission validation in a somewhat reasonable way. Adds some initial tests of the dashboard repository, but needs to be extended later. At least now you can mock the dashboard guardian * dashboards: removes validation logic in the save dashboard api layer Use the dashboard repository solely for create/update dashboards and let it do all the validation. One exception regarding quota validation which still is in api layer since that logic is in a macaron middleware. Need to move out-commented api tests later. * dashboards: fix database tests for validate and saving dashboards * dashboards: rename dashboard repository to dashboard service Split the old dashboard repository interface in two new interfaces, IDashboardService and IDashboardProvisioningService. Makes it more explicit when using it from the provisioning package and there's no possibility of calling an incorrect method for saving a dashboard. * database: make the InitTestDB function available to use from other packages * dashboards: rename ValidateDashboardForUpdateCommand and some refactoring * dashboards: integration tests of dashboard service * dashboard: fix sqlstore test due to folder exist validation * dashboards: move dashboard service integration tests to sqlstore package Had to move it to the sqlstore package due to concurrency problems when running against mysql and postgres. Using InitTestDB from two packages added conflicts when clearing and running migrations on the test database * dashboards: refactor how to find id to be used for save permission check * dashboards: remove duplicated dashboard tests * dashboards: cleanup dashboard service integration tests * dashboards: handle save dashboard errors and return correct http status * fix: remove log statement * dashboards: import dashboard should use dashboard service Had to move alerting commands to models package due to problems with import cycles of packages. * dashboards: cleanup dashboard api tests and add some tests for post dashboard * dashboards: rename dashboard service interfaces * dashboards: rename dashboard guardian interface
2018-02-19 04:12:56 -06:00
guardian := guardian.New(query.Result.DashboardId, c.OrgId, c.SignedInUser)
if canEdit, err := guardian.CanEdit(); err != nil || !canEdit {
if err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Error while checking permissions for Alert", err)
}
2018-03-22 16:13:46 -05:00
return Error(403, "Access denied to this dashboard and alert", nil)
}
cmd := m.PauseAlertCommand{
OrgId: c.OrgId,
2018-03-22 16:13:46 -05:00
AlertIds: []int64{alertID},
Paused: dto.Paused,
}
if err := bus.Dispatch(&cmd); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "", err)
}
var response m.AlertStateType = m.AlertStateUnknown
pausedState := "un-paused"
if cmd.Paused {
response = m.AlertStatePaused
pausedState = "paused"
}
result := map[string]interface{}{
2018-03-22 16:13:46 -05:00
"alertId": alertID,
"state": response,
"message": "Alert " + pausedState,
}
2018-03-22 16:13:46 -05:00
return JSON(200, result)
}
//POST /api/admin/pause-all-alerts
2018-03-07 10:54:50 -06:00
func PauseAllAlerts(c *m.ReqContext, dto dtos.PauseAllAlertsCommand) Response {
updateCmd := m.PauseAllAlertCommand{
2016-12-16 09:07:23 -06:00
Paused: dto.Paused,
}
if err := bus.Dispatch(&updateCmd); err != nil {
2018-03-22 16:13:46 -05:00
return Error(500, "Failed to pause alerts", err)
}
var response m.AlertStateType = m.AlertStatePending
pausedState := "un paused"
if updateCmd.Paused {
response = m.AlertStatePaused
pausedState = "paused"
}
result := map[string]interface{}{
"state": response,
2016-12-19 09:44:59 -06:00
"message": "alerts " + pausedState,
"alertsAffected": updateCmd.ResultCount,
}
2018-03-22 16:13:46 -05:00
return JSON(200, result)
}