Skip to content

Commit

Permalink
Add prometheus query api
Browse files Browse the repository at this point in the history
  • Loading branch information
Cairry committed Jul 22, 2024
1 parent fa5dce8 commit 137ea17
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
38 changes: 36 additions & 2 deletions api/datasource.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
package api

import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io"
middleware "watchAlert/internal/middleware"
"watchAlert/internal/models"
"watchAlert/internal/services"
"watchAlert/pkg/utils/http"
)

type DatasourceController struct{}

/*
数据源 API
/api/w8t/datasource
数据源 API
/api/w8t/datasource
*/
func (dc DatasourceController) API(gin *gin.RouterGroup) {
datasourceA := gin.Group("datasource")
Expand All @@ -37,6 +41,7 @@ func (dc DatasourceController) API(gin *gin.RouterGroup) {
datasourceB.GET("dataSourceList", dc.List)
datasourceB.GET("dataSourceGet", dc.Get)
datasourceB.GET("dataSourceSearch", dc.Search)
datasourceB.GET("promQuery", dc.PromQuery)
}

}
Expand Down Expand Up @@ -112,3 +117,32 @@ func (dc DatasourceController) Delete(ctx *gin.Context) {
return services.DatasourceService.Delete(r)
})
}

func (dc DatasourceController) PromQuery(ctx *gin.Context) {
r := new(models.PromQueryReq)
BindQuery(ctx, r)

Service(ctx, func() (interface{}, interface{}) {
var res models.PromQueryRes
path := "/api/v1/query"
if r.DatasourceType == "VictoriaMetrics" {
path = "/prometheus" + path
}
get, err := http.Get(fmt.Sprintf("%s%s?query=%s", r.Addr, path, r.Query))
if err != nil {
return nil, err
}

all, err := io.ReadAll(get.Body)
if err != nil {
return nil, err
}

err = json.Unmarshal(all, &res)
if err != nil {
return nil, err
}

return res, nil
})
}
20 changes: 20 additions & 0 deletions internal/models/datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,23 @@ func (ds AlertDataSource) CheckHealth() (bool, error) {

return true, nil
}

type PromQueryReq struct {
DatasourceType string `json:"datasourceType"`
Addr string `form:"addr"`
Query string `form:"query"`
}

type PromQueryRes struct {
Data data `json:"data"`
}

type data struct {
Result []result `json:"result"`
ResultType string `json:"resultType"`
}

type result struct {
Metric map[string]interface{} `json:"metric"`
Value []interface{} `json:"value"`
}
4 changes: 4 additions & 0 deletions internal/models/user_permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,5 +287,9 @@ func PermissionsInfo() map[string]UserPermissions {
Key: "获取系统配置",
API: "/api/w8t/setting/getSystemSetting",
},
"promQuery": {
Key: "Prometheus指标查询",
API: "/api/w8t/datasource/promQuery",
},
}
}

0 comments on commit 137ea17

Please sign in to comment.