dataproxy.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package api
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/grafana/grafana/pkg/api/pluginproxy"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/metrics"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/plugins"
  10. )
  11. const HeaderNameNoBackendCache = "X-Grafana-NoCache"
  12. func (hs *HTTPServer) getDatasourceFromCache(id int64, c *m.ReqContext) (*m.DataSource, error) {
  13. nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
  14. cacheKey := fmt.Sprintf("ds-%d", id)
  15. if !nocache {
  16. if cached, found := hs.cache.Get(cacheKey); found {
  17. ds := cached.(*m.DataSource)
  18. if ds.OrgId == c.OrgId {
  19. return ds, nil
  20. }
  21. }
  22. }
  23. query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
  24. if err := bus.Dispatch(&query); err != nil {
  25. return nil, err
  26. }
  27. hs.cache.Set(cacheKey, query.Result, time.Second*5)
  28. return query.Result, nil
  29. }
  30. func (hs *HTTPServer) ProxyDataSourceRequest(c *m.ReqContext) {
  31. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  32. ds, err := hs.getDatasourceFromCache(c.ParamsInt64(":id"), c)
  33. if err != nil {
  34. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  35. return
  36. }
  37. // find plugin
  38. plugin, ok := plugins.DataSources[ds.Type]
  39. if !ok {
  40. c.JsonApiErr(500, "Unable to find datasource plugin", err)
  41. return
  42. }
  43. // macaron does not include trailing slashes when resolving a wildcard path
  44. proxyPath := ensureProxyPathTrailingSlash(c.Req.URL.Path, c.Params("*"))
  45. proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
  46. proxy.HandleRequest()
  47. }
  48. // ensureProxyPathTrailingSlash Check for a trailing slash in original path and makes
  49. // sure that a trailing slash is added to proxy path, if not already exists.
  50. func ensureProxyPathTrailingSlash(originalPath, proxyPath string) string {
  51. if len(proxyPath) > 1 {
  52. if originalPath[len(originalPath)-1] == '/' && proxyPath[len(proxyPath)-1] != '/' {
  53. return proxyPath + "/"
  54. }
  55. }
  56. return proxyPath
  57. }