dataproxy.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. proxyPath := c.Params("*")
  44. proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
  45. proxy.HandleRequest()
  46. }