Merge pull request 'add elastic status overview api' (#34) from status_overview_api into master

This commit is contained in:
silenceqi 2023-03-16 10:56:30 +08:00
commit 157fc43ee8
2 changed files with 54 additions and 0 deletions

View File

@ -233,3 +233,56 @@ func (handler APIHandler) getLastActiveHostCount() (int, error){
return len(searchRes.Aggregations["week_active_host"].Buckets), nil
}
func (handler APIHandler) ElasticsearchStatusSummaryAction(w http.ResponseWriter, req *http.Request, ps httprouter.Params){
clusterGrp, err := handler.getGroupMetric(orm.GetIndexName(elastic.ElasticsearchConfig{}), "labels.health_status")
if err != nil {
log.Error(err)
handler.WriteError(w, err.Error(), http.StatusInternalServerError)
return
}
nodeGrp, err := handler.getGroupMetric(orm.GetIndexName(elastic.NodeConfig{}), "metadata.labels.status")
if err != nil {
log.Error(err)
handler.WriteError(w, err.Error(), http.StatusInternalServerError)
return
}
hostCount, err := handler.getMetricCount(orm.GetIndexName(elastic.NodeConfig{}), "metadata.host", nil)
if err != nil {
log.Error(err)
handler.WriteError(w, err.Error(), http.StatusInternalServerError)
return
}
handler.WriteJSON(w, util.MapStr{
"cluster": clusterGrp,
"node": nodeGrp,
"host": util.MapStr{
"online": hostCount,
},
}, http.StatusOK)
}
func (handler APIHandler) getGroupMetric(indexName, field string) (interface{}, error){
client := elastic.GetClient(global.MustLookupString(elastic.GlobalSystemElasticsearchID))
queryDSL := util.MapStr{
"size": 0,
"aggs": util.MapStr{
"group": util.MapStr{
"terms": util.MapStr{
"field": field,
},
},
},
}
searchRes, err := client.SearchWithRawQueryDSL(indexName, util.MustToJSONBytes(queryDSL))
if err != nil {
log.Error(err)
return 0, err
}
groups := map[string]interface{}{}
for _, bk := range searchRes.Aggregations["group"].Buckets {
if key, ok := bk["key"].(string); ok {
groups[key] = bk["doc_count"]
}
}
return groups, nil
}

View File

@ -49,6 +49,7 @@ func Init(cfg *config.AppConfig) {
api.HandleAPIMethod(api.PUT, path.Join(pathPrefix, "elasticsearch/command/:cid"), handler.RequirePermission(handler.HandleSaveCommonCommandAction, enum.PermissionCommandWrite))
api.HandleAPIMethod(api.GET, path.Join(pathPrefix, "elasticsearch/command"), handler.RequirePermission(handler.HandleQueryCommonCommandAction, enum.PermissionCommandRead))
api.HandleAPIMethod(api.DELETE, path.Join(pathPrefix, "elasticsearch/command/:cid"), handler.RequirePermission(handler.HandleDeleteCommonCommandAction,enum.PermissionCommandWrite))
api.HandleAPIMethod(api.GET, "/elasticsearch/overview/status", handler.RequireLogin(handler.ElasticsearchStatusSummaryAction))
//task.RegisterScheduleTask(task.ScheduleTask{
// Description: "sync reindex task result",