mirror of https://github.com/grafana/grafana.git
				
				
				
			
		
			
				
	
	
		
			80 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Go
		
	
	
	
			
		
		
	
	
			80 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Go
		
	
	
	
| package api
 | |
| 
 | |
| import (
 | |
| 	"crypto/tls"
 | |
| 	"net"
 | |
| 	"net/http"
 | |
| 	"net/http/httputil"
 | |
| 	"net/url"
 | |
| 	"time"
 | |
| 
 | |
| 	"github.com/grafana/grafana/pkg/bus"
 | |
| 	"github.com/grafana/grafana/pkg/middleware"
 | |
| 	m "github.com/grafana/grafana/pkg/models"
 | |
| 	"github.com/grafana/grafana/pkg/util"
 | |
| )
 | |
| 
 | |
| var dataProxyTransport = &http.Transport{
 | |
| 	TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
 | |
| 	Proxy:           http.ProxyFromEnvironment,
 | |
| 	Dial: (&net.Dialer{
 | |
| 		Timeout:   30 * time.Second,
 | |
| 		KeepAlive: 30 * time.Second,
 | |
| 	}).Dial,
 | |
| 	TLSHandshakeTimeout: 10 * time.Second,
 | |
| }
 | |
| 
 | |
| func NewReverseProxy(ds *m.DataSource, proxyPath string) *httputil.ReverseProxy {
 | |
| 	target, _ := url.Parse(ds.Url)
 | |
| 
 | |
| 	director := func(req *http.Request) {
 | |
| 		req.URL.Scheme = target.Scheme
 | |
| 		req.URL.Host = target.Host
 | |
| 		req.Host = target.Host
 | |
| 
 | |
| 		reqQueryVals := req.URL.Query()
 | |
| 
 | |
| 		if ds.Type == m.DS_INFLUXDB_08 {
 | |
| 			req.URL.Path = util.JoinUrlFragments(target.Path, "db/"+ds.Database+"/"+proxyPath)
 | |
| 			reqQueryVals.Add("u", ds.User)
 | |
| 			reqQueryVals.Add("p", ds.Password)
 | |
| 			req.URL.RawQuery = reqQueryVals.Encode()
 | |
| 		} else if ds.Type == m.DS_INFLUXDB {
 | |
| 			req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
 | |
| 			reqQueryVals.Add("db", ds.Database)
 | |
| 			req.URL.RawQuery = reqQueryVals.Encode()
 | |
| 			if !ds.BasicAuth {
 | |
| 				req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.User, ds.Password))
 | |
| 			}
 | |
| 		} else {
 | |
| 			req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
 | |
| 		}
 | |
| 
 | |
| 		if ds.BasicAuth {
 | |
| 			req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
 | |
| 		}
 | |
| 
 | |
| 		// clear cookie headers
 | |
| 		req.Header.Del("Cookie")
 | |
| 		req.Header.Del("Set-Cookie")
 | |
| 	}
 | |
| 
 | |
| 	return &httputil.ReverseProxy{Director: director}
 | |
| }
 | |
| 
 | |
| //ProxyDataSourceRequest TODO need to cache datasources
 | |
| func ProxyDataSourceRequest(c *middleware.Context) {
 | |
| 	id := c.ParamsInt64(":id")
 | |
| 	query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
 | |
| 
 | |
| 	if err := bus.Dispatch(&query); err != nil {
 | |
| 		c.JsonApiErr(500, "Unable to load datasource meta data", err)
 | |
| 		return
 | |
| 	}
 | |
| 
 | |
| 	proxyPath := c.Params("*")
 | |
| 	proxy := NewReverseProxy(&query.Result, proxyPath)
 | |
| 	proxy.Transport = dataProxyTransport
 | |
| 	proxy.ServeHTTP(c.RW(), c.Req.Request)
 | |
| }
 |