This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
graphite_proxy.go
69 lines (58 loc) · 1.71 KB
/
graphite_proxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package api
import (
"context"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"sync"
log "github.com/sirupsen/logrus"
"github.com/grafana/metrictank/api/response"
"github.com/grafana/metrictank/stats"
)
var proxyStats graphiteProxyStats
func init() {
proxyStats = graphiteProxyStats{
funcMiss: make(map[string]*stats.Counter32),
}
}
type graphiteProxyStats struct {
sync.Mutex
funcMiss map[string]*stats.Counter32
}
func (s *graphiteProxyStats) Miss(fun string) {
s.Lock()
counter, ok := s.funcMiss[fun]
if !ok {
counter = stats.NewCounter32(fmt.Sprintf("api.request.render.proxy-due-to.%s", fun))
s.funcMiss[fun] = counter
}
s.Unlock()
counter.Inc()
}
func NewGraphiteProxy(u *url.URL) *httputil.ReverseProxy {
graphiteProxy := httputil.NewSingleHostReverseProxy(u)
// remove these headers from upstream. we will set our own correct ones
graphiteProxy.ModifyResponse = func(resp *http.Response) error {
// if kept, would be duplicated. and duplicated headers are illegal)
resp.Header.Del("access-control-allow-credentials")
resp.Header.Del("access-control-allow-origin")
// if kept, would errorously stick around and be invalid because we gzip responses
resp.Header.Del("content-length")
return nil
}
graphiteProxy.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
if graphiteProxy.ErrorLog != nil {
graphiteProxy.ErrorLog.Printf("http: proxy error: %v", err)
} else {
log.Printf("http: proxy error: %v", err)
}
if req.Context().Err() == context.Canceled {
// if the client disconnected before the query was fully processed
rw.WriteHeader(response.HttpClientClosedRequest)
} else {
rw.WriteHeader(http.StatusBadGateway)
}
}
return graphiteProxy
}