dataproxy.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. if err != nil {
  49. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  50. return
  51. }
  52. // find plugin
  53. plugin, ok := plugins.DataSources[ds.Type]
  54. if !ok {
  55. c.JsonApiErr(500, "Unable to find datasource plugin", err)
  56. return
  57. }
  58. // macaron does not include trailing slashes when resolving a wildcard path
  59. proxyPath := ensureProxyPathTrailingSlash(c.Req.URL.Path, c.Params("*"))
  60. proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
  61. proxy.HandleRequest()
  62. }
  63. // ensureProxyPathTrailingSlash Check for a trailing slash in original path and makes
  64. // sure that a trailing slash is added to proxy path, if not already exists.
  65. func ensureProxyPathTrailingSlash(originalPath, proxyPath string) string {
  66. if len(proxyPath) > 1 {
  67. if originalPath[len(originalPath)-1] == '/' && proxyPath[len(proxyPath)-1] != '/' {
  68. return proxyPath + "/"
  69. }
  70. }
  71. return proxyPath
  72. }