dataproxy.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. "github.com/grafana/grafana/pkg/middleware"
  9. m "github.com/grafana/grafana/pkg/models"
  10. "github.com/grafana/grafana/pkg/plugins"
  11. )
  12. const HeaderNameNoBackendCache = "X-Grafana-NoCache"
  13. func (hs *HttpServer) getDatasourceById(id int64, orgId int64, nocache bool) (*m.DataSource, error) {
  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 == orgId {
  19. return ds, nil
  20. }
  21. }
  22. }
  23. query := m.GetDataSourceByIdQuery{Id: id, OrgId: 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 *middleware.Context) {
  31. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  32. nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
  33. ds, err := hs.getDatasourceById(c.ParamsInt64(":id"), c.OrgId, nocache)
  34. if err != nil {
  35. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  36. return
  37. }
  38. // find plugin
  39. plugin, ok := plugins.DataSources[ds.Type]
  40. if !ok {
  41. c.JsonApiErr(500, "Unable to find datasource plugin", err)
  42. return
  43. }
  44. proxyPath := c.Params("*")
  45. proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
  46. proxy.HandleRequest()
  47. }