-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathwebsocket_server.go
More file actions
102 lines (87 loc) · 2.35 KB
/
websocket_server.go
File metadata and controls
102 lines (87 loc) · 2.35 KB
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
package proxy
import (
"fmt"
"log"
"net/http"
"strings"
"time"
"code.cloudfoundry.org/loggregator-release/src/metricemitter"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
websocketKeepAliveDuration = 30 * time.Second
slowConsumerEventTitle = "Traffic Controller has disconnected slow consumer"
slowConsumerEventBody = `Remote Address: %s
X-Forwarded-For: %s
Path: %s
When Loggregator detects a slow connection, that connection is disconnected to prevent back pressure on the system. This may be due to improperly scaled nozzles, or slow user connections to Loggregator`
)
type WebSocketServer struct {
slowConsumerMetric *metricemitter.Counter
slowConsumerTimeout time.Duration
metricClient MetricClient
}
func NewWebSocketServer(slowConsumerTimeout time.Duration, m MetricClient) *WebSocketServer {
// metric-documentation-v2: (doppler_proxy.slow_consumer) Counter
// indicating occurrences of slow consumers.
slowConsumerMetric := m.NewCounter("doppler_proxy.slow_consumer",
metricemitter.WithVersion(2, 0),
)
return &WebSocketServer{
slowConsumerMetric: slowConsumerMetric,
slowConsumerTimeout: slowConsumerTimeout,
metricClient: m,
}
}
func (s *WebSocketServer) ServeWS(
w http.ResponseWriter,
r *http.Request,
recv func() ([]byte, error),
egressMetric *metricemitter.Counter,
) {
data := make(chan []byte)
handler := NewWebsocketHandler(
data,
websocketKeepAliveDuration,
egressMetric,
)
go func() {
defer close(data)
timer := time.NewTimer(s.slowConsumerTimeout)
timer.Stop()
for {
resp, err := recv()
if err != nil {
status, ok := status.FromError(err)
if ok && status.Code() != codes.Canceled {
log.Printf("error receiving from doppler via gRPC %s", err)
}
return
}
if resp == nil {
continue
}
timer.Reset(s.slowConsumerTimeout)
select {
case data <- resp:
if !timer.Stop() {
<-timer.C
}
case <-timer.C:
s.slowConsumerMetric.Increment(1)
eventBody := fmt.Sprintf(slowConsumerEventBody,
r.RemoteAddr,
strings.Join(r.Header["X-Forwarded-For"], ", "),
r.URL)
s.metricClient.EmitEvent(
slowConsumerEventTitle,
eventBody,
)
log.Printf("Doppler Proxy: Slow Consumer from %s using %s", r.RemoteAddr, r.URL) //nolint:gosec
return
}
}
}()
handler.ServeHTTP(w, r)
}