grafana/pkg/api/dataproxy.go

68 lines
1.7 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"
func (hs *HTTPServer) getDatasourceFromCache(id int64, c *m.ReqContext) (*m.DataSource, error) {
nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
cacheKey := fmt.Sprintf("ds-%d", id)
if !nocache {
if cached, found := hs.cache.Get(cacheKey); found {
ds := cached.(*m.DataSource)
if ds.OrgId == c.OrgId {
return ds, nil
}
}
}
query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.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)
ds, err := hs.getDatasourceFromCache(c.ParamsInt64(":id"), c)
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
2018-09-20 01:02:04 +08:00
// Check for a trailing slash, and pass it to the proxy
// macaron does not include trailing slashes when resolving a wildcard path
2018-09-19 02:16:09 +08:00
if len(proxyPath) > 1 {
path := c.Req.URL.Path
2018-09-20 01:02:04 +08:00
if path[len(path)-1] == '/' && proxyPath[len(proxyPath)-1] != '/' {
2018-09-19 02:16:09 +08:00
proxyPath += "/"
}
}
proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
proxy.HandleRequest()
}