dataproxy.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package api
  2. import (
  3. "fmt"
  4. "github.com/pkg/errors"
  5. "time"
  6. "github.com/grafana/grafana/pkg/api/pluginproxy"
  7. "github.com/grafana/grafana/pkg/bus"
  8. "github.com/grafana/grafana/pkg/metrics"
  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) getDatasourceFromCache(id int64, c *m.ReqContext) (*m.DataSource, error) {
  14. userPermissionsQuery := m.GetDataSourcePermissionsForUserQuery{
  15. User: c.SignedInUser,
  16. }
  17. if err := bus.Dispatch(&userPermissionsQuery); err != nil {
  18. if err != bus.ErrHandlerNotFound {
  19. return nil, err
  20. }
  21. } else {
  22. permissionType, exists := userPermissionsQuery.Result[id]
  23. if exists && permissionType != m.DsPermissionQuery {
  24. return nil, errors.New("User not allowed to access datasource")
  25. }
  26. }
  27. nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
  28. cacheKey := fmt.Sprintf("ds-%d", id)
  29. if !nocache {
  30. if cached, found := hs.cache.Get(cacheKey); found {
  31. ds := cached.(*m.DataSource)
  32. if ds.OrgId == c.OrgId {
  33. return ds, nil
  34. }
  35. }
  36. }
  37. query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
  38. if err := bus.Dispatch(&query); err != nil {
  39. return nil, err
  40. }
  41. hs.cache.Set(cacheKey, query.Result, time.Second*5)
  42. return query.Result, nil
  43. }
  44. func (hs *HTTPServer) ProxyDataSourceRequest(c *m.ReqContext) {
  45. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  46. dsId := c.ParamsInt64(":id")
  47. ds, err := hs.getDatasourceFromCache(dsId, c)
  48. hs.log.Debug("We are in the ds proxy", "dsId", dsId)
  49. if err != nil {
  50. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  51. return
  52. }
  53. // find plugin
  54. plugin, ok := plugins.DataSources[ds.Type]
  55. if !ok {
  56. c.JsonApiErr(500, "Unable to find datasource plugin", err)
  57. return
  58. }
  59. // macaron does not include trailing slashes when resolving a wildcard path
  60. proxyPath := ensureProxyPathTrailingSlash(c.Req.URL.Path, c.Params("*"))
  61. proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
  62. proxy.HandleRequest()
  63. }
  64. // ensureProxyPathTrailingSlash Check for a trailing slash in original path and makes
  65. // sure that a trailing slash is added to proxy path, if not already exists.
  66. func ensureProxyPathTrailingSlash(originalPath, proxyPath string) string {
  67. if len(proxyPath) > 1 {
  68. if originalPath[len(originalPath)-1] == '/' && proxyPath[len(proxyPath)-1] != '/' {
  69. return proxyPath + "/"
  70. }
  71. }
  72. return proxyPath
  73. }