grafana/pkg/models/dashboard_queries.go
Jesse Weaver 0371884cdd
Start of dashboard query API (#49547)
This PR adds endpoints for public dashboards to retrieve data from the backend (trusted) query engine. It works by executing queries defined on the backend without any user input and does not support template variables.

* Public dashboard query API
* Create new API on service for building metric request
* Flesh out testing, implement BuildPublicDashboardMetricRequest
* Test for errors and missing panels
* Refactor tests, add supporting code for multiple datasources
* Handle queries from multiple datasources
* Explicitly pass no user for querying public dashboard

Co-authored-by: Jeff Levin <jeff@levinology.com>
2022-06-13 15:23:56 -08:00

50 lines
1.1 KiB
Go

package models
import (
"github.com/grafana/grafana/pkg/components/simplejson"
)
func GetQueriesFromDashboard(dashboard *simplejson.Json) map[int64][]*simplejson.Json {
result := make(map[int64][]*simplejson.Json)
for _, panelObj := range dashboard.Get("panels").MustArray() {
panel := simplejson.NewFromAny(panelObj)
var panelQueries []*simplejson.Json
for _, queryObj := range panel.Get("targets").MustArray() {
query := simplejson.NewFromAny(queryObj)
if _, ok := query.CheckGet("datasource"); !ok {
query.Set("datasource", panel.Get("datasource"))
}
panelQueries = append(panelQueries, query)
}
result[panel.Get("id").MustInt64()] = panelQueries
}
return result
}
func GroupQueriesByDataSource(queries []*simplejson.Json) (result [][]*simplejson.Json) {
byDataSource := make(map[string][]*simplejson.Json)
for _, query := range queries {
dataSourceUid, err := query.GetPath("datasource", "uid").String()
if err != nil {
continue
}
byDataSource[dataSourceUid] = append(byDataSource[dataSourceUid], query)
}
for _, queries := range byDataSource {
result = append(result, queries)
}
return
}