grafana/pkg/api/dataproxy.go

69 lines
1.6 KiB
Go
Raw Normal View History

package api
import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/api/pluginproxy"
2015-02-05 17:37:13 +08:00
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/metrics"
2015-02-05 17:37:13 +08:00
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
)
const HeaderNameNoBackendCache = "X-Grafana-NoCache"
2018-03-23 05:13:46 +08:00
func (hs *HTTPServer) getDatasourceByID(id int64, orgID int64, nocache bool) (*m.DataSource, error) {
cacheKey := fmt.Sprintf("ds-%d", id)
if !nocache {
if cached, found := hs.cache.Get(cacheKey); found {
ds := cached.(*m.DataSource)
2018-03-22 19:37:35 +08:00
if ds.OrgId == orgID {
return ds, nil
}
}
}
2018-03-22 19:37:35 +08:00
query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgID}
if err := bus.Dispatch(&query); err != nil {
2015-10-08 23:30:13 +08:00
return nil, err
}
hs.cache.Set(cacheKey, query.Result, time.Second*5)
return query.Result, nil
2015-10-08 23:30:13 +08:00
}
2018-03-23 05:13:46 +08:00
func (hs *HTTPServer) ProxyDataSourceRequest(c *m.ReqContext) {
c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
2018-03-22 19:37:35 +08:00
ds, err := hs.getDatasourceByID(c.ParamsInt64(":id"), c.OrgId, nocache)
2015-10-08 23:30:13 +08:00
if err != nil {
c.JsonApiErr(500, "Unable to load datasource meta data", err)
return
}
// find plugin
plugin, ok := plugins.DataSources[ds.Type]
if !ok {
c.JsonApiErr(500, "Unable to find datasource plugin", err)
return
}
proxyPath := c.Params("*")
2018-09-19 02:16:09 +08:00
// Check for a trailing slash
if len(proxyPath) > 1 {
path := c.Req.URL.Path
if path[len(path)-1] == '/' && path[len(path)-2] != '/' {
proxyPath += "/"
}
}
proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
proxy.HandleRequest()
}