dataproxy.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package api
  2. import (
  3. "crypto/tls"
  4. "net"
  5. "net/http"
  6. "net/http/httputil"
  7. "net/url"
  8. "time"
  9. "github.com/grafana/grafana/pkg/bus"
  10. "github.com/grafana/grafana/pkg/middleware"
  11. m "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/util"
  13. )
  14. var dataProxyTransport = &http.Transport{
  15. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  16. Proxy: http.ProxyFromEnvironment,
  17. Dial: (&net.Dialer{
  18. Timeout: 30 * time.Second,
  19. KeepAlive: 30 * time.Second,
  20. }).Dial,
  21. TLSHandshakeTimeout: 10 * time.Second,
  22. }
  23. func NewReverseProxy(ds *m.DataSource, proxyPath string) *httputil.ReverseProxy {
  24. target, _ := url.Parse(ds.Url)
  25. director := func(req *http.Request) {
  26. req.URL.Scheme = target.Scheme
  27. req.URL.Host = target.Host
  28. req.Host = target.Host
  29. reqQueryVals := req.URL.Query()
  30. if ds.Type == m.DS_INFLUXDB_08 {
  31. req.URL.Path = util.JoinUrlFragments(target.Path, "db/"+ds.Database+"/"+proxyPath)
  32. reqQueryVals.Add("u", ds.User)
  33. reqQueryVals.Add("p", ds.Password)
  34. req.URL.RawQuery = reqQueryVals.Encode()
  35. } else if ds.Type == m.DS_INFLUXDB {
  36. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  37. reqQueryVals.Add("db", ds.Database)
  38. reqQueryVals.Add("u", ds.User)
  39. reqQueryVals.Add("p", ds.Password)
  40. req.URL.RawQuery = reqQueryVals.Encode()
  41. } else {
  42. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  43. }
  44. if ds.BasicAuth {
  45. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  46. }
  47. }
  48. return &httputil.ReverseProxy{Director: director}
  49. }
  50. //ProxyDataSourceRequest TODO need to cache datasources
  51. func ProxyDataSourceRequest(c *middleware.Context) {
  52. id := c.ParamsInt64(":id")
  53. query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
  54. if err := bus.Dispatch(&query); err != nil {
  55. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  56. return
  57. }
  58. proxyPath := c.Params("*")
  59. proxy := NewReverseProxy(&query.Result, proxyPath)
  60. proxy.Transport = dataProxyTransport
  61. proxy.ServeHTTP(c.RW(), c.Req.Request)
  62. }