-
Notifications
You must be signed in to change notification settings - Fork 6
/
proxy.go
231 lines (193 loc) · 5.69 KB
/
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main
import (
"context"
"fmt"
"strconv"
"sync"
"time"
"net/http"
"net/http/httputil"
"net/url"
"github.com/hagen1778/chproxy/config"
"github.com/hagen1778/chproxy/log"
"github.com/prometheus/client_golang/prometheus"
)
func newReverseProxy() *reverseProxy {
return &reverseProxy{
ReverseProxy: &httputil.ReverseProxy{
Director: func(*http.Request) {},
ErrorLog: log.ErrorLogger,
},
}
}
func (rp *reverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
log.Debugf("Accepting request from %s: %s", req.RemoteAddr, req.URL)
name, password := getAuth(req)
s, err := rp.getScope(name, password)
if err != nil {
respondWithErr(rw, err)
return
}
log.Debugf("Request scope %s", s)
if !s.user.allowedNetworks.Contains(req.RemoteAddr) {
respondWithErr(rw, fmt.Errorf("user %q is not allowed to access from %s", name, req.RemoteAddr))
return
}
label := prometheus.Labels{
"user": s.user.name,
"host": s.host.addr.Host,
"cluster_user": s.clusterUser.name,
}
requestSum.With(label).Inc()
if err = s.inc(); err != nil {
concurrentLimitExcess.With(label).Inc()
respondWithErr(rw, err)
return
}
defer s.dec()
timeStart := time.Now()
req = s.decorateRequest(req)
var (
timeout time.Duration
timeoutErrMsg error
)
if s.user.maxExecutionTime > 0 {
timeout = s.user.maxExecutionTime
timeoutErrMsg = fmt.Errorf("timeout for user %q exceeded: %v", s.user.name, timeout)
}
if timeout == 0 || (s.clusterUser.maxExecutionTime > 0 && s.clusterUser.maxExecutionTime < timeout) {
timeout = s.clusterUser.maxExecutionTime
timeoutErrMsg = fmt.Errorf("timeout for cluster user %q exceeded: %v", s.clusterUser.name, timeout)
}
ctx := context.Background()
if timeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
}
req = req.WithContext(ctx)
cw := &cachedWriter{ResponseWriter: rw}
rp.ReverseProxy.ServeHTTP(cw, req)
switch {
case req.Context().Err() != nil:
cw.statusCode = http.StatusGatewayTimeout
if err := s.killQuery(); err != nil {
log.Errorf("error while killing query: %s", err)
}
fmt.Fprint(rw, timeoutErrMsg.Error())
case cw.statusCode == http.StatusOK:
requestSuccess.With(label).Inc()
log.Debugf("Request scope %s successfully proxied", s)
case cw.statusCode == http.StatusBadGateway:
fmt.Fprintf(rw, "unable to reach address: %s", req.URL.Host)
}
statusCodes.With(
prometheus.Labels{
"user": s.user.name,
"cluster_user": s.clusterUser.name,
"host": req.URL.Host,
"code": strconv.Itoa(cw.statusCode),
},
).Inc()
requestDuration.With(label).Observe(float64(time.Since(timeStart).Seconds()))
}
// Applies provided config to reverseProxy
// New config will be applied only if non-nil error returned
func (rp *reverseProxy) ApplyConfig(cfg *config.Config) error {
clusters := make(map[string]*cluster, len(cfg.Clusters))
for _, c := range cfg.Clusters {
hosts := make([]*host, len(c.Nodes))
for i, node := range c.Nodes {
addr, err := url.Parse(fmt.Sprintf("%s://%s", c.Scheme, node))
if err != nil {
return err
}
hosts[i] = &host{
addr: addr,
}
}
clusterUsers := make(map[string]*clusterUser, len(c.ClusterUsers))
for _, u := range c.ClusterUsers {
if _, ok := clusterUsers[u.Name]; ok {
return fmt.Errorf("cluster user %q already exists", u.Name)
}
clusterUsers[u.Name] = &clusterUser{
name: u.Name,
password: u.Password,
maxConcurrentQueries: u.MaxConcurrentQueries,
maxExecutionTime: u.MaxExecutionTime,
}
}
if _, ok := clusters[c.Name]; ok {
return fmt.Errorf("cluster %q already exists", c.Name)
}
cluster := &cluster{
hosts: hosts,
users: clusterUsers,
}
cluster.killQueryUserName = c.KillQueryUser.Name
cluster.killQueryUserPassword = c.KillQueryUser.Password
clusters[c.Name] = cluster
}
users := make(map[string]*user, len(cfg.Users))
for _, u := range cfg.Users {
c, ok := clusters[u.ToCluster]
if !ok {
return fmt.Errorf("error while mapping user %q to cluster %q: no such cluster", u.Name, u.ToCluster)
}
if _, ok := c.users[u.ToUser]; !ok {
return fmt.Errorf("error while mapping user %q to cluster's %q user %q: no such user", u.Name, u.ToCluster, u.ToUser)
}
if _, ok := users[u.Name]; ok {
return fmt.Errorf("user %q already exists", u.Name)
}
users[u.Name] = &user{
toCluster: u.ToCluster,
toUser: u.ToUser,
allowedNetworks: u.Networks,
name: u.Name,
password: u.Password,
maxConcurrentQueries: u.MaxConcurrentQueries,
maxExecutionTime: u.MaxExecutionTime,
}
}
rp.mu.Lock()
rp.clusters = clusters
rp.users = users
rp.mu.Unlock()
return nil
}
type reverseProxy struct {
*httputil.ReverseProxy
mu sync.Mutex
users map[string]*user
clusters map[string]*cluster
}
func (rp *reverseProxy) getScope(name, password string) (*scope, error) {
rp.mu.Lock()
defer rp.mu.Unlock()
u, ok := rp.users[name]
if !ok {
return nil, fmt.Errorf("invalid username or password for user %q", name)
}
if u.password != password {
return nil, fmt.Errorf("invalid username or password for user %q", name)
}
c, ok := rp.clusters[u.toCluster]
if !ok {
panic(fmt.Sprintf("BUG: user %q matches to unknown cluster %q", u.name, u.toCluster))
}
cu, ok := c.users[u.toUser]
if !ok {
panic(fmt.Sprintf("BUG: user %q matches to unknown user %q at cluster %q", u.name, u.toUser, u.toCluster))
}
return newScope(u, cu, c), nil
}
type cachedWriter struct {
http.ResponseWriter
statusCode int
}
func (cw *cachedWriter) WriteHeader(code int) {
cw.statusCode = code
cw.ResponseWriter.WriteHeader(code)
}