/
proxy_muxer.go
461 lines (412 loc) · 12 KB
/
proxy_muxer.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package gateway
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/TykTechnologies/again"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/tcp"
proxyproto "github.com/pires/go-proxyproto"
cache "github.com/pmylund/go-cache"
"golang.org/x/net/http2"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
// handleWrapper's only purpose is to allow router to be dynamically replaced
type handleWrapper struct {
router *mux.Router
}
func (h *handleWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// make request body to be nopCloser and re-readable before serve it through chain of middlewares
nopCloseRequestBody(r)
if NewRelicApplication != nil {
txn := NewRelicApplication.StartTransaction(r.URL.Path, w, r)
defer txn.End()
h.router.ServeHTTP(txn, r)
return
}
h.router.ServeHTTP(w, r)
}
type proxy struct {
listener net.Listener
port int
protocol string
useProxyProtocol bool
router *mux.Router
httpServer *http.Server
tcpProxy *tcp.Proxy
started bool
}
func (p proxy) String() string {
ls := ""
if p.listener != nil {
ls = p.listener.Addr().String()
}
return fmt.Sprintf("[proxy] :%d %s", p.port, ls)
}
// getListener returns a net.Listener for this proxy. If useProxyProtocol is
// true it wraps the underlying listener to support proxyprotocol.
func (p proxy) getListener() net.Listener {
if p.useProxyProtocol {
return &proxyproto.Listener{Listener: p.listener}
}
return p.listener
}
type proxyMux struct {
sync.RWMutex
proxies []*proxy
again again.Again
}
var defaultProxyMux = &proxyMux{
again: again.New(),
}
func (m *proxyMux) getProxy(listenPort int) *proxy {
if listenPort == 0 {
listenPort = config.Global().ListenPort
}
for _, p := range m.proxies {
if p.port == listenPort {
return p
}
}
return nil
}
func (m *proxyMux) router(port int, protocol string) *mux.Router {
if protocol == "" {
if config.Global().HttpServerOptions.UseSSL {
protocol = "https"
} else {
protocol = "http"
}
}
if proxy := m.getProxy(port); proxy != nil {
if proxy.protocol != protocol {
mainLog.WithField("port", port).Warningf("Can't get router for protocol %s, router for protocol %s found", protocol, proxy.protocol)
return nil
}
return proxy.router
}
return nil
}
func (m *proxyMux) setRouter(port int, protocol string, router *mux.Router) {
if port == 0 {
port = config.Global().ListenPort
}
if protocol == "" {
if config.Global().HttpServerOptions.UseSSL {
protocol = "https"
} else {
protocol = "http"
}
}
router.SkipClean(config.Global().HttpServerOptions.SkipURLCleaning)
p := m.getProxy(port)
if p == nil {
p = &proxy{
port: port,
protocol: protocol,
router: router,
}
m.proxies = append(m.proxies, p)
} else {
if p.protocol != protocol {
mainLog.WithFields(logrus.Fields{
"port": port,
"protocol": protocol,
}).Warningf("Can't update router. Already found service with another protocol %s", p.protocol)
return
}
p.router = router
}
}
func (m *proxyMux) addTCPService(spec *APISpec, modifier *tcp.Modifier) {
hostname := spec.GlobalConfig.HostName
if spec.GlobalConfig.EnableCustomDomains {
hostname = spec.Domain
} else {
hostname = ""
}
if p := m.getProxy(spec.ListenPort); p != nil {
p.tcpProxy.AddDomainHandler(hostname, spec.Proxy.TargetURL, modifier)
} else {
tlsConfig := tlsClientConfig(spec)
p = &proxy{
port: spec.ListenPort,
protocol: spec.Protocol,
useProxyProtocol: spec.EnableProxyProtocol,
tcpProxy: &tcp.Proxy{
DialTLS: dialWithServiceDiscovery(spec, customDialTLSCheck(spec, tlsConfig)),
Dial: dialWithServiceDiscovery(spec, net.Dial),
TLSConfigTarget: tlsConfig,
// SyncStats: recordTCPHit(spec.APIID, spec.DoNotTrack),
},
}
p.tcpProxy.AddDomainHandler(hostname, spec.Proxy.TargetURL, modifier)
m.proxies = append(m.proxies, p)
}
}
func flushNetworkAnalytics(ctx context.Context) {
mainLog.Debug("Starting routine for flushing network analytics")
tick := time.NewTicker(time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case t := <-tick.C:
apisMu.RLock()
for _, spec := range apiSpecs {
switch spec.Protocol {
case "tcp", "tls":
// we only flush network analytics for these services
default:
continue
}
if spec.DoNotTrack {
continue
}
record := AnalyticsRecord{
Network: spec.network.Flush(),
Day: t.Day(),
Month: t.Month(),
Year: t.Year(),
Hour: t.Hour(),
ResponseCode: -1,
TimeStamp: t,
APIName: spec.Name,
APIID: spec.APIID,
OrgID: spec.OrgID,
}
record.SetExpiry(spec.ExpireAnalyticsAfter)
analytics.RecordHit(&record)
}
apisMu.RUnlock()
}
}
}
func recordTCPHit(specID string, doNotTrack bool) func(tcp.Stat) {
if doNotTrack {
return nil
}
return func(stat tcp.Stat) {
// Between reloads, pointers to the actual spec might have changed. The spec
// id stays the same so we need to pic the latest refence to the spec and
// update network stats.
apisMu.RLock()
spec := apisByID[specID]
apisMu.RUnlock()
switch stat.State {
case tcp.Open:
atomic.AddInt64(&spec.network.OpenConnections, 1)
case tcp.Closed:
atomic.AddInt64(&spec.network.ClosedConnection, 1)
}
atomic.AddInt64(&spec.network.BytesIn, stat.BytesIn)
atomic.AddInt64(&spec.network.BytesOut, stat.BytesOut)
}
}
type dialFn func(network string, address string) (net.Conn, error)
func dialWithServiceDiscovery(spec *APISpec, dial dialFn) dialFn {
if dial == nil {
return nil
}
if spec.Proxy.ServiceDiscovery.UseDiscoveryService {
log.Debug("[PROXY] Service discovery enabled")
if ServiceCache == nil {
log.Debug("[PROXY] Service cache initialising")
expiry := 120
if spec.Proxy.ServiceDiscovery.CacheTimeout > 0 {
expiry = int(spec.Proxy.ServiceDiscovery.CacheTimeout)
} else if spec.GlobalConfig.ServiceDiscovery.DefaultCacheTimeout > 0 {
expiry = spec.GlobalConfig.ServiceDiscovery.DefaultCacheTimeout
}
ServiceCache = cache.New(time.Duration(expiry)*time.Second, 15*time.Second)
}
}
return func(network, address string) (net.Conn, error) {
hostList := spec.Proxy.StructuredTargetList
target := address
switch {
case spec.Proxy.ServiceDiscovery.UseDiscoveryService:
var err error
hostList, err = urlFromService(spec)
if err != nil {
log.Error("[PROXY] [SERVICE DISCOVERY] Failed target lookup: ", err)
break
}
log.Debug("[PROXY] [SERVICE DISCOVERY] received host list ", hostList.All())
fallthrough // implies load balancing, with replaced host list
case spec.Proxy.EnableLoadBalancing:
host, err := nextTarget(hostList, spec)
if err != nil {
log.Error("[PROXY] [LOAD BALANCING] ", err)
host = allHostsDownURL
}
lbRemote, err := url.Parse(host)
if err != nil {
log.Error("[PROXY] [LOAD BALANCING] Couldn't parse target URL:", err)
} else {
if lbRemote.Scheme == network {
target = lbRemote.Host
} else {
log.Errorf("[PROXY] [LOAD BALANCING] mis match scheme want:%s got: %s", network, lbRemote.Scheme)
}
}
}
return dial(network, target)
}
}
func (m *proxyMux) swap(new *proxyMux) {
m.Lock()
defer m.Unlock()
listenAddress := config.Global().ListenAddress
// Shutting down and removing unused listeners/proxies
i := 0
for _, curP := range m.proxies {
match := new.getProxy(curP.port)
if match == nil || match.protocol != curP.protocol {
mainLog.Infof("Found unused listener at port %d, shutting down", curP.port)
if curP.httpServer != nil {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
curP.httpServer.Shutdown(ctx)
cancel()
} else if curP.listener != nil {
curP.listener.Close()
}
m.again.Delete(target(listenAddress, curP.port))
} else {
m.proxies[i] = curP
i++
}
}
m.proxies = m.proxies[:i]
// Replacing existing routers or starting new listeners
for _, newP := range new.proxies {
match := m.getProxy(newP.port)
if match == nil {
m.proxies = append(m.proxies, newP)
} else {
if match.tcpProxy != nil {
match.tcpProxy.Swap(newP.tcpProxy)
}
match.router = newP.router
if match.httpServer != nil {
match.httpServer.Handler.(*handleWrapper).router = newP.router
}
}
}
p := m.getProxy(config.Global().ListenPort)
if p != nil && p.router != nil {
// All APIs processed, now we can healthcheck
// Add a root message to check all is OK
p.router.HandleFunc("/"+config.Global().HealthCheckEndpointName, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello Tiki")
})
}
m.serve()
}
func (m *proxyMux) serve() {
for _, p := range m.proxies {
if p.listener == nil {
listener, err := m.generateListener(p.port, p.protocol)
if err != nil {
mainLog.WithError(err).Error("Can't start listener")
continue
}
_, portS, _ := net.SplitHostPort(listener.Addr().String())
port, _ := strconv.Atoi(portS)
p.port = port
p.listener = listener
}
if p.started {
continue
}
switch p.protocol {
case "tcp", "tls":
mainLog.Warning("Starting TCP server on:", p.listener.Addr().String())
go p.tcpProxy.Serve(p.getListener())
case "http", "https":
mainLog.Warning("Starting HTTP server on:", p.listener.Addr().String())
readTimeout := 120 * time.Second
writeTimeout := 120 * time.Second
if config.Global().HttpServerOptions.ReadTimeout > 0 {
readTimeout = time.Duration(config.Global().HttpServerOptions.ReadTimeout) * time.Second
}
if config.Global().HttpServerOptions.WriteTimeout > 0 {
writeTimeout = time.Duration(config.Global().HttpServerOptions.WriteTimeout) * time.Second
}
addr := config.Global().ListenAddress + ":" + strconv.Itoa(p.port)
p.httpServer = &http.Server{
Addr: addr,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
Handler: &handleWrapper{p.router},
}
if config.Global().CloseConnections {
p.httpServer.SetKeepAlivesEnabled(false)
}
go p.httpServer.Serve(p.listener)
}
p.started = true
}
}
func target(listenAddress string, listenPort int) string {
return fmt.Sprintf("%s:%d", listenAddress, listenPort)
}
func CheckPortWhiteList(w map[string]config.PortWhiteList, listenPort int, protocol string) error {
if w != nil {
if ls, ok := w[protocol]; ok {
if ls.Match(listenPort) {
return nil
}
}
}
return fmt.Errorf("%s:%d trying to open disabled port", protocol, listenPort)
}
func (m *proxyMux) generateListener(listenPort int, protocol string) (l net.Listener, err error) {
listenAddress := config.Global().ListenAddress
if !config.Global().DisablePortWhiteList {
if err := CheckPortWhiteList(config.Global().PortWhiteList, listenPort, protocol); err != nil {
return nil, err
}
}
targetPort := listenAddress + ":" + strconv.Itoa(listenPort)
if ls := m.again.GetListener(targetPort); ls != nil {
return ls, nil
}
switch protocol {
case "https", "tls":
mainLog.Infof("--> Using TLS (%s)", protocol)
httpServerOptions := config.Global().HttpServerOptions
tlsConfig := tls.Config{
GetCertificate: dummyGetCertificate,
ServerName: httpServerOptions.ServerName,
MinVersion: httpServerOptions.MinVersion,
ClientAuth: tls.NoClientCert,
InsecureSkipVerify: httpServerOptions.SSLInsecureSkipVerify,
CipherSuites: getCipherAliases(httpServerOptions.Ciphers),
}
if httpServerOptions.EnableHttp2 {
tlsConfig.NextProtos = append(tlsConfig.NextProtos, http2.NextProtoTLS)
}
tlsConfig.GetConfigForClient = getTLSConfigForClient(&tlsConfig, listenPort)
l, err = tls.Listen("tcp", targetPort, &tlsConfig)
default:
mainLog.WithField("port", targetPort).Infof("--> Standard listener (%s)", protocol)
l, err = net.Listen("tcp", targetPort)
}
if err != nil {
return nil, err
}
if err := (&m.again).Listen(targetPort, l); err != nil {
return nil, err
}
return l, nil
}