forked from knative/pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.go
More file actions
399 lines (336 loc) · 11.2 KB
/
Copy pathconnection.go
File metadata and controls
399 lines (336 loc) · 11.2 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
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
/*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package websocket
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"io"
"net/http/httputil"
"sync"
"time"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/gorilla/websocket"
)
var (
// ErrConnectionNotEstablished is returned by methods that need a connection
// but no connection is already created.
ErrConnectionNotEstablished = errors.New("connection has not yet been established")
// errShuttingDown is returned internally once the shutdown signal has been sent.
errShuttingDown = errors.New("shutdown in progress")
// pongTimeout defines the amount of time allowed between two pongs to arrive
// before the connection is considered broken.
pongTimeout = 10 * time.Second
)
// RawConnection is an interface defining the methods needed
// from a websocket connection
type rawConnection interface {
WriteMessage(messageType int, data []byte) error
NextReader() (int, io.Reader, error)
Close() error
SetReadDeadline(deadline time.Time) error
SetPongHandler(func(string) error)
}
// ManagedConnection represents a websocket connection.
type ManagedConnection struct {
connection rawConnection
connectionFactory func() (rawConnection, error)
closeChan chan struct{}
closeOnce sync.Once
establishChan chan struct{}
establishOnce sync.Once
// Used to capture asynchronous processes to be waited
// on when shutting the connection down.
processingWg sync.WaitGroup
// If set, messages will be forwarded to this channel
messageChan chan []byte
// This mutex controls access to the connection reference
// itself.
connectionLock sync.RWMutex
// Gorilla's documentation states, that one reader and
// one writer are allowed concurrently.
readerLock sync.Mutex
writerLock sync.Mutex
// Used for the exponential backoff when connecting
connectionBackoff wait.Backoff
// OnConnect is called when a connection is successfully established.
// This callback is invoked each time the connection is established,
// including reconnections.
OnConnect func()
// OnDisconnect is called when a connection is lost.
// The error parameter contains the reason for the disconnection.
OnDisconnect func(error)
}
// ConnectionOption is a functional option for configuring ManagedConnection.
type ConnectionOption func(*ManagedConnection)
// WithOnConnect sets a callback that is invoked when a connection is established.
func WithOnConnect(f func()) ConnectionOption {
return func(c *ManagedConnection) {
c.OnConnect = f
}
}
// WithOnDisconnect sets a callback that is invoked when a connection is lost.
func WithOnDisconnect(f func(error)) ConnectionOption {
return func(c *ManagedConnection) {
c.OnDisconnect = f
}
}
// NewDurableSendingConnection creates a new websocket connection
// that can only send messages to the endpoint it connects to.
// The connection will continuously be kept alive and reconnected
// in case of a loss of connectivity.
func NewDurableSendingConnection(target string, logger *zap.SugaredLogger, opts ...ConnectionOption) *ManagedConnection {
return NewDurableConnection(target, nil, logger, opts...)
}
// NewDurableSendingConnectionGuaranteed creates a new websocket connection
// that can only send messages to the endpoint it connects to. It returns
// the connection if the connection can be established within the given
// `duration`. Otherwise it returns the ErrConnectionNotEstablished error.
//
// The connection will continuously be kept alive and reconnected
// in case of a loss of connectivity.
func NewDurableSendingConnectionGuaranteed(target string, duration time.Duration, logger *zap.SugaredLogger) (*ManagedConnection, error) {
c := NewDurableConnection(target, nil, logger)
select {
case <-c.establishChan:
return c, nil
case <-time.After(duration):
c.Shutdown()
return nil, ErrConnectionNotEstablished
}
}
// NewDurableConnection creates a new websocket connection, that
// passes incoming messages to the given message channel. It can also
// send messages to the endpoint it connects to.
// The connection will continuously be kept alive and reconnected
// in case of a loss of connectivity.
//
// Note: The given channel needs to be drained after calling `Shutdown`
// to not cause any deadlocks. If the channel's buffer is likely to be
// filled, this needs to happen in separate goroutines, i.e.
//
// go func() {conn.Shutdown(); close(messageChan)}
// go func() {for range messageChan {}}
func NewDurableConnection(target string, messageChan chan []byte, logger *zap.SugaredLogger, opts ...ConnectionOption) *ManagedConnection {
websocketConnectionFactory := func() (rawConnection, error) {
dialer := &websocket.Dialer{
// This needs to be relatively short to avoid the connection getting blackholed for a long time
// by restarting the serving side of the connection behind a Kubernetes Service.
HandshakeTimeout: 3 * time.Second,
}
conn, resp, err := dialer.Dial(target, nil) //nolint:bodyclose
if err != nil {
if resp != nil {
dresp, _ := httputil.DumpResponse(resp, true /*body*/) // This is for logging so don't care if it fails.
logger.Errorw("Websocket connection could not be established", zap.Error(err),
zap.String("request", string(dresp)))
} else {
logger.Errorw("Websocket connection could not be established", zap.Error(err))
}
}
return conn, err
}
c := newConnection(websocketConnectionFactory, messageChan)
// Apply options before starting the goroutine
for _, opt := range opts {
opt(c)
}
// Keep the connection alive asynchronously and reconnect on
// connection failure.
c.processingWg.Add(1)
go func() {
defer c.processingWg.Done()
for {
select {
default:
logger.Info("Connecting to ", target)
if err := c.connect(); err != nil {
logger.Errorw("Failed connecting to "+target, zap.Error(err))
continue
}
logger.Debug("Connected to ", target)
if c.OnConnect != nil {
c.OnConnect()
}
if err := c.keepalive(); err != nil {
logger.Errorw(fmt.Sprintf("Connection to %s broke down, reconnecting...", target), zap.Error(err))
if c.OnDisconnect != nil {
c.OnDisconnect(err)
}
}
if err := c.closeConnection(); err != nil {
logger.Errorw("Failed to close the connection after crashing", zap.Error(err))
}
case <-c.closeChan:
logger.Infof("Connection to %s is being shutdown", target)
return
}
}
}()
// Keep sending pings 3 times per pongTimeout interval.
c.processingWg.Add(1)
go func() {
defer c.processingWg.Done()
ticker := time.NewTicker(pongTimeout / 3)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
logger.Errorw("Failed to send ping message to "+target, zap.Error(err))
}
case <-c.closeChan:
return
}
}
}()
return c
}
// newConnection creates a new connection primitive.
func newConnection(connFactory func() (rawConnection, error), messageChan chan []byte) *ManagedConnection {
conn := &ManagedConnection{
connectionFactory: connFactory,
closeChan: make(chan struct{}),
establishChan: make(chan struct{}),
messageChan: messageChan,
connectionBackoff: wait.Backoff{
Duration: 100 * time.Millisecond,
Factor: 1.3,
Steps: 20,
Jitter: 0.5,
},
}
return conn
}
// connect tries to establish a websocket connection.
func (c *ManagedConnection) connect() error {
return wait.ExponentialBackoff(c.connectionBackoff, func() (bool, error) {
select {
default:
conn, err := c.connectionFactory()
if err != nil {
return false, nil
}
// Setting the read deadline will cause NextReader in read
// to fail if it is exceeded. This deadline is reset each
// time we receive a pong message so we know the connection
// is still intact.
conn.SetReadDeadline(time.Now().Add(pongTimeout))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongTimeout))
return nil
})
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
c.connection = conn
c.establishOnce.Do(func() {
close(c.establishChan)
})
return true, nil
case <-c.closeChan:
return false, errShuttingDown
}
})
}
// keepalive keeps the connection open.
func (c *ManagedConnection) keepalive() error {
for {
select {
default:
if err := c.read(); err != nil {
return err
}
case <-c.closeChan:
return errShuttingDown
}
}
}
// closeConnection closes the underlying websocket connection.
func (c *ManagedConnection) closeConnection() error {
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
if c.connection != nil {
err := c.connection.Close()
c.connection = nil
return err
}
return nil
}
// read reads the next message from the connection.
// If a messageChan is supplied and the current message type is not
// a control message, the message is sent to that channel.
func (c *ManagedConnection) read() error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
c.readerLock.Lock()
defer c.readerLock.Unlock()
messageType, reader, err := c.connection.NextReader()
if err != nil {
return err
}
// Send the message to the channel if its an application level message
// and if that channel is set.
// TODO(markusthoemmes): Return the messageType along with the payload.
if c.messageChan != nil && (messageType == websocket.TextMessage || messageType == websocket.BinaryMessage) {
if message, _ := io.ReadAll(reader); message != nil {
c.messageChan <- message
}
}
return nil
}
func (c *ManagedConnection) write(messageType int, body []byte) error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
c.writerLock.Lock()
defer c.writerLock.Unlock()
return c.connection.WriteMessage(messageType, body)
}
// Status checks the connection status of the webhook.
func (c *ManagedConnection) Status() error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
return nil
}
// Send sends an encodable message over the websocket connection.
func (c *ManagedConnection) Send(msg interface{}) error {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
if err := enc.Encode(msg); err != nil {
return err
}
return c.write(websocket.BinaryMessage, b.Bytes())
}
// SendRaw sends a message over the websocket connection without performing any encoding.
func (c *ManagedConnection) SendRaw(messageType int, msg []byte) error {
return c.write(messageType, msg)
}
// Shutdown closes the websocket connection.
func (c *ManagedConnection) Shutdown() error {
c.closeOnce.Do(func() {
close(c.closeChan)
})
err := c.closeConnection()
c.processingWg.Wait()
return err
}