From 3aaedf5743775330531ba5f0a7327fe26a66566a Mon Sep 17 00:00:00 2001 From: liugq Date: Wed, 18 May 2022 21:08:53 +0800 Subject: [PATCH] update alert api --- model/alerting/alert.go | 9 +-- plugin/api/alerting/alert.go | 38 ---------- plugin/api/alerting/api.go | 1 + plugin/api/alerting/message.go | 1 + plugin/api/alerting/rule.go | 97 ++++++++++++++++++++---- service/alerting/elasticsearch/engine.go | 4 +- 6 files changed, 90 insertions(+), 60 deletions(-) diff --git a/model/alerting/alert.go b/model/alerting/alert.go index 293ffcd1..8ff4b6d7 100644 --- a/model/alerting/alert.go +++ b/model/alerting/alert.go @@ -42,15 +42,14 @@ type ActionExecutionResult struct { } const ( - AlertStateActive string = "active" - AlertStateAcknowledge = "acknowledged" - AlertStateOK = "normal" + AlertStateAlerting string = "alerting" + AlertStateOK = "ok" AlertStateError = "error" ) const ( - MessageStateActive = "active" - MessageStateIgnored = "ignored" + MessageStateAlerting = "alerting" + MessageStateIgnored = "ignored" MessageStateRecovered = "recovered" ) diff --git a/plugin/api/alerting/alert.go b/plugin/api/alerting/alert.go index a3138561..6e3117fc 100644 --- a/plugin/api/alerting/alert.go +++ b/plugin/api/alerting/alert.go @@ -44,44 +44,6 @@ func (h *AlertAPI) getAlert(w http.ResponseWriter, req *http.Request, ps httprou }, 200) } -func (h *AlertAPI) acknowledgeAlert(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { - body := struct { - AlertIDs []string `json:"ids"` - }{} - err := h.DecodeJSON(req, &body) - if err != nil { - h.WriteError(w, err.Error(), http.StatusInternalServerError) - return - } - - if len(body.AlertIDs) == 0 { - h.WriteError(w, "alert ids should not be empty", http.StatusInternalServerError) - return - } - queryDsl := util.MapStr{ - "query": util.MapStr{ - "terms": util.MapStr{ - "_id": body.AlertIDs, - }, - }, - "script": util.MapStr{ - "source": fmt.Sprintf("ctx._source['state'] = '%s'", alerting.AlertStateAcknowledge), - }, - } - err = orm.UpdateBy(alerting.Alert{}, util.MustToJSONBytes(queryDsl)) - if err != nil { - h.WriteError(w, err.Error(), http.StatusInternalServerError) - log.Error(err) - return - } - - h.WriteJSON(w, util.MapStr{ - "ids": body.AlertIDs, - "result": "updated", - }, 200) -} - - func (h *AlertAPI) searchAlert(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { var ( diff --git a/plugin/api/alerting/api.go b/plugin/api/alerting/api.go index d2f2a0df..005d13fb 100644 --- a/plugin/api/alerting/api.go +++ b/plugin/api/alerting/api.go @@ -26,6 +26,7 @@ func (alert *AlertAPI) Init() { api.HandleAPIMethod(api.POST, "/alerting/rule/info", alert.fetchAlertInfos) api.HandleAPIMethod(api.POST, "/alerting/rule/:rule_id/_enable", alert.enableRule) api.HandleAPIMethod(api.GET, "/alerting/rule/:rule_id/metric", alert.getMetricData) + api.HandleAPIMethod(api.GET, "/alerting/rule/:rule_id/info", alert.getRuleDetail) api.HandleAPIMethod(api.GET, "/alerting/channel/:channel_id", alert.getChannel) api.HandleAPIMethod(api.POST, "/alerting/channel", alert.createChannel) diff --git a/plugin/api/alerting/message.go b/plugin/api/alerting/message.go index a06feb74..da592566 100644 --- a/plugin/api/alerting/message.go +++ b/plugin/api/alerting/message.go @@ -240,6 +240,7 @@ func (h *AlertAPI) getAlertMessage(w http.ResponseWriter, req *http.Request, ps "resource_object": rule.Resource.Objects, "condition_expressions": conditionExpressions, "duration": duration.Milliseconds(), + "status": message.Status, } h.WriteJSON(w, detailObj, http.StatusOK) } \ No newline at end of file diff --git a/plugin/api/alerting/rule.go b/plugin/api/alerting/rule.go index 98da1348..18498c9b 100644 --- a/plugin/api/alerting/rule.go +++ b/plugin/api/alerting/rule.go @@ -90,7 +90,6 @@ func (alertAPI *AlertAPI) createRule(w http.ResponseWriter, req *http.Request, p } func (alertAPI *AlertAPI) getRule(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { id := ps.MustGetParameter("rule_id") - obj := alerting.Rule{} obj.ID = id @@ -103,12 +102,6 @@ func (alertAPI *AlertAPI) getRule(w http.ResponseWriter, req *http.Request, ps h }, http.StatusNotFound) return } - if err != nil { - log.Error(err) - alertAPI.WriteError(w, err.Error(), http.StatusInternalServerError) - log.Error(err) - return - } alertAPI.WriteJSON(w, util.MapStr{ "found": true, @@ -118,6 +111,85 @@ func (alertAPI *AlertAPI) getRule(w http.ResponseWriter, req *http.Request, ps h } +func (alertAPI *AlertAPI) getRuleDetail(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { + id := ps.MustGetParameter("rule_id") + obj := alerting.Rule{} + obj.ID = id + + exists, err := orm.Get(&obj) + if !exists || err != nil { + log.Error(err) + alertAPI.WriteJSON(w, util.MapStr{ + "_id": id, + "found": false, + }, http.StatusNotFound) + return + } + conditionExpressions := make([]string, 0, len(obj.Conditions.Items)) + metricExpression, _ := obj.Metrics.GenerateExpression() + for _, cond := range obj.Conditions.Items { + expression, _ := cond.GenerateConditionExpression() + conditionExpressions = append(conditionExpressions, strings.ReplaceAll(expression, "result", metricExpression)) + } + alertNumbers, err := alertAPI.getRuleAlertMessageNumbers([]string{obj.ID}) + if err != nil { + log.Error(err) + alertAPI.WriteJSON(w, util.MapStr{ + "error": err.Error(), + }, http.StatusInternalServerError) + return + } + queryDSL := util.MapStr{ + "_source": "state", + "size": 1, + "sort": []util.MapStr{ + { + "created": util.MapStr{ + "order": "desc", + }, + }, + }, + "query": util.MapStr{ + "term": util.MapStr{ + "rule_id": util.MapStr{ + "value": obj.ID, + }, + }, + }, + } + q := &orm.Query{ + WildcardIndex: true, + RawQuery: util.MustToJSONBytes(queryDSL), + } + err, result := orm.Search(alerting.Alert{}, q) + if err != nil { + log.Error(err) + alertAPI.WriteJSON(w, util.MapStr{ + "error": err.Error(), + }, http.StatusInternalServerError) + return + } + var state interface{} = "N/A" + if len(result.Result) > 0 { + if resultM, ok := result.Result[0].(map[string]interface{}); ok { + state = resultM["state"] + } + } + + detailObj := util.MapStr{ + "resource_name": obj.Resource.Name, + "resource_objects": obj.Resource.Objects, + "period_interval": obj.Metrics.PeriodInterval, + "updated": obj.Updated, + "condition_expressions": conditionExpressions, + "message_count": alertNumbers[obj.ID], + "state": state, + } + + alertAPI.WriteJSON(w, detailObj, 200) + +} + func (alertAPI *AlertAPI) updateRule(w http.ResponseWriter, req *http.Request, ps httprouter.Params) { id := ps.MustGetParameter("rule_id") obj := &alerting.Rule{} @@ -288,7 +360,7 @@ func (alertAPI *AlertAPI) searchRule(w http.ResponseWriter, req *http.Request, p w.Write(searchResult.Raw) } -func (alertAPI *AlertAPI) getRuleAlertNumbers(ruleIDs []string) ( map[string]interface{},error) { +func (alertAPI *AlertAPI) getRuleAlertMessageNumbers(ruleIDs []string) ( map[string]interface{},error) { esClient := elastic.GetClient(alertAPI.Config.Elasticsearch) queryDsl := util.MapStr{ "size": 0, @@ -300,11 +372,6 @@ func (alertAPI *AlertAPI) getRuleAlertNumbers(ruleIDs []string) ( map[string]int "rule_id": ruleIDs, }, }, - { - "terms": util.MapStr{ - "state": []string{alerting.AlertStateError, alerting.AlertStateActive}, - }, - }, }, }, }, @@ -317,7 +384,7 @@ func (alertAPI *AlertAPI) getRuleAlertNumbers(ruleIDs []string) ( map[string]int }, } - searchRes, err := esClient.SearchWithRawQueryDSL(orm.GetWildcardIndexName(alerting.Alert{}), util.MustToJSONBytes(queryDsl) ) + searchRes, err := esClient.SearchWithRawQueryDSL(orm.GetWildcardIndexName(alerting.AlertMessage{}), util.MustToJSONBytes(queryDsl) ) if err != nil { return nil, err } @@ -372,7 +439,7 @@ func (alertAPI *AlertAPI) fetchAlertInfos(w http.ResponseWriter, req *http.Reque alertAPI.WriteJSON(w, util.MapStr{}, http.StatusOK) return } - alertNumbers, err := alertAPI.getRuleAlertNumbers(ruleIDs) + alertNumbers, err := alertAPI.getRuleAlertMessageNumbers(ruleIDs) if err != nil { log.Error(err) alertAPI.WriteJSON(w, util.MapStr{ diff --git a/service/alerting/elasticsearch/engine.go b/service/alerting/elasticsearch/engine.go index c39e8d4b..4fac2a4d 100644 --- a/service/alerting/elasticsearch/engine.go +++ b/service/alerting/elasticsearch/engine.go @@ -629,14 +629,14 @@ func (engine *Engine) Do(rule *alerting.Rule) error { alertItem.Severity = severity alertItem.Message = message alertItem.Title = title - alertItem.State = alerting.AlertStateActive + alertItem.State = alerting.AlertStateAlerting if alertMessage == nil || alertMessage.Status == alerting.MessageStateRecovered { msg := &alerting.AlertMessage{ RuleID: rule.ID, Created: time.Now(), Updated: time.Now(), ID: util.GetUUID(), - Status: alerting.MessageStateActive, + Status: alerting.MessageStateAlerting, Severity: severity, Title: title, Message: message,