dataproxy.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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) getDatasourceById(id int64, orgId int64, nocache bool) (*m.DataSource, error) {
  13. cacheKey := fmt.Sprintf("ds-%d", id)
  14. if !nocache {
  15. if cached, found := hs.cache.Get(cacheKey); found {
  16. ds := cached.(*m.DataSource)
  17. if ds.OrgId == orgId {
  18. return ds, nil
  19. }
  20. }
  21. }
  22. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  23. if err := bus.Dispatch(&query); err != nil {
  24. return nil, err
  25. }
  26. hs.cache.Set(cacheKey, query.Result, time.Second*5)
  27. return query.Result, nil
  28. }
  29. func (hs *HttpServer) ProxyDataSourceRequest(c *m.Context) {
  30. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  31. nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
  32. ds, err := hs.getDatasourceById(c.ParamsInt64(":id"), c.OrgId, nocache)
  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. }